Você está na página 1de 290

PICRobotics

Thispageintentionallyleftblank.

PICRobotics

A BeginnersGuideto RoboticsProjects UsingthePICmicro

JohnIovine

McGrawHill
NewYork Chicago SanFrancisco Lisbon London Madrid MexicoCity Milan NewDelhi SanJuan Seoul Singapore Sydney Toronto

Copyright 2004 by The McGrawHill Companies, Inc. All rights reserved. ManufacturedintheUnitedStatesofAmerica.ExceptaspermittedundertheUnited StatesCopyrightActof1976,nopartofthispublicationmaybereproducedordis tributed in any form or by any means, or stored in a database or retrieval system, withoutthepriorwrittenpermissionofthepublisher. 0071394559 ThematerialinthiseBookalsoappearsintheprintversionofthistitle: 0071373241. Alltrademarksaretrademarksoftheirrespectiveowners.Ratherthanputatrade marksymbolaftereveryoccurrenceofatrademarkedname,weusenamesinanedi torial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designations appear in this book, they havebeenprintedwithinitialcaps. McGrawHilleBooksareavailableatspecialquantitydiscountstouseaspremiums andsalespromotions,orforuseincorporatetrainingprograms.Formoreinforma tion,pleasecontactGeorgeHoare,SpecialSales,atgeorge_hoare@mcgrawhill.comor (212)9044069. TERMSOFUSE This is a copyrighted work and The McGrawHill Companies, Inc. (McGrawHill) anditslicensorsreserveallrightsinandtothework.Useofthisworkissubjectto theseterms.ExceptaspermittedundertheCopyrightActof1976andtherightto storeandretrieveonecopyofthework,youmaynotdecompile,disassemble,reverse engineer,reproduce,modify,createderivativeworksbasedupon,transmit,distribute, disseminate,sell,publishorsublicensetheworkoranypartofitwithoutMcGraw Hillspriorconsent.Youmayusetheworkforyourownnoncommercialandpersonal use;anyotheruseoftheworkisstrictlyprohibited.Yourrighttousetheworkmay beterminatedifyoufailtocomplywiththeseterms. THEWORKISPROVIDEDASIS.McGRAWHILL ANDITSLICENSORSMAKE NO GUARANTEES OR WARRANTIESAS TO THEACCURACY,ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK,INCLUDINGANYINFORMATIONTHATCANBEACCESSEDTHROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANYWARRANTY,EXPRESSORIMPLIED,INCLUDINGBUTNOTLIMITEDTO IMPLIEDWARRANTIESOFMERCHANTABILITYORFITNESSFORA PARTIC ULARPURPOSE.McGrawHillanditslicensorsdonotwarrantorguaranteethat thefunctionscontainedintheworkwillmeetyourrequirementsorthatitsoperation will be uninterrupted or error free. Neither McGrawHill nor its licensors shall be liabletoyouoranyoneelseforanyinaccuracy,errororomission,regardlessofcause, intheworkorforanydamagesresultingtherefrom.McGrawHillhasnoresponsi bility for the content of any information accessed through the work. Under no cir cumstances shall McGrawHill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the useoforinabilitytousethework,evenifanyofthemhasbeenadvisedofthepossi bilityofsuchdamages.Thislimitationofliabilityshallapplytoanyclaimorcause whatsoeverwhethersuchclaimorcausearisesincontract,tortorotherwise. DOI:10.1036/0071394559

Formoreinformationaboutthistitle,clickhere.

Contents

Preface

xi

Chapter1. RobotIntelligence
WhatIsaMicrocontroller? WhyUseaMicrocontroller? DesignerComputersSoManyMicrocontrollers TheCompiler PICProgrammingOverview SoftwareandHardware PicBasicandPicBasicProCompilers EPICProgrammer Firmware Consumables 16F84PICMicrocontroller Step1:WritingCode(theBasicProgram) Step2:UsingtheCompiler Step3:InstallingtheFirmware,orProgrammingthePICChip Ready,Steady,Go PartsList

1
1
2
2
2
2
3
4
5
5
5
6
7
7
8
8

Chapter2. InstallingtheCompiler
InstallingthePicBasicCompilerSoftware InstallingthePicBasicProCompiler

11

11
12

Chapter3. InstallingtheEPICSoftware
InstallingtheEPICSoftwareinWindows InstallingtheEPICSoftware,DOSVersion SupplementalApplicationsDirectory

19

19
22
22

Chapter4. CodeDesigner
CodeDesignerFeatures SoftwareInstallation

23

23
25

vi

Contents

SettingCodeDesignerOptions FirstProgram TheEPICProgrammingBoardSoftware PartsList

25
31
33
35

Chapter5. UsingDOStoCode,Compile,andProgram
Compile ProgrammingthePICChip TheEPICProgrammingBoardSoftware UsingEPICDOSVersion Continuingwiththewink.bas Program

37

39
43
44
45
45

Chapter6. TestingthePICMicrocontroller
ThePICMicrontroller TheSolderlessBreadboard ThreeSchematics,OneCircuit Wink TroubleshootingtheCircuit PICExperimentersBoardandLCDDisplay PICExperimentersBoard Use SimpleExperiment BuiltinLCD UsingtheLCD:PicBasicandPicBasicProExamples IntroductiontoBinaryandthePICMicrocontroller UsingTRISandPortRegisters AccessingthePortsforOutput CountingProgram CountinginBinaryby1 Input Thebutton Command A button Example

49

49
49
50
53
54
54
56
56
58
60
63
65
68
70
71
71
72
72
74
75
76
77
78
79

peek peek andPicBasicPro


BasicInputandOutputCommands Servomotors PartsList

Chapter7. Intelligence
ApproachestoBuildingIntelligence WherestheIntelligence? LayeredBehavioralResponses BehaviorBasedRobotics

83

83
85
85
86

Chapter8. WaltersTurtle
BehaviorBasedRobotics WilliamGreyWalterRoboticsPioneer FourModesofOperation

87

87
87
88

Contents

vii

ObservedBehavior
BuildingaWalterTortoise
DriveandSteeringMotors
ModifyingtheHS425BBServomotor
SheetMetalFabrication
Shell
FindingtheCenterofGravity
AttachingBumpertoRobotBase
BumperSwitch
MountingtheSteeringServomotor
Photoresistor
TrimmingtheSensorArray
Schematic
Program
AddingSleepMode
Power
Behavior
FudgeFactor
LightIntensity
Handedness
PartsList

88 89 90 91 97 99 100 101 104 107 109 112 114 115 121 121 121 121 121 123 123

Chapter9. BraitenbergVehicles

NeuralI/ORelationships
Vehicles
BuildingVehicles
BackWheels
FrontWheels
CdSPhotoresistorCells
TrimmingtheSensorArray
PIC16F84Microcontroller
Testing
SecondBraitenbergVehicle(AvoidanceBehavior) PartsList

125
126 126 128 129 131 133 137 139 139 141
141

Chapter10. HexapodWalker
ImitationofLife SixLegsTripodGait ThreeServomotorWalkerRobot Function MovingForward MovingBackward TurningLeft TurningRight Construction MountingtheServomotors LegPositioning Linkage

143

143
143
144
144
145
146
147
148
148
151
152
154

viii

Contents

Center(Tilt)Servomotor Sensors Electronics MicrocontrollerProgram PartsList

154
155
158
159
164

Chapter11. SpeechRecognition
Applications SoftwareApproach LearningtoListen SpeakerDependentandSpeakerIndependentRecognition RecognitionStyle SpeechRecognitionCircuit CircuitConstruction Keypad ToTrain TestingRecognition ErrorCodes ClearingtheTrainedWordMemory IndependentRecognitionSystem VoiceSecuritySystem SpeechInterfaceControlCircuit HowtheCircuitWorks PIC16F84MicrocontrollerProgram ActiveHighOutput SPDTRelayOutput CircuitConstruction ProgrammingtheSpeechRecognitionCircuit:Training,Testing,andRetraining SRI02andSRI03Interfaces RobotControl PartsList

165

167
167
167
167
168
168
168
169
169
172
172
172
172
173
173
174
176
177
177
177
177
180
180
181

Chapter12. RoboticArm
ServomotorBuildingBlocksforRobotics BasicServomotorBracketAssembly AssemblingMultipleServomotorAssemblies BuildingaFiveServomotorRoboticArm Servomotors ServomotorControllers SimpleServomotorController FourandFiveServomotorControllers IncreasingtheLiftingCapacityoftheRoboticArm AddingaRoboticArmBase PartsList

185

185
186
189
192
197
199
200
204
215
216
223

Chapter13. BipedalWalkerRobot
A QuestionofBalance? A LittleFeedback Servomotors

225

226
227
227

Contents

ix

ServomotorBrackets Footpads Assembly Schematic Program SubroutinesM1,M2,andM3 GoingFurther TurningRightandLeft PartsList

228
228
230
231
233
234
241
242
242

Chapter14. ColorRoboticVisionSystem
CMUCamera SerialCommunication VBApplicationProgram InterfacingtheCMUCameratoaRobot PIC16F84Runsat16MHz Program1 Program2 IncandescentorFluorescentLighting ServomotorsforRobot Program3 RobotConstruction RunningtheProgram GoingFurther PartsList

243

244
245
248
250
251
251
254
254
259
261
264
266
267
267

Suppliers 269
Index 271

Thispageintentionallyleftblank.

Preface

Thisisaprojectbookonbuildingsmallrobots.EachrobotutilizesthePICmicro seriesofmicrocontrollersfromMicrochipTechnologiesInc.forintelligence,nav igation,motorcontrol,andsensoryreadings.Bychangingthemicrocontroller programmingandsensoryelectronicswecancreateazooofrobotsthatincludes photovores,behaviorbased(neural)robots,hexapodandbipedalwalkers,and artificialvisionsystemsthatcantrackandfollowobjects. Eachrobotprojecthassomethingtoteach. JohnIovine

xi

Thispageintentionallyleftblank.

Chapter

1
RobotIntelligence
TheroboticprojectsoutlinedinthisbookmakeextensiveuseofthePICseries ofmicrocontrollerfromMicrochipTechnologyInc.Inadditiontoitsabilityto runprograms,themicrocontrollerhasinputandoutputlines(pins)thatare used to control motor drive systems, read sensors, and communicate. We demandalotfromourmicrocontroller(s),soitsimportanttohaveagoodidea ofwhatamicrocontrollerisrightfromthestart. WhatIsaMicrocontroller? A microcontroller is essentially an inexpensive singlechip computer. Single chipmeanstheentirecomputersystemlieswithintheconfinesofasliverof silicon encapsulated inside the plastic housing of an integrated circuit. The microcontrollerhasfeaturessimilartothoseofastandardpersonalcomputer. ThemicrocontrollercontainsaCPU(centralprocessingunit),RAM(random accessmemory),ROM(readonlymemory),I/O(input/output)lines,serialand parallelports,timers,andsometimesotherbuiltinperipheralssuchasana logtodigital (A/D) and digitaltoanalog (D/A) converters. The key feature, however,isthemicrocontrollerscapabilityofuploading,storing,andrunning aprogram. WhyUseaMicrocontroller? Beinginexpensivesinglechipcomputers,microcontrollersareeasytoembed intolargerelectroniccircuitdesigns.Theirabilitytostoreandrununiquepro grams makes them extremely versatile. For instance, one can program a microcontrollertomakedecisionsandperformfunctionsbasedonsituations (I/Olinelogic)andevents.Themathandlogicfunctionsallowthemicrocon trollertomimicsophisticatedlogicandelectroniccircuits.

Copyright2004TheMcGrawHillCompanies.Clickherefortermsofuse.

ChapterOne

Programs can also make the microcontroller behave as a neural network and/orafuzzylogiccontroller.Microcontrollersareincorporatedinconsumer electronicsandareresponsiblefortheintelligenceinthesesmartelectronic devices. DesignerComputersSoManyMicrocontrollers Therearealargevarietyofmicrocontrollersonthemarket.Wewillusethe versatile microcontroller chips called PIC chips (or PICmicro chips) from MicrochipTechnologyInc. TheCompiler Thereareanumberofcompilersonthemarketthatallowuserstowritepro grams(code)indifferenthighlevellanguages.Highlevellanguagefreesthe programmer from wrestling with and controlling the microcontrollers regis ters when writing code and accessing the different aspects of the microcon trollersfeaturesandmemory. The highlevel language I use is a derivative of the Basic language. It is called PicBasic. (The PicBasic and PicBasic Pro compilers used to write PicBasic programs are products and trademarks of microEngineering Labs, Inc.) PicBasic is similar to the PBasic language used in programming the Basic Stamp series. Programming microcontrollers directly using the PicBasic(orPicBasicPro)compileroffertwomajoradvantagesovertheBasic Stamp series of microcontrollers which use external serial EEPROM for memory storage, faster program execution speed (20 to 100fold increase), andreducedcost. PICProgrammingOverview Programming PIC microcontrollers is a simple threestep process: Write the code,compilethecode,anduploadthecodeintoamicrocontroller.Following isanoverviewoftheprocess;stepbystepinstructionswillbeprovidedinthe followingchapters. SoftwareandHardware Youwillneedtwoitemstobeginprogrammingandbuildingmicrocontroller based projects and robotics. First is the compiler, either the PicBasic Pro or PicBasic compiler (see Fig. 1.1). The PicBasic Pro compiler from microEngineering Labs, Inc. has a suggested retail price of $249.95. The PicBasic compiler from microEngineering Labs, Inc. has a suggested retail price of $99.95. In addition to a compiler you need the EPIC programming board and software; this package sells for $59.95 (see Fig. 1.2). (EPIC is a productandtrademarkofmicroEngineeringLabs,Inc.)

RobotIntelligence

Figure1.1 PicBasicProandPicBasicsoftwarepackagesandmanuals.

Figure1.2 EPICProgrammersoftwareandhardware.

PicBasicandPicBasicProCompilers ThePicBasicandPicBasicProcompilersbothfunctioninthesameway.Saved program code (text file) is run through a compiler (either the PicBasic or PicBasicProcompiler).Thecompilerreadsthroughthetextfileandcreates (compiles) an equivalent machine code instruction listing (.hex file) of the program.Themachinecode(.hex file)isalistofhexadecimalnumbersthat representthePicBasicprogram.Thelistofhexadecimalnumbers(.hex file) isuploaded(programmed)intothemicrocontroller.Whenthemicrocontroller

ChapterOne

isstarted,itsCPUwillrunthroughtheprogrammedlistofhexadecimalnum bers,runningthePicBasicprogram.Uploadingthemachinecode(.hex file) into the microcontroller is the job of the EPIC Programmer board and soft ware,whichwewilllookatshortly. ThePicBasicProcompilerisconsiderablymoreexpensivethanthestandard PicBasiccompiler.TheProversionoffersanenhancedandricherbasiccommand syntaxthanisavailableinthePicBasiccompilerpackage.A fewoftheaddition alcommandsthatcanbefoundintheProversionallowtheuseofinterrupts, directcontrolofLCDmodules,DTMFout,andX10commands,tonameafew. WhilethePicBasicProisamoresophisticatedpackage,thecompilerdoes nothandletwoofmyfavoriteBasiccommands,peekandpoke.Althoughthe commandsarelistedasfunctionalinthePromanual,itisemphasizedthat PEEKandPOKEshouldneverbeusedinaPicBasicProprogram.Thereare workaroundstousingthepeekandpokecommandsintheProversionthat willbecoveredwhenneededlateron. In the balance of this book, at times I will refer to both the PicBasic and PicBasicProcompilerssimplyasthecompiler(s).Thissavesmefromcontinu allywritingPicBasicandPicBasicProcompilerthroughoutthebook.Whena distinctionbecomesnecessary,Iwillspecifytheindividualcompiler. The compiler program may be run manually in DOS or in an MSDOS Promptwindow.A thirdoption,andoneyouwillprobablyuse,istorunthe compiler within a Windows program called CodeDesigner. CodeDesigner is discussedlaterinthischapterandfullyinChap.4. TheminimumsystemrequirementforthecompilerisanXTclasspersonal computer(PC)runningDOS3.3orhigher.Thecompilercancompileprograms foralargevarietyofPICmicrocontrollers. EPICProgrammer The second item needed is the EPIC Programmer, also made by microEngineering Labs, Inc. The EPIC Programmer consists of software (EPIC) and a programming carrier board (hardware). The EPIC software packagehastwoexecutablefiles,oneforDOSandanotherversionofthesoft wareforWindows. ItistheEPIChardwareandsoftwarethattakesthecompiled.hex filegen eratedbythecompileranduploadsitintothemicrocontroller,whereitmaybe run.TheEPICProgrammeriscompatiblewithboththePicBasicandPicBasic Procompilers. Theprogrammingcarrierboard(seeFig.1.3)hasasocketforinsertingthe PICchipandconnectingittothecomputer,viatheprinterport,forprogram ming.Theprogrammingboardconnectstothecomputersprinterportviaa DB25cable.Ifthecomputeronlyhasoneprinterportwithaprinterconnect edtoit,theprintermustbetemporarilydisconnectedtoprogramPICchips. TheEPICprogrammingcarrierboardsupportsalargevarietyofPICmicro controllers.

RobotIntelligence

Figure1.3 CloseupofEPICprogrammingcarrierboard.

Firmware Many writers use the term firmware. This word is used when software is embeddedinahardwaredevicethatcanreadandexecutebythedevicebut cannotbemodified.Sowhenourprogram(software)isembedded(uploaded) intothemicrocontroller,itmaybereferredtoasfirmware.Otherphrasesmay includetheterm firmware insteadof software, suchasuploadthefirmware oroncethefirmwarehasbeeninstalledintothedevice. Consumables Consumables are the electronic components, the PIC microcontroller chip itself,withafewsupportcomponentstogetthemicrocontrollerupandrun ning.Irecommendbeginningwiththe16F84PICmicrocontroller.The16F84 isan18pindipchipwith13I/Olinesandhas1K 14ofrewritablememory. TherewritablememoryallowsyoutoreprogramthePICchipupto1000times to test and troubleshoot your programs and circuits. The minimal support componentsarea5Vdcpowersupply,oscillator(4.0MHzcrystal),andone pullup14Wresistor(4.7k). 16F84PICMicrocontroller ThePIC16F84microcontrollerisshowninFig.1.4.Itisaversatilemicrocon trollerwithflashmemory. Flashmemory istheterminologyusedtodescribe rewriteable memory. The 1K 14bit onboard flash memory can endure a

ChapterOne

Figure1.4 Pinoutof16F84PICmicrocontrollerintegratedcir

cuit.Generalfeatures:RISCCPU35singlewordinstructions;
operatingspeeddc,10MHzclockinput;1Kprogrammemory;
14bitwide instructions; 8bitwide data path; direct, indirect,
andrelativeaddressing;1000erase/writecycles.Peripheralfea
tures:13I/Opinswithindividualdirectioncontrol;highcurrent
sink/sourcefordirectLEDdrive(25mA sinkmax.perpin,20
mA sourcemax.perpin);TMRO8bittimer/counterwith8bit
programmableprescaler.

minimumof1000erase/writecycles.SoyoucanreprogramandreusethePIC chip at least 1000 times. The program retention time between erase/write cyclesisapproximately40years.The18pinchipdevotes13pinstoI/O.Each pinmaybeprogrammedindividuallyforinputoroutput.Thepinstatus(I/O directioncontrol)maybechangedontheflyviaprogramming.Otherfeatures include power on reset, powersaving sleep mode, powerup timer, and code protection.AdditionalfeaturesandarchitecturaldetailsofthePIC16F84will begivenaswecontinue. Step1:WritingCode(theBasicProgram) BoththePicBasicandPicBasicProcompilersarepackagedwithafreeversion of CodeDesigner software. CodeDesigner is an integrated development envi ronment (IDE) for writing and programming PIC microcontrollers. CodeDesignerisanadvancedtexteditorthatiscapableofcallingandusing boththePicBasicandPicBasicProcompilersandtheEPICsoftware.

RobotIntelligence

IfyoudontwanttouseCodeDesigner,programtextfilesmaybewritten usinganywordprocessoraslongasitisabletosaveitstextfileasASCII or DOS text. If you dont own a commercial word processor, you can use WindowsNotepad,whichisincludedwithWindows3.X,95,and98.Ifyou workattheDOSlevel,youcanusetheEditprogramtowritetextfiles. Whenyousavethetextfile,saveitwitha .bas suffix.Forexample,ifyou weresavingaprogramnamedwink, saveitaswink.bas. Step2:UsingtheCompiler Oncesetup,theCodeDesignersoftwarewillcallandcontrolthecompilerand programmer software. The compiler may be run manually from a DOS win dow.Torunthecompilerprogrammanually,enterthecommandpbc followed bythenumberofthePICchipbeingprogrammed(thatis,16F84),thenfol lowedbythenameofthesourcecodetextfile.ForthePicBasicProcompiler program,thecommandstartswithpbp insteadofpbc, followedbythename ofthesourcecodetextfile.Forexample,forthePicBasiccompiler,ifthesource codetextfilewecreatedisnamed wink, thenattheDOScommandprompt enter
pbcp16f84wink.bas

ForthePicBasicProcompiler,thecommandlinewouldbe
pbpp16f84wink.bas

The compiler reads the text file and compiles two additional files, an .asm (assemblylanguage)anda.hex (hexadecimal)file. The wink.asm file is the assembly language equivalent to the Basic pro gram.Thewink.hex fileisthemachinecodeoftheprogramwritteninhexa decimalnumbers.Itisthe.hex filethatisuploadedintothePICchip. IfthecompilerencounterserrorswhencompilingthePicBasicsourcecode, itwillissuealistoferrorsithasfoundandwillterminate.Theerrorslisted needtobecorrectedinthesourcecode(textfile)beforeitwillsuccessfully compile. Step3:InstallingtheFirmware,orProgrammingthe PICChip Connect the EPIC programming board to the computers printer port via a DB25 cable. If you are using CodeDesigner, launch the EPIC Programmer fromthemenu.TheEPICprogrammingboardmustbeconnectedtothepar allelportandswitchedonbeforeyoustartthesoftware,orelsethesoftware will issue an error message EPIC Programmer not found.Aside from the EPICWindowssoftware(epicwin.exe),whichmaybestartedmanuallyin WindowsorthroughtheCodeDesignersoftware,thereisalsoaDOSversion oftheprogramcalledepic.exe.

ChapterOne

Figure1.5 WindowsversionofEPICsoftware.

Figure1.5isapictureoftheEPICWindowsprogramscreen.UsetheOpen File option and select wink.hex from the files displayed in the dialog box. Thefilewillloadandnumberswillbedisplayedinthecodewindowontheleft. Insert the 16F84 into the socket on the programming board, and select the ProgramoptionfromtheRunmenu.Analternativetousingthemenuoption is to press the Ctrl and P buttons on the keyboard. The software is then uploadedintothePICmicrocontrollerandisreadytobeinsertedintoyourcir cuitandgotowork. Ready,Steady,Go Subsequentchapterscontainstepbystepinstructionsforinstallingthesoft wareontoyourharddriveandprogrammingyourfirstPICmicrochip. PartsList
PicBasicProcompiler PicBasiccompiler EPICProgrammer Microcontroller(16F84) $249.95 99.95 59.95 7.95

RobotIntelligence 9

6ftcable(DB25) 4.0MHzXtal (2)22pFcapacitors

6.95 2.50 0.10each

AvailablefromImagesSIInc.(seeSuppliersatendofbook). AdditionalcomponentsarerequiredinChap.6:
(1)Solderlessbreadboard (1)0.1Fcapacitor (8)RedLEDs (8)470 resistors* (1)4.7k resistor (1)Voltageregulator(7805) (2)FourpositionPCmountedswitches (1)9Vbatteryclip RadioShackPN#276175 RadioShackPN#2721069 RadioShackPN#276208 RadioShackPN#2701115 RadioShackPN#2711126 RadioShackPN#2761770 RadioShackPN#2751301 RadioShackPN#270325

Available from RadioShack, Images SI Inc., Jameco Electronics, and JDR Microdevices(seeSuppliers).

*Theseresistorsarealsoavailablein16pindippackage.

Thispageintentionallyleftblank.

Chapter

2
InstallingtheCompiler
To compile your PicBasic programs (text files) into something that can be uploadedintothePICmicrocontrollersandrun, youneedtofirstrunthepro gramtextfilethroughacompiler. Sothefirststepistoloadthecompilersoft ware onto your computers hard drive. The following are instructions for installingthePicBasiccompiler. AsectiononinstallingthePicBasicProcom pilerfollowstheseinstructions. InstallingthePicBasicCompilerSoftware Thefirstthingyouneedtodoistocreateasubdirectoryonyourcomputers hard drive for the PicBasic compiler software. I will use Windows Explorer (Windows95, 98, ME, 2000, XP)tocreatethisdirectory. WindowsExplorercan be found in the Programs folder in Windows 95 and 98 (see Fig. 2.1). For Windows ME, 2000, and XP users, Windows Explorer can be found in the Accessoriesfolder(seeFig. 2.2). Create a subdirectory called PBC on the computers hard drive; then copy the files from the diskette into it. For the conventions in this book it is assumedthatthereadersharddriveisdriveletterC. StarttheWindowsExplorerprogram. Highlightyourcomputersharddrive (usuallytheCdrive)intheFolderswindow. NexthighlighttheFilemenu, then Newmenu, andclickontheFolderoption(seeFig. 2.3). EnterthenamePBC intheNewFoldericon(seeFig. 2.4). Placethe3.5inPicBasiccompilerdisketteintoyourcomputersfloppydrive, usuallytheAdrive. HighlighttheAdriveinWindowsExplorersFolderwin dow(seeFig. 2.5). Allthefilesonthe3.5indiskettewillbedisplayedinthe rightsidearea. Selectallthefiles, gotoEditmenuoptions, andchooseCopy (see Fig. 2.6). Next select the PBC directory on the left side of theWindows Explorerwindow. ThengobacktotheEditmenuandselectthePasteoption. All the files and subdirectories on the 3.5in diskette will be copied into the PBCdirectoryontheharddrive.
11

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

12

ChapterTwo

Figure2.1 FindingWindowsExplorerinWindows95and98.

Analternatetopastingtheselectedfilesistoselectallthefilesasbefore, copythefiles, dragtheselectedfilestothePBCdirectoryusingthemouse, and thenreleasethemousebutton(seeFig. 2.7). InstallingthePicBasicProCompiler InstallingthePicBasicProcompilerisnotthesameprocedureasoutlinedfor thePicBasiccompiler. ToinstallthePicBasicProcompiler, youmustexecutea selfextractingprogramthatdecompressesthenecessaryprogramsandfiles. It is recommended that you create a subdirectory named PBP on your com putersharddrive. StarttheWindowsExplorerprogram. Highlightyourcomputersharddrive (usuallytheCdrive)intheFolderswindow. NexthighlighttheFilemenu, then Newmenu, andclickontheFolderoption(seeFig. 2.3). EnterthenamePBP intheNewFoldericon(seeFig. 2.4). Placethe3.5inPicBasicProCompilerdisketteintoyourcomputersfloppy drive, usually the A drive. Now heres where the installation procedure changes. ForthoseusingWindows95or98, startanMSDOSPromptwindow. ClickonStart, selectPrograms, thenclickonMSDOSPrompt(seeFig. 2.8). For Windows ME, 2000, and XP users, start a Command Prompt window

Figure2.2 FindingWindowsExplorerinWindows2000andXP.

Figure2.3 Creatinganewfolder(subdirectory)oncomputersharddriveC.

Figure2.4 TypesubdirectorysnameintheNewFoldericon.

Figure2.5 SelectingtheAdrivecontainingthePicBasicprogramdiskette. 14

Figure2.6 SelectingandcopyingallfilesandsubdirectoriesonthePicBasicprogram

diskette.

Figure2.7 UsingmousetocopyallselectedfilesonthePicBasicprogramdisketteintheA

drivetothePBCdirectoryontheharddrive.
15

16

ChapterTwo

Figure2.8 StartingMSDOSPromptwindowinWindows95and98.

(equivalent to an MSDOS Prompt window). Click on All Programs, select Accessories, andthenclickonCommandPrompt(seeFig. 2.9). IneithertheCommandPromptwindoworMSDOSwindow, youwillneed to type in and use a few oldfashioned DOS commands. DOS commands are typedinonthecommandline, andthentheReturnkeyishittoexecutethe command. TheDOSinstructionsareprovidedtohelpthereaderandserveasasup plement to the installation directions provided with the software packages. TheinstructionsarenotmeantasaDOStutorial. MoreinformationonDOS commandscanbefoundinanynumberofDOSmanuals. HereisalistofDOS commandswewillbeusingandwhatactiontheyperform:
Command cd md copy xcopy path dir Action Changedirectory Makedirectory Copyfiles Copyfilesandsubdirectories Setasearchpathforexecutablefiles Directory

InstallingtheCompiler

17

Figure2.9 StartingCommandPromptwindowinWindows2000andXP.

Fromthispointon, theMSDOSPromptwindowandtheCommandPrompt window will be referred to as the DOS window. When the DOS window is opened, youwillbelocatedinasubdirectoryontheharddrive. Yourprompt maylooklikethis: C:\WINDOWS. TheDOSpromptprovidesvitalinformation. TheC: tellsusweareontheC drive. The\WINDOWStellsusweareintheWindowssubdirectory. Wewanttoworkfromtherootdirectoryofthecomputersharddrive(usual lytheCdrive). Weaccomplishthisbyusingthecd (changedirectory)command. The cd.. commandbringsoneupasinglelevelinthedirectoryhierarchy. Usingthecd\ commandbringsoneuptotherootdirectoryregardlessofhow deep(levels)onehasmovedintosubdirectories. Therootdirectoryisthetopof thedirectoryhierarchy. FromtheWindowssubdirectorytypein cd\ andhit theEnterkeytomovetotherootdirectoryoftheharddrive. Typein(enter) thefollowingcommandandhittheEnterkey.
cd\

WealreadycreatedoursubdirectoryPBPbyusingWindowsExplorerforthe PicBasicProcompiler. WewanttomoveintothePBPsubdirectory, enterthe followingcommand, andhitEnter.

18

ChapterTwo

Figure2.10 UsingDOScommandsinDOSPromptwindowtoexecutePicBasicProinstalla
tionprogram.

c:\>cdpbp

Nextplacethe3.5inPicBasicProdisketteintoyourAdrive, andtypethefol lowingattheDOSprompt:


c:\pcp>a:\pbpxxxd

Herexxx istheversionnumberofthecompileronthedisk(seeFig. 2.10). This commandcopiesandinstallsalltherequiredfilesintothePBPdirectory. With thefilessafelyloadedontoyourharddrive, removethedisketteandstoreitin asafeplace, incaseitisneededinthefuture. ThePicBasicProprogramisnowinstalled. YoumayclosetheDOSwindow andstorethe3.5indiskette.

Chapter

3
InstallingtheEPICSoftware
Installing the EPIC software from Windows is simple. To install, run the install.bat file on the 3.5in EPIC diskette. The install.bat file exe cutesthemainselfextractingprogramthatautomaticallycreatesasubdirec toryEPIConyourcomputersharddrive, thendecompressestheprogramand itssupportfiles, andcopiesthemintotheEPICsubdirectory. IfasubdirectorycalledEPICalreadyexistsonyourharddrive, whenyou runtheinstall.bat file, youwillreceiveanerrormessage. IfyouarestillinthesameDOSsessionasinlastchapterandwanttocon tinuetouseDOStoinstalltheEPICsoftware, skipdowntotheInstallingthe EPICSoftware, DOSVersion section. ForthosewhowishtouseWindowsto installthissoftware, continuetoread. InstallingtheEPICSoftwareinWindows From Windows click on the Start button, then Run (see Fig. 3.1). Place the EPIC programming diskette into the A drive. When the Run menu window opens, selectBrowse. FromtheBrowsewindowselecttheAdrive. Thisaction will list the files on theA drive. Select the install.bat file and click the Openbutton(seeFig. 3.2). This action brings you back to the Run window. The install.bat file shouldbelistedinthewindow. SeeFig. 3.3. ClickontheOKbutton. Thisaction automaticallyopensaDOSwindowandstartstheexecutableprogramonthe EPICdiskette. Theexecutableprogramcreatesanewsubdirectoryonthecom putersharddrivecalledEPIC. Itdecompressesandcopiesallthenecessary filesintotheEPICsubdirectory, asshowninFig. 3.4. IfyoujustinstalledtheEPICprogramusingWindows, skipoverthenext section, InstallingtheEPICSoftware, DOSVersion andcontinuereadingat theSupplementalApplicationsDirectory section.

19

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

Figure3.1 SelectingRunoptiononWindowsstartmenu.

Figure3.2 Selectinginstall.bat fileonEPICdiskette. 20

Figure3.3 HittingOKon install.bat tobeginexecution.

Figure3.4 SelfextractingEPICprogramrunninginMSDOSwindow.

22

ChapterThree

InstallingtheEPICSoftware,DOSVersion IfyouarestilloperatinginthesameDOSsessionasinChap. 2, moveback intotherootdirectory, andenterattheprompt


c:\>pbpcd..

IfyouareenteringanewDOSwindow, thepromptmayappearalittledif ferent, butthecommandisthesame.


c:\>windowscd/

FromtherootdirectoryoftheCdrivewewillrunthe install.bat pro gramontheEPIC3.5indiskette. Theselfextractingfilecreatesitselfasub directorycalledEPIC. Placethe3.5inEPICdisketteintothefloppydrive. At theDOSpromptenter


c:\>a:

This places the command prompt into the A drive; the command prompt shouldlooklikethis:
a:\>

Nowruntheinstall.bat filebyenteringthefollowingcommand:
a:\>install.bat

This starts the selfextracting file that creates the EPIC subdirectory and installsalltherequiredfilesintothesubdirectory. With the program and files installed onto your hard drive, remove the disketteandstoreitinasafeplace, incaseitisneededinthefuture. SupplementalApplicationsDirectory Itwouldbeagoodideaatthistimeifwecreatedanothersubdirectorywhere wecanstoreallourPicBasicapplicationprograms. ThiswillkeepthePBC(or PBP) and EPIC directories clean, neat, and uncluttered with programs and programrevisions. FromWindowsExplorercreateanApplicssubdirectoryonyourcomputers harddrive.

Chapter

4
CodeDesigner
In this chapter we will set up and work with the CodeDesigner software. CodeDesignerisaWindowsintegrateddevelopmentenvironment(IDE)inter face for the PIC series of microcontrollers. This IDE interface allows one to writecode, compilethecode, andthenprogramthecodeintoaPICmicrocon trollerwhilestayinginthesameWindowsenvironment. ThecompilingofcodewithinCodeDesignerstillrequirestheuseofoneof thePicBasiccompilers. ProgrammingthecompiledcodeintoaPICmicrocon troller requires the EPIC software and hardware. CodeDesigner integrates these software and hardware packages so that they can operate within its Windowsenvironment. CodeDesignerhasmanyusefulfeaturesthathelpyouwritecodeandthat makeitfarsuperiortousingasimpletexteditor. CodeDesignerFeatures

AutoCodeCompletion. CodeDesigner makes writing code much easier with smartpopuplistboxesthatcanautomaticallyfillinstatementsandparam etersforyou. Multidocumentsupport. Line error highlighting. Compile your PicBasic project and CodeDesigner willreaderrordataandhighlighterrorlines. QuickSyntaxHelp. TheQuickSyntaxHelpfeaturedisplaysstatementsyntax whenyoutypeinavalidPicBasicstatement. Statement description. Statement descriptions are displayed in the status barwhenyoutypeinavalidPicBasicstatement. StatementHelp. SimplypositionyourcursoroveraPicBasicstatementand getstatementspecifichelp.
23

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

24

ChapterFour

Labellistbox. Thelabellistboxdisplaysthecurrentlabelandallowsyouto selectalabelfromthelisttojumpto. ColoredPicBasicsyntax. Thissetscolorsforreservedwords, strings, num bers, comments, defines, etc. Colored PicBasic syntax makes for easy code reading. Bookmarks. Never lose your place again. CodeDesigner allows you to set bookmarks. Multipleundo/redoactions. Ifyoudidntwanttodeletethatlastline, itsno problem. SimplyclickontheUndobutton. Multipleviews. Multipleviewsofyoursourcecodeallowyoutoeasilyedit yourcode. Printsourcecode. Draganddroptext. Row/columnbasedInsert, Delete, andCopy. Searchandreplace. Compileandlaunchdeviceprogrammer.

One feature I like is that each typed line of code is colorcoded, making it easiertospoterrorsandreadthroughyourcode. WhenyoupurchaseeitherthePicBasicorPicBasicProcompilers, itispack agedwithanadditionaldiskettethatcontainsafreeversionofCodeDesigner calledCodeDesignerLite. TheLiteversionallowsyoutowriteprogramsupto 150linesandopenupthreesourcefilesatonceforeasycopyandpaste. Ifyou wouldliketotryCodeDesignerwithoutpurchasingacompiler, CodeDesigner LiteisfreelydownloadablefromtheInternet(seePartsListatendofchapter). Theideais, ifyoulikethefreeCodeDesignersoftware, youcanthenupgrade tothefullfeaturedCodeDesigner. ThestandardversionofCodeDesignercosts $75.00andremovestherestrictionsimposedintheLiteversion. Thisstandard versionallowsyoutowriteprogramswithanunlimitedamountofcodelines andtoopenanunlimitedamountofsourcefiles. Ofcourse, unlimited means withrespecttothelimitsofyourcomputerscapabilities. IfforanyreasonsomeonedoesnotwishtousetheCodeDesignersoftware, theproceduresforwritingcodeandcompilingandprogrammingaPICmicro chipmanuallyfromaDOSenvironmentarecoveredinChap. 5. CodeDesignerincreasesproductivityandtheeasewithwhichyoucanwrite, debug, andloadPicBasicprogramsintothemicrocontroller. Ifthereisaprob lem(moreoftenthannot), debuggingthecodeandrecompilingaremucheas ier and faster when you are using CodeDesigner. When the program is completelydebugged, itcanbeuploadedintothePICmicrocontrollerviathe EPICsoftwareandprogrammingboard. Atthispointthemicrocontrollerand circuitaretested. Iftheyfunctionproperly, Imfinished; ifnot, Ibeginrewrit ingtheprogramorredesigningtheelectronics.

CodeDesigner

25

SoftwareInstallation The CodeDesigner software loads as most standardWindows software does. Loadthesoftwareonyourcomputersharddriveaccordingtotheinstructions givenwiththesoftware. WhenCodeDesignerinstalls, itcreatesasubdirectoryintheProgramFiles directory. It places a CodeDesigner shortcut on the Start, Program menu in Windows. SettingCodeDesignerOptions InorderforCodeDesignertocompilecodeandprogramtheresultingcodeinto PIC microcontrollers, we need to configure the default locations where CodeDesignerlooksforitssupportprograms. Wesetupthedefaultlocations byenteringthesoftwarepathswhereCodeDesignerstoresprograms, looksfor thePicBasiccompilerandwheretofindtheEPICprogram. StarttheCodeDesignersoftware(seeFig. 4.1); theevaluationcopyopenswith thisversionofthewindow. Thenextwindowisthestandardopeningscreento theCodeDesignersoftware(seeFig. 4.2). Tobeginsettingtheoptions, clickon theCompilemenuoptionandthenonCompilerOptions(seeFig. 4.3).

Figure4.1 CodeDesignerLiteversionstartupscreen.

26

ChapterFour

Figure4.2 ProgramwritteninCodeDesignerreadyforcompilingandprogramming.

Figure4.3 ErrorcreatedwhenWindowscannotidentifyEPICProgrammerattachedtoprint

erport.

CodeDesigner

27

Figure4.4 Schematicfor wink program.

TheCompilerOptionswindowopens(seeFig. 4.4). Inthetoptextfield, use thepulldownmenutoselectwhichcompileryouareusing, thePicBasicPro orPicBasic. InFig. 4.4thePicBasicProcompilerischosen. In the second text field, you select the compilers pathname. The compiler pathandname(pbpw.exe)ischosenforthePicBasicProcompiler, inthesub directoryofC:\PBP. InthethirdtextfieldwechoosewheretheCodeDesignersoftwarelooksto load and save our source code files. Hit the Browse button next to the text field. Thisopensabrowserwindow(seeFig. 4.5); selecttheApplicssubdirec toryontheharddriveandclickonOK. The Default Source Code Directory text field now contains the path C:\Applics subdirectory (see Fig. 4.6). Click the OK button to close the CompilerOptionswindow. Now we need to set the Programmer Options. Click on the Programmer, Programmer Options on the top menu (see Fig. 4.7). This opens the ProgrammerOptionswindow(seeFig. 4.8). ClickontheBrowsebuttonnextto the Programmer Pathname text field. A browser window opens; select the epicwin.exe programintheEPICsubdirectoryonyourcomputersharddri ve (see Fig. 4.9). Click Open, and this brings you back to the Programmer Options window. The new path you select should be in the Programmer Pathnametextfield(seeFig. 4.10). ClickOKtosetthisoption.

Figure4.5 Completecircuitbuiltonsolderlessbreadboard.

Figure4.6 Selectingcompiler(CodeDesigner). 28

Figure4.7 OpeningProgrammeroptions(CodeDesigner).

Figure4.8 Programmeroptionswindow(CodeDesigner).

Figure4.9 Selecting epicwin.exe ProgrammerinEPICsubdirectory.

Figure4.10 HittingOKtoconfirmselection. 30

CodeDesigner

31

WiththeCodeDesigneroptionsset, wearereadytowriteourfirstprogram. FirstProgram StartCodeDesignerandenterthefollowingcodeforthePicBasiccompiler.


FirstPicBasicprogramtowinktwoLEDsconnectedtoportb.
loop:high0 TurnonLEDconnectedtopinrb0 low1 TurnoffLEDconnectedtopinrb1 pause500 Delayfor.5second low0 TurnoffLEDconnectedtopinrb0 high1 TurnonLEDconnectedtopinrb1 pause500 Delayfor.5second gotoloop Gobacktoloopandblink&winkLEDsforever end

Thenextprogramisidenticalinfunction(notcode)tothePicBasicprogram above. StartCodeDesignerandenterthefollowingcode(seeFig. 4.11):


Winkprogram
BlinksandwinkstwoLEDsconnectedtoportb

Figure4.11 PicBasicProprogramwritteninCodeDesigner.

32

ChapterFour loop: highportb.0 lowportb.1 pause500 lowportb.0 highportb.1 pause500 gotoloop

TurnonLEDconnectedtorb0 TurnoffLEDconnectedtorb1 Wait1/2second TurnoffLEDconnectedtorb0 TurnonLEDconnectedtorb1 Wait1/2second Loopbackrepeatcycleblink&winkforever

CodeDesignerdefaultstowritingcodeforthePIC16F84microcontroller. This is the microcontroller I recommend to start with. To change the microcon troller, simply pull down the device menu and select the appropriate micro controller(seeFig. 4.12). WhenCodeDesignerattemptstocompileaprogramfromtheWindowsenvi ronment, itautomaticallyopensaDOSPromptwindow, compilestheprogram, andthenendstheDOSsession. TocompiletheprogramusingCodeDesigner, eitherselectcompileunderthe CompilemenuorhitF5. CodeDesignerautomaticallystartsthePicBasicPro compiler(orPicBasiccompiler)tocompiletheprogram. Beforeyouattemptto compile a program, make sure you have set up Compiler Options under the Compilemenu.

Figure4.12 Pulldownmenulocationforselectingmicrocontroller.

CodeDesigner

33

Figure4.13 ErrormessagegeneratedwhenCodeDesignercannotfindProgrammer.

Oncetheprogramiscompiled, wecangotothenextstepofloadingthepro gramintoaPICmicrocontrollerchip. ConnecttheEPICprogrammingboardtotheprinterport. Ifyourcomputer hasonlyoneprinterport, disconnecttheprinter, ifoneisconnected, andattach theEPICprogrammingboard, usinga6ftDB25cable. When you connect the EPIC programming board to the computer, there shouldnotbeanymicrocontrollerinstalledontotheboard. Ifyouhaveanac adapterfortheEPICprogrammerboard, plugitintotheboard. Ifnot, attach twofresh9Vbatteries. Connectthebatteryon jumpertoapplypower. The programmingboardmustbeconnectedtotheprinterportwithpowerapplied totheprogrammingboardbeforetheEPICprogrammingsoftwareisstarted. Ifitisnot, thesoftwarewillnotseetheprogrammingboardconnectedtothe printerportandwillgivetheerrormessageEPICProgrammerNotFound (seeFig. 4.13). TheEPICProgrammingBoardSoftware To program the 16F84 microcontroller from within CodeDesigner, select the Launch Programmer menu item from the Programmer menu, or hit F6. CodeDesignerautomaticallystartstheepicwin.exe Windowssoftware.

34

ChapterFour

Figure4.14 Settingconfigurationswitchesinepicwin.exe program.

WiththeEPICWindowssoftwarestarted, settheconfigurationswitchesone byoneundertheOptionsmenuitem(seeFig. 4.14). Device: Setsthedevicetype. Setitfor16F84(default). MemorySize(K): Setsmemorysize. Choose1. OSC: Setsoscillatortype. ChooseXTforcrystal. WatchdogTimer: ChooseOn. CodeProtect: ChooseOff. PowerUpTimerEnable: ChooseOn. Aftertheconfigurationswitchesareset, insertthePIC16F84microcontroller intotheopensocketontheEPICprogrammingboard. Ifyoureceivedanerror message EPIC Programmer Not Found when CodeDesigner started the EPIC Windows program (see Fig. 4.13), you have the option of either trou bleshootingtheproblemorusingtheEPICDOSprogram. Forinstructionson usingtheEPICsoftware, DOSversion, seeChap. 5. TheschematicofthecircuitneededtotestthePICmicroisgiveninChap. 6. If you have successfully written, compiled, and uploaded the code into the PICmicro chip using CodeDesigner, then you can skip the DOS material in Chap. 5andpickupatTestingthePICMicrocontroller inChap. 6.

CodeDesigner

35

PartsList
CodeDesignerLite Free

DownloadfromInternetat: www.imagesco.com/catalog/pic/codedesigner.html.
CodeDesignerStandard $75.00

AvailablefromImagesSIInc. (seeSuppliersatendofbook).

Thispageintentionallyleftblank.

Chapter

5
UsingDOStoCode, Compile,andProgram
In Chap. 4 we compiled and programmed our microcontroller, using the CodeDesignerprogram. Ifforsomereasonyoudonotwishtouseorcannotuse CodeDesigner Lite, this chapter will instruct you in how to perform all the functionsforwritingcode, compilingthecode, andprogrammingthecodeina PICmicrochipfromDOSoraDOSPromptwindow. WhenyoustartanewDOSsession, usethepathcommand(seeFig. 5.1), so thatyouwillnothavetocopyandswapfilesbackandforthacrossdirectories. Ifyouhavecreatedthedirectorynamesassuggestedinthisbook, youcanuse thefollowingcommand. ForPicBasicusersthecommandis
path\;c:\pbc;c:\epic;c:\windows\command;

ForPicBasicProusers, thecommandis
path\;c:\pbp;c:\epic;c:\windows\command;

Nowwecanbeginbyusingastandardwordprocessorortexteditortowrite thePicBasicprograminDOS. WindowsuserscanusetheNotepadprogram. DOSlevel users can use the Edit program. In DOS we will work from and storeourprogram(s)inthesubdirectorywecreatedearlier, calledApplics. MoveintotheApplicssubdirectory. Usethecd (changedirectory)command. EnterthisattheDOSprompt(seeFig. 5.1):
c:\>cdapplics

Onceinthisdirectory, thepromptchangesto
c:\applics>

37

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

38

ChapterFive

Figure5.1 EnteringDOScommandsforpath, changingdirectories, andstartingtheEditprogram.

InthisexampleIwillbeusingthefreeEditprogrampackagewithWindows towritetheprogram. StartEditbytypingEditatthecommandprompt(see Fig. 5.1).


c:\applics>edit

ThisstartstheEditprogram(seeFig. 5.2). Enterthisprograminyourword processorexactlyasitiswritten:


1stPicBasicprogram
WinktwoLEDsconnectedtoportb.
loop:high0 TurnonLEDconnectedtopinrb0 low1 TurnoffLEDconnectedtopinrb1 pause500 Delayfor.5second low0 TurnoffLEDconnectedtopinrb0 high1 TurnonLEDconnectedtopinrb1 pause500 Delayfor.5second gotoloop Gobacktoloopandblink&winkLEDsforever end

SeeFig. 5.3. SavethetextfileintheApplicsdirectory. UsetheSavefunc tionundertheFilemenu. Namethefilewink.bas (seeFig. 5.4). Ifbyacci dentyousavedthefileas wink.txt, dontgetdiscouraged. Youcandoa

UsingDOS toCode,Compile,andProgram

39

Figure5.2 StartscreenofEditprogram.

Save As from the Edit program (under File menu) and rename the file

wink.bas.
ForPicBasicProusers, enterthefollowingtextinyourwordprocessorand savethefileaswink.bas.
1stPicBasicProprogram
WinkstwoLEDsconnectedtoportb
loop:
highportb.0 TurnonLEDconnectedtorb0
lowportb.1 TurnoffLEDconnectedtorb1
pause500 Wait1/2second
lowportb.0 TurnoffLEDconnectedtorb0
highportb.1 TurnonLEDconnectedtorb1
pause500 Wait1/2second
gotoloop Loopbackrepeatcycleblink&winkforever

Compile The PicBasic compiler (or PicBasic Pro compiler) may be run from DOS or fromaDOSPromptwindowwithinWindows.

40

ChapterFive

Figure5.3 Enteringwink.bas program.

Figure5.4 Savingwink.bas program.

UsingDOS toCode,Compile,andProgram

41

Figure5.5 EnteringDOScommandtorunPicBasiccompilerprogramonthewink.bas program

forthe16F84microcontroller.

WewillrunthePicBasiccompilerfromtheApplicsdirectory, typethecom mand pbc p16f84 wink.bas attheDOSprompt, andhittheEnterkey (seeFig. 5.5).
c:\applics>pbcp16f84wink.bas

(ForPicBasicProthecommandisc:/applics>pbpp16f84wink.bas.) Thecompilerdisplaysaninitializationcopyrightmessageandbeginsprocess ing the Basic source code (see Fig. 5.6). If the Basic source code is without errors(andwhyshouldntitbe?), itwillcreatetwoadditionalfiles. Ifthecom pilerfindsanyerrors, alistoferrorswiththeirlinenumberswillbedisplayed. Usethelinenumbersintheerrormessagetolocatethelinenumber(s)inthe .bas text file where the error(s) occurred. The errors need to be corrected beforethecompilercancompilethesourcecodecorrectly. Themostcommon errorsarewithBasiclanguagesyntaxandusage. Youcanlookatthefilesbyusingthe dir directorycommand. Type dir at thecommandprompt
c:\applics>dir

andhitEnter(seeFig. 5.7).

42

ChapterFive

Figure5.6 TypicalcopyrightnoticeandnoticeprovidedbythePicBasiccompilerwhenitisrun successfully.

Figure5.7 ExecutingDOSdir (directory)commandtoseethetwoadditionalfiles(.asm and

.hex)createdbythePicBasiccompiler.

UsingDOS toCode,Compile,andProgram

43

The dir commanddisplaysallthefilesandsubdirectorieswithinthesub directorywhereitisissued. InFig. 5.7wecanseethetwoadditionalfilesthat thecompilercreated. Onefileisthewink.asm fileandistheassemblersource code file that automatically initiated the macroassembler to compile the assemblycodetomachinelanguagehexadecimalcode. Thehexcodefileisthe secondfilecreated, calledwink.hex. ProgrammingthePICChip To program the PIC chip, we must connect the EPIC programming carrier board(seeFig. 5.8), tothecomputer. TheEPICboardconnectstotheprinter port. Theprinterportisalsocalledtheparallelport. Eithernamemaybeused; they are both correct. A computer may contain up to four parallel (printer) ports. Eachportisassignedanumber, from1through4. Thecomputerlists theseportsasLPT1toLPT4. Ifyourcomputerhasonlyoneprinterport, disconnecttheprinter, ifoneis connected, andattachtheEPICprogrammingboardusinga6ftDB25cable. Insomecasesitmaybenecessarytotemporarilyremovetheprinterdriver. Figure5.9showsatypicalwindowtodisableanHPprinter. When you are connecting the programming board to the computer, make suretherearenoPICmicrocontrollersinstalledontotheboard. Ifyouhavean ac adapter for the EPIC Programmer board, plug it into the board. If not, attachtwofresh9Vbatteries. Connectthebatteryon jumpertoapplypow

Figure5.8 EPICprogrammingboardandsoftware.

44

ChapterFive

Figure5.9 Messageboxwindowusedtotemporarilycloseprinterdrivertoprovidebetteraccess

toprinterportforEPICprogrammer.

er. Theprogrammingboardmustbeconnectedtotheprinterportwithpower applied to the programming board before the software is started. If not, the softwarewillnotseetheprogrammingboardconnectedtotheprinterportand willgivetheerrormessageEPICProgrammerNotFound. Whenpowerisappliedanditisconnectedtotheprinterport, theLEDon theEPICProgrammerboardmaybeonoroffatthispoint. DonotinsertaPIC microcontrollerintotheprogrammingboardsocketuntiltheEPICprogram mingsoftwareisrunning. TheEPICProgrammingBoardSoftware There are two versions of the EPIC software: epic.exe for DOS and epicwin.exe for Windows. The Windows software is 32bit. It may be usedwithWindows95, 98, NT, andXP, butnot 3.X. Ithasbeenmyexperi encethatWindows95and98printerdriversmanytimesliketoretaincon troloftheprinter(LPT1)port. Ifthisisthecasewithyourcomputer, the WindowsEPICprogrammaynotfunctionproperly, andyoumaybeforced to use the DOSlevel program. If you receive an error message EPIC ProgrammerNotFound whenyoustarttheEPICWindowsprogram, you

UsingDOS toCode,Compile,andProgram

45

have the option of either troubleshooting the problem or using the EPIC DOSprogram.
UsingEPICDOSversion

IfusingWindows95orhigher, youcouldeitheropenaMSDOSPromptwin doworrestartthecomputerintheDOSmode. Windows3.XXusersendthe Windowssession.


Continuingwiththewink.bas program

AssumewearestillinthesameDOSsessionandhavejustrunthePBCcom pileronthe wink.bas program. WearestillintheApplicsdirectory. Atthe DOS prompt, type EPIC and hit Enter to run the DOS version of the EPIC software(seeFig. 5.10). IfyouareoperatingoutofaDOSwindow, youmaygetadeviceconflictmes sagebox, showninFig. 5.11. WewantMSDOStocontroltheLPTportsothe EPIC programming software will work. Select the MSDOS Prompt and hit theOKbutton. EPICsopeningscreenisshowninFig. 5.12. Usethemousetoclickonthe Openbutton, orpressALTOonyourkeyboard. Selectthewink.hex file(see Fig. 5.13). Whenthe.hex fileloads, youwillseealistofnumbersinthewin

Figure5.10 EnteringDOSEPICcommandtostartprogram.

Figure 5.11 Possible Device Conflict error message when DOS and Windows both try to use

printerport. SelectDOSandhitOKbutton.

Figure5.12 OpeningscreenoftheEPICprogrammingsoftware. HitOpenFilebutton. 46

UsingDOS toCode,Compile,andProgram

47

Figure5.13 Selectwink.hex inOpenFilemessageboxandhittheOKbutton.

dowontheleft(seeFig. 5.14). Thisisthemachinecodeofyourprogram. On therighthandsideofthescreenareconfigurationswitchesthatweneedto checkbeforeweprogramthePICchip. Letsgothroughtheconfigurationswitchesoncemore. Device: Setsthedevicetype. Setitfor8X. MemorySize(K): Setsmemorysize. Choose1. OSC: Setsoscillatortype. ChooseXTforcrystal. WatchdogTimer: ChooseOn. CodeProtect: ChooseOff. PowerUpTimerEnable: ChooseOn. Aftertheconfigurationswitchesareset, insertthePIC16F84microcontroller intothesocket. ClickonProgramorpressALTPonthekeyboardtobeginpro gramming. TheEPICprogramfirstlooksatthemicrocontrollerchiptoseeifit isblank. Ifthechipisblank, theEPICprograminstallsyourprogramintothe microcontroller. Ifthemicrocontrollerisnotblank, youaregiventheoptionsto canceltheoperationoroverwritetheexistingprogramwiththenewprogram. IfthereisanexistingprograminthePICchipsmemory, writeoverit.

48

ChapterFive

Figure5.14 HexadecimalnumbersshowinginEPICwindowarethemachinelanguageversionof thewink.bas programthatisuploaded(programmed)intothe16F84microcontroller.

IhavenoticedthatwhenIplaceabrandnewPICmicro16F84chipintothe EPIC compiler to program, EPIC always reports existing code on the chip. I dontknowifMicrochipTechnologyInc. loadsnumbersintothechipsmemory fortestingpurposes. DontletitthrowyouthePICmicrochipisnew. The machine language code lines are highlighted as the EPIC software uploads the program into the PICmicro chip. When it is finished, the micro controllerisprogrammedandreadytorun. Youcanverifytheprogramifyou likebyhitting(orhighlighting)theVerifybutton. Thisinitiatesacomparison of the program held in memory to the program stored in the PIC microcon troller.

Chapter

6
TestingthePICMicrocontroller
ThePICMicrocontroller ThisiswherewewillbuildthetestingcircuitforthePICmicrochipwepro grammed. ThecomponentsneededforthecircuitwerelistedinChap. 1; ifyou purchasedthecomponents, youcanquicklysetupthetestcircuit. Ifnot, the componentsarelistedagainattheendofthischapter; youwillneedthecom ponentstobuildthecircuit.
Thesolderlessbreadboard

For those of us who have not dabbled in electronics very much, I want to describethesolderlessbreadboard(seeFig. 6.1)indetail. Asthenameimplies, you can breadboard (assemble and connect) electronic components onto it withoutsolder. Thebreadboardisreusable; youcanchange, modify, orremove circuitrycomponentsfromthebreadboardatanytime. Thismakesiteasyto correctanywiringerrors. Thesolderlessbreadboardisanimportantitemfor constructingandtestingcircuitsoutlinedinthisbook. Thestyleofbreadboardontheleftisavailablefromanynumberofsources includingRadioShack. Thebreadboardontherightissimilarbutprovidesa largerprototypingarea. Ifyouwishtomakeanycircuitpermanent, youcantransferthecomponents onto a standard printedcircuit board and solder it together with the fore knowledgethatthecircuitfunctionsproperly. Apartialcutawayofthetopsurfaceshowssomeoftheinternalstructureof a board (Fig. 6.2). The holes on the board are plugs. When a wire or pin is insertedintothehole, itmakesintimatecontactwiththemetalconnectorstrip inside. Theholesareproperlydistancedsothatintegratedcircuitsandmany othercomponentscanbepluggedin. Youconnectcomponentsontheboardby
49

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

50

ChapterSix

Figure6.1 Topviewofsolderlessbreadboards.

Figure6.2 Topviewofsolderlessbreadboardswithapartialcutawayshowingunderneathconductivecontactstrips.

using22gauge(solidorstranded)wire. Iprefertousestrandedwirebecause ithasgreaterflexibility; otherpeopleprefersolidwirebecauseitsstifferand easiertopushintothebreadboardhole. Thecompleteinternalwiringstructureofthesolderlessboardsisshownin Fig. 6.3. ThesolderlessbreadboardontheleftshowstheXandYrowsthatare typicallyusedtosupplypower(Vcc)andgroundconnectionstothecircuit. The columnsbelowtheXrowandabovetheYrowareusedformountingcompo nents. Thesolderlessbreadboardontherighthasdoublerowslocatedatthe topandbottom. TheseareusedtosupplybothVccandgroundoneachsideof thebreadboard.
Threeschematics,onecircuit

Figures6.4, 6.5, and6.6areidenticalschematicsofourtestcircuit. The16F84 PICmicrocontrollerintheschematicisthemicrocontrolleryouprogrammed ineitherChap. 4or5. Idrewthreeschematicstohelporientexperimenters whomaynotbefamiliarwithstandardelectricaldrawings. Figure6.4shows

TestingthePIC Microcontroller

51

Figure6.3 Topviewofsolderlessbreadboardsdetailingconductivestrips.

+5V

1
RA2 RA1 RA0 OSC1/CLKIN OSC2/CLKOUT Vdd RB7 RB6 RB5 RB4

18
RA3 RA4IT0CKI MCLR Vss RB0/INT RB1 RB2 RB3

4.7k

2 3 4 5 6 7 8

17 16

4MHz 22pF 22pF

15 14 13 12 11 10

PIC16F84

.1uF

470
+

470
+

Xtal Electrical Symbol

LED

Resistor

Capacitor

All resistors 1/4 watt Component Appearance


4.0 MHz +

Figure6.4 Isometricschematicoftestcircuitforwink.bas program.

howthePIC16F84microcontrollerandcomponentsappear. Thereisalegend atthebottomthatshowstheelectricalsymbolandthetypicalappearanceof the component. Figure 6.5 is a line drawing showing how the components appearmountedononeofthesolderlessbreadboards. ThewritingonFig. 6.5 pointsouteachelectricalcomponent.

52

ChapterSix

X 1 A B C D E 5 10 15 20 Xtal 22 pF

PIC16F84
7805 Volt Reg. +Vcc Gnd .1uF 470 4.7k Ground LEDs F G H I J Y 1 5 10 15

+ + Red LED Side View 20 Ground +

Figure6.5 Isometricdrawingshowingtestcircuitconstructedonsolderlessbreadboard.

Figure6.6 Schematicoftestcircuitforwink.bas program.

Ifyouexaminetheplacementofthecomponentsmountedonthesolderless breadboardwithitsinternalelectricalwiring(Figs. 6.2and6.3), youcansee howthecomponentsconnecttooneanotherandproduceacircuit. Figure 6.6 is the same schematic drawn as a standard electrical drawing withthepinnumbersgroupedandorientedtofunction. Fortheremainderof thebook, standardelectricaldrawingswillbeused. Theschematicshowshowminimalarethecomponentsneededtogetyour microcontrollerupandrunning. Primarilyyouneedapullupresistoronpin

TestingthePIC Microcontroller

53

Figure6.7 Photographof wink.bas circuitconstructedonsolderlessbreadboard.

4(MCLR), a4MHzcrystalwithtwo(22pF)capacitorsanda5Vpowersup ply. Note: The4MHzcrystalandtwo(22pF)capacitorsmakeupanoscillator thatisrequiredbythemicrocontroller. Thesethreepartsmaybesubstituted witha4MHzceramicresonator. ThetwoLEDsandthetworesistorsconnectedinserieswitheachLEDare theoutput. Itallowsustoseethatthemicrocontrollerandprogramarefunc tioningproperly. Assemblethecomponentsasshownintheschematic(Fig. 6.5)ontothesol derlessbreadboard. Whenyouhavefinished, yourworkshouldappearasin Fig. 6.7. Although the specifications sheet on the 16F84 states the microcontroller willoperateonvoltagesfrom2to6V, Iprovidedaregulated5Vpowersupply forthecircuit. Theregulatedpowersupplyconsistsofa7805voltageregula torandtwofiltercapacitors.
Wink

Apply power to the circuit. The LEDs connected to the chip will alternately turnonandoff. Wink, , wink. Nowyouknowhoweasyitistoprogramthese microcontrollersandgetthemupandrunning.

54

ChapterSix

Troubleshootingthecircuit

Thereisnottoomuchthatcangowronghere. IftheLEDsdonotlight, the firstthingtocheckistheorientationoftheLEDs. Iftheyareputinbackward, theywillnotlight. Nextcheckyourgroundwires. Seethejumperwiresontherighthandside ofthesolderlessbreadboard. Theybringthegrounduptothetwo22pFcapac itors. Check all your connections. Look back at Figs. 6.2 and 6.3 to see how the underlying conductive strips relate to the push in terminals on top of the board. PICExperimentersBoardandLCDDisplay Therearetwooptionaltoolsyoumaywantifyouplanonexperimentingwith the PIC16F84 and microcontrollers in general. They are the PIC ExperimentersBoardandLCDdisplay. WewilllookattheLCDdisplayfirst because a similar LCD display is incorporated into the PIC Experimenters BoardandwhatwesayaboutthestandaloneLCDdisplayisalsotrueforthe PICExperimentersBoardLCDdisplay. OnethingPICmicrocontrollerslackissometypeofdisplay. Withadisplay, thechipcouldshowushowaprogramisrunningorwhatitisdetecting. In addition a display would allow the microcontroller to output textual and numericmessagestotheuser. TothisendthereareserialLCDdisplaysonthemarketthatonlyrequirea single microcontrollers I/O lines (pin) and a circuit ground. The particular LCDdisplayweareusingreceivesstandardserialdata(RS232)at300, 1200, 2400, and9600baud(Bd)(invertedortrue). TheLCDmoduleisatwoline, 16 charactervisibledisplay. Thefulldisplayisactuallytwolinesby40characters, but the additional 24 characters per line are off screen. We can use the PicBasicandPicBasicProserout commandtocommunicateandoutputmes sagestotheLCDdisplay. The PicBasic and PicBasic Pro compilers can send and receive serial information at 300, 1200, 2400, and 9600 Bd. Data are sent as 8 bits, no parity, and 1 stop bit. The serial mode may be set to be true or inverted. ThesedatamatchtheserialcommunicationprotocolsrequiredoftheLCD display. TheLCDmodulehasthreewires: 5V(red), GND(blackorbrown), anda serialinline(white). Thebaudratemaybesetto300, 1200, 2400, or9600by usingasetofjumpers(J1, J2, andJ3)onthebackoftheLCDdisplay. This first program prints the messageHelloWorld. The cursor (printing position)automaticallymovesfromlefttoright. TheschematicisshowninFig. 6.8, andtheLCDdisplayisshowninFig. 6.9.
PicBasicprogram
LCDtest
pause1000

Wait1secondforLCDtoinitialize

TestingthePIC Microcontroller

55

+5V

Serial Line PIC Microcontroller Ground

Figure6.8 SchematicofLCDdisplaytestcircuit.

Figure6.9 PhotographofLCDdisplayHelloWorld.

start: serout1,t1200,(254,1) Clearscreen pause40 serout1,t1200,(HelloWorld) Printmessage pause400 gotostart end

IkeptthisprogramsmalltoshowhoweasyitistoprintamessageontheLCD display. HereisthesameprogramwrittenforthePicBasicProcompiler.


PicBasicProprogram
LCDtest
pause1000 Wait1secondforLCDtoinitialize
start:
seroutportb.1,1,[254,1] Clearscreen
pause40
seroutportb.1,1,[HelloWorld]Printmessage
pause400
gotostart
end

56

ChapterSix

Noticethat, inline5oftheprogram(s), serout1,t1200,(254,1) isacom mand. TheLCDmodulehaseightcommoncommands. Allcommandsarepre fixedwiththedecimalnumber254. TheLCDmodulewillinterpretanynumber followinga254prefixasaninstruction. Insteadofdecimalnumbers, youmay also use hexadecimal numbers, if you wish. So in hexadecimal the command becomes serout 1, t1200, ($fe, $01). Thefollowingisalistofafew commoncommands. Rememberallcommandsareprefixedwitha254($fe).
Code 1 2 16 20 24 28 192 Instruction Clearscreen. Homeposition(movecursortopleftofdisplay). Movecursoronecharacterpositionleft. Movecursoronecharacterpositionright. Scrolldisplayonecharacterpositionleft. Scrolldisplayonecharacterpositionright. Movecursortofirstpositiononsecondline.

PICExperimentersBoard

ThePICExperimentersBoardisaprefabricateddevelopingboardforproto typingcircuits(seeFig. 6.10). TheboardallowseasyaccesstoalltheI/Opins, portA(RA0RA4), andportB(RB0RB7)ofthe16F84. Theboardmayalsobe used with the 16F8X, 16C55X, 16C62X, 16C7X, and 16C8X family of 18pin PICmicrocontrollers. Its168pointsolderlessconnectionareaallowsforquickandeasyaccessto allportA(RA0RA4)andportB(RB0RB7)I/Olines. Thereisanopen18pin socketforinsertingthemicrocontrolleryouaredeveloping. Theboardincludes anintegrated16 2serialLCDdisplay(optionalbacklight), whichcanbeeas ilyconnectedwithonewiretoanyI/Oline(orexternalsource).
Use

Theboardcanbepoweredbyeitheranonboard9Vbatteryoranac/dctrans former. Thepowerswitchintheupperrightturnspowertotheboardonand off. The board includes a reset button, for resetting the microcontroller. The LCDhasitsownpowerswitch, locateddirectlyabovetheLCD. IfyourLCD hasabacklight, thebacklightswitchislocatedabovetheLCDpowerswitch. IwilldescribetheprototypingsectiononthePICExperimentersBoard, as Ididwiththesolderlessbreadboards, andfinishupthedescriptionbywiring asimplemicrocontrollerLEDprojectontheExperimentersBoard. Theproto typingislocatedatthelowerleftcornerofthePICExperimentersBoard(see Fig. 6.11). There is an open 18pin socket to hold the microcontroller being developed.

TestingthePIC Microcontroller

57

Figure6.10 PhotographofPICExperimentersprototypedevelopingboard.

Theprototypingareaissimilarindesignandfunctiontosolderlessbread boards; see Fig. 6.12. You can breadboard (assemble and connect) electronic components and electronic circuits into the prototyping area without solder ing. Theprototypingareaisreusable; youcanchange, modify, orremovecir cuitcomponentsatanytime. Thismakesiteasytocorrectanywiringerrors. A cutaway of the prototyping area is shown in Fig. 6.13. The square holes shown in the area are sockets. When a wire or pin is inserted into a hole, it makeselectricalcontactwiththeunderlyingmetalstrip. Theholesarespaced sothatintegratedcircuitsandmanyothercomponentscanbepluggedrightin. Theinternalelectricalconnectionstructureoftheprototypingareaisshown inFig. 6.14. Looking at Fig. 6.15, at the top of the prototyping area we see that the columnsofbank1arelabeledwiththepinassignmentsfromthe16F84. These columns are directly connected to those microcontroller pins. Connecting a wireordevicetoanyofthethreesocketsinaparticularcolumniselectrically connectingthatwireordevicetothatI/Opinofthe16F84. Bank2provides14individualfoursocketcolumns. Thefoursocketsaligned ineachindividualcolumnareelectricallyconnected. Theindividualcolumns areseparateelectricallyfromoneanother. Bank3isthesameasbank2.

58

ChapterSix

Figure6.11 PhotographofPICExperimentersBoardwithbreadboardingareaand18pinsocket

highlighted.

Figure6.12 Diagramofthe breadboardarea.

Thelastrow, labeledGND(ground), iselectricallyconnectedacrossthe entire row. There are an additional three ground sockets at the top of bank1. A5Vpowerisavailablefromafoursocketcolumnadjacenttobank1.
Simpleexperiment

Weshallwireasimpleexperimenttoillustratetheuseoftheexperimenters prototypingarea: blinkinganLED. Yes, thisisverysimilartothewinkpro

TestingthePIC Microcontroller

59

Figure6.13 Cutawayviewof breadboardarea.

Figure6.14 Underlyingelectrical

connectionsofbreadboardarea.

gram, withtheexceptionthatweareonlyusingoneLEDthistime. Thefol lowing are a small PicBasic program and PicBasic Pro program to blink an LEDonpinRB1.
PicBasicprogram
start:high1 pause250

PicBasicProprogram
start:highportb.1
pause250

60

ChapterSix

Figure6.15 Diagramofbreadboardareawithbanks, ground, and


5Vpowersupplyhighlighted.

low1 pause250 gotostart

lowportb.1
pause250
gotostart

ThecompleteschematicforthisexperimentisshowninFig. 6.16. Asidefrom aprogrammed16F84, weonlyneedtwoothercomponents: a470, 14Wresis tor and a subminiature LED. All the other components needed to make the 16F84workarealreadyhardwiredonthePICExperimentersBoard. TheLEDhastwoterminals, onelongerthantheother. Thelongerterminal ontheLEDispositive, showninthelegendofFig. 6.17. Ontheschematicthe LEDappearsasadiode. Towirethiscircuit, connectoneleadofthe14Wresis torintooneoftheRB1sockets. Connecttheotherleadofthe14Wresistorinto asocketinbank2. TakethepositiveleadoftheLEDandplugitintoasocket inthesamecolumnastheonecontainingtheresistorlead. Connecttheoppo siteleadoftheLED, andplugitintooneofthegroundsocketsatthebottom. Plugtheprogrammed16F84microcontrollerintothe18pinsocketonthe PIC Experimenters board, and turn on the power. The LED should begin blinkingonfor 14 s, thenofffora 14 s. Thison/offcycle(blinking)continually repeats.
BuiltinLCD

TheonboardLCDdisplaycombinesaserialinterfaceanda2lineby16char acterdisplay(seeFig. 6.18). TheLCDdisplaycanbesettoreceiveserialdata at300, 1200, or2400Bd(trueorinverted, switchselectable).

TestingthePIC Microcontroller

61

Figure6.16 Schematicofblink

circuit.

Figure6.17 Diagramofblinkcircuitassembledinbreadboardareaof PICExperimentersBoard.

TousetheLCD, connectajumperfromthedesiredoutputpinonthemicro controllertotheserialinput. Itisnotnecessarytoconnectasecondaryground linetotheserialinputgroundunlesstheserialdataarecomingfromasource offtheExperimentersBoard. LiketheLCDmodule, theonboardLCDdisplayhastwooperationalmodes: text and instruction. The default is text mode; data received via the serial inputlineappearsonthescreen. SendthestringImages andImages will appear on the LCD. To input instructions to the LCD display, such as clear

62

ChapterSix

Figure6.18 PhotographofPICExperimentersBoardwithLCDcontrolshighlighted.

screen, go to line 2, etc., you must prefix the instruction with ASCII 254 (0xFE). The byte following the prefix is seen and treated as an instruction code. Aftertheinstructioncode, theunitautomaticallyreturnstotextmode. Everyinstructioncodemustbesentwithitsown254prefix. IfyourLCDisbacklit, youmayadjustthebacklightcontrasttotheoptimal settingviatheLCDcontrastcontrol. Thecontrastcontrolissetfullyclockwise (highestcontrast)atthefactory, butyoucanadjustthecontrolbyhand. To set the baud rate, there are three sets of jumpers: J1 to J3. Set the jumpersinaccordancewiththesilkscreendiagramontheExperimentersPC Board. Atallbaudrates, serialdataarereceivedat8databits, 1stopbit, no parity. Notethatthebaudratesettingisonlyreadonceatstartup, sochang ingthejumperswhilethemoduleisactivewillnothaveanyeffectonthebaud rateuntiltheExperimentersBoardisreset. OncetheLCDmoduleisconnectedandconfiguredtomatchthebaudrate ofthecomputer/microcontroller, itwillreceivethosetransmitteddataanddis playtheinformationontheLCDdisplay. Forexample, ifyousendHello, then Hello appears on the display. The cursor (printing position) automatically movesfromlefttoright. TheonboardLCDdisplaywillacceptthestandardLCDinstructions. Apar ticularbyteisidentifiedasaninstructionwhenitisprecededbyaninstruc tion prefix character, ASCII 254 (0xFE hex, 11111110 binary). The onboard LCDtreatsthebyteimmediatelyaftertheprefixasaninstruction, thenauto matically returns to data mode. For example, the clearscreen instruction is ASCII1. Toclearthescreen, send2541 (wherethe symbolsmean singlebytessettothesevalues, nottextastypedfromthekeyboard). Notice thisinstructioncodematchestheinstructioncodefortheserialLCDdisplay module.
Instruction Clearscreen Code(decimal) 1

TestingthePIC Microcontroller

63

Figure6.19 PhotographofLCDdisplayinselftestmode.

Homeposition(movecursortopleftofdisplay) Movecursoronecharacterpositionleft Movecursoronecharacterpositionright Scrolldisplayonecharacterpositionleft Scrolldisplayonecharacterpositionright Setcursorposition(DDRAMaddress) Setpointincharactergenerator(CG)RAM

2 16 20 24 28 128 addr 64 addr

The onboard LCD also has a selftesting mode that will print the current baudrateasdeterminedbythejumpersettingsandmode(true/inverted); see Fig. 6.19. Toenterselftestmode, connecttheserialinlinetoground(fortrue) or5V(forinverted)uponLCDmodulestartup. Note: Iftheserialinputlineisimproperlyconnectedforselftestmode, for instanceconnectedto5Vwhenjumpersaresetfortruemode, theLCDdis playwillremainblank. Themodulestaysinselftestmodeaslongastheser ial input line is held either high (inverted mode) or low (true mode). LCD modulemaybeexitedfromselftestmodeontheflybysimplyconnectingthe serialinputlinetoaserialsource. Whenyouprintpasttheendofaline, thenext24charactersdonotshow upontheLCDscreen. Theyarenotlost; theyareinanoffscreenmemory area. All alphanumeric LCD modules have 80 bytes of memory, arranged appropriately for a 2 40 screen. On LCDs with smaller screens (such as this2 16), textprintedpasttheendofavisiblelinegoesintomemory, but cantbeseenonthescreen. Usecursorpositioninginstructionstoprinttoa particularlocationonthedisplay. Ordeliberatelyprintinoffscreenmemo rytotemporarilyhidetext, thensendscrollleftinstructionstorevealit.
UsingtheLCD:PicBasicandPicBasicProexamples

ConnecttheserialinputoftheLCDtoportb.0ofaPICmicrocontroller. Thefol lowingPicBasicprogramdemonstratessendingdataandcommandstotheLCD.


main:pause1000 serout0,t2400,($fe,$01) WaitfortheLCDtostartup
Clearthescreen

64

ChapterSix pause40 serout0,t2400,(Whereveryougo) serout0,t2400,($fe,$c0) serout0,t2400,(thereyouare) pause1000 gotomain

Movetoline2 Wait1second Doitagain

TheprogramclearstheLCDandsendsthemessageWhereveryougothere youare at2400Bd(truemode), waitsfor2s, andthenloopsindefinitely(see Fig. 6.20). Notethatintheaboveexample, thecontrolcodeswerewrittenin hexadecimal(base16). Hexadecimalisspecifiedbyadollarsign($)prefix. If youwish, thelines
serout0,t2400,($fe,$01) serout0,t2400,($fe,$c0) Clearthescreen
Movetoline2

couldalsobewrittenwithdecimal(base10)notationas
serout0,t2400,(254,1) Clearthescreen
serout0,t2400,(254,192) Movetoline2

Whichnotationyouchoosetouseisamatterofpreference. Anequivalentpro gramcanbewrittenwithPicBasicProasfollows:

Figure6.20 PhotographofmessagefrompinRB0of16F84microcontrollersenttoonboardLCD

display.

TestingthePIC Microcontroller main:pause1000 seroutportb.0,0,[$fe,$01] pause40 seroutportb.0,0,[Whereveryougo] seroutportb.0,0,[$fe,$c0] seroutportb.0,0,[thereyouare] pause1000 gotomain WaitfortheLCDtostartup Clearthescreen

65

Movetoline2 Pauseforasecond Loop

IntroductiontoBinaryandthePICMicrocontroller Theterm binary meansbasedon2, asintwonumbers0and1. Itsalsolike anelectricswitchthathastwovalues: on(1)andoff(0). Theterm bit isanacronymthatstandsfortheterm binarydigit. Abitor binarydigitcanhavetwovalues, either0or1. A byte isadigitalexpression (number)containing8bits. Binaryisimportanttocomputersandmicrocontrollers. Thebitvaluesof0 and1aretheonlythingsacomputercanread. Actuallythecomputerormicro controllercantreallyread, butitcansensevoltagevalues. Soabitthatison 1isrepresentedbyapositivevoltage. Consequentiallyabit0isoff0andis representedasnovoltage. A single bit by itself is of little value, but start putting them together to makebytes(8bits), words(16bits, 32bits, 64bits, 128bits), andsoon, andwe can make the computers perform mathematics, create word processors and spreadsheets, create a cyberspace (Internet), etc. All these applications are basedonabit. To read or write to a port register requires understanding a little binary. When we read and write to any port, we use standard decimal numbers. However its the binary equivalent of those decimal numbers that the PIC microcontrollerseesanduses. The 16F84 uses 8bit port registers so we only need to concern ourselves withsmall8bitnumbersandtheirdecimalequivalents. Rememberthatan8 bitnumberiscalledabyte. An8bitnumbercanrepresentanydecimalvalue between0and255. Whenwewriteadecimalnumberintoaregister, thePIC microcontroller can only see the binary equivalent of that decimal number (byte)wewrotetotheregister. Forustounderstandwhatshappeninginside theregister, weneedtobeabletolookatthebinaryequivalentsofthedecimal (byte)numberalso. Oncewecandothis, ourabilitytoeffectivelyandelegant lyprogramthePICmicrocontrollersisgreatlyenhanced. Examinethebinarynumbertableatthetopofthenextpage. Itshowsallthe decimal and binary number equivalents for numbers 0 through 32. By using thisinformation, thebinarynumbersfrom32to255canbeextrapolated. Eachdecimalnumberontheleftsideoftheequalssignhasitsbinaryequiv alentontherightside. Sowhereweseeadecimalnumber, themicrocontroller willseethesamenumberasaseriesof8bits (thereare8bitstoabyte).

66

ChapterSix BinaryNumberTable 0 00000000 1 00000001 2 00000010 3 00000011 4 00000100 5 00000101 6 00000110 7 00000111 8 00001000 9 00001001 10 00001010 11 00001011 12 00001100 13 00001101 14 00001110 15 00001111 16 00010000 17 00010001 18 00010010 19 00010011 20 00010100 21 00010101 22 00010110 23 00010111 24 00011000 25 00011001 26 00011010 27 00011011 28 00011100 29 00011101 30 00011110 31 00011111 32 00100000 . . . 64 01000000 . . . 128 10000000 . . . 255 11111111

Figure 6.21 shows the relationship between a binary number and the two PICmicrocontrollerregistersthatcontrolportb. Noticeeachregisterhaseight openpositions. Thisregistercanholdan8bit(1byte)number. Letslookatthe secondbinarynumbertablebelow. Noticeforeachprogressionofthebinary1 totheleft, theexponentialpowerof2isincreasedby1.
SecondBinaryNumberTable Bitno. Bit0 Bit1 Bit2 Bit3 Decimal 1 2 4 8 Binary 00000001 00000010 00000100 00001000 Bitno. Bit4 Bit5 Bit6 Bit7 Decimal 16 32 64 128 Binary 00010000 00100000 01000000 10000000

Thesearerelevantnumbers, becauseeachprogressiontotheleftidentifies anotherbitlocationandbitweightwithinthe8bitbyte. For instance, suppose we wanted to write binary 1s at the RB6 and RB2 locations. Todoso, weaddtheirbitweights, inthiscase64(RB6)plus4(RB2), whichequals68. Thebinaryequivalentofdecimalnumber68is01000100. If youpushthatnumberintotheportBregister, youwillseethatthebinary1s areintheRB6andRB2positions. Rememberthisitisimportant. TheopenTRISBregistershowninFig. 6.21maybeusedtoexaminenum bersplacedintheTRISB. TheportBregistermaybeusedtoexaminenum bersplacedattheportBregister. Notice the correlation between the register bit locations, bit weights, and

Port B
86 Hex
Binary 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000 23 = 8 24 = 16 25 = 32 26 = 64 27 = 128 22 = 4 21 = 2 20 = 1 Power of Two

TRISB

Decimal 134

Port B

Decimal 6

06 Hex

Binary

Power of Two

00000001

20 = 1

00000010

21 = 2

00000100

22 = 4

00001000

23 = 8

00010000

24 = 16

00100000

25 = 32

01000000

26 = 64

10000000

27 = 128

Bit Weight/Values Register Location


RB7 RB6 RB5 RB4 RB3 RB2 RB1

128

64

32

16

1
RB0

Bit Weight/Values Register Location

128
RB7

64
RB6

32
RB5

16
RB4

8
RB3

4
RB2

2
RB1

1
RB0

Figure6.21 DiagramofportBregisters.

67

68

ChapterSix

portBI/Opins. Thiscorrespondencebetweenthebitnumber, bitweight, and theI/Olineisusedtoprogramandcontroltheport.


UsingtheTRISandportregisters

TheTRIS(tristateenable)registerisa1byte(8bit)programmableregister onthePIC16F84thatcontrolswhetheraparticularI/Opinisconfiguredas aninputoroutputpin. ThereisaTRISregisterforeachport. TRISAcontrols theI/OstatusforthepinsonportA, andTRISBcontrolstheI/Ostatusforthe pinsonportB. Ifoneplacesabinary0atabitlocationinTRISBforportB, thecorrespond ingpinlocationonportBwillbecomeanoutputpin. Ifoneplacesabinary1at abitlocationintheTRISB, thecorrespondingpinonportBbecomesaninput pin. TheTRISBdatamemoryaddressforportBis134(or86hinhex). AfterportBhasbeenconfiguredusingtheTRISBregister, theusercanread orwritetotheport, usingaportBaddress(decimalnumber6). Hereisanexample. SupposewewanttomakeallportBlinesoutputlines. Todoso, weneedtoputabinary0ineachbitpositionintheTRISBregister. Sothenumberwewouldwriteintotheregisterisdecimal0. NowallourI/O linesareconfiguredasoutputlines. IfweconnectanLEDtoeachoutputline, wecanseeavisualindicationof anynumberwewritetoportB. IfwewanttoturnontheLEDsconnectedto RB2andRB6, weneedtoplaceabinary1ateachbitpositiononportBreg ister. Toaccomplishthis, welookatthebitweightsassociatedwitheachline. RB2hasabitweightof4, andRB6hasabitweightof64. Weaddthesenum bers(4 64 68)andwritethatnumberintotheportBregister. Whenwewritethenumber68intotheportBregister, theLEDsconnected toRB2andRB6willlight. ToconfigureportA, weusetheTRISAregister, decimaladdress133(seeFig. 6.22). On portA, however, only the first 5 bits of the TRISA and the corre spondingI/Olines(RA0RA4)areavailableforuse. ExaminetheI/Opinout onthe16F84, andyouwillfindthereareonlyfiveI/Opins(RA0RA4)corre sponding to portA. These pins are configured using theTRISA register and usedwiththeportAaddress.
Register PortA PortB TRISA TRISB Memorylocation, hexadecimal 05h 06h 85h 86h Memorylocation, decimal 5 6 133 134

Onpowerupandreset, alltheI/OpinsofportBandportAareinitial ized(configured)asinputpins. Wecanchangethisconfigurationwithour program.

Port A
Decimal 133
Binary 00000001 00000010 00000100 00001000 00010000 21 = 2 22 = 4 23 = 8 24 = 16 20 = 1 Power of Two

TRISA

85 Hex

Port A

Decimal 5

05 Hex

Binary

Power of Two

00000001

20 = 1

00000010

21 = 2

00000100

22 = 4

00001000

23 = 8

00010000

24 = 16

Bit Weight/Values Register Location

16

Bit Weight/Values Register Location

16

RA4

RA3

RA2

RA1

RA4

RA3

RA2

RA1

Figure6.22 DiagramofportAregisters.

RA0

RA0

69

70

ChapterSix

Heresanotherexample. LetsconfigureportBsothatbit0(RB0)isaninput pinandallotherpinsareoutputlines. Toplacebinary0sand1intheproper bit location, we use the bit weights shown in the binary number table. For instance, toturnbit0on(1)andallotherbitsoff(0), wewouldwritethedec imalnumber1intoTRISBforportB. DependinguponwhichPicBasiccompilerisused, thecommandsarealittle different. ForthePicBasiccompiler, thecommandtowritetoaregisteristhe poke command. Theprogramlinetowritethedecimalvalue1intotheTRISB registerwilllooklikethis:
poke134,1

Thenumberafterthepoke commandisthememoryaddressthatthecom mandwillwriteto, inthiscase134. Thenumber134isthememoryaddressof theTRISBforportB. Thenextnumber, separatedbyacomma, isthevaluewe wanttowriteinthatmemoryaddress. Inthiscaseitsthenumber1. ForthePicBasicProcompiler, theTRISBandTRISAregistersarealready predefined. ThuswhenthecompilerseesTRISB, itaccessesthepropermemo ry(134)location. SotheequivalentcommandforthePicBasicProis
TRISB=1

Lookatthebinaryequivalentofthedecimalnumber1: 00000001 Mentallyplaceeach1and0intotheTRISBregisterlocationsshowninFig. 6.21. Seehowthe1fitsintothebit0place, makingthatcorrespondinglinean inputline, whileallotherbitlocationshavea0writteninthem, makingthem outputlines. Sobypoking(writing)thislocationwithadecimalnumberthatrepresents a binary number containing the proper sequence of bits (0s and 1s), we can configureanypinintheporttobeeitheranoutputoraninputinanycombi nationwemightrequire. Inaddition, wecanchangetheconfigurationofthe portonthefly astheprogramisrunning. To summarize, writing a binary 1 into theTRIS register turns that corre spondingbit/pinontheporttoaninputpin. Likewise, pokingabinary0will turnthebitintoanoutput.
Accessingtheportsforoutput

Oncetheportlineshavebeenconfigured(inputoroutput)usingtheTRISreg ister, wecanstartusingit. Tooutputabinarynumberattheport, simplywrite thenumbertotheport, usingthepoke (PicBasic)ortrisx.x (PicBasicPro) command. Thebinaryequivalentofthedecimalnumberwillbeoutputted, as showninourfirstexample. TooutputahighsignalonRB3usingthePicBasic compiler, wecouldusethiscommand:

TestingthePIC Microcontroller

71

Figure6.23 SchematicofeightLEDsconnectedtoportBforcountingprogram.

poke6,8

where6isthememoryaddressforportBand8isthedecimalequivalentof thebinarynumber(00001000)wewanttooutput. ForthePicBasicProcompiler, theequivalentcommandis


outputportb.3=1

Countingprogram

Toillustratemanyoftheseconcepts, Ihavewrittenasimplebasicprogram. TheschematicfortheprogramisshowninFig. 6.23. Itisabinarycounting programthatwilllighteightLEDsconnectedtoportBseightoutputlines. The counting program will light the LEDs in the sequence shown in the binarynumbertable. Eachbinary1inanumberthetablewillberepresented withalitLED. Every250milliseconds(ms)(14 s), thecountincrements. After reachingthebinarynumber255(themaximumvalueofabyte), thesequence repeats, startingfromzero.
Countinginbinaryby1

ThefollowingprogramiswrittenforthePicBasiccompiler.
Programbinarycounting
Initializevariables symbol trisb = 134 symbolportb=6 Initializeport(s) poketrisb,0 loop:

AssignTRISBofportbtodecimalvalueof134 Assignportbtodecimalvalueof6 Setportbpinstooutput

72

ChapterSix forb0=0to255 pokeportb,b0 pause250 nextb0 gotoloop End

PlacecountatportbtolightLEDs Pause14 soritstoofasttosee Nextcountervalue Startoveragain

ThefollowingprogramiswrittenforthePicBasicProcompiler.
Programbinarycounting
Initializevariables ctvarbyte Initializeport trisb=0 loop: forct=0to255 portb = ct pause250 nextct gotoloop End

Countingvariable Setportbpinstooutput Counter PlacecounteronportbtolightLEDs Pause14 s Nextcountervalue Startoveragain

Input

The ability of our microcontroller to read the electrical status of its pin(s) allowsthemicrocontrollertoseetheoutsideworld. Theline(pin)statusmay represent a switch, sensor, or electrical information from another circuit or computer.
Thebutton command

ThePicBasiccompilercomesequippedwithasimplecommandtoreadthe electrical status of a pin, called the button command. The button com mand, whileuseful, hasafewlimitations. Onelimitationofthiscommand isthatitmayonlybeusedwiththeeightpinsthatmakeupportB. TheI/O pinsavailableonportAcannotbereadwiththebuttoncommand. Another limitationisthatyoucannotreadmultipleportpininputsatonce, onlyone pinatatime. Wewillovercomethesebutton commandlimitationsusingthepeek com mand. Butforthetimebeing, letsuseandunderstandthebutton command. Asthenameimplies, the button commandismadetoreadthestatusof anelectricalbuttonswitchconnectedtoaportBpin. Figure6.24showstwo basicswitchschematics, labeledAandB, ofasimpleswitchconnectedtoan I/Opin. Thebutton commandstructureisasfollows:
buttonpin,down,delay,rate,var,action,label

TestingthePIC Microcontroller

73

Figure6.24 Schematicofelectricswitchessuitableforuse withPICmicrocontrollers.

Pin Down Delay Rate Var Action Label

Pinnumber(07), portB. Stateofpinwhenbuttonispressed(0or1). Cyclecountbeforeautorepeatstarts(0255). If0, nodebounceorauto repeatisperformed. If255, debounce, butnoautorepeatisperformed. Autorepeatrate(0255). Bytevariableusedfordelay/repeatcountdown. Shouldbeinitializedto0 priortouse. Stateofbuttontoperformgoto (0ifnotpressed, 1ifpressed). ExecutionresumesatthislabelifActionistrue.

LetstakeanotherlookattheswitchschematicinFig. 6.24beforewestart using the button switch. Lets visualize how the switches affect the I/O pin electrically. TheswitchlabeledAinFig. 6.24connectstheI/Opintoa5Vpowersup plythrougha10,000 resistor. Withtheswitchopen, theelectricalstatusof theI/Opiniskepthigh(binary1). Whentheswitchisclosed, theI/Opincon nectstoground, andthestatusoftheI/Opinisbroughtlow(binary0). The switch labeled B in Fig. 6.24 has an electrical function opposite the switchlabeledA. Inthiscase, whentheswitchisopen, theI/Opinisconnect edtoground, keepingtheI/Opinlow(binary0). Whentheswitchisclosed, the I/Opinisbroughthigh(binary1). Inplaceofaswitch, wecansubstituteanelectricsignal, highorlow, that canalsobereadusingthebutton command. Typically the button command is used inside a program loop, where the programislookingforachangeofstate(switchclosure). Whenthestateofthe I/Opin(line)matchesthestatedefinedintheDownparameter, theprogram executionjumpsoutofthelooptothelabel portionoftheprogram.

74

ChapterSix

A button example

IfwewanttoreadthestatusofaswitchofI/Opin7, hereisacommandwe willuseinthenextprogram.


button7,0,254,0,b1,1,loop

Thenextprogramissimilartothepreviousprogram3, inasmuchasitper formsabinarycounting. However, sinceweareusingPB7(pin7)asaninput, andnotanoutput, weloseitsbitweightinthenumberwecanoutputtoport B. Thebitweightforpin7is128. Sowithoutpin7wecanonlydisplaynum bersuptodecimalnumber127(255 128 127). Thisisreflectedinthefirst loop(pin7/bit7 128). Theprogramcontainstwoloops. Thefirstloopcountsto127, andthecur rent numbers binary equivalent is reflected by the Lite LEDs connected to portB. TheloopcontinuestocountaslongastheswitchSW1remainsopen. WhenSW1isclosed, the button commandjumpsoutofloop1intoloop2. Loop2isanoncountingloopwheretheprogramremainsuntilswitchSW1is reopened. You can switch back and forth between counting and noncounting states. Figure6.25isaschematicofourbuttontestcircuit. ThefollowingprogramiswrittenforthePicBasiccompiler.
ProgramforPicBasiccompiler
symboltrisb=134 SetTRISBto134 symbolportb=6 Setportbto6 InitializePort(s) poketrisb,128 Setportbpins(16output),pin7input

Figure6.25 SchematicofsevenLEDsandoneswitchconnectedtoportBfortheswitchdetectionand

countingprogram.

TestingthePIC Microcontroller label1:b1s=0 loop1: forb0=0to127 pokeportb,b0 pause250 button7,0,254,0,b1,1,label2 nextb0 gotoloop1 label12:b1=0 loop2: pokeportb,0 button7,1,254,0,b1,1,label1 gotoloop2 Setbuttonvariableto0 Countingloop Placeb0valueatporttolightLEDs Pausecountingoritstoofasttosee Checkbuttonstatus;ifclosed,jump Nextb0value

75

Setbuttonvariableto0 Secondloopnotcounting TurnoffallLEDs Checkbuttonstatus;ifopen,jumpback

Whentheprogramisrun, itbeginscounting. Whentheswitchisclosed, allthe LEDswillturnoff, anditstopscounting. Opentheswitch, andthecounting resumes, startingfrom0.
ProgramforPicBasicProcompiler
ctvarbyte
c1varbyte
Initializeport(s)
trisb = 128
Setportbpins(16output),pin7input
label1:c1=0
Setbuttonvariableto0
loop1:
Countingloop
Forct=0to127
portb=ct
PlacectvalueatporttolightLEDs
pause250
Pausecountingoritstoofasttosee
button7,0,254,0,c1,1,label2
Checkbuttonstatus;ifclosed,jump
nextct
Nextcountingvalue
gotoloop1
label2:c1=0
Setbuttonvariableto0
loop2:
Secondloopnotcounting
portb=0
TurnoffallLEDs
button7,1,254,0,c1,1,label1
Checkbuttonstatus;ifopen,jumpback
gotoloop2

peek

Thepeek commandcanonlybeusedwiththePicBasiccompiler. Wecanalso usethe peek commandtocheckthestatusofanyinputline. Theadvantages ofthe peek commandareasfollows. Using peek, wecanreadthefiveI/O linesofportA(ortheeightI/OlinesofportB)atonce. Thisincreasesthever satilityofthePICchipandallowsourprogramtobemoreconcise(lesscon voluted), shorter, andeasiertoread. Toemphasizethesepoints, letsrewriteourlastprograms, usingthe peek command. Thisprogramusesthesameschematic.

76

ChapterSix PicBasicprogramthatusesthepeekcommand
Initializeport(s) symboltrisb=134 SetTRISBto134 symbolportb=6 Setportbto6 poketrisb,128 Setportbpins(1..6)output,pin7input loop1: Countingloop forb0=0to127 pokeportb,b0 Placeb0valueatporttolightLEDs pause250 Pausecountingoritstoofasttosee peekportb,b0 Checkbuttonstatus ifbit7=0thenloop2 Ifsw1isclosed,jumptoloop2 nextb0 Nextb0value gotoloop1 loop2: Secondloopnotcounting pkeportb,0 TurnoffallLEDs peekportb,b0 Checkbuttonstatus;ifopen,jumpback ifbit7=1thenloop1 Ifsw1isopen,jumptoloop1 gotoloop2

The variable b0 is performing double duty. First it is holding our current countingnumbers0through127. Thenumbers0to127require7bitsofthe variableb0(bit0throughbit6). Thisleavestheeighthbit(bit7)availablefor use. Weusebit7tocheckthestatusoftheswitch. Ifitsopen, itsvaluewillbe abinary1; ifitsclosed, itsequaltobinary0. Thecommandpeek isfollowedbyamemoryaddress, thenacomma, thena storagevariable.
peekaddress,var

Asitsnameimplies, the peek commandallowsonetoview(orpeekat)the contentsofaspecifiedmemoryaddress. Typicallythememoryaddresspeeked at isoneofthePICmicrocontrollersregisters. Thepeeked valueisstoredin avariablevardefinedinthecommand. InthisprogramwepeekedattheoneinputlineonportB:
peekportb,b0

The peek commandcanreadanentirebyte(8bits)atonce. Orasinthis case, onlytheupperbit(bit7)ofthepeekedvalueisrelevant. (Therestofthe bitsareholdingourcountingnumberthatsoutputtedtotheLEDs).


peek andPicBasicPro

WhenyouareusingthePicBasicProcompiler, itisrecommended not touse the peek command. Fortunately there is an easy workaround to the peek command. Wesimplyassignavariabletotheportwewishtopeekat.
var=portb

TestingthePIC Microcontroller

77

Thevalueplacedinthevariablevar isourpeek value.


PicBasicProprogramthatusesapeekequivalentcommand ctvarbyte c1varbyte Initializeport(s) trisb=128 Setportbpins(1..6)output,pin7input loop1: Countingloop forct=0to127 portb=ct PlacectvalueatporttolightLEDs pause250 Pausecountingoritstoofasttosee c1=portb Checkbuttonstatus ifc1.7=0thenloop2 Ifsw1isclosed,jumptoloop2 nextct Nextctvalue gotoloop1 loop2: Secondloopnotcounting portb=0 TurnoffallLEDs c1=portb Checkbuttonstatus;ifopen,jumpback ifc1.7=1thenloop1 Ifsw1isopen,jumptoloop1 gotoloop2

Basicinputandoutputcommands

InourprogramswedirectlywrotetothePICmicrocontrollerTRISregisters (AorB)andportregisters. Bydoingsowewereabletocreateinputandout put pins and then access them in our programs. There are other commands youcanusetoaccomplishthesamething. ThePicBasicandPicBasicProcompilershavetwobasiccommandsformak ingindividualpinseitherinputoroutputlines. Thecommandsareinput and output. UnfortunatelythesetwobasiccommandsonlyworkonportBpins (0to7)forPicBasic. ForPicBasicPro, anyportmaybeused. Thecommand
inputpin

makesthespecifiedpinaninputline. Onlythepinnumberitself, thatis, 0to 7, isspecified(i.e., not pin0), forexample,


input2 Makespin2(rb2)aninputline.

Theoppositeoftheinput commandistheoutput command. Thecommand


outputpin

makesthespecifiedpinanoutputline. Onlythepinnumberitself, thatis, 0to 7, isspecified(i.e., not pin0), forexample,


output0 Makesportb,pin0(rb0)anoutput

TheaboveexamplesareintendedforusewitheitherPicBasicorPicBasicPro.

78

ChapterSix

The PicBasic Pro has an additional command structure that can be used withboththe input and output commands. Thisallowsonetomakeinput andoutputpinsonotherportsbesidesportB. Thisisaccomplishedbyspeci fyingtheportandthepin. Forinstance, toaccessportA, pin2, youusethefollowingformat:
porta.2

Tousethisinacommand:
inputporta.2 outputporta.3 Makeporta,pin2aninput
Makeporta,pin3anoutput

Servomotors Servomotors(seeFig. 6.26)areusedinmanyradiocontrolledmodelairplanes, cars, boats, andhelicopters. Becauseofthislargehobbyistmarket, servomo torsarereadilyavailableinanumberofstocksizes. Servomotorsareusedin afewofourrobots. Primarily, servomotorsaregeareddcmotorswithapositionalfeedbackcon trolthatallowstherotortobepositionedaccurately. Thespecificationsstate thattheshaftcanbepositionedthroughaminimumof90 (45). Inreality wecanextendthisrangecloserto180 (90)byadjustingthepositionalcon trolsignal. Therearethreewireleadstoaservomotor. Twoleadsareforpower 5V andGND. Thethirdleadfeedsapositioncontrolsignaltothemotor. Theposi tion control signal is a single variable width pulse. The pulse can be varied from1to2ms. Thewidthofthepulsecontrolsthepositionoftheservomotor shaft. A1mspulserotatestheshafttotheextremecounterclockwise(CCW)posi tion(45). A1.5mspulseplacestheshaftinaneutralmidpointposition(0). A2mspulserotatestheshafttotheextremeCWposition(45). Thepulsewidthissenttotheservomotorapproximately50timespersec ond(50Hz). Figure6.27illustratestherelationshipofpulsewidthtoservo motorposition. In most of the robots that use servomotors, the servomotor must be posi tionedtoitscenterlocationbeforebeingassembledintotherobot. Tocenter theservomotor, webuildasimplecircuitandPicBasicprogram. Thecircuitis showninFig. 6.28. TheprogramsforthePicBasicandPicBasicProcompilers follow:
PicBasicprogramtocenterservomotor
start:
pulsout0,150 Sendpulseoutonrb0
pause18 Delayneededtosendpulseat55Hz
gotostart Repeat

TestingthePIC Microcontroller

79

Figure6.26 Photographofaservomotor.

ThefollowingprogramisforthePicBasicProcompiler.
PicBasicProprogramtocenteraservomotor
start:
pulsoutportb.0,150 Sendpulseoutonrb0
pause18 Delayneededtosendpulseat55Hz
gotostart Repeat

Thiscenteringprogramandcircuitwillbereferredtoinlaterpartsofthe bookwhenservomotorsarediscussed. PartsList


LCDserialdisplay
PicExperimentersBoard

AvailablefromImagesSIInc. (seeSuppliersatendofbook).
Microcontroller(16F84) 4.0MHzXtal $7.95
$2.50

80

ChapterSix

Figure6.27 Diagramofpulsewidthssenttocontrolservomotorposition.

Figure6.28 Schematicofservomotorcircuitusedtocenterservomotors.

TestingthePIC Microcontroller

81

(2)22pFcapacitors (1)Solderlessbreadboard (1)0.1Fcapacitor (2)RedLEDs (2)470 resistors* (1)4.7k resistor (1)Voltageregulator(7805) (1)9Vbatteryclip RadioShackPN#276175 RadioShackPN#2721069 RadioShackPN#276208 RadioShackPN#2701115 RadioShackPN#2711126 RadioShackPN#2761770 RadioShackPN#270325

Available from RadioShack, Images SI Inc., Jameco Electronics, and JDR Microdevices(seeSuppliers).

*Theseresistorsarealsoavailablein16pindippackage.

Thispageintentionallyleftblank.

Chapter

7
Intelligence
Programmingintelligenceintoarobot(orcomputer)isadifficulttaskandone thathasnotbeenverysuccessfultodateevenwhensupercomputersareused. Thisisnottosaythatrobotscannotbeprogrammedtoperformveryuseful, detailed, anddifficulttasks; theyare. Sometasksareimpossibleforhumans toperformquicklyandproductively. Forinstance, imaginetryingtosolder28 filamentwirestoa 14insquaresliverofsiliconin2stomakeanintegrated circuitchip. Itsnotverylikelythatahumanwouldbeabletoaccomplishthis taskwithoutamachine. Butmachinetaskperformance, asimpressiveasitis, isntintelligence. ApproachestoBuildingIntelligence Therearetwoschoolsofthoughtconcerningthecreationofintelligenceinarti ficialsystems. Thefirstapproachprogramsanexpertsystem(topdown); the secondisaneuralorbehaviorbasedsystem(bottomup). The expert system uses rules to guide the robot in task performance. Behaviorbasedprogramscreateanartificial behaviorintherobotthatcaus esittoreflectively(automatically)performthetaskrequired. Behaviorsmay beprogrammed (software)ormaybehardwired intotherobot. Behaviorbased intelligencedoesntrequireacentralprocessor, althoughsuchasystemmay haveone. Letslookatapracticalprogrammingproblemandseehoweachapproach differs. Supposeyouworkedforacompanythatdesignedanewroboticvacu um cleaner. The purpose of the robot is to vacuum the floor of a customers homeorapartment. Yourjobistoprogramthenavigationsystem. Therobot needstomoveautonomouslythroughoutthehouse. Howwouldyougoabout programmingtherobottoaccomplishnavigationaroundthehomesoitcould travelinandoutofroomswithoutdestroyingtheplace?

83

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

84

ChapterSeven

Lets assume you first decide to try an expert navigation system. This approachusesbruteforceprogrammingandalotofmemory. Youmightbegin bydividingthetaskofvacuumingtheapartmentorhomeintosmallertasks such as vacuuming individual rooms. You begin by programming into the robotsmemoryanelectronicmap(floorplan)ofthehomeorareawherethe robotneedstovacuum. Thenyoumapouteachindividualroomanditscon tents. Therobotmusthavetheabilitytomeasureitsmovementasitmovesas wellascompassdirectiontomaintainitslocationintegrity. Oncethisisaccom plished, therobotmusthaveanexactstartlocationonthefloorplan. Therobotsmovementfromthestartpositionismeasuredandplottedonits internalfloorplanmap. Problemsoccurifanobjectispositioneddifferentlyor isoutofplace, suchasatrashreceptacleorchairthathasbeenmoved. Inthis situationtherealworlddoesnotmatchtherobotsinternalmap. Similarprob lemsoccurifnewobjectsareleftonthefloorsuchasabag, toy, orpet. Even so, these obstacles would not present too much of a problem for an expert system. To compensate, a secondary collision detection subprogram couldbewrittentodetect, map, andgoaroundanobstaclenotexistingonthe internalmap. Therobotcontinuestomoveandvacuumthefloor. Keepinmind thatastherobotnavigatesaroundnewobstacles, itscontinuallyupdatingits internalmapasittravels, tomaintainitslocationintegrity. Thesetasksare gobblingupcomputertimeandmemory. The robot vacuum accomplished its task. Now suppose you want to share thisrobotorrentit. Nowyouhaveaproblem. Eachnewhouseandeveryroom inthenewhousewouldrequireitsownelectronicmap. Althoughexpertpro grammingdoeswork, ittendstobeinflexibleandnotadaptivetowardnewor innovativesituations. Nowletstrytheotherapproachthatusesbehaviorbasedorbottomuppro gramming. Instead of programming internal maps, we program sensor responsesandbehaviorbasedalgorithms(feedforwardandfeedbackloops)for sensingandtravelingaroundobstaclesandavoidinggettingstuckunderneath furnitureortrappedincorners. Withoutanyinternalmapweallowtherobot to travel and move around the house in a random manner. The idea is that while traveling in a haphazard manner, it will eventually make its way throughouttherooms, cleaningthefloorasitgoes. Becausetherobottravels randomly, it will take longer for the robot to vacuum the entire floor, and it maymissaspothereandthere, butitgetsthejobdone. Sincethisbehavior basedtypeofrobotvacuumisntprogrammedforaparticularhouseorroom, itmaybeusedinanyhouseinanyroomatanytime. Whileourexampleissimple, itdoesillustratethemaindifferencesbetween expert and behaviorbased (neural) programming. But lets look at just one moreexamplebeforewemoveon. Expertsystemstypicallyhavealltheanswersthatthedesignersbelievewill berequiredbythesystemprogrammedintothesystembeforeitbegins. Itmay storeandcategorizenewinformation, butbasedonpreviouslydeterminedcat egories and existing knowledge. An example of this system could be a rock

Intelligence

85

identification system. The robot examines unknown rocks based on known characteristics of rocks, such as color, hardness, scratchability, acid reaction tests, mass, etc. Theexpertsystemfailsifitinadvertentlypicksupapieceof icethatmeltstowaterduringthetests. Well, itfailsaslongasthedesigner(s) never anticipated the robot picking up a piece of ice by mistake and made allowancesforit. Neural(behaviorbased)systemsarenotprogrammedandaremoreadap tive, asshowninthepreviousexample. Butisaneuralsystemsuitableforthis taskofrockidentification?Probablynot!Thereareinstancesinwhichexpert systemsarethemethodofchoice. Oneshouldntblindlyassumeonesystemis betterthantheotherinallcases. Todate, behaviorbasedrobotsaremoresuccessfulattaskaccomplishments such as traveling over unfamiliar and rough terrain than are programmed robots. (Otherneuralbasedintelligenceincludesspeechrecognition, artificial vision, speech generation, complex analysis of stock market data, and life insurancepolicies.) WherestheIntelligence? Behaviorbasedsystemsattheirmostbasiclevelareneuralreflexactions, so wherestheintelligenceinthat?However, truebehaviorbasedsystems, when layered on top of one another, generate what appears to be (meaning to us homosapiens)intelligenceactions. Thisisnotaconsciousnessmind, whichis a whole other category of intelligence, but the layer behaviorbased circuits mimicintelligentactionsquiteconvincingly. LayeredBehavioralResponses Letslayerafewbehavioralresponsesontopofoneanothertoseehowintel ligence behavior emerges. This particular robot is a modifiedphotovore. It willuseanumberofstandardphotoresistorsassensors. Layer1isasimpleonandoffsystem. Itusesasinglephotoresistortoread ambientlightintensity. Indarknessthesystemturnsitselfoffandshutsdown all electric power to the robot. When the ambient light increases to a low threshold, thesystemturnsitselfonandtherobottravelsforwardslowly. Layer2isatwophotoresistorsensor. Itdeterminesinwhichdirectionthe lightintensityisgreater. Thesesensorssteertherobotinthedirectionofthe greatestlightintensity. Layer3isasinglephotoresistorsensor. Underhighintensitylightitshuts downtherobotsdrivesystemandallowstherobottobatheinstrongintensi tylight. Anoutsiderwhodidntknowhowthisrobotwaswiredwouldobservethefol lowingbehavior. Atnighttherobotsleeps. Atdawnitbeginstotravel, looking forabrightlightsource(food). Whenitfindsasufficientlybrightlightsource, itstopstofeed, rechargingitsbatteriesthroughsolarpanels.

86

ChapterSeven

So our simple photovore robot exhibits three (dare we say intelligent?) behaviorssleep, searchingorhunting, andfeeding. Thatsnotbadforahand fulofcomponentsandsomeneuralglue. BehaviorBasedRobotics Behaviorbased programs and robotics are not new concepts. Seminal work has been written and experiments carried out since the 1940s. In the 1940s neuralnetworksandbehaviorbasedroboticswerehardwiredelectricalcom ponents. Inthe1940sDr. W. GreyWalterbuilttwoturtlelikemobilerobotsthatexhib it complex behavior using a few electrical neurons. The behavior generated wasatthetimecalledroboticreflexes. Todaythisbehaviorismoreaccurately describedaslayeredneuralarchitecture. In the 1980s Valentino Braitenberg wrote a book entitled Vehicles ExperimentsinSyntheticPsychology inwhichhedescribedcomplexbehavior emergingfromtheuseofafewartificialneurons. RodneyBrooks, headofMITsArtificialIntelligenceLaboratory, isaleader in the field of subsumption architecture, which again is behaviorbased and neural. Mark Tilden, creator of the nervous network technology, which again is reflexbased, doesntprogramstrategiessuchaswalkingintohisbiomorphic robots. Instead he creates a nervous network whose desired state creates a walkinggait. Whatthesescientistshavediscoveredisthatneuralbehaviorbasedarchi tectureoffersuniqueadvantagesoverstandardbasedexpertprogramming. Inthisbookwewillbuildafewbehaviorbasedrobots, usingthePICmicro controllerextensivelyintheirconstruction.

Chapter

8
WaltersTurtle
BehaviorBasedRobotics Behaviorbasedroboticswerefirstbuiltinthe1940s. Atthattimetheserobots weredescribedasexhibitingreflexivebehavior. Thisisidenticaltotheneural basedapproachtoimplementingintelligenceinrobots, asoutlinedinChap. 7. WilliamGreyWalterRoboticsPioneer ThefirstpioneerinthebottomupapproachtoroboticsisWilliamGreyWalter. WilliamGreyWalterwasborninKansasCity, Missouri, intheyear1910. When he was 5, his family moved to England. He attended school in the United KingdomandgraduatedfromKingsCollege, Cambridge, in1931. Aftergradu ationhebegandoingbasicneurophysiologicalresearchinhospitals. EarlyinhiscareerhefoundinterestintheworkofthefamousRussianpsy chologistIvanPavlov. Doyourememberfromyourhighschoolscienceclasses thefamousPavlovsdogs stimulusresponseexperiment?Incaseyouforgot, Pavlovrangabelljustbeforeprovidingfoodfordogs. Afterawhilethedogs becameconditionedtosalivatejustbyhearingthebell. AnothercontemporaryofWalter, HansBerger, inventedtheEEGmachine. WhenWaltervisitedBergerslaboratory, hesawrefinementshecouldmake toBergersEEGmachine. Indoingso, thesensitivityoftheEEGmachinewas improved, and new EEG rhythms below 10 Hz could be observed in the humanbrain. Walters studies of the human brain led him to study the neural network structuresinthebrain. Thevastcomplexitiesofthebiologicalnetworkswere toooverwhelmingtomapaccuratelyorreplicate. Soonhebeganworkingwith individualneuronsandtheelectricalequivalentofabiologicalneuron. Hewon deredwhattypeofbehaviorcouldbegatheredwithusingjustafewneurons.
87

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

88

ChapterEight

To answer this question, in 1948Walter built a small threewheel mobile robot. Themobilerobotmeasured12inhighandabout18inlong. Whatisfas cinatingaboutthisrobotisthatbyusingjusttwoelectricalneurons, therobot exhibitedinterestingandcomplexbehaviors. Thefirsttworobotswereaffec tionately named Elmer and Elsie (electromechanical robot, light sensitive). WalterlaterrenamedthestyleofrobotsMachinaSpeculatrixafterobserving thecomplexbehaviortheyexhibited. Intheearly1940stransistorshadnotbeeninvented, sotheelectronicneu ronsinthisrobotwereconstructedbyusingvacuumtubes. Vacuumtubescon sume considerably greater power than semiconductors do, so the original turtlerobotswerefittedwithlargerechargeablebatteries. Therobotsreflexornervoussystemconsistedoftwosensorsconnectedto two neurons. One sensor was a lightsensitive resistor, and the other sensor wasabumpswitchconnectedtotherobotsouterhousing. The three wheels of the robot are in a triangle configuration. The front wheelhadamotorizedsteeringassemblythatcouldrotateafull360 inone direction. Inaddition, thefrontwheelcontainedadrivemotorforpropulsion. Sincethesteeringcouldcontinuallyrotateafull360, thedrivemotorselec tricpowercamethroughslipringsmountedonthewheelsshaft. A photosensitive resistor was mounted onto the shaft of the front wheel steeringdrive assembly. This ensured that the photosensitive resistor was alwaysfacinginthedirectioninwhichtherobotwasmoving. FourModesofOperation Whileprimarilyaphotovore(lightseeking)typeofrobot, therobotexhibited fourmodesofoperation. Itshouldbementionedthattherobotssteeringmotor anddrivemotorwereusuallyactiveduringtherobotsoperation. Search. Ambient environment at a low light level or darkness. Robots responses, steeringmotoronfullspeed, drivemotoron12 speed. Move. Foundlight. Robotsresponses, steeringmotoroff, drivemotorfullspeed. Dazzle. Bright light. Robots responses, steering 12 speed, drive motor reversed. Touch. Hitobstacle. Robotsresponse, steeringfullspeed, reversedrivemotor.

ObservedBehavior Inthe1950sWalterwrotetwoScientificAmerican articles(AnImitationof Life, May1950; AMachineThatLearns, August1951)andabooktitled The Living Brain (Norton, New York, 1963). The interaction between the neural system and the environment generated unexpected and complex behaviors. In one experiment Walter built a hutch, where Elsie could enter and recharge its battery. The hutch was equipped with a small light that would

WaltersTurtle

89

drawtherobottoitasitsbatteriesrandown. Therobotwouldenterthehutch, anditsbatterywouldautomaticallyberecharged. Oncethebatteryrecharged, therobotwouldleavethehutchtosearchfornewlightsources. Inanotherexperimenthefixedsmalllampsoneachtortoiseshell. Therobots developedaninteractionthattoanobserverappearsasakindofsocialbehav ior. Therobotsdancedaroundeachother, attimesattractedandthenrepelled, remindinghimofaroboticmatingritualorterritorialmarkingbehavior. BuildingaWalterTortoise WecanimitatemostfunctionsinWaltersfamoustortoise. Myadaptationof WalterstortoiseisshowninFig. 8.1. Tofabricatethechassis, weneedtodoa littlemetalwork. Workingmetalismadealoteasierwithafewtoolssuchas acenterpunch, handshears, nibbler, drill, vise, andhammer(seeFig. 8.2). Center punch: Used to make a dimple in sheet metal to facilitate drilling. Withoutthedimple, thedrillismorelikelytowalk offthedrillmark. Hold thetipofthecenterpunchinthecenteroftheholeyouneedtodrill. Hitthe centerpunchsharplywithahammertomakeasmalldimpleinthematerial. Shears: Usedtocutsheetmetal. Iwouldadvisepurchasing8to14inmetal shears. Useasascissorstocutmetal. Nibbler: Usedtoremove(nibble)smallbitsofmetalfromsheetandnibble cutoutsandsquareholesinlightgaugesheetmetal. NoteRadioShacksells aninexpensivenibbler.

Figure8.1 AdaptationofWaltersturtlerobot.

90

ChapterEight

Figure8.2 Afewsheetmetaltools.

Vise: Usedtoholdmetalfordrillingandbending. Drillandhammer. Selfexplanatory. Awellstockedhardwarestorewillcarrythesimplemetalworkingtoolsout lined. Most will also carry the lightgauge sheet metal and aluminum bar materialsneededtomakethechassis. Ibuiltthechassisoutof(18 12in)aluminumrectanglebarand22to24 gaugestainlesssteelsheetmetal. Stainlesssteelishardertoworkwiththan coldrolledsteel(CRS). AndCRSishardertoworkwiththansheetaluminum. IfIweretodothisprojectover, Iwouldusealuminumextensivelybecauseit iseasiertoworkwiththanCRSorstainlesssteel. DriveandSteeringMotors Therobotusesservomotorsforboththedriveandsteering. Thedriveservo motor is a HiTec HS425BB 51oz torque servomotor (see Fig. 8.3). The HS 425BBservomotorismodifiedforcontinuousrotation. ForsteeringtherobotI used a less expensive HiTec HS322 42oz torque servomotor (unmodified). Before we go into the robot fabrication, we must first modify the HS425BB servomotorforcontinuousrotation.

WaltersTurtle

91

Figure8.3 HS425servomotor.

ModifyingtheHS425BBServomotor IchosetheHS425BBservomotorbecauseIfoundittobetheeasiestservo motortomodifyforcontinuousrotation. Tocreateacontinuousrotationser vomotor, itisnecessarytomechanicallydisconnecttheinternalpotentiometer fromtheoutputgear. First remove the four back screws that hold the servomotor together (see Fig. 84). Keep the servomotor horn attached to the front of the servomotor. Oncethescrewsareremoved, gentlypulloffthefrontcoveroftheservomotor. Theoutputgearwillstayattachedtothefrontcover, separatingfromtheshaft ofthepotentiometerleftintheservomotorscase(seeFig. 8.5). Sometimesthe idler gear will fall out. Dont panic; its easy enough to put back in position whenyoureassembletheservomotor. Nextremovetheplasticclipfromtheservomotorshaft(seeFig. 8.6). Withthe plastic clip removed, the shaft of the potentiometer will no longer follow the rotationoftheoutputgear. Alignthepotentiometershaftsothattheflatsides oftheshaftareparalleltothelongsidesoftheservomotorcase(seeFig. 8.7). Takeoffthefrontcoveroftheservomotor, andremovethecenterscrewhold ing the servomotor horn and output gear (see Fig. 8.8). The output gear is

92

ChapterEight

Figure8.4 Removingscrewsfrombackofservomotorcase.

Output Gear

Idler Gear

Plastic Clip

Servomotor Horn

Figure8.5 InsideviewofHS425servomotor.

WaltersTurtle

93

Figure8.6 Removingplasticclip.

Figure8.7 Topviewofservomotorgearswithplasticclipremoved.

showninFig. 8.9. Removethebearingfromtheoutputgear(seeFig. 8.10). The bearingneedstoberemovedsothatyoucancutawaythestoptabfromthe gear. Useahobbyknifeorminiaturesawtocutawaythestoptab. Whenyou arefinishedcuttingoffthetab, checkthatthecutsurfacesaresmooth. Ifnot, useafiletosmoothoutthesurfaces. Nextremountthebearingontothegear(seeFig. 8.11). Reassembletheidler andoutputgearsontotheservomotorsgeartraininthecase(seeFigs. 8.12and 8.13). Nowfitontheservomotorcover, andreattachthecover, usingthefour screws.

94

ChapterEight

Figure8.8 Removingservomotorhornfromfrontofcase.

Bearing

Stop Tab

Output Gear

Figure8.9 Outputgearremovedfromfrontcase.

WaltersTurtle

95

Stop Tab

Figure8.10 Stoptabonoutputthatmustberemoved.

Figure8.11 Stoptabremovedandbearingplacedbackongear.

96

ChapterEight

Idler Gear

Output Gear

Figure8.12 Outputgearfittedbackontoservomotor.

Figure8.13 Readyforreassemblyofservomotor.

The output shaft of the servomotor is now free to rotate continuously. A pulsewidthof1mssent50to60timespersecond(Hz)willcausetheservo motortorotateinonedirection. Apulsewidthof2mswillcausetheservo motortoturnintheoppositedirection. There are two ways we can stop the servomotor from rotating. The first methodistosimplystopsendingpulsestotheservomotor. Thesecondmethod isalittletrickier. Apulsewidthofapproximately1.5mswillstoptheservo

WaltersTurtle

97

motor. Theexactpulsewidthforeachservomotormustbedeterminedexperi mentally. Theexactpulsewidthrequiredisbaseduponthepositionofthesta tic potentiometer shaft inside the servomotor. If you followed the directions provided, itshouldbeabout1.5ms. Tofindtheexactpulsewidthtostopthe servomotor, youhavetwooptions. Thefirstistokeepmanuallyadjustingthe pulsewidthuntilyoufindthecorrectpulsewidth. Asyouapproachthepulse widthneededtostoptheservomotor, youwillnoticethattherotationalspeed of the servomotor will slow down. You can use this as a feature to create a speedcontrol, ifyouwish. ThesecondoptionistolookattheservomotorcircuitdescribedinChap. 14(see Fig. 14.11). Thissimplecircuitallowsyoutoquicklyfindthecorrectpulsewidth. SheetMetalFabrication Therearethreepiecesofsheetmetaloneneedstofabricate. TheUbracket, showninFig. 8.14, holdsthefrontwheelanddriveservomo tor. The U bracket may be fabricated from 22gauge 1.25 5in aluminum sheet metal. I would recommend purchasing the U bracket (see Parts List) becausethecuttingrequiredforthisfabricationisextensiveandprecise. TheUbracketmountsthedriveservomotor(seeFig. 8.15). Inaddition, on thetopoftheUbracketareholesformountingaservomotorhorn, whichis usedtoconnectthesteeringservomotor. Figure8.16isadiagramofthebasewithacutoutforthe42ozservomotor. Thebasemeasures3in 5.5in. Thebasewillholdthepowersupplyandthe electronics. Followtheservomotordiagraminremovingmetalfromthebase. Firstdrillthefour(18in)holesformountingtheservomotor. Nextusethe same drill bit to drill holes along the inside perimeter of the servomotor cutout. Removingmetalinthiswayisalittleeasierthantryingtosawornib bleitaway. Whenyouhavedrilledasmanyholesaspossible, usethemetal nibblertocutthematerialbetweentheholestofinishremovingthismaterial. Thencontinuetonibbleawayatthesidesofthecutoutuntilyouhavetherec tangle shape needed. Before you mount the servomotor, file the edges of the holesmooth. Finishthebasebydrillingtheotherholesoutlinedinthedrawing. TherearaxlebracketisshowninFig. 8.17; itismadefrom18 12 10in aluminumbar. Drillthefour18inholesinthealuminumbeforebendingitinto shape. FortherearaxleIusedthewirefromametalcoathanger. Mountthe rearaxleandwheelstotherobotbase, usingtwo632machinescrewsandnuts. Tocontinue, weneedtomountthefrontdrivewheeltotheservomotor. The drivewheelhasadiameterof234 inandis18 inthick(seeFig. 8.18). Theholes aredrilledinthewheeltoacceptastandardHiTecservomotorhorn(seeFig. 8.19). The horn is secured to the wheel using four no. 2 14in sheet metal screws(seeFig. 8.20). BeforeyouattachtheservomotortotheUbracket, secureaservomotorhorn tothetopoftheUbracket, usingthepredrilledholes(seeFig. 8.21).

98

ChapterEight

1.25

C/L

C/L 2.14 Rectangle cutout .83 x 1.62 Bracket bent at 90 1.53

.37
.31 .94

C/L .224

.625

.14

1.11

.29 dia. Four small shaded holes 1/8 dia.

Bend 90

2.37 .288 .39 .6 .8 .91

Hole size 5/32 2.97

Bend 90

3.57 All dimensions in inches

Material 1.25 x 5.80 x .050 Aluminum 6061

5.2

/32 dia. hole

5.80 .625 Fits HS-322, HS-325, HS-425 servomotors

Figure8.14 DrawingofUbracketformountingthedriveservomotor.

WaltersTurtle

99

Figure8.15 Ubracketwithdriveservomotorattached.

Thefrontofthemountingears, bothtopandbottom, ontheservomotorhas smalltabs(seeFig. 8.22). Cutandfileawaythesetabssothattheservomotor canbemountedflushagainstthebracket(seeFig. 8.23). Nextmounttheser vomotor to the U bracket, using 632 machine screws and nuts. Attach the wheel/horn assembly to the servomotor (see Figs. 8.24 and 8.25). Put this assemblytothesidewhileweworkonothercomponents. Shell Theoriginaltortoisesusedatransparentplasticshell. Theshellwasconnect edtoabumpswitchthatcausedtherobottogointoavoid modewhenacti vated. Ilookedat, tried, andrejectedanumberofdifferentshells. FinallyIwas leftwithnochoiceotherthantofabricatemyownshell. Rather than fabricate an entire shell, I made a bumper that encompasses therobot. Thebumperisfabricatedfrom18 12 32inaluminumbar(see Fig. 8.26). Thealuminumbarismarkedatthecenter. Eachbendrequiredin thebumperisalsomarkedinpencil. Thematerialisplacedinaviseateach pencilmarkandbenttotheanglerequired. Thetwoendsofthealuminumbar endupatthecenterbackofthebumper. Thesetwoendsarejoinedtogether usinga 18 12 1inlongpieceofaluminumbar. A 18inholeisdrilledon eachendofthealuminumbar. Matchingholesaredrilledintheendsofthe

100

ChapterEight

42-oz servo

Front

Sheet metal 3 in x 5.5 in

wire pass-through hole

1/ 2

1/ - in holes to match rear axle bracket 8

Figure8.16 Robotbaseshowing cutoutfor42ozservomotorand holesforrearaxlebracket.

bumper. Thebarissecuredtothebumperusingtwo540machinescrewsand nuts(seeFig. 8.27). Theupperbracketusedtoconnectthebumpertotherobotisidenticaltothe frontendofthebumper(seeFig. 8.28). Theupperbracketismadefrom18 1 2 14.5in aluminum bar. As with the bumper, the center of the bar is marked, andeachbendrequiredisalsomarkedinpencil. Thematerialisbent inavisethesamewayasthebumper. FindingtheCenterofGravity Itisimportanttofindthecenterofgravitylineofthebumper, becausethiswill marktheoptimumlocationwheretheupperbracketshouldbeattached. Rest the bumper on a length of aluminum bar. Move the bumper back and forth untilitbalancesevenlyonthealuminumbar. Markthecenterlinepositionson eachsideofthebumper. Drilla18inholeoneachside. Drillmatchingholeson

WaltersTurtle
1/ - in 8

101

holes

23/4 in

125 23/4 in

10 in

Wheel

35/8 in
3/ 4

in Axle Height
1/ - in 8

hole for axle

1/ 8

- in hole for axle

Wheel size

2 in

Figure8.17 Rearaxlebracketdetail.

theendsoftheupperbracket. Thensecuretheupperbrackettothebumper using540machinescrewsandnuts. AttachingBumpertoRobotBase Thebumperisattachedtotherobotbodybytheupperbracket. Drillthree18in holesinthetopoftheupperbracket. One18inholeisinthecenter, andthetwo otherholesare118 inawayfromthecenterhole(seeFig. 8.29). Threematching holesaredrilledintherobotbasebehindtheservomotor. Theholesshouldbe placedsothatthebumper(oncesecuredtothebase)hasadequateclearance(18 to14 in)fromthebackwheels. Thematchingcenterholeonthebasemustbeoff setbymovingthedrilledholeforwardonthebasebyabout14 in.

102

ChapterEight

.575

.575

Center hole .300 diameter All other holes 1/8 diameter

.385

.385 Material /8 - thick hardwood

2.75 diameter

1/ 8

Side view All dimensions in inches

Figure8.18 Drawingofdrivewheel.

Figure8.19 Servomotordrivewheelwithholesformounting

servomotorhorn.

WaltersTurtle

103

Figure8.20 Drivewheelwithservomotorhornattached.

Figure8.21 Ubracketbeforemountingofdriveservomotor.

Thebracketissecuredtothebaseusingtwo1inlong632machinescrews, four632nuts, andtwo1inlong2lbcompressionsprings, witha18incenter diameter (see Fig. 8.30). The tension and resiliency of the bumper can be adjustedbytighteningorreleasingtheupper632machinescrewnuts. Once assembled, the bumper will tilt back and close the bumper switch when the robot(bumper)encounters(pushesagainst)anobstacle.

104

ChapterEight

Tab

Figure8.22 Tabonservomotorcasethatneedstobefiledoff.

Tab Filed Away

Figure8.23 Tabfilesoffservomotorcase.

BumperSwitch Thebumperswitchmakesuseofthecenterholes. LookingbackatFig. 8.30, weseethecenterholeisfittedwitha632machinescrewheldonbyastan dard(zincplated)nut, followedbyabrassnut. Thebrassnuthasawiresol deredtoit. Thepurposeofthislittleassemblyisjusttoattachawiretothe bracketbumperassembly. Brassnutsareusedbecauseitispossibletosolder wirestobrasstomakeelectricalconnections. Thisisincontrasttothestan dardzincplatedsteelnutsthatareverydifficult(impossible)tosolder.

WaltersTurtle

105

Figure 8.24 Attaching drive servomotor to U bracket by using plastic screwsandnuts.

Figure8.25 AnotherviewofdriveservomotorandUbracket.

106

ChapterEight

31/2 in

41/2 in

41/2 in

32 in 43/4 in 43/4 in

91/2 in
Figure8.26 Topdimensionalviewofbumperfabricatedfrom18in 12in

32inaluminumbar.

5-40 nuts Aluminum bumper

1-in-long aluminum bar

5-40 machine screws


Figure8.27 Cutawaycloseupofaluminumbracketusedtosecuretheopenendsof thebumpers.

Thesecondhalfofthetileswitchiscomprisedofa1in632plasticmachine screwandthree632machinescrewnuts. Onenutmustbebrasswithawire solderedtoit(seeFig. 8.31). Figures8.32and8.33arecloseupphotographsof thefinishedbumperswitch. Theassemblyisadjustedsothatthebrassnuton thetopofthe632machinescrewliesjustunderneaththeupperaluminum bracket without touching. When the upper bracket tilts forward, contact is madebetweenthealuminumbracketandbrassnut, whichisreadasaswitch closure.

WaltersTurtle
31/2 in

107

41/2 in

41/2 in

141/2 in 1 in 1 in

Figure8.28 Sidedimensionalviewofupperbracketfabricatedfrom18in
1

2in 1412inaluminumbar.

11/8 in

11/8 in

/8 -in hole

Figure8.29 Sidedimensionalviewforholeplacementintopoftheupperbracket.

6-32 machine screw

6-32 nut

6-32 brass nut

Soldered wire

6-32 nut

6-32 nut

1-in-long compression spring

6-32 /2 machine screw

1-in-long compression spring

Figure8.30 Sideviewofupperbracketdetailingthemountingoftheupper brackettotherobotbaseusingmachinescrewsandcompressionsprings. Alsodetailsbrackethalfofthebumperswitch.

MountingtheSteeringServomotor Ifyouhaventdoneso, mountthesteeringservomotortotherobotbase, using four632plasticmachinescrewsandnuts. BeforeyouattachtheUbracketto the steering servomotor, make sure the steering servomotor spindle is in its centerposition. Thiswillensurethattherobotwillsteerforwardrightandleft

108

ChapterEight
Upper bracket

6-32 brass nut 6-32 nuts

Wire

Base

6-32 plastic machine screw

Robot base

Figure8.31 Sidedimensionaldetail(robotbasesideofthebumpswitch)ofplasticscrew withtopbrassnut.

Figure8.32 Closeupphotographdetailingbumpswitchandspringmountingofupperbracket.

properly. The following short program will place a servomotor in its center position:
start:
pulsoutportb.1,150
pause18
gotostart

TheoutputpulsesignalfortheservomotoristakenaspinRB1. Oncetheser vomotorisinitscenterposition, attachtheUbrackettotheservomotorsothat thedrivewheelispointingforward.

WaltersTurtle

109

Figure8.33 Closeupphotographdetailingbumpswitch.

Photoresistor TheCdSphotoresistors(seeFig. 8.34)usedinthisrobothaveadarkresistance ofabout100k andalightresistanceof10k. TheCdSphotoresistorshave largevariancesinresistancebetweencells. ItisusefultouseapairofCdScells forthisrobotthatmatches, asbestasonecanmatchthem, inresistance. Since the resistance value of the CdS cells can vary so greatly, its a good ideatobuyafewmorethanyouneedandmeasuretheresistances, tofinda pairwhoseresistancesareclose. Thereareafewwaysyoucanmeasurethe resistance. Thesimplestmethodtouseavoltohmmeter, settoohms. Keepthe lightintensitythesameasyoumeasuretheresistance. ChoosetwoCdScells thatarecloselymatchedwithinthegroupofCdScellsyouhave. ThesecondmethodinvolvesbuildingasimplePIC16F84circuitconnected to an LCD display. The advantage of this circuit is that you can see the responseoftheCdScellsundervaryinglightconditions. Inaddition, youcan see the difference in resistance between the CdS cells when they are held underthesameillumination. ThisnumericdifferenceoftheCdScellsunder exactlightingisusedasafudgefactorinthefinalturtleprogram. Ifyoujust testtheCdScellswithjustanohmmeter, youwillendupusingalargerfudge factorfortherobottooperateproperly. The schematic for testing the CdS cells is shown in Fig. 8.35. The circuit, builtonaPICExperimentersBoard, isshowninFig. 8.36. ThePicBasicPro testingprogramfollows:
CdScelltest PicBasicProprogram Serialcommunication1200baudtrue Serialinformationsentoutonportbline0

110

ChapterEight

Figure8.34 CdSphotoresistorcell.

+5V
14 VDD

R1 4.7K U1 4 X1 16 4MHz 15 C1 .1F

V1 100K CdS Cell

13 12 11 10 9 8 7 6

C2 .1F 50V C3 .1F 50V

RB7 RB6 MCLR' RB5 OSC1 RB4 RB3 RB2 OSC2 RB1 RB0/INT RA4/TOCKI RA3 RA2 RA1 RA0

Serial Line +5V SW4

3 2 1 18 17

PIC 16F84

VSS

LCD Display
CdS Cell V2 100K Gnd
Figure8.35 ElectricalschematicfortestingandcalibratingCdScells.

ReadCdScell#1onportbline1 ReadCdScell#2onportbline7 v1 var byte Variablev1holdsCdS#1information Variablev2holdsCdS#2 v2varbyte

WaltersTurtle

111

Figure8.36 TestcircuitbuiltonPICExperimentersBoard.

information pause1000 main: potportb.1,255,v1 potportb.7,255,v2 Displayinformation seroutportb.0,1,[$fe,$01] pause25 seroutportb.0,1,[CdS1=] seroutportb.0,1,[#v1] seroutportb.0,1,[$fe,$C0] pause5 seroutportb.0,1,[CdS2=] seroutportb.0,1,[#v2] pause100 gotomain

AllowtimeforLCDdisplay ReadresistanceofCdS#1photocell ReadresistanceofCdS#2photocell Clearthescreen

Movetoline2

NoticeinFig. 8.36thatCdScell1isreading37andCdScell2isreading46 under identical lighting. Keep in mind that this is a closely matched pair of CdScells. Wecanuseafudgefactorof15points. Thismeansthataslongas thereadingsbetweencellsvaryfromeachotherby15points, themicrocon trollerwillconsiderthemnumericallyequal.

112

ChapterEight

TrimmingtheSensorArray IfyouareusingtheExperimentersBoard, youcantrimandmatchtheCdS cellstooneanother. Doingsoallowsyoutoreducethefudgefactorandpro ducesacrisperresponsefromtherobot. TypicallyoneCdScellresistancewillbelowerthanthatoftheotherCdScell. TothelowerresistanceCdScelladda1k (or4.7k)trimmerpotentiometer inseries(seeFig. 8.37). Adjustthepotentiometer(trim)resistanceuntiltheout putsshownontheLCDdisplayequaleachother. TrimtheCdScellunderthe samelightingconditionsinwhichtherobotwillfunction. Thereasonforthisis that when the light intensity varies from that nominal point to which youve trimmed the CdS cell, the responses of the individual CdS cells to changes in lightintensityalsovaryfromoneanotherandthenarenotascloselymatched. OnceyouhaveapairofCdScellstouse, theyneedtobeattachedtothe robot. IsolderedtheCdScellsandcapacitorstoasmallpieceofperforated board(seeFig. 8.38). Figure8.38showsboththefrontandbackofthesen sorarray. Theoppositesideoftheservomotorbracketthatholdsthecontinuousrota tionservomotorisperfectformountingthephotoresistor. Iusedasmallpiece oftransparentplastic, 12 inwide 6inlong 116 inthick(12.5mm 152mm 1.5mmthick)tocreateanLbracketonwhichtomountthephotoresistors (seeFig. 8.39). A18inholeisdrilled12 inupfromoneend(seeFig. 8.37). Theplasticisthen gentlyheatedabout212 inupfromtheend(seebendpoint). Whentheplastic softens, bendittoa90 angleandholditinpositionuntiltheplastichardens again.
+5V
14 VDD

R1 4.7K U1 X1 4MHz C1 .1F

V1 100K CdS Cell

13 12 11 10 9 8 7 6

C2 .1F 50V C3 .1F 50V

RB7 4 RB6 MCLR' RB5 OSC1 16 RB4 RB3 15 RB2 OSC2 RB1 RB0/INT RA4/TOCKI RA3 RA2 RA1 RA0

1K V3 SW4

Serial Line +5V

3 2 1 18 17

PIC 16F84

VSS 5

LCD Display
CdS Cell V2 100K Gnd
Figure8.37 Electricalschematicoftestingcircuitwithpotentiometertrimmer.

WaltersTurtle

113

BACK

FRONT

Figure 8.38 Front and back mounting of CdS cells and capacitorstoperforatedboard.

6 in

Bend point

90 31/2 in

1/ in 2

Material: Plastic Size 1/2 in x 6 in x 3/32 in

21/2 in

31/2 in
Figure8.39 FabricationdrawingforplasticbracketforCdScells.

114

ChapterEight

Figure8.40 CdSsensorarrayattachedtoplasticbracket.

NextIusedhotgluetosecuretheCdScellstothebackoftheplasticL(see Fig. 8.40). ThenImountedanopaquevaneonthefrontsurfaceoftheplastic inbetweenthephotoresistors(seeFig. 8.41). Theopaquevaneismadefroma smallpieceofconductivefoamIhadlyingaround. Isimplyhotglueoneedge totheplastic. UsingtheopaquevaneandthetwoCdSphotosensorsinthisconfiguration alleviatesmuchofthecomputationneededtotrackalightsource. Theoperation ofthesensorarrayisshowninFig. 8.42. Whenbothsensorsareequallyillumi nated, theirrespectiveresistancesareapproximatelythesame. Aslongaseach sensoriswithin10pointsoftheother, thePICprogramwillseethemasequal andwontmovetheservomotor(steering). Whenthesensorarrayisnotproper lyaimedatthelightsource, thevanesshadowfallsononeoftheCdScells. This pushestheresistancebeyondthe10pointrange. ThePICmicrocontrolleracti vatesthesteeringservomotortobringbothsensorsbackunderevenillumina tion. Indoingso, thissteerstherobotstraighttothelightsource. Ifthesensorsdetecttoogreatalightintensity, therobotwillgointoavoidmode. Mounting the photoresistor array on the drive wheel assembly keeps the sensorspointinginthesamedirectionasthedrivewheel(seeFig. 8.43). This replicatesthefunctionoftheoriginaltortoiserobots. Thearrayissecuredto theUbracketbyusingasmallplasticscrewandwingnut. Schematic TheschematicfortherobotisshowninFig. 8.44. Intelligencefortherobotis provided by a single PIC 16F84 microcontroller. The forward servomotor is

WaltersTurtle

115

1/ 2

in SIDE VIEW Vane CdS Cell

Plastic "L"

21/2 in

Perf. Board

CdS Cell

TOP VIEW
Figure8.41 DrawingshowingCdScellsattachedtobracketwithvane.

connected to RB7, and the steering servomotor control signal is provided by RB6. Sensor readings of the CdS cell are read off pins RB2 and RB3. The bumperswitchisreadoffpinRA0. Thereisnothingcriticalaboutthecircuit; itmaybehardwiredonapro totyping board. I chose a simpler route. Images SI Inc. sells a fourservo motor controller board. This board has all the connections needed for the sensorsandservomotors. MyconnectionstothePCboardareshowninFig. 8.45. ApictureofthefinishedcircuitisshowninFig. 8.46. Noticeinthepic tureIusedterminalblockstoconnectthesensorarrayandbumperswitch. Program Uponpowerup, thedrivemotorisoff, andthemicrocontrollerbeginsscanning forthebrightestlightsource, usingtheservomotor. Ifalightsourceistoobright, therobotjumpsintoavoidmode. Inavoidmode therobotbacksawayfromthelightsourcebyreversingthedrivemotorwhile steeringthedrivewheelleftorright. Ifthelightisntsobrightastoactivate

116

ChapterEight

Light source

A cell in shadow; tracker rotates to right.

Equal illumination; no movement.

B cell in shadow; tracker rotates to left.

SIDE VIEW
Figure8.42 Operationofsensorarrayfortargetinglightsource.

theavoidmode, therobotsteersinthedirectionofthelightandactivatesthe drivewheelforward. Ifthebumperswitchisactivated, therobotassumesithashitanobstacle andsogoesintoavoidmode. Therobotusesavoidmodefortoobrightalight andcollisions. Ifthetiltswitchisnotactivated(nocollision), thentheprogram jumpstothebeginningandtheprocesscontinuesscanningandmovingtothe brightestlightsource. TheprogramiswrittenforthePicBasicProcompilerthatisprogrammed intoaPIC16F84. Theprogramshouldbeabletobecompiledandrunwith fewmodificationsonthePicBasicversion. IngroupvariancesinCdSsensors, drivemotors, robotstructure, andthelikecanbeadjustedforormodifiedin theprogram.
Turtleprogram
PicBasicProprogram
ReadCdScell#1onportbline1
ReadCdScell#2onportbline7
v1varbyte Variablev1holdsCdS#1information
v2varbyte Variablev2holdsCdS#2information

WaltersTurtle

117

Figure8.43 AttachingsensoryarraytodriveservomotorsUbracket.

v3varbyte s1varbyte s2varword rvvarbyte s1=150 rv=10 ctvarbyte

Variableforcalculation Variables1holdsservomotor#1pulsewidthinfo Variableforrandomfunction Variablervholdstherangevalue Initializesteeringservomotorfacingforward Adjustasneededforsmoothoperation Counter

Driveservomotor**continuousrotationinformation Connectedtopinportb.7**variablepulsewidthnumbers 157forward*165slowforward 167stop 169slowbackward*177backward start: potportb.2,255,v1 potportb.3,255,v2

ReadresistanceofCdS#1photocell ReadresistanceofCdS#2photocell

CheckbumperswitchDidIhitsomething? ifporta.0=0thenavoid Hitobstaclegointoavoidmode Isitsleepytime? ifv1<=230thenskp Isitdarkenoughtosleep?

118

ChapterEight

+5V Servo Motor 2

+5V Servo Motor 1

+5V

R1 4.7K C1 .1F

V1 100K CdS Cell

+5V R2 10K

13 12 11 10 9 8 7 6 3 2 1 18 17

C2 .1F 50V C3 .1F 50V

U1 14 VDD RB7 4 RB6 MCLR' RB5 16 RB4 OSC1 RB3 15 RB2 OSC2 RB1 RB0/INT
RA4/TOCKI RA3 RA2 RA1 RA0 VSS 5

X1 4MHz

Bumper switch

PIC 16F84

SW4

SW3

CdS Cell

V2 100K

Figure8.44 Schematicofrobot.

ifv2>230thenslp
Isittoobrighttosee?
skp:
ifv1>=12thenskip2
ifv2<12thenavoid
WhichwaydoIgo?
skip2:
ifv1=v2thenstraight
ifv1>v2thengreater
ifv1<v2thenlesser
straight:
pulsoutportb.6,s1
pulsoutportb.7,157
gotostart
greater:
v3=v1v2
ifv3>rvthenright
gotostraight
lesser:

Yes
Nosleepkeepmoving
Isittoobrighttolive?
Yes

NotsobrightshouldIsteer?
Lightisequalgostraight
Checklightintensitytoturnright
Checklightintensitytoturnleft
Goforwardinthedirectionyourefacing
Dontmovesteering
Goforward

ChecknumericaldifferencebetweenCdScells
Ifmorethanrvturnright
Ifnotgostraight

WaltersTurtle
Servomotor #1 Forward

119

Servomotor #2 Turn

Servomotor Signal

Servomotor Connector

1
S + S

2
+ S

3
+ S

4
+

Images SI Inc., NY
4.7K

Ground

+5V

470

Ser Out Gnd

DC Power Jack PJ-102B

10K

Top U1 16F 84 Reset

mottoB +

10K

9V Battery

Gnd

C1
C1

Gnd On Off C2

2 3 Servomotor Controller

To Bumper Switch

To Gnd Sensor Array

Figure8.45 UsinganexistingPCBboardforbuildingrobotselectronics.

v3 = v2v1 ifv3>rvthenleft gotostraight right: s1=s1+1 ifs1>225thens1=225 pulsoutportb.6,s1 pulsoutportb.7,165 gotostart left:

ChecknumericaldifferencebetweenCdScells Ifmorethanrvturnleft Ifnotgostraight Turnright Incrementvariables1toturnright Limits1to225 Movesteeringservomotor Goforwardslowly Turnleft

120

ChapterEight

Figure8.46 Closeupofelectriccircuitboard.

s1=s11
ifs1<65thens1=65
pulsoutportb.6,s1
pulsoutportb.7,165
gotostart
slp:
pulsoutportb.6,s1
pulsoutportb.7,167
gotostart
avoid:
randoms2
s1=s2/256
ifs1<65thens1=65
ifs1>225thens1=225
forct=1to125
pulsoutportb.6,s1
pulsoutportb.7,177
pause18
nextct
s1=150

Decrementvariables1toturnleft
Limits1to65
Movesteeringservomotor
Goforwardslowly

Goasleep
Dontmovesteering
Stopdriveservomotor

Avoidmode,send
Randomizes2
Reducerangeofs1to1to255
Setlowerlimit
Setupperlimit
Startcounter
Steer(turn)inarandomdirection
Reversedrivemotor(slow)
Pausetosendinstructionsat50Hz
Loop
Steerbacktocenter

WaltersTurtle gotostart

121

AddingSleepMode I added a sleep mode for occasions when the ambient light is very low. The robotmovesforwardwhenbothCdSsensorsreceiveapproximatelythesame lightintensity. TherobotsteersrightorleftwhenoneCdScellreceivesmore light than the other. If each CdS cell receives too much light or the bump switchisactivated, therobotgoesintoavoidmode. Power A9VbatteryonthePCboardsuppliesadequateelectricalpowerfortherobot forashorttime. AlthoughIusedthispowersupplyfortestingrobotfunction, youwillneedastrongerpowersupplyforextendeduse. ThePCBboardhasa dcvoltagesocketwhereanexternalpowersupplycanbeconnected. ThefinishedrobotisshowninFigs. 8.47and8.48. Behavior This robot exhibits the following behavior. In ambient light, no bright light source, therobottravelsinastraightline(orcircledependinguponthelast lightsourcetarget). Iftheambientlightistoobright, itjerksbackward. With amediocrelightsource, itwillaimandtraveltowardthelight. Theprogramcanbedevelopedfurthertoexploremoreinterestingandexotic behaviors. Beforewedoso, letsfirstlookathowthestandardprogramfunctions. FudgeFactor ThevariableRV(rangevalue)isthefudgefactor. Atthebeginningofthepro gramthevariableRVisassignedavalueof10. InmyprototypeIactuallyused anRVof2becauseIhadmatchedtheresistancevaluesofCdScells, asdis cussedearlier. Tolerance between the two CdS photoresistors may be increased or decreasedbymodifyingthenumericalvalueofthisvariable. Youmayneedto adjustthisvariableaccordingtohowcloselytheresistancevaluesofyourCdS cellsmatch. LightIntensity The program continually checks the light intensity received (resistance) by eachCdSsensorandthenmakesadecisionbasedonthosereadings. Themax imumreadingfromthesensoris255(totaldarkness). Iftheroomgetsdark enoughtogenerateavalueof230ineachCdScell, thentherobotgoesinto sleepmode.
Isitsleepytime?

122

ChapterEight

Figure8.47 Frontviewofturtlerobot.

Figure8.48 Sideviewofturtlerobot.

WaltersTurtle ifv1<=230thenskp ifv2>230thenslp Isitdarkenoughtosleep?


Yes

123

Theoppositeofsleepmodeisthetoobrighttolive. Ifthelightbecomestoo intense, thistriggerstheavoidmode.


Isittoobrighttosee?
skp: Nosleepkeepmoving ifv1>=12thenskip2 Isittoobrighttolive? ifv2<12thenavoid Yes

Increasingthenumericalvalue, inthiscase12, decreasesthelightintensity thatputstherobotintoavoidmode. Decreasingthenumericalvalueincreases thelightintensityneededtothrowtherobotintoavoidmode. Inmostcasesyou willwanttodecrease thisnumber. However, Iwouldadviseyounottogobelow anumericalvalueof9, becauseevenatfulllightsaturationoftheCdScell, its resistanceneverdropstozero. Andinmylightsaturationteststhesensornev eryieldedavaluelessthan5. Inthisrobot, intenselightpushestherobotintoavoidmode. Ifthiswerea truephotovorerobot, highlightintensitywouldputitintoafeedingmode. Handedness Inaddition, onecouldcreatehandednessintherobot(rightorlefthanded)by modifying either greater or lesser subroutines, not both. This will create a robotthatismorelikelytoturninonedirectionthanintheother.
greater:
v3=v1v2 ifv3>rvthenright gotostraight ChecknumericaldifferencebetweenCdScells
Ifmorethanrvturnright
Ifnotgostraight

Forinstance, ifRV 10, wecansubstitutethevalue7likethis


ifv3>7thenright

Then in the lesser subroutine the RV is kept the same. The result of this manipulationisthatwewouldcreatearobotthatismorelikelytoturntothe right. This robot offers opportunities to the robotists and experimenters for con tinuedexperimentationanddevelopmentinbothhardwareandsoftware. PartsList 12in 12insheetmetalsheetof22or24gauge (1)Aluminumbar18 in 12 in 32inlong (1)Aluminumbar18 in 12 in 1412 inlong (1)Aluminumbar18 in 12 in 2inlong

124

ChapterEight

(1)42oztorquehobbyservomotor(HS322) (1)Hobbyservomotor(HS425) (1)234indiameterdrivewheel (2)CdSphotocells, 100k dark, 10k light (1)10k, 14Wresistor (1)4.7k, 14Wresistor (2)22pFcaps (1)4MHzceramicresonatororXtal (1)(IC1)PICmicrocontroller(16F8404)
(1)Ubracketfordriveservomotor Miscellaneousneedsincludeperforatedboard, 116inthicktransparentplastic, 540 machine screw and nuts, plastic 632 1in machine screw, 632 brass nuts, 1inlong compression springs (2 lb). Aluminum bars, machine screws, tubing, andcompressionspringsareavailableinmostwellstockedhardware stores. Servomotorsmaybepurchasedathobbyshopsorelectronicsdistributors. ElectroniccomponentsmaybepurchasedfromRadioShack, ImagesSIInc., JamecoElectronics, JDRMicrodevices(seeSuppliersatendofbook). PCboard, servomotordrivewheel, andUbracketfordriveservomotormay bepurchasedfromImagesSIInc.

Chapter

9
BraitenbergVehicles
In1984ValentinoBraitenbergpublishedabooktitled VehiclesExperiments inSyntheticPsychology. InhisbookValentinodescribesanumberofwondrous vehiclesthatexhibitinterestingbehaviorsbasedontheuseofafewelectron icneurons. SimilarinconcepttoWaltersseminalneuralworkwithhisrobottortoises, Valentinosvehiclebehaviorismorestraightforward, makingitsomewhateas iertofollowboththeoreticallyandlogically. Thisalsomakesiteasiertoimple menthisideasintorealdesignsforrobots. InthischapterwewillbuildafewBraitenbergtypevehicles. At the heart of Braitenberg vehicles is his description of a basic vehicle, whichisasensorconnectedtoamotor. Braitenbergcontinuestoexplainthe relationshipbetweenthesensorandmotor. Therelationshipisessentiallythe connectionbetweenthesensorandmotor, andthisconnectionoughttobecon sideredasaneuron. Withtheconnectionconfiguredasaneuron, thestructure isshowninFig. 9.1. Insteadofavehiclewewilldescribethestructurediagram asasmallneuralnetwork. Atthefrontendofthenetworkwefindasensor, followedbytheneuron and finally the output motor. The sensor detects the intensity of light and outputs a proportional signal to the motor. Highintensity light produces highrpms(revolutionsperminute)fromthemotor. Lowintensitylightpro ducesslowrpms. Considerthesensorportionasmodularandinterchangeable. Othersensors can be plugged in and incorporated to detect any number of environmental variables, forexample, heat, pressure, sound, vibration, magneticfields(com pass), electricalfields, radioactivity, andgases(toxicorotherwise). Inaddition, themotor, likethesensor, representsasingularexampleofan outputmodule. Otheroutputmodulescouldincludeasecondneuron(orneur allayer), electriccircuit, on/offswitch, lightsource, etc.

125

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

126

ChapterNine

Figure9.1 Basicneuronsetup, sensorinput, neuron, andmotoroutput.

The neurons input is the output of the sensor, and the neurons output activates a motor in relationship to its input. The input/output relation ship oftheneuroncanbemadetobeoneofmanydifferentmathematical functions. The relationship may also be called connection strength or con nection function when you are reading the neural network literature. The relationshipisoneofthemostimportantvariableswecanmodifywhenpro grammingourrobot. NeuralI/ORelationships Whentheneuronisstimulated, itgeneratesanoutput. Asstated, therearea number of mathematical functions that can exist inside the neuron. These functions act upon the neurons input (sensor output) and pass through the resultstotheneuronsoutput. Letsexamineafewofthem. Positiveproportional. Asinputfromthesensorincreases, activation(rpms) ofthemotorincreasesinproportion; seeFig. 9.2.
Negativeproportional. Asinputfromthesensorincreases, activation(rpms)
ofthemotordecreasesinproportion(seeFig. 9.3).
Digital. As input from the sensor output exceeds a predetermined (programmed) threshold (that may be positive or negative), the motor is activated(seeFig. 9.4). Gaussian. As input from the sensor increases, output passes through a gaussianfunctionformotoractivation(seeFig. 9.5). Essentially the neuron may incorporate any mathematical function. It wouldperformthisfunctiononthesensoryinputtogenerateanappropriate output. Ihaveprovidedanexampleofonlyafewofthemorecommonfunc tionsavailable. Vehicles Using the basic neural setup, we can construct a few simple vehicles that exhibitinterestingbehaviors. Figure9.6illustratestwovehicleslabeledAand B. Bothvehiclesusethepositiveproportionalneuralsetupwithalightinten sitysensor.

BraitenbergVehicles

127

Figure9.2 Graphofpositivepro

portional transfer function. As sensor output increases, motor outputincreases.

Figure 9.3

Graph of negative proportional transfer function. As sensor output increases, motoroutputdecreases.

Figure9.4 Graphofdigitaltransferfunction. Assensoroutputincreases, output

remainsunchangeduntilthresholdisreached, thenoutputswitchesfullon.

VehicleA, ifbothsensorsareevenlyilluminatedbyalightsource, willspeed upand, ifpossible, runintothelightsource. However, ifthelightsourceisoff tooneside, thesensoronthesideofthelightsourcewillspeedalittlefaster thanthesensor/motoronotherside. Thiswillcausethevehicletoveeraway fromthelightsource(seeFig. 9.7). VehicleB, ifbothsensorsareevenlyilluminatedbyalightsource, willspeed up and, if possible, run into the light source (same as vehicleA). If the light sourceisofftooneside, vehicleBwillturntowardthelightsource(seeFig. 9.7).

128

ChapterNine

Figure9.5 Graphofgaussianfunction. Assensoroutputincreases, output followsagaussiancurve.

Figure9.6 WiringoftwoBraitenbergvehicleslabeledAandB.

Negativeproportionalneuralsetupswouldshowtheoppositebehavior. BuildingVehicles Itstimetoputthetheorytothetestandseeifitworks. Letsassemblethe materialsneededtobuildavehicle. Thephotovoresbasicoperatingprocedure islikeWaltersrobot. Ittracksandfollowsalightsource. Thebaseofthevehicleisasheetofaluminum8inlongby4inwideby 18 inthick. Wewillusetwogearboxmotorsforpropulsionandsteeringandone multidirectionalfrontwheel. Wewilltryanewconstructionmethodwiththisrobot. Insteadofsecuringthe gearbox motors with machine screws and nuts, we will use 3Ms industrial branddoublesidedtape. Thisdoublesidedtape, oncecured, isasstrongaspop rivets. Itriedtoseparateasampleprovidedby3M. Itconsistedoftwoflatpieces ofmetalsecuredwiththetape. EvenwhenIusedpliers, itwasimpossible. 3M statesthatthetaperequires24htoreachfullstrength. Youmaynotachievethe fullstrengthcapabilityofthetapeunlessyoufollowthe3Mprocedure.

BraitenbergVehicles

129

Figure9.7 FunctionofAandBBraitenbergvehicles.

Thegearboxmotorisa918Dtype(seeFig. 9.8). Thegearboxmotoratthe topofthepicturehasanorangecowlthatiscoveringthegears. Noticetheflat mountingbracketthatisperfectforsecuringtothevehiclebase. Thedouble sidedtapeiscutlengthwisetofitthebaseofbrackettothegearboxmotor. The exposedsideofthetapeisimmediatelysecuredtothegearboxmotorbracket. Thenthemotorispositionedonthebottomofthevehiclebase, theprotective coveringofthetapeisremoved, andthegearboxmotorisfirmlyplacedonto thebottomofthevehiclebase(seeFig. 9.9). Thesecondgearboxmotorissecuredtotheothersideinasimilarmanner.
Backwheels

Theshaftdiameterofthegearboxmotorisalittletoosmalltomakeagood frictionfittotherubberwheel. Tobeefupthediameter, cutasmall1to1.5 inlengthofthe3mmtubing; seePartsList. Placethetubingoverthegearbox motor shaft, and collapse the tubing onto the shaft, using pliers. There is a smallcutawayonthegearboxmotorshaft(seeFig. 9.10). Ifyoucancollapse thetubingintothiscutaway, youwillcreateastrongfitbetweentheshaftand thetubingthatwillnotpulloffeasily(seeFig. 9.11). Thetubingaddstothediameteroftheshaftandwillmakeagoodfriction fitwiththerubberwheels(seeFig. 9.12). Simplypushthecenterholesofthe wheelsontothetubing/shaft, andyouarefinished.

130

ChapterNine

Figure9.8 A918D100:1Gearboxmotor.

Figure9.9 3Mdoublesidedtapeisusedtosecuregearboxmotortobase

ofvehicle.

BraitenbergVehicles

131

Figure9.10 Gearboxmotorshowingcutawayonoutputshaft.

Figure9.11 A112inlengthof3mmdiametertubingattachedtogearbox

motorshaft.

Frontwheels

Steeringisaccomplishedbyturningonoroffthegearboxmotors. Forinstance, turningontherightwhiletheleftgearboxmotorisoffwillturnthevehicletothe left, andviceversa. Insimilarvehiclesmanytimestherobotistswillforgofront wheelsentirelyanduseaskidinstead. Thisallowsthevehicletoturnwithout concernaboutthefrontwheelspivotingandturningintheproperdirection Themultidirectionalwheelaccomplishesmuchthesamethingasaskid, but doessowithlessresistance. Figure9.13showsthemultidirectionalwheel. It isconstructedusingrollersarounditscircumferencethatallowthewheelto rotateforwardandmovesidewayswithoutturning.

132

ChapterNine

Figure9.12 Rubberwheelusedtofrictionfitontogearboxmotorshaft.

ThemultidirectionalwheelisattachedusingabasicUshapedbracket(see Fig. 9.14). Thebracketissecuredtothefrontofthevehiclebaseusingthe3M doublesidedtape. ThemultidirectionalwheelissecuredinsidetheUbracket usingasmall2.25inpieceof1420threadedrodandtwomachinescrewnuts (seeFig. 9.15). Withthemotorsandthemultidirectionalwheelmounted, weareready for the electronics. Figure 9.16 shows the underside of the Braitenberg vehicleatthispoint. Idrilleda1 4inholeinthealuminumplatetoallows wires from the gearbox motors underneath the robot to be brought top side. TheschematicfortheelectroniccircuitisshowninFig. 9.17. Ibuiltthecir cuitontwosmallsolderlessbreadboards. Youcandothesameorhardwirethe componentstoaPCboard. Thecircuitisprettystraightforward. Thegearbox motorsrequireapowersupplyof1.5to3.0V. Ratherthanplaceanothervolt ageregulatorintothecircuit, Iwiredthreesilicondiodesinseriesoffthe5V dcpower. Thevoltagedropacrosseachdiodeisapproximately0.7V. Acrossthe threeseriesdiodes(0.7 3 2.1V)equalsapproximately2.1V. Ifwesubtract this voltage drop from our regulated 5V dc power supply, we can supply approximately3Vdctothegearboxmotors.

BraitenbergVehicles

133

Figure9.13 Multidirectionalwheel.

Figure9.14 DrawingofUbracket formultidirectionalwheel.

CdSphotoresistorcells

AswithWaltersturtletyperobot, weusetwoCdSphotoresistorcells. TheCdS photoresistors(seeFig. 9.18)usedinthisrobothaveadarkresistanceofabout 100k andalightresistanceof10k. TheCdSphotoresistorstypicallyhave largevariancesinresistancebetweencells. ItisusefultouseapairofCdScells forthisrobotthatmatches, asbestasonecanmatchthem, inresistance. SincetheresistancevaluesoftheCdScellscanvarysogreatly, itsagood ideatobuyafewmorethanyouneedandmeasuretheresistancestofinda pairwhoseresistancesareclose. Thereareafewwaysyoucanmeasurethe resistance. Thesimplestmethodtouseavoltohmmeter, settoohms. Keepthe lightintensitythesameasyoumeasuretheresistance. ChoosetwoCdScells thatarecloselymatchedwithinthegroupofCdScellsyouhave.

Figure 9.15 Multidirectional wheel and U bracket attached to vehicle

base.

Figure 9.16 Underside of Braitenberg vehicle showing wheels and gearbox motordrive. 134

+5 V D3 D4 D5 1N4002 1N4002 1N4002


+

+3 V

6V
+

U2 LM2940 1 I R 2 C5 100 F 20 V 14 VDD MCLR' OSC 1 OSC 2 4 +5 V Vcc U1 O 3


+

C4 10 F 20 V

R1 4.7 k

C1 .1 F

+3 V Vcc R2 330 D1 1N4002 Q1 2N3904 Sensor 2 V1 50 k C2 .1 F Sensor 1 CdS Photocell CdS Photocell

+3 V Vcc

X1 16 4 MHz 15

R3 330

D2 1N4002

13 12 11 10 9 8 7 6

RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0/INT

Q1 2N3904

V1 50 k C3 .1 F

3 2 1 18 17

RA4/TOCKI RA3 RA2 RA1 RA0 VSS 5

PIC 16F84

DC Motor

DC Motor

Figure9.17 SchematicofBraitenbergvehicle.

135

136

ChapterNine

Figure 9.18

CdS photoresistor

cell.

ThesecondmethodinvolvesbuildingasimplePIC16F84circuitconnected to an LCD display. The advantage of this circuit is that you can see the responseoftheCdScellsundervaryinglightconditions. Inaddition, youcan see the difference in resistance between the CdS cells when they are held underthesameillumination. ThisnumericdifferenceoftheCdScellsunder exactlightingisusedasafudgefactorinthefinalturtleprogram. Ifyoujust testtheCdScellswithjustanohmmeter, youwillendupusingalargerfudge factorfortherobottooperateproperly. The schematic for testing the CdS cells is shown in Fig. 9.19. The circuit, builtonaPICExperimentersBoard, isshowninFig. 9.20. ThePicBasicPro testingprogramfollows:
CdScelltest
PicBasicProprogram
Serialcommunication1200baudtrue
Serialinformationsentoutonportbline0
ReadCdScell#1onportbline1
ReadCdScell#2onportbline7
v1varbyte Variablev1holdsCdS#1information v2varbyte Variablev2holdsCdS#2information Pause1000 AllowtimeforLCDdisplay main: potportb.1,255,v1 ReadresistanceofCdS#1photocell potportb.7,255,v2 ReadresistanceofCdS#2photocell Displayinformation seroutportb.0,1,[$fe,$01] Clearthescreen

BraitenbergVehicles

137

+5V
14 VDD

R1 4.7K U1 4 X1 16 4MHz 15 C1 .1F

V1 100K CdS Cell

13 12 11 10 9 8 7 6

C2 .1F 50V C3 .1F 50V

RB7 RB6 MCLR' RB5 OSC1 RB4 RB3 RB2 OSC2 RB1 RB0/INT RA4/TOCKI RA3 RA2 RA1 RA0

Serial Line +5V SW4

3 2 1 18 17

PIC 16F84

VSS

LCD Display
CdS Cell V2 100K Gnd
Figure9.19 SchematicoftestcircuittomatchCdScellsforuseinBraitenbergvehicle.

pause25
seroutportb.0,1,[CdS1=]
seroutportb.0,1,[#v1]
seroutportb.0,1,[$fe,$c0] pause5
seroutportb.0,1,[CdS2=]
seroutportb.0,1,[#v2]
pause100
gotomain

Movetoline2

NoticeinFig. 9.20thatCdScell1isreading37andCdScell2isreading46 underidenticallighting. Keepinmind, thisisacloselymatchedpairofCdS cells. Wecanuseafudgefactorof15points, meaningthataslongastheread ingsbetweencellsvaryfromeachotherby15points, themicrocontrollerwill considerthemnumericallyequal.
Trimmingthesensorarray

IfyouareusingtheExperimentersBoard, youcantrimandmatchtheCdS cellstooneanother. Doingsoallowsyoutoreducethefudgefactorandpro ducesacrisperresponsefromtherobot. TypicallyoneCdScellresistancewillbelowerthanthatoftheotherCdS cell. To the lowerresistance CdS cell add a 1k (or 4.7k) trimmer poten tiometer in series (see Fig. 9.21). Adjust the potentiometer (trim) resistance untiltheoutputsshownontheLCDdisplayequaleachother. TrimtheCdS cellunderthesamelightingconditionsinwhichtherobotwillfunction. The

138

ChapterNine

Figure9.20 TestcircuitbuiltonPICExperimentersBoard.

+5V
14 VDD

R1 4.7K U1 X1 4MHz C1 .1F

V1 100K CdS Cell

13 12 11 10 9 8 7 6

C2 .1F 50V C3 .1F 50V

RB7 4 RB6 MCLR' RB5 OSC1 16 RB4 RB3 15 RB2 OSC2 RB1 RB0/INT RA4/TOCKI RA3 RA2 RA1 RA0

1K V3 SW4

Serial Line +5V

3 2 1 18 17

PIC 16F84

VSS 5

LCD Display
CdS Cell V2 100K Gnd
Figure9.21 Schematicoftestcircuitwithtrimmerpotentiometer.

BraitenbergVehicles

139

reasonforthisisthatwhenthelightintensityvariesfromthatnominalpoint towhichyouvetrimmedtheCdScell, theresponsesoftheindividualCdScells tochangesinlightintensityalsovaryfromoneanotherandthenarenotas closelymatched.


PIC16F84microcontroller

The 16F84 microcontroller used in this robot simulates two neurons. Each neuronsinputisconnectedtoaCdScell. Theoutputofeachneuronactivates onegearboxmotor. IntheprogramIputinafudgefactor, orrange, overwhichthetwoCdScells can deviate from one another in resistance readings and still be considered equal. If the robot doesnt travel straight ahead when the two CdS cells are equallyilluminated, youcanincreasetherangeuntilitdoes.
PicBasicCompilerprogram Braitenbergvehicle1
start:
pot1,255,b0
pot2,255,b1
Ifb0=b1thenstraight
ifb0>b1thenleft
ifb1>b0thenright
straight:
high3:high4
gotostart
left:
b2=b0b1
ifb2>15thenleft1
gotostraight
left1:
high3:low4
gotostart
right:
b2=b1b0
ifb2>15thenright1
gotostraight
right1:
high4:lo3
gotostart

ReadCdScell#1
ReadCdScell#2

Comparenumericalvalues+/15
Ifgreaterthan15turnleft
Ifnotgotostraightsubroutine
Turnleft
Motorcontrol

Comparenumericalvalues+/15
Ifgreaterthen15points
Turntowardtheright
Ifnotgostraight
Turnright
Motorcontrol
Doagain

Testing

ThefinishedrobotisshowninFig. 9.22. ForpowerIused4AAcellbatteries. IpointedoneCdScelltotheleftandtheothertotheright(seeFig. 9.23). To

140

ChapterNine

Figure9.22 FinishedBraitenbergvehicle.

Figure9.23 CloseupofCdScellsmountedinsolderlessbreadboard.

BraitenbergVehicles

141

testtherobotsfunction, Iusedaflashlight. Usingtheflashlight, Iwasableto steerthemobileplatformaroundbyshiningtheflashlightontheCdScells. SecondBraitenbergVehicle(AvoidanceBehavior) Giventhewaytherobotiscurrentlywired, itisattractedtoandsteerstoward abrightlightsource. Byreversingthewiringgoingtothegearboxesyoucan createtheoppositebehavior. PartsList (1)Microcontroller(16F84) (1)4.0MHzcrystal (2)22pFcaps (1)0.1Fcap (1)100Fcap (1)10Fcap (2)0.1Fcaps (2)330, 14Wresistors (1)4.7k, 14Wresistor (2)CdSphotoresistorcells(seetext) (2)100:1gearboxmotors(918D) (2)NPNtransistors(2N3904) (5)Diodes(1N4002) (2)2.25indiameterwheels (1)Multidirectionalwheel (1)Voltageregulator(lowdropdownvoltage5V)(LM2940) Miscellaneous items needed include 6in length of 3mm hollow tubing, alu minum 8 in 4 in 18 in thick, 2 solderless breadboards, 3M doublesided tape, batteryholderfor4Dbatteries, 3in 1420threadedrod, and2machine screwnuts.

Thispageintentionallyleftblank.

Chapter

10
HexapodWalker
Legged walkers are a class of robots that imitate the locomotion of animals andinsects, usinglegs. Leggedrobotshavethepotentialtotransverserough terrainsthatareimpassablebystandardwheeledvehicles. Itiswiththisin mindthatrobotistsaredevelopingwalkerrobots. ImitationofLife Leggedwalkersmayimitatethelocomotionstyleofinsects, crabs, andsome times humans. Biped walkers are still a little rare, requiring balance and a gooddealmoreengineeringsciencethanmultileggedrobots. Abipedalrobot walkerisdiscussedindetailinChap. 13. Inthischapterwewillbuildasix leggedwalkerrobot. SixLegsTripodGait Usingasixleggedmodel, wecandemonstratethefamoustripodgaitusedby themajorityofleggedcreatures. Inthefollowingdrawingsadarkcirclemeans thefootisfirmlyplantedonthegroundandissupportingtheweightofthe creature(orrobot). Alightcirclemeansthefootisnotsupportinganyweight andismovable. Figure10.1Ashowsourwalkeratrest. Allsixfeetareontheground. From the resting position our walker decides to move forward. To step forward, it leaves lifts three of its legs (see Fig. 10.1B, white circles), leaving its entire weightdistributedontheremainingthreelegs(darkcircles). Noticethatthe feetsupportingtheweight(darkcircles)areintheshapeofatripod. Atripod isaverystableweightsupportingposition. Ourwalkerisunlikelytofallover. Thethreefeetthatarenotsupportinganyweightmaybelifted(whitecircles) andmovedwithoutdisturbingthestabilityofthewalker. Thesefeetmovefor ward.
143

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

144

ChapterTen

Figure10.1 Samplebiologicaltripodgait.

Figure 10.1C illustrates where the three lifted legs move. At this point, the walkers weight shifts from the stationary feet to the moved feet (see Fig. 10.1D). Noticethatthecreaturesweightisstillsupportedbyatripod position of feet. Now the other set of legs moves forward and the cycle repeats. Thisiscalleda tripodgait, becauseatripodpositioningoflegsalwayssup portstheweightofthewalker. ThreeServomotorWalkerRobot TherobotwewillbuildisshowninFig. 10.2. Thiswalkerrobotisacompro mise in design, but allows us to build a sixlegged walker using just three servomotors. Thethreeservomotorhexapodwalkerdemonstratesatruetri podgait. Itisnotidenticaltothebiologicalgaitwejustlookedat, butclose enough. ThisleggedhexapodusesthreeinexpensiveHS322(42oztorque)servo motorsformotionandonePIC16F84microcontrollerforbrains. Themicro controller stores the program for walking, controls the three servomotors, and reads the two sensor switches in front. The walking program contains subroutines for walking forward and backward, turning right, and turning left. Thetwoswitchsensorspositionedinthefrontofthewalkerinformthe microcontrollerofanyobstaclesinthewalkerspath. Basedonthefeedback fromtheseswitchsensors, thewalkerwillturnorreversetoavoidobstacles placedinitspath. Function The tripod gait I programmed into this robot isnt the only workable gait. Thereareotherperfectlyusablegaitsyoucandeveloponyourown. Consider

HexapodWalker

145

Figure10.2 Hexapodrobot.

thiswalkingprogramaworkingstartpoint. Tomodifytheprogram, itsimpor tanttounderstandboththeprogramandrobotlegfunctions. Firstletslookat therobot. Attherearofthewalkeraretwoservomotors. OneisidentifiedasLforthe leftside, theotherasRfortherightside. Eachservomotorcontrolsboththe frontandbacklegsonitsside. Thebacklegisattacheddirectlytothehornof theservomotor. Itiscapableofswingingthelegforwardandbackward. The back leg connects to the front leg through a linkage. The linkage makes the frontlegfollowtheactionofthebacklegasitswingsforwardandback. Thethirdservomotorcontrolsthetwocenterlegsofthewalker. Thisservo motor rotates the center legs 20 to 30 clockwise (CW) or counterclockwise (CCW), tiltingtherobottoonesideortheother(leftorright). Withthisinformationwecanexaminehowthisleggedrobotwillwalk. MovingForward Westartintherestposition(seeFig. 10.3). Asbefore, eachcirclerepresentsa foot, andthedarkcirclesshowtheweightbearingfeet. Noticeintherestposi tion, thecenterlegsdonotsupportanyweight. Thesecenterlegsaremadeto be1/8 inshorterthanthefrontandbacklegs. InpositionAthecenterlegsarerotatedCWbyabout25 fromcenterposi tion. Thiscausestherobottotilttotheright. Theweightdistributionisnow onthefrontandbackrightlegsandthecenterleftleg. Thisisthestandard tripodpositionasdescribedearlier. Sincethereisnoweightonthefrontand backleftlegs, theyarefreetomoveforwardasshownintheBpositionof Fig. 10.3.

146

ChapterTen

Figure10.3 Forwardgaitforhexapodrobot.

IntheCpositionthecenterlegsarerotatedCCWbyabout25 fromcenter position. Thiscausestherobottotilttotheleft. Theweightdistributionisnow onthefrontandbackleftlegsandthecenterrightleg. Sincethereisnoweight onthefrontandbackrightlegs, theyarefreetomoveforward, asshowninthe Dposition. InpositionEthecenterlegsarerotatedbacktotheircenterposition. The robotisnotinatiltedpositionsoitsweightisdistributedonthefrontand back legs. In the F position, the front and back legs are moved backward simultaneously, causing the robot to move forward. The walking cycle can thenrepeat. MovingBackward Westartintherestposition(seeFig. 10.4), asbefore. InpositionAthecen terlegsarerotatedCWbyabout25 fromcenterposition. Therobottilts to the right. The weight distribution is now on the front and back right legsandthecenterleftleg. Sincethereisnoweightonthefrontandback leftlegs, theyarefreetomovebackward, asshownintheBpositionofFig. 10.4.

HexapodWalker

147

Figure10.4 Backwardgaitforhexapodrobot.

IntheCpositionthecenterlegsarerotatedCCWbyabout25 fromcenter position. Therobottiltstotheleft. Sincethereisnoweightonthefrontand backrightlegs, theyarefreetomovebackward, asshownintheDposition. In position E the center legs are rotated back to their center position. The robotisnotinatiltedposition, soitsweightisdistributedonthefrontandback legs. IntheFposition, thefrontandbacklegsaremovedforwardsimultane ously, causingtherobottomovebackward. Thewalkingcyclecanthenrepeat. TurningLeft ThelegmotionsequencetoturnleftisshowninFig. 10.5. InpositionAthe centerlegsarerotatedCWbyabout25 fromcenterposition. Therobottiltsto theright. Theweightdistributionisnowonthefrontandbackrightlegsand thecenterleftleg. Sincethereisnoweightonthefrontandbackleftlegs, they arefreetomoveforward, asshowninFig. 10.4. IntheBposition, thecenterlegsarerotatedCCWbyabout25 fromcenter position. Therobottiltstotheleft. Sincethereisnoweightonthefrontand backrightlegs, theyarefreetomovebackward, asshownintheCposition.

148

ChapterTen

Figure10.5 Turningleftgaitforhexapodrobot.

InpositionD, thecenterlegsarerotatedbacktotheircenterposition. The robotisnotinatiltedposition, soitsweightisdistributedonthefrontand backlegs. Inposition, theleftlegsmovedbackwardwhiletherightlegsmoved forward, simultaneouslycausingtherobottoturnleft. Ittypicallytakesthree turningcyclestoturntherobot90. TurningRight Turningrightfollowsthesamesequenceasturningleft, withthelegpositions reversed. Construction ForthemainbodyIusedasheetofaluminum3inwide 9inlong 0.032 in thick. The servomotors are mounted to the front of the body (seeFig. 10.6). Thefour11/64indiameterholesalittlepasthalfwaydownthemainbodyare for mounting the center servomotor. These four holes are offset to the right side. Thisisnecessarytoaligntheservomotorshorninthecenterofthebody.

HexapodWalker
1-1/16
5/8

149

1-1/16
5/8

11/16

1-3/16

2-9/16
1/2 SERVO-

MOTOR HOLE PLACEMENT


7/8 7/8

1/2 HOLE TO PASS WIRES THROUGH

2-1/2

FOUR 11/64 BRACKET HOLES FOR 3/16 CENTER SERVOMOTOR

3 1 PIVOT HOLES FOR LEGS


3/4 3/4

3 ALL DIMENSIONS IN INCHES

Figure10.6 Diagramofrobotbase.

Thebottomtwoholesareformountingthepivotsforthetwobacklegs. Use a punch to dimple the metal in the center of each hole you plan to drill. Thiswillpreventthedrillbitfromwalkingwhenyoudrillthehole. If you dont have a punch available, use the pointed tip of a nail for a quick substitute.

150

ChapterTen
1/16 HOLE (FOR 0-80 SCREWS) 1/4

HOLE

1/4

HOLE

3/4

3/4

2-3/4

2-3/4

BEND 90 3-3/4

3-1/4

FRONT LEG (QUAN. 2) BACK LEG (QUAN. 2) ALL DIMENSIONS IN INCHES

Diagram of robot legs(frontandback).


Figure 10.7

Thelegsfortherobotaremadefrom1/2inwide 1/8inthickaluminumbar stock(seeFig. 10.7). Therearefourdrilledholesneededinthetwobacklegs. Thethreeholesthatareclusteredtogethertowardoneendofthelegarefor mountingthelegtoaservomotorhorn. Thetwo1/16inholesallowa080screw topassthrough. Thecentered1/4inholeallowsyoutoremoveorattachtheser vomotorscrewthatholdstheservomotorhorn(andlegassembly)totheser vomotor. Makesurethesethreeholeslineupwiththeholesontheservomotor hornyouintendtouse. Thefrontlegsonlyneedtwoholesoneforthepivotandtheotherforthe linkage. Alsonoticethatthefrontlegsare0.25inshorterthanthebacklegs. Thiscompensatesfortheheightoftheservomotormountinghornontheback servomotors where the back legs are attached. Shortening the front legs makestherobotplatformapproximatelylevel.

HexapodWalker

151

90 TWIST 90

13/4

90 53/4 MATERIAL 1/8 1/2 91/4 ALUMINUM BAR ALL DIMENSIONS IN INCHES

Figure10.8 Diagramofcentertiltlegs, whichareconstructedofasinglepiece ofaluminumandare1/8 inshorterthanthefrontandbacklegs.

Aftertheholesaredrilled, weneedtobendthealuminumbarintoshape. Securethealuminumbarinavise23/4 infromtheendwiththedrilledholes. Pressureisappliedtobendthealuminumbarata90 angle. Itsbesttoapply pressureatthebaseofthealuminumbarclosetothevise. Thiswillbendthe legata90 angle, whilekeepingthelowerportionofthelegstraightwithout anybowingofthelowerportion. The center legs are made from one piece of aluminum (see Fig. 10.8). The centerlegsareabout 1/8 inshorterthanthefrontandbacklegswhenmount edtotherobot. Sowhencentered, thelegsdonotsupportanyweight. These legsarefortiltingtherobottotheleftorright. Thelegstilttherobotbyrotat ingthecenterservomotorapproximately20. Toproducethecenterlegs, firstdrilltheservomotorhornsmountingholes inthecenterofthe 1/8in 1/2in 91/4inaluminumbar. Thisshouldbesimi lartothethreeclusteredholesyoudrilledinthebacklegs. Nextsecurethe aluminumbarinavise. Thetopoftheviseshouldholdthealuminumbar 3/4 infromthecenterofthealuminumbar. Grabthealuminumbarwithpliers about 1/2 inabovethevise. Keepingasecuregripwiththepliers, slowlytwist thealuminumbar90. Dontgofast, oryoucouldeasilysnapthealuminum bar. Repeatthetwistontheotherside. Afterthetwo90 twistshavebeenmade, maketheother90 bendforthe legs, aswehavedonebeforeforthefrontandbacklegs.
Mountingtheservomotors

Thebackservomotorsareattachedtothealuminumbodyusingplastic632 machinescrewsandnuts. ThereasonIusedplasticscrewsisthattheplas

152

ChapterTen

ticisalittleflexible, allowingthedrilledholestobeslightlyoffcenterfrom themountingholesontheservomotorwithoutcreatingaproblem. Thelegsareattachedtotheservomotorsplastichorn. ForthisIused080 machinescrewsandnuts. Whenyoumounttheservomotorhornontheservo motor, make sure that each leg can swing forward and backward an equal amountfromaperpendicularposition.
Legpositioning

Thelegsmustbepositionedaccurately, orthewalkingprogramwillnotcause thehexapodrobottowalkproperly. ToaidinthispositioninglookatFig. 10.9. Thenumbersnexttothelegpositionsrepresentthepulsewidthoutputsignal fortheservomotors. Thecircuitwewillusetocontrolandpowerthehexapodwalkermayalsobe usedtoadjustthelegpositions. AsimplifiedschematicisshowninFig. 10.10 thatisusefulforadjustingthelegs. Thisschematicisalmostidenticaltothe schematicthatwillcontroltherobot; theonlydifferenceisthatthetwosensor switchesareremoved. Thelegadjustmentprogramissmall; seebelowforboth PicBasicProandPicBasicversions. IfyoudecidetobuythePCBboardforthisrobot(Fig. 10.22), youcanusethe PCBboardforthistestcircuitandprogram. Toalignthelegs, firstdisconnecttheservomotorhornfromtheservomo tor by unscrewing the center mounting screw from the horn. Once the screwisremoved, pullthehornoff. Keepthelegattachedtothehorn. Apply powertotheservomotorandconnectthecontrollineoftheservomotorto RB4. Thiswillcentertheservomotorsrotationalposition. Nowreattachthe servomotorhorntotheservomotor, positioningthelegtobeinthecenter position, asshowninFig. 10.9. Locktheservomotorhorninplace, usingthe centerscrew. Thelegisnowinproperposition. Byconnectingtheservomo

Figure10.9 Diagramoflegposi tionsrelatingtopulsewidths.

HexapodWalker

153

+5 V
14

+5 V Servo Motor Tilt Servo Motor Right

+5 V Servo Motor Left

13 12 11 10 9 8 7 6 3 2 1 18 17

VDD
RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0/INT RA4/TOCKI RA3 RA2 RA1 RA0 VSS 5 MCLR OSC1 4

U1

R1 4.7 K X1

C1 .1 F

16 4 MHz

OSC2

15

6-9 V
+

U2 7805
1

I
2

+5 V

PIC 16F84

Figure10.10 Schematicoftestcircuit.

torcontrollinetopinsRB5andRB6, youcanverifythelegsfrontandback swing. Adjusttheprogramifnecessarytoensureaproperswing. Whenswitchingaservomotorfrompintopin, youmustpowerdownthecir cuitfirst. Ifyoujustswitchpinswithoutpoweringdown, themicrocontroller couldlatchupandyouwillgetinaccuratepositioning.
Legadjustmentprogram(PicBasicPro)for16f84microcontroller
start: pulsoutportb.4,150 Pinrb4 pulsoutportb.5,120 Pinrb5 pulsoutportb.6,180 Pinrb6 pause18 gotostart end

Legadjustmentprogram(PicBasic)for16f84microcontroller
start:
pulsout4,150 Pinrb4
pulsout5,120 Pinrb5
Pinrb6
pulsout6,180 pause18
gotostart
end

154

ChapterTen

VIEW A

PIVOT

BINDING POST LEG BODY

PLASTIC WASHERS SCREW ALL DIMENSIONS IN INCHES

VIEW A
Figure10.11 Diagramofrobotbasewithfrontandbackleglinkage. ViewAshowsdetailofpivot forfrontlegs.

Linkage

The linkage between the front and back legs is made from standard Radio Control(RC)clevislinkage(seeFig. 10.11). Intheprototyperobotthelinkageis 63/4 incentertocenter. Thelinkagefitsinsidetheholesinthefrontandbacklegs. Thebacklegsmustbeattachedtothebodyoftherobotbeforeyoumakethe linkage. The pivot for the front legs is made from a 3/8in binding post and screw. ThelegisattachedasshowninthecloseupinFig. 10.11. Theplastic washersunderneaththebodyarenecessary. Theyfillupthespacebetweenthe aluminumbodyandthebottomofthescrew. Thiskeepsthelegclosetothealu minumbodywithoutsagging. Ichooseplasticwashersforlessfriction. Donot usesomanywashersthatforceiscreated, bindingthelegtothebody. Thejoint shouldpivotfreely.
Center(tilt)servomotor

ToattachthecenterservomotortothebodyrequirestwoLshapedbrackets (seeFig. 10.12). Drilltheholesandbendata90 angle.

HexapodWalker

155

Figure10.12 Closeupofclevislinkage.

AttachthetwoLbracketstothecenterservomotor, usingtheplasticscrews andnuts(seeFig. 10.13). Nextmountthecenterservomotorassemblyunder the robot body. Align the four holes in the body with the top holes in the L brackets. Securewithplasticscrewsandnuts. Youmustalignthecenterlegsonthecenterservomotorproperly, orelsethe robotwillnottiltproperly. Firstremovethehornfromthecenterservomotor. Then attach the center leg to the removed horn, using the 080 screws ands nuts. Applythecentercontrolsignal(RB4fromFig. 10.10)tothecenterservo motor. Withtheservomotorcentered, reattachthehorn/centerlegassemblyto the servomotor, making sure that the legs are in the center position when securingitinposition. Oncethecenterlegisattached, youcanremovepower fromtheservomotor. Figures10.14and10.15showtheundersideandtopside ofthehexapodrobot.
Sensors

This hexapod has two front switch sensors for detecting obstacles (see Fig. 10.16). The switch is a miniature snapaction flat lever arm, model number TFCGV3VT185BC manufactured by C&K Components. The levers on the switches are retrofitted with feelers that extend the range of the levers for wardandtotheside. Thefeelersaremadewithminiaturemetaltubingorstiff wire(aluminum, steel, orcopper).

156

ChapterTen

BEND 90

Figure10.13 DiagramofLbracket

neededfortiltservomotor.
ALL DIMENSIONS IN INCHES

Figure10.14 Tiltservomotorwith bracketsreadytobeattachedto robotbase.

Toattachthefeelerstothelever, Iuseda 3/8inlongpieceofsmallrubber tubing. I slid two sections of tubing onto the lever, then slid the stiff wire underneaththetubing(seeFig. 10.17). Attachingtheswitchestothefrontofthehexapodrequiredasmallfixture topreventthemountingscrewsfortheswitchesfromgettinginthewayofthe movingfrontlegs. Thefixtureismadefromtwopiecesofwood. Onepieceof woodmeasures 1/2 inwide 1/4 inthick 1inlong. Thesecondpieceofwood measures3/4 inwide 1/4 inthick 3inlong.

HexapodWalker

157

Figure10.15 Tiltservomotorattachedtorobotbase.

Figure10.16 Snapactionleverswitchusedforfrontobstaclesensors.

Figure10.17 Bottomviewofswitchassemblyshowingfeelers.

158

ChapterTen

Figure10.18 Switchassemblycutawaydrawing.

Figure 10.18 illustrates the construction of the switch assembly. The two switchesaremounteddiagonallyonthe3inlongpieceofwoodusingplastic machinescrewsandnuts. The1inlongpieceofwoodismountedontopofthe 3inlongpieceofwood. Twoholesaredrilledthroughtheroboticbaseandtwo piecesofwood. Theassemblyismountedtotheroboticbaseusingtwoplastic machinescrewsandnuts. Figures 10.19 and 10.20 show the front and bottom views of the switch assembly.
Electronics

Figure 10.21 shows the schematic for the servomotors and PIC microcon troller. Noticethe6Vbatterypackispoweringthemicrocontrolleraswellas theservomotors. Thebatterypackisa16VunitusingfourAAbatteries. Themicrocontrollercircuitmayalsobebuiltonasmallprintedcircuitboard thatisavailablefromImagesSIInc. (seeFig. 10.22). Therobotwillfunction forashorttimeusingafresh9Vbattery, itwilldepletequickly. Asecondary batterypackmaybelaidontopofthealuminumbodyandconnectedtothePC boardusingapowerplug.

HexapodWalker

159

Figure10.19 Frontviewofswitchassemblyattachedtorobotbase.

Figure10.20 Bottomviewcloseupofswitchassembly.

Figure10.23showsthecompletedwalkerreadytorun.
Microcontrollerprogram

The16F84microcontrollercontrolsthethreeservomotors, usingjustthreeI/O lines. Thisleaves10availableI/Olinesandplentyofprogrammingspaceleft overtoimproveandaddtothisbasicwalker. Theprogramfollows:


Hexapodwalker
Notes
Servomotorconfiguration
Leftleg(s)servomotorconnectedtorb4
Rightleg(s)servomotorconnectedtorb5
Centertiltservomotorconnectedtorb6
Pulsewidthoutsignalsforfollowingservomotors:
Leftleg(150center)(180forward)(120back)
Rightleg(150center)(120forward)(180back)
Tilt(left170)(right130)(center150)

160

ChapterTen
+5 V +5 V +5 V Servo Motor Tilt +5 V Servo Motor Right +5 V Servo Motor Left
13 12 11 10 9 8 7 6 3 2 1 18 17

+5 V

14

VDD
RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0/INT RA4/TOCKI RA3 RA2 RA1 RA0 VSS 5 4 MCLR

U1

R1 4.7 K X1

C1 .1 F

R3 10 K

R2 10 K

OSC1

16 4 MHz

OSC2

15

PIC 16F84

SW1 Right

SW2 Left

6-9 VDC
+

U2 7805
1

I
2

+5 V

Figure10.21 Schematicofhexapodcircuit.

Tilt Servomotor Right Servomotor Left Servomotor 1 2 3 D1 + 4 Images SI Inc. NY

470

LED

Ser Out Gnd

4.7 K

DC Power Jack PJ-102B Top mottoB +

10 K 10 K

10 K 10 K

10 K 10 K

10 K 10 K

10 K

U1 16F84 Reset

9V Battery

C1 On 1 SW2 Left SW1 Right 2 3 4 Servomotor Controller Off

+ C2

Figure10.22 PlacementofcomponentsonstockPCboardavailablefromImagesSIInc.

C1

HexapodWalker

161

Figure10.23 Finishedrobot.

Declarevariables lsvarbyte rsvarbyte csvarbyte ctvarbyte b0varbyte b1varbyte Definevariables


ls=150
rs=150
cs=150
pause250
start:
Readforwardsensors

Leftservomotorpulsewidth Rightservomotorpulsewidth Centerservomotorpulsewidth Count Count Count

Frontcollision?
if(porta.1=0&&porta.2=0)then
Bothleftandrightsensorsarehit,movebackward
forb0=1to3
gosubbackstep
next
forb0=1to4
gosubrturn
next
endif
Collisiononright?

162

ChapterTen if(porta.1=1&&porta.2=0)then
Rightsensorhit,collisiononright
forb0=1to2
gosubbackstep
next
forb0=1to4
gosublturn
next
endif
Collisiononleft?
if(porta.1=0&&porta.2=1)then
Leftsensorhit,collisiononleft
forb0=1to2
gosubbackstep
next
forb0=1to4
gosubrturn
next
endif
Nocollisionkeepmovingforward
if(porta.1=1&&porta.2=1)then
Sensorsclear
gosubfrward
endif
gotostart
============================================================
Functionsubroutines
============================================================
backstep: Backwardstep
gosubrtilt
gosubrlf
gosubltilt
gosubllf
gosubcenter
ls=150:rs=150
gosubdo_it
return
frward: Forwardstep
gosubrtilt
gosubrlb
gosubltilt
gosubllb
gosubcenter
ls=150:rs=150

HexapodWalker gosubdo_it
return
lturn: Leftturn
gosubrtilt
gosubrlb
gosubltilt
gosubllf
gosubcenter
ls=150:rs=150
gosubdo_it
return
rturn: Rightturn
gosubrtilt
gosubrlf
gosubltilt
gosubllb
gosubcenter
ls=150:rs=150
gosubdo_it
return
=============================================================
Primarysubroutines
=============================================================
do_it: Moverobotforward,backward,leftorright
forb1=1toct
pulsoutportb.6,cs
pulsoutportb.5,rs
pulsoutportb.4,ls
pause18
nextb1
return
center: ct=15
cs=150
gosubdo_it
return
rlf: ct=20
rs=120
gosubdo_it
return
rlb: ct=20

163

Centertiltservomotor

Rightlegforward

Rightlegback

164

ChapterTen rs=180
gosubdo_it
return
llf: ct=20
ls=180
gosubdo_it
return
llb: ct=20
ls=120
gosubdo_it
return
rtilt: ct=15
cs=130
gosubdo_it
return
ltilt: ct=15
cs=170
gosubdo_it
return
Leftlegforward

Leftlegback

Rightsidetilt

Leftsidetilt

ThisPicBasicprogramprovidesforforward, backward, turnleft, andturn rightmotions. Twosensorsswitchesonthefrontoftherobotinformthemicro controllerwhenithasencounteredanobstacle. Whenanobstacleisencoun tered, therobotstepsbackandturnstotheleftorright, dependingonwhich sidetheobstaclewasencountered. Therobotisprovidedwitharighthandedness. Ifafrontcollisionisdetect ed, therobotstepsback, thenturnstotherightandproceedsforward. PartsList Servomotors
Microcontrollers(16F84)
PCB
Aluminumbars
Aluminumsheets
Threadedrodsandnuts(440)
Plasticmachinescrews, nuts, andwashers
AvailablefromImagesSIInc. (seeSuppliersatendofbook).

Chapter

11
SpeechRecognition
Inthenearfuture, speechwillbethemethodforcontrollingappliances, toys, tools, computers, androbotics. Thereisahugecommercialmarketwaitingfor thistechnologytomature. Ourspeechrecognitioncircuitisastandalonetrainablespeechrecognition circuitthatmaybeinterfacedtocontroljustaboutanythingelectrical(seeFig. 11.1). Theinterfacecircuitwewillbuildinthesecondpartofthischapterwill allow this speech recognition circuit to control a variety of electrical devices suchasappliances, testinstruments, VCRs, TVs, andofcourserobots. Thecir cuitistrained(programmed)torecognizewordsyouwantittorecognize. The unitcanbetrainedinanylanguageandevennonlanguagessuchasgrunts, birdcalls, andwhistles. Tobeabletocontrolandoperateanappliance(computer, VCR, TVsecurity system, etc.)orrobotbyspeakingtoitmakesiteasiertoworkwiththatdevice, while increasing the efficiency and effectiveness. At the most basic level, speechcommandsallowtheusertoperformparalleltasks(i.e., handsandeyes are busy elsewhere) while continuing to work with the computer, appliance, instrument, orrobot. TheheartofthecircuitistheHM2007speechrecognitionintegratedcircuit (see Fig. 11.2). The chip provides the options of recognizing either 40 words each with a length of 0.96 s or 20 words each with a length of 1.92 s. This speech recognition circuit has a jumper setting (jumperWD on main board) thatallowstheusertochooseeitherthe0.96swordlength(40wordvocabu lary)orthe1.92swordlength(20wordvocabulary). Formemorythecircuitusesan8K 8staticRAM. Thereisabackupmem orybatteryfortheSRAMonthemainboard. Thisbatterykeepsthetrained wordssafelystoredintheSRAMwhenthemainpoweristurnedoff. Thebut tonbatterylastsapproximately2years. Withoutthebatterybackupyouwould havetoretrainthecircuiteverytimethecircuitwasswitchedoff.

165

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

166

ChapterEleven

Figure11.1 Speechrecognitioncircuitassembled.

Figure11.2 HM2007integratedcircuit.

Thechiphastwooperationalmodes: manualmodeandCPUmode. TheCPU modeisimplementedwhenitisnecessaryforthechiptoworkasaspeechrecog nitioncoprocessorunderahostcomputer. Thisisanattractiveapproachtospeech recognitionforcomputersbecausethejoboflisteningtosoundandrecognitionof commandwordsdoesntoccupyanyofthemaincomputersCPUtime. Inonetype ofprogrammingscenario, whentheHM2007recognizesacommand, itcansignal an interrupt to the host CPU and then relay the command it recognized. The HM2007chipcanbecascadedtoprovidealargerwordrecognitionlibrary. TheSR06circuitwearebuildingoperatesinthestandalonemanualmode. Asastandalonecircuit, thespeechrecognitioncircuitdoesntrequireahost computerandmaybeintegratedintootherdevicestoaddspeechcontrol.

SpeechRecognition

167

Applications Applications of command and control of appliances and equipment include these: Telephoneassistancesystems Dataentry Speechcontrolledtoys Speechandvoicerecognitionsecuritysystems Robotics

SoftwareApproach Currentlymostspeechrecognitionsystemsavailabletodayaresoftwarepro grams that run on personal computers. The software requires a compatible sound card be installed in the computer. Once activated, this software runs continuouslyinthebackgroundofthecomputersoperatingsystem(Windows, OS/2, etc.)andanyotherapplicationprogram. While this speech software is impressive, it is not economically viable for manufacturers to add personal computer systems to control a washing machine or VCR. The speech recognition software steals processing power from the operating system and adds to the computers processing tasks. Typicallythereisanoticeableslowdownintheoperationandfunctionofthe computerwhenvoicerecognitionisenabled. LearningtoListen Wetakeourabilitytolistenforgranted. Forinstance, wearecapableoflis teningtoonepersonspeakamongseveralataparty. Wesubconsciouslyfilter out the extraneous conversations and sound. This filtering ability is beyond thecapabilitiesoftodaysspeechrecognitionsystems. Speechrecognitionisnotspeechunderstanding. Understandingthemeaning ofwordsisahigherintellectualfunction. Thefactthatacomputercanrespond toavocalcommanddoesnotmeanitunderstandsthecommandspoken. Voice recognition systems will one day have the ability to distinguish linguistic nuancesandthemeaningofwords, toDowhatImean, notwhatIsay! SpeakerDependentandSpeakerIndependent Recognition Speech recognition is classified into two categories, speakerdependent and speakerindependent. Speakerdependentsystemsaretrainedbytheindividualwhowillbeusing thesystem. Thesesystemsarecapableofachievingahighcommandcountand better than 95 percent accuracy for word recognition. The drawback to this

168

ChapterEleven

approach is that the system only responds accurately to the individual who trainedthesystem. Thisisthemostcommonapproachemployedinsoftware forpersonalcomputers. Speakerindependentsystemsaretrainedtorespondtoawordregardlessof who speaks. Therefore the system must respond to a large variety of speech patterns, inflections, andenunciationsofthetargetword. Thecommandword count is usually lower than that of the speakerdependent system; however, high accuracy can still be maintained within processing limits. Industrial requirementsmoreoftenrequirespeakerindependentvoicesystems, suchas theAT&Tsystemusedinthetelephonesystems. RecognitionStyle Speech recognition systems have another constraint concerning the style of speechtheycanrecognize. Theyarethreestylesofspeech: isolated, connected, andcontinuous. Isolatedspeechrecognitionsystemscanjusthandlewordsthatarespoken separately. This is the most common speech recognition system available today. The user must pause between each word or command spoken. The speechrecognitioncircuitissetuptoidentifyisolatedwordsof0.96slength. Connected speech recognition system is a halfway point between isolated word and continuous speech recognition. It allows users to speak multiple words. TheHM2007canbesetuptoidentifywordsorphrases1.92sinlength. Thisreducesthewordrecognitionvocabularynumberto20. Continuous speech is the natural conversational speech we are used to in everydaylife. Itisextremelydifficultforarecognizertosiftthroughthetext as the words tend to merge together. For instance, Hi, how are you doing? sounds like Hi, howyadoin. Continuous speech recognition systems are on themarketandareundercontinualdevelopment. SpeechRecognitionCircuit ThespeechrecognitioncircuitisavailableasakitfromImagesSIInc. Youcan purchase the main components, HM2007, SRAM, and printedcircuit boards separatelyifyoulikeandbuildfromscratch. Thekittakesamodularapproach andusesthreeseparateprintedcircuit(PC)boards. ThethreePCboardsare themaincircuitboardcontainingthespeechrecognitioncircuit, digitaldisplay board, andkeypad(seeFig. 11.3). Thekeypadanddigitaldisplayareremovable from the main circuit board. They are needed to communicate with and pro gram the main speech recognition circuit. After the programming is accom plished, thedigitaldisplayandkeyboardcanberemoved, andthemaincircuit embeddedintoanothercircuittoaddspeechcontrol.
Circuitconstruction

TheschematicisshowninFig. 11.4. Youcanhardwirethiscircuittoabread boardifyoulike. IwouldrecommendpurchasingthethreePCBboardsthat

SpeechRecognition

169

Keypad

Display Board

Main Circuit Board


Figure11.3 Threemodularcircuitboards.

areavailableforthisproject; seePartsList. WhenyouusethePCboard, the components are mounted on the top silkscreen side of the board. Begin con structionbysolderingtheICsocketsontothePCboards. Nextmountandsol deralltheresistors. Nowmountandsolderthe3.57MHzcrystalandredLED. ThelongleadoftheLEDispositive. Nextsolderthecapacitorsand7805volt ageregulator. Solderthesevenpositionheadersonthekeypadtothemaincir cuitboard. Nextsolderthe10positionheadersonthedisplayboardandmain circuitboard.
Keypad

Thekeypadismadeupof12normallyopen(N.O.)pushbuttonswitches(see Fig. 11.5).


1 4 7 * Clear 2 5 8 0 3
6
9
#
Train

Totrain

Totrainthecircuit, firstattachthekeypadanddigitaldisplaytothemaincir cuitboard(seeFig. 11.6). Nextselectyourwordlength. Placeajumperonthe twopinWDheaderonthemaincircuitboardtoselecta20wordvocabulary, eachwitha2swordlength. Leavethejumperofftoselecta40wordvocab ulary, each with a 1s word length. Plug in the headset microphone. When powerisapplied, theHM2007checksthestaticRAM, outputs00 onthedig ital display, and lights the red LED (READY). The circuit is in the ready

7448

13 12 11 10 9 15 14 3 4 5 6 2 1 7

13 12 11 10 9 15 14

7448

8K x 8 SRAM

74LS373

25 47 15

HM 2007

170

Keypad (See Switch Matrix) 1 4 7 Vcc +5V CLR 0 TRN 16-Pin Dip Resistor 220 16-Pin Dip Resistor 220 8 9 5 6 2 3
12 4 12 4

7805

14 13 8 7 6 1 2

14 13 8 7 6 1 2

Vcc +5V

VDC In

Vcc +5V

Vcc +5V

3 4 5 6 2 1 7

C3 100 F

XTAL 3.57 MHz LED

R3

4 5 6 8 9 10 11 2 3 7 44

22K

19 16 5 2 6 9 12 15 Header 26 R1 100K 27 22 20 .0047 F C1

R2 6.8K
46

.1 F

Microphone

C2

36 37 38 40 39 41 42 43 31 30 29 28 27 24 23 22 21 20 19 18 17 35 34 16 2 23 21 24 25 3 4 5 6 7 8 9 10 11 12 13 15 16 17 18 19 28

14 13 8 18 7 17 4 3 Vcc +3V 11 Backup

12

26

Figure11.4 Schematicofspeechrecognitioncircuit.

SpeechRecognition

171

Figure11.5 Keypadwiring.

Figure11.6 Modularcomponents

puttogetherfortraining.

mode. Inthereadymodethecircuitislisteningforaverbalcommandorwait ingtobetrained. Totrainthecircuit, beginbypressingthewordnumberyouwanttotrainon thekeypad. InthisexerciseIamassumingyouchoosethe20wordvocabulary. Inthismodethecircuitcanbetrainedtorecognizeupto20words. Useany

172

ChapterEleven

numbers between 1 and 20. For example, press the number 1 to train word number1. Whenyoupressthenumber(s)onthekeypad, theredLEDwillturn off. Thenumberpressedonthekeypadisshownonthedigitaldisplay. Next pressthe#keyfortrain. Whenthe#keyispressed, itsignalsthechiptolis tenforatrainingword, andtheredLEDturnsbackon. Nowspeaktheword youwantthecircuittorecognizeintotheheadphonemicrophoneclearly. The LED should blink off momentarily; this is a signal that the word has been accepted. Continue training new words in the circuit, using the procedure outlined above. Pressthe2key, thenthe#keytotrainthesecondword, andsoon. The circuitwillacceptuptoeither20or40words, dependingonthelengthsofthe words. Youdonothavetoenter20wordsintomemorytousethecircuit. Ifyou want, youcanuseasfewwordspacesasyourequire. Theprocedurefortraining40wordsisidentical, exceptthatyoucanchoose wordnumbersbetween1and40. TestingRecognition The circuit is continually listening. Repeat a trained word into the micro phone. Thenumberofthewordshouldbedisplayedonthedigitaldisplay. For instance, iftheworddirectory wastrainedaswordnumber5, thensayingthe worddirectory intothemicrophonewillcausethenumber5tobedisplayed.
Errorcodes

Thechipprovidesthefollowingerrorcodes. 55 wordtoolong 66 wordtooshort 77 wordnomatch

Clearingthetrainedwordmemory

ToeraseallthewordsintheSRAMmemory(training), press99onthekeypad and then press the * key. The display will scroll through the numbers 1 through20(or1through40ifin1swordlengthmode)quickly, clearingout thememory. Toeraseasinglewordspace, pressthenumberofthewordyouwanttoclear andthenpressthe*key. IndependentRecognitionSystem Inadditiontospeechcommands, thiscircuitallowsyoutoexperimentwithoth er facets of speech recognition technology. For instance, you can experiment

SpeechRecognition

173

with speakerindependent systems. This system is inherently speakerdepen dent, meaningthatthevoicethattrainedthecircuitalsousesit. Toexperiment withspeakerindependentrecognition(multiuser), trythefollowingtechnique. SettheWDjumperonthemaincircuitboardtothe40wordvocabularywitha 0.96swordlength. Nowwewillusefourwordspacesforeachcommandword. Wewillarrangethewordssothatthecommandwordswillberecognizedby justdecodingtheleastsignificantdigit(number)onthedigitaldisplay. Thisisaccomplishedbyallocatingthewordspaces01, 11, 21, and31tothe firsttargetorcommandword. Whenthecircuitisinrecognitionmode, weonly decodetheleastsignificantdigitnumber, inthiscaseX1(whereXisanynum berfrom0to3)torecognizethetargetword. We do this for the remaining word spaces. For instance, the second target wordwillusewordspaces02, 12, 22, and32. Wecontinueinthismanneruntil allthewordsareprogrammed. Ifpossible, useadifferentpersontospeaktheword. Thiswillenablethesys tem to recognize different voices, inflections, and enunciations of the target word. Themoresystemresourcesthatareallocatedforindependentrecogni tion, themorerobustthecircuitwillbecome. There are certain caveats to be aware of. First you are trading off word vocabularynumberforspeakerindependence. Theeffectivevocabularydrops from40wordsto10words. Thespeechinterfacecontrolcircuitshownlatermaybeusedinthisspeaker independentexperimentalcapacity. VoiceSecuritySystem This HM2007 wasnt designed for use in a voice security system. But this doesnt prevent you from experimenting with it for that purpose. You may want to use three or four keywords that must be spoken and recognized in sequenceinordertoactivateacircuitthatopensalockorallowsentry. SpeechInterfaceControlCircuit Okay, you have a functioning speech recognition circuit, so now what? You needamethodofallowingthosevoicecommandstoactivateotherelectrical devicesorfunctions. Todothis, weneedtobuildauniversalspeechinterface circuit. Whendesigningthisinterface, IweighedoptionsthatIthoughtwouldmake thisinterfaceusefultoasmanydifferentusersaspossible. Thefirstparame ter I considered was how many outputs the interface should have. I decided upon 10 outputs. The second consideration was the type of output that the interfaceboardshouldprovide. Herewasatoughchoice. Ihadtheoptionto maketheoutputanactivehighsignalthattheusercouldusetoactivateorbe detected. ThisoutputcouldbeusedonaTTLlogiclineorCMOSlogicline, or toturnonatransistorswitchorpowerrelayintheircircuitry.

174

ChapterEleven

TheotheroptionIthoughtofwastoput10miniatureSPDTrelaysonthe interface board. This way the interface board could switch electric power on andoffdirectlyfromtheboard. Theadvantageoftheactivehighoutputsignaliscost. Thisboardwouldcost muchlessthantheinterfaceboardcontaining10relays. Theadvantageofthe relayboardisthattheminiaturepowerrelayshaveenoughcurrentcapacity todirectlycontrolsmalldcmotorsandotherelectriccircuits. I couldnt decide between the two approaches, so I have included both designs. You can choose which interface circuit suits you. The front ends of bothcircuitsareidenticalandfunctioninthesamemanner. Theoutputsare differentandareexplainedseparately. Sincewearecontrolling10outputs, weonlyneed11commands10com mandsforactiveon/offswitchesand1commandtoturneverythingoff. Ingen eral, itisbetterifthemainspeechrecognitionboardjumper(WD)issettothe 20twosecondwordlengthoption. The20twosecondwordmodehasabetter wordrecognitionaccuracythanthe40onesecondsetting. However, theinter face board will work with both modes. This makes it possible to experiment withthespeakerindependentsystemdescribedearlier. Thespeechinterfacecircuitneedstoperformacoupleofjobs. Firstitneeds todeterminewhenthespeechrecognitioncircuithasdetectedaspokenword. Afterawordhasbeendetected, itmustdistinguishwhethertheworddetected isarecognizedcommandwordoranunrecognizedword. Ifthewordisarecog nized command word, it passes the binary information to the output. If the detectedwordisnotacommandword, itmustblockanychangetotheoutput.
Howthecircuitworks

Beforewecangetintothenutsandboltsofhowtheinterfacecircuitfunctions, wemustlookatthebinaryinformationoutputbythespeechrecognitioncir cuit. Theoutputofthespeechrecognitioncircuitconsistsoftwo4bitbinary codeddecimal(BCD)numbers. Thisbinary(BCD)informationisshownonthe speechcircuitstwodigitdigitaldisplay. Wheneverawordisdetected, thecir cuitusesthedigitaldisplaytooutputthewordnumberithasrecognized, or elseitoutputsitsunrecognized/errorcode. Iftheworddetectedisnotrecog nized, thecircuitwilldisplayoneofthefollowingerrorcodes: 55 wordtoolong 66 wordtooshort 77 wordnomatch Our interface design incorporates a PIC microcontroller (see Fig. 11.7 or 11.8). Apreprogrammedmicrocontrollers(16F84)firstjobistodetermineifa wordhasbeenspoken. Todothis, weuseanLM339comparator. Areference voltage for the comparator is generated using a voltage divider made up of

SpeechRecognition

175

Vcc R4 5.6K
3 5 + 12 U3 4 LM339

R5 15K

R3 10K

U7d 4049 U7c 4049 U7b 4049

10

10

LED Input
Vcc 14 1 U4a 2 4011 6 5 U4b 4011 4

A B C D

3 8 U4c 9 4011 10

U7a 4049 U6f

14

15

4049

13 U4d 12 4011

11

11

U6e

12

Vcc

4049

D C B A

14 4.7K VDD U5 10 4 3 RB4 RA4 MCLR' 11 X1 RB5 16 OSC1 15 OSC2 4MHz

R11

U6d

10

Vcc
24 7 Q10 Q9 Q8 Q7 Q6 Q5 Q4 Q3 Q2 Q1 19 Q0 11 10 9 8 7 6 5 4 3 2 1 74154

4049 U6c

4049 U6b

GND

2 RB3 1 RA3 RB2 18 RA2 RA1 RB1 17 RA0 RB0/INT VSS 5 PIC16F84

9 8 7 6

20 D 21 C 22 B 23 A 12 18

4049 U6a

4049

Figure11.7 Speechrecognitioninterface(activehighoutputs)SRI03.

resistorsR4andR5. Thereferencevoltageisplacedonpin5ofthecomparator. Pin4ofthecomparatorisconnectedtotheLEDleadonthespeechrecognition circuit. Wheneverawordisdetected, theLEDblinksoffmomentarily. Theout putofthecomparator(pin2)isconnectedtopin10(RB4)ofthe16F84micro controller. Theoutputofthecomparator(pin2)isusuallyhigh(5V). Whena

Output

176

ChapterEleven

wordisdetected, theoutput(pin2)dropstogroundmomentarily. Themicro controllermonitorsthislinetodeterminewhenawordhasbeendetected. Onceawordhasbeendetected, itisnecessaryfortheinterfacetoreadthe BCDoutputfromthespeechrecognitioncircuit. Byusingthehighandlow digitBCDnibbles, itspossibletodistinguishtrainedtargetwords. Todoso, the interface must distinguish the error codes 55, 66, and 77 from trained wordsnumbered5, 6, and7. Toaccomplishthis, theinterfacecircuitusesfour NANDgatesoffthe4011integratedcircuit. TheNANDgatesareconnectedto the highdigit nibble. If the highdigit BCD nibble has the equivalent word numbersof5, 6, or7, theoutputfromthefourNANDgatesislow. Theoutput from the four NAND gates is connected to pin 11 (RB5) of the 16F84. The 16F84readsthispintodetermineifthehighdigitnibbleisa5, 6, or7(0Vor ground). Ifthesenumbersarenotdisplayed, theoutputoftheNANDgatesis high(5V). Sofarourcircuitcantellwhenawordhasbeendetectedandiftheresult ingwordisanerrorcode. Iftheoutputofthespeechrecognitioncircuitisan errorcode, nothingelsehappens; themicrocontrollerloopsbacktothebegin ningoftheprogram, waitingforanotherworddetection. Ontheotherhand, if awordisdetectedanditisnotanerrorcode, themicrocontrollerpassesthe lowdigit number through to the 74HC154 (4 to 16line decoder) IC. The 74HCT154decoderreadsthebinarynumberpassedtoitandbringsthecor respondingpinequivalenttothatnumberlow.
PIC16F84microcontrollerprogram

ThePIC16F84usedinbothinterfacecircuitscontainsthefollowingPicBasic program:
Speechrecognitioninterfaceprogram
symbolporta=5 symboltrisa=133 symbolportb=6 symboltrisb=134 poketrisa,255 poketrisb,240 start: peekportb,b0 ifbit4=0thentrigger Triggerenabled,readspeechrecognition circuit gotostart Repeat trigger: pause500 Wait.5second Readbcdnumber peekportb,b0 Outputnumber ifbit5=1thensend gotostart Repeat send: Readporta peekporta,b0 ifbit4=1theneleven Isthenumber11 Outputnumber pokeportb,b0

SpeechRecognition gotostart eleven: ifbit0=0thenten pokeportb,11 gotostart ten: pokeportb,10 gotostart end Repeat

177

Repeat

Repeat

Activehighoutput

Theoutputsfromthe74HCT154eachpassthrougha4049invertingbufferto supplya15Vdcactivehighoutputsignal.
SPDTrelayoutput

InFig. 11.8, thefrontendofthecircuitisidenticaltoFig. 11.7. Thechanges areseeninthebackendofthecircuit. Theactivelowoutputsignalsfromthe 74HCT154eachconnecttooneofthe10PNPtransistors, eachofwhichcon trolsacorrespondingrelay. Eachrelayhasanormallyopen(N.O.)switchand normallyclosed(N.C.)switch. Therelayswitchesareratedat124Vacat0.5 Aor24Vdcat1A. Therelayitselfconsumesapproximately30mAofcurrent whenitisturnedon. CircuitConstruction There is nothing critical about the circuit construction. The circuit may be wiredpointtopointonabreadboard, ifyoulike. Printedcircuitboardsmake theconstructioneasierandareavailableaskitsfromImagesSIInc. Theonlycomponentthatneedsspecialnoticeisthe10pinfemaleheader. If youarenotusingthePCboardsfromthekit, youmustfollowtheschematic and wire the 10pin female header exactly; or else the interface will not be receivingthesignalsitexpects, andtheunitwillfail. ProgrammingtheSpeechRecognitionCircuit: Training,Testing,andRetraining Programthespeechrecognitioncircuitperthedirectionsgivenpreviously. Choose thewordsyouwanttousetocontrolthe10electricalrelaysoroutputs. Toturnoff allelectricaloutputsontheinterface, trainwordnumber11asstop, end, orquit. Before you connect the interface to any circuit, repeat all the trained words into the microphone. The corresponding word number will be dis playedonthedigitaldisplay. Youshouldachieverecognitionaccuracyofbet terthan95percent. Ifthecircuitcontinuallyconfusestwotrainingwords, tryretrainingoneofthewords. Toretrainaword, pressthewordnumber, usingthekeypad; thewordnumberwillbedisplayedonthedigitaldisplay.

178

ChapterEleven
Vcc R4 5.6K
3 5 + 12 U3 4 LM339 100K

R5 15K

R3 10K

1N4002 100K Vcc 2N3906 1N4002 100K

1N4002 Vcc 14 1 U4a 2 4011 6 5 U4b 4011 4 100K 3 8 U4c 9 4011 10 100K Vcc 2N3906 1N4002 Vcc 2N3906 1N4002 100K U4d 12 4011 11

A B C D

Vcc

1N4002 100K Vcc 2N3906

C B A

GND

2N3906

74154

1N4002

Figure11.8 Speechrecognitioninterface(relayswitchoutputs)SRI02.

PresstheT(training)key, andsaythewordintothemicrophone. Ifthecir cuit still confuses the two words, you may have to change one of the sug gestedwords. Onceyouaresatisfiedwiththeaccuracy, removethedigitaldisplayboard andthekeypad. Nextconnectthespeechinterfaceboardtothe10pinheader usedforthedigitaldisplay, andyourereadytogo.

Relay

2 RB3 1 RA3 RB2 18 RA2 RB1 17 RA1 RA0 RB0/INT VSS 5 PIC16F84

9 8 7 6

20 D 21 C 22 B 23 A 12 18

Q10 Q9 Q8 Q7 Q6 Q5 Q4 Q3 Q2 Q1 19 Q0

11 10 9 8 7 6 5 4 3 2 1

1N4002 100K Vcc 2N3906 1N4002 100K Vcc

Relay

Relay

14 4.7K VDD U5 10 RB4 4 3 RA4 MCLR' 11 X1 RB5 16 OSC1 15 OSC2 4MHz

Vcc
24 100K

1N4002 Vcc 2N3906

Relay

R11

Relay

13

Vcc 2N3906

Relay

Relay

Relay

LED Input

Vcc 2N3906

Relay

Relay

Vcc 2N3906

SpeechRecognition

179

Figure11.9

FinishedspeechrecognitionboardSRI02.

Figure11.10 FinishedspeechrecognitionboardSRI03.

180

ChapterEleven

SRI02andSRI03Interfaces The SRI02 and SRI03 built from kits available from Images SI Inc. are shown in Figs. 11.9 and 11.10, respectively. Once the speech recognition circuit is programmed, the speech recognition interfaces may be plugged into the display board output on the main speech recognition board and used. Figure 11.11 shows the SRI02 connected to the speech recognition board, andFig. 11.12showstheSRI03connectedtothespeechrecognition board. RobotControl Thespeechrecognitioncircuitusesaheadphonemicrophone. Formobileoper ationoneneedstoaddawirelessmicrophone. Thereareanumberofmethods ofimplementingwirelesscontrol. The simplest method is to add a suitable microphone to the main circuit board and acoustically couple it to the output of a radio receiver or walkie talkie. You would use the matching walkietalkie to give voice commands. When using this method, you should train the circuit by using your walkie talkiesandacousticcoupling.

Figure11.11 SRI02connectedtospeechrecognitioncircuit.

SpeechRecognition

181

Figure11.12 SRI03connectedtospeechrecognitioncircuit.

PartsList
Speechrecognitionkit(SR06)

(1)SpeechrecognitionIC(HM2007) (1)8KstaticRAM(6264) (1)Octallatch(74LS373) (1)Displaychip(74LS48) (1)3.57MHzcrystal (12)PCmountedN.O. switches (2)Sevensegmenteddisplays(MAN74) (1)Headsetmicrophone (1)9Vbatteryclip (1)Coinbatteryholder(2032) (1)PCmountedmicrophonejack (1)22k, 1/4Wresistor (1)6.8k, 1/4Wresistor

182

ChapterEleven

(1)330, 1/4Wresistor (8)220, 1/4Wresistor (1)100k, 1/4Wresistor (1)0.1fcapacitor (1)100fcapacitor (1)0.0047fcapacitor (2)10to22pFcapacitor (1)Voltageregulator(7805) (1)LED (2)1N914diode MiscellaneousitemsneededincludePCboards, ICsockets, headers(maleand female), twoandthreepinconnectors, jumpers.
Speechinterfacekit(SRI02)

(1)5.6k, 1/4Wresistor (1)15k, 1/4Wresistor (1)10k, 1/4Wresistor (10)100k, 1/4Wresistor (10)Diodes(1N4002) (1)Comparator(LM339) (1)4011CMOSNAND (1)74154IC (1)PIC16F84microcontroller* (10)OmronG5V1relays MiscellaneousitemsneededincludePCboard, 10pinfemaleheader, 9Vbat teryclips, anda7805regulator.
Speechinterfacekit(SRI03)

(1)5.6k, 1/4Wresistor (1)15k, 1/4Wresistor (1)10k, 1/4Wresistor (10)100k, 1/4Wresistor


*Preprogrammed16F84availableseparatelyfor$10.00fromImagesSIInc.

SpeechRecognition

183

(10)Diodes(1N4002) (1)Comparator(LM339) (1)4011CMOSNAND (1)74154IC (1)PIC16F84microcontroller* (2)Invertingbuffers(4049) MiscellaneousitemsneededincludePCboard, 10pinfemaleheader, 9Vbat teryclips, anda7805regulator. Speech recognition and interface kits (all components including prepro grammed16F84andPCB)availablefromImagesSIInc. (seeSuppliersatend ofbook):
Speechrecognitionkit(SR06) Speechinterfacekit(SRI03) Speechinterfacekit(relay)(SRI02) $79.95 $89.95 $159.95

*Preprogrammed16F84availableseparatelyfor$10.00fromImagesSIInc.

Thispageintentionallyleftblank.

Chapter

12
RoboticArm
ServomotorBuildingBlocksforRobotics The servomotor brackets discussed in this chapter will allow you to create variousservomotorrobotsandprojects. Servomotors are ideal for powering robots. They are readily available in many sizes, are inexpensive, provide powerful torque for their size and weight, andarepositional. Theoutputshaftsonmosthobbyservomotorsare guaranteed positional between 0 and 90. Most servomotors output shaft rangeextendspast90, comingcloseto180. TheservomotorbracketcomponentsareshowninFig. 12.1. Eachofthealu minum U brackets that make up the assembly has multiple holes for con nectingastandardHiTecservomotorhornaswellasbottomandtopholesfor connectingUbracketsandassembliestooneanother. Theservomotorhornsusedontheseservomotorbracketsareincludedwith allthecompatibleHiTecservomotors, suchasHS322, HS425, HS475, and HS35645. ThesebracketsmayalsobeusedwithsimilarsizeFutabaservo motors, butyoumayhavetopurchasethehornsseparately. Eachservomotorbracketassemblyconsistsofthefollowingcomponents: two aluminumUbrackets, labeledAandB, onebindingheadpostscrew, four632 plasticmachinescrewswithnuts, andfoursheetmetalscrewsformountinga servomotor horn. When assembled with a compatible servomotor (see Fig. 12.2), thebracketbecomesamodularcomponentthatmaybeattachedtooth er brackets and components. The bracket allows the top and bottom compo nentstoswivelalongtheaxisoftheservomotorsshaft(seeFig. 12.3). By connecting multiple servomotors using the brackets, you can create a varietyofroboticdesigns. Inthischapterwewillusethebracketstocreatea

185

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

186

ChapterTwelve

A B

Figure12.1 Servomotorbracketkit.

Tilts

Front View

Side View

Figure12.2 Frontandsideviewsofservomotorbracket.

fiveservomotorroboticarm. InChap. 13weusethesesamebracketstocre ateabipedalwalkerrobot. Thebottomandtophavemultipleholesforattachingotherbracketsorser vomotorhorns(seeFig. 12.4). BasicServomotorBracketAssembly Toassembleaservomotorbracket, beginbyplacingthebindingpostthrough thebackholeonparta(seeFig. 12.5). NextplaceservomotorintotheAbrack et, as shown in Fig. 12.6. Attach the servomotor using 632 3/8inlong machinescrewsandnuts(seeFig. 12.7). Noticetheservomotorshornhasbeen

RoboticArm

187

Tilt Left

Center

Tilt Right

Figure12.3 Servomotorbrackettravel.

Bracket Holes

Horn-Mounting Holes

Bracket-to-Bracket Holes

Figure12.4 DiagramoftopandbottommountingholesintheAandBbrackets.

Figure 12.5

A bracket with bindingscrew.

188

ChapterTwelve

Figure12.6 Sideviewofplacing servomotorinAbracket.

Figure 12.7 A bracket with ser

vomotor attached with plastic screwsandnuts.

removedfromtheservomotor. Tosecurethescrewsatthebottomtwopositions of the servomotor, place the screw through the hole from the inside of the bracket. It helps if you have a small screwdriver to hold the screw in place. Thentheplasticnutsarechaseddownonthescrewsfromtheoutsideofthe bracket(seeFig. 12.7). Theservomotorhorn(seeFig. 12.8), isattachedtothesideholesontheB bracket(seeFig. 12.9).

RoboticArm

189

Figure12.8 HiTecservomotorhorn.

Back

Front

Figure12.9 Bbracketwithservomotorhornattached.

ToplacetheservomotorsecureinbracketAintoitsmatingpartbracketB, sliptheendofthebindingheldpostthroughtheholeinthematingpart(see Fig. 12.10). Nextsliptheservomotorsspindleintothehorn(seeFig. 12.11). FinishedassemblyisshowninFig. 12.12. AssemblingMultipleServomotorAssemblies Whenyouareusingmultipleservomotorassemblies, itisessentialtopreplan how the servomotors will be connected. When two or more servomotors assembliesareconnected, theconnectingbracketsofthejointsshouldbepre assembled(seeFig. 12.13). Thebracketsmaybeorientatedtooneanotherin anumberofways, dependinguponyourdesign. The top and bottom brackets of each assembly are connected to one anotherbyfour632 3/8inlongplasticmachinescrewsandeightplastic hexnuts. Thescrewsareinsertedthoughthetopbracketholes. Hexnuts

190

ChapterTwelve

Figure 12.10 Bringing top bracket onto lower bracket to

assemble.

Figure12.11

Sideviewshowinghornassemblyconnected toservomotor.

RoboticArm

191

Figure12.12 Standaloneservomotorbracketassembly.

Figure12.13 Twodifferentbracketassemblies.

192

ChapterTwelve

Figure12.14 Closeuptopviewoftwoassembledbrackets.

Figure12.15 Closeupsideviewoftwoassembledbrackets.

arechaseddown, securingthemachinescrewstothetopbracket. Thesec ondbracketisthenattachedtothescrews, andhexnutsarechaseddown, securingthebottombracket. Figures12.14and12.15arecloseuppictures ofthetopandsideviewsoftheplasticscrewsconnectingtwobrackets. BuildingaFiveServomotorRoboticArm Aside from the servomotor brackets we have already outlined, we need one other specialized componenta robotic arm gripper (see Fig. 12.16). This gripper requires two servomotors, one for wrist movement and the other to open and close the gripper fingers. The gripper fingers can accommodate objectsuptoabout1.0in(25mm).

RoboticArm

193

Figure12.16 Roboticarmgripper.

Theroboticarmusesfiveservomotors: fourHiTecHS322HDservomo tors and one HS475 HB servomotor. The HS475 servomotor has 50 per cent more torque than the HS322 and is used in the second position up from the bottom (or base) servomotor on the robotic arm. This particular servomotor requires the greatest torque in order to lift the arm and any objectthearmisholding. Figure 12.17 shows how the servomotors are attached to the gripper. AssembleonepartAandBbracket, asshowninFig. 12.18. Attachaser vomotortotheAportionofthebracket; thiswillbethewristservomotor. The wrist servomotor motor is attached to the gripper first. Remove the servomotor horn from the servomotor, if you havent done so already, and putthehornscrewtotheside; wewillneedit. Centerthewristservomo tor, usingthecenteringservomotorcircuitdescribedlaterinthischapteror attheendofChap. 6. Withpowerappliedtotheservomotorfromthecen tering circuit, place the servomotor into the wrist position. Replace the horn screw removed earlier, and tighten the servomotor horn screw. Removepowerfromtheservomotor. Next position the gripper fingers in midposition. Center the finger servo motor, usingthecenteringcircuitasbefore. Positionthefingerservomotorin the finger position. Tighten the horn servomotor screw, then back off the screwtounbindthefingers. Whenyouarefinished, thesubassemblyshould looklikeFig. 12.19. To finish up the arm, assemble anA and B component, as shown in Fig. 12.20. NextwerequiretwomoreAbracketcomponents. OneAbracketcom ponenthasaservomotorhornattachedtoitsbottomholes, andtheotherA bracketcomponenthasaservomotorattachedandislaidonitsbackasabase (seeFig. 12.21). ThetwobracketsareassembledasshowninFig. 12.22. When you assemble the base, center the bottom servomotor before attaching the upperAbracket. Thisformsthebaseoftheroboticarm. Tosecurethebaseto aplatform, fourholesaredrilledinthebottombracket(seeFig. 12.23). Only twodrilllocationsareshownonthebottom. Drilltwosimilarholesatthetop. To prevent the A bracket from bending with the weight of the robotic arm whenitisassembled, placeaspacermadeofwood, plastic, ormetalasshown inFig. 12.23. Thebaseassemblyissecuredtoasquarepieceofwoodormet

194

ChapterTwelve

Wrist Servo

Figure 12.17 Diagram showing how servomotor assembles to gripper.

Finger Servo

Figure 12.18 Assembled brack etsforgripper.

RoboticArm

195

Figure12.19 Roboticarmgripperassembly.

Figure 12.20 Assembled middle

bracketforroboticarm.

196

ChapterTwelve

Figure12.21 Bottombracketsforroboticarm.

Figure12.22 Assembledbottom

bracketsforroboticarm.

RoboticArm

197

Drill Holes

Spacer
Figure12.23 Closeupbasebracket.

altoprovideagoodbasethatdoesnttopplewhentheroboticarmmovesand liftsobjects. Thetwomiddleservomotorsareassembledontothebase, andtheservogrip perisattachedtothetop, completingtheroboticarm(seeFigs. 12.24and12.25). Servomotors ServomotorsarerelativelyeasytocontrolusingPICmicrocontrollers. Ifyou remember, servomotors were introduced in Chap. 6. In Chap. 6 we just described the basic function of a servomotor; now we will review in a little greaterdetail. Servomotorsaregeareddcmotorswithapositionalfeedbackcontrolthat allowstheshaft(rotor)toberotatedandpositionedaccurately. Whenacon trolsignalisbeingfedtotheservomotor, theservomotorsshaftrotatestothe positionspecifiedbythecontrolsignal. Thepositioningcontrolisadynamic feedbackloop, meaningthatifyouforciblyrotatetheservomotorsshaftaway fromitscontrolsignalcommandposition, theservomotorcircuitrywillread thisasapositionerrorandwillincreaseitstorqueinanattempttorotatethe shaftbacktoitscommandposition. Hobby servomotor specifications usually state that the shaft can be posi tionedthroughaminimumrangeof90 (45). Inrealitythisrangecanbe extended closer to 180 (90) by adjusting the position control signal describedinamoment. Therearethreewireleadstoahobbyservomotor. Twoleadsareforpower 15V(redwire)andground(blackwire). Thethirdlead(yelloworwhitewire) feedsapositioncontrolsignaltothemotor.

198

ChapterTwelve

Figure12.24 Fiveservomotor

roboticarm(leftview).

Fiveservomotor roboticarm(rightview).
Figure12.25

RoboticArm

199

Pulse Width 1-2 ms

(Approx. Frequency 55 Hz)

Period 18 ms 1-ms Pulse Train Servomotor Position Left

1.5-ms Pulse Train Servomotor Position Midrange

2-ms Pulse Train Servomotor Position Right


Figure12.26 Servomotorcontrolsignaldiagram.

Thepositioncontrolsignalisasinglevariablewidthpulse. Thepulsewidth typicallyvariesbetween1and2ms. Thewidthofthepulsecontrolstheposi tionoftheservomotorshaft. Figure12.26illustratestherelationshipofpulse widthtoservomotorposition. A1mspulserotatestheshafttotheextreme counterclockwise(CCW)position(45). A1.5mspulseplacestheshaftina neutralmidpointposition(0). A2mspulserotatestheshafttotheextreme CWposition(45). The pulse width signal is sent to the servomotor approximately 55 times persecond(55Hz). By extending our pulse width past the typical parameters, a 1 to 2ms pulsewidth, wecanextendtherotationalpositionoftheservomotorsshaft. Inmanycasescloseto180 positioningcontrolispossible. However, caremust be exercised not to provide a control signal to the servomotor that will attempttorotatetheshafttoofar, wheretheshaftwillpushagainstitsinter nalstop. Asmentionedpreviously, thepositionfeedbackcontrolisdynamic, and the servomotor will increase its torque (and increase its current con sumption)torotatetheshaftintoposition, placingasmuchforceaspossible againstitsinternalstop. Thiswillcreateunnecessarystrainontheinternal gearsandmotor, decreasingitsworkinglifeconsiderably.
Servomotorcontrollers

OurservomotorcontrollersusethePicBasicandPicBasicPropulsout com mand. Thecommandformatisasfollows:

200

ChapterTwelve pulsoutpin,period

Thepulsout commandgeneratesapulseonthepinspecifiedfortheperiod oftimespecified. Thetimeisin10s(microsecond)increments. Sotosenda1.5 mspulseoutonportBpin0, youcoulduseoneofthefollowingcommand(s). ForthePicBasiccompiler:


pulsout0,150

ForthePicBasicProcompiler:
pulsoutportb.0,150

Thispulsout commandwillputtheservomotorshaftintoitscenterposition. Theonlythingsmissingareadelayandloopbacklinestosendthe pulsout signaltotheservomotor55timespersecond. Soacompletecenterservomotor programisasfollows:


PicBasicprogram start: pulsout0,150 pause18 gotostart PicBasicProprogram start: pulsoutportb.0,150 pause18 gotostart

TheschematicforabasicservomotorcircuitisshowninFig. 12.27. Ifyou prototypeservomotorcircuitsonasolderlessbreadboard, aservomotorcon nector (see Fig. 12.28) makes connecting a servomotor to the breadboard easy. Althoughthiscenteringservomotorcircuitmayappeartobeuseless, itis not. In most cases when building a servomotor device or robot, you want to centertheservomotortoaknown(center)positionbeforeattachinganyhard ware. Thiscenteringtechniqueisusedbeforeattachingthewheelassembly to the steering servomotor when you are constructing Walters turtle (see Chaps. 8and10amongothers).
Simpleservomotorcontroller

Thissecondservomotorcircuit(seeFig. 12.29), allowsustocontroltheservo motor by using a singlepole doublethrow (SPDT) switch. This particular SPDT switch has a centeroff position that is critical to proper operation of thiscircuit. Pushingtheswitchupwillrotatetheservomotorinaclockwise rotation. In the center position the servomotor stops and holds its position. Pushing the switch in the down position will rotate the servomotor in the counterclockwisedirection. The following two programs for the simple servomotor controller are the basis for the programming for the four and fiveservomotor controllers. In general, whenyouareprogrammingthePICmicrocontrollers, makesurethe watchdogtimerisdisabled.

RoboticArm

201

+5V +5V U1 R1 4.7K

Servo Motor

13 12 11 10 9 8 7 6 3 2 1 18 17

14 VDD RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0/INT RA4/TOCKI RA3 RA2 RA1 RA0 VSS 5 MCLR' OSC1 OSC2

C1 .1F

4 16 15

X1 4MHz

PIC 16F84

Figure12.27 Centeringtheservomotorcontrollercircuit.

Figure12.28 Servomotorconnectorusefulforprototypingonsolderlessbreadboards.

202

ChapterTwelve

+5V

+5V

Servo Motor

+5V

R2 10k

R3 10k

13 12 11 10 9 8 7 6 3 2 1 18 17

14 VDD

U1

R1 4.7k X1 4MHz

RB7 4 MCLR' RB6 RB5 16 RB4 OSC1 RB3 15 OSC2 RB2 RB1 RB0/INT RA4/ITOCKI RA3 RA2 RA1 RA0 VSS 5

C1 .1F

SW2 SPDT Center Off Switch SW1

PIC 16F84

Figure12.29 Primaryservomotorcontrollercircuit.

PicBasicProprogram
ManualcontrolofservomotorusingSPDTswitch
Useb1toholdpulsewidthvariableforservo1
Declarevariables
b1varbyte
Initializevariables
b1=150 start:
Outputservomotorposition
pulsoutportb.0,b1 Checkforswitchclosures
ifporta.0=0thenleft1 ifporta.1=0thenright1 Issw1leftactive?
Issw1rightactive?
Startservo1atcenterposition

Sendcurrentservo1positionout

Routinetoadjustpausevalue(nom18)togenerateapprox50Hzupdate
pause18
gotostart

RoboticArm Routinesforservomotor1 left1: b1=b1+1 ifb1>254thenmax1 gotostart right1: b1=b11 ifb1<75thenmin1 gotostart max1: b1=254 gotostart min1: b1=75 gotostart

203

Increasethepulsewidth Maximum2.54milliseconds

Decreasethepulsewidth Minimum.75millisecond

Capmaxb1at2.54milliseconds

Capminb1at.75millisecond

PicBasicprogram ManualcontrolofservomotorusingSPDTswitch
Useb1toholdpulsewidthvariableforservo1
Declarevariables Initializevariables symbolporta=6 b1=150 start: Outputservomotorposition pulsout0,b1 Checkforswitchclosures peekporta,b0 ifbit0=0thenleft1 ifbit1=0thenright1 Sendcurrentservo1positionout Startservo1atcenterposition

Issw1leftactive? Issw1rightactive?

Routinetoadjustpausevalue(nom18)togenerateapprox55Hzupdate
pause18 gotostart Routinesforservomotor1 left1: b1=b1+1 ifb1>254thenmax1 gotostart right1:

Increasethepulsewidth Maximum2.54milliseconds

204

ChapterTwelve b1=b11 ifb1<75thenmin1 gotostart max1: b1=254 gotostart min1: b1=75 gotostart Decreasethepulsewidth Minimum.75millisecond

Capmaxb1at2.54milliseconds

Capminb1at.75millisecond

FourandFiveServomotorControllers Thepreviousschematicisthebasicbuildingblockusedinthefourandfive servomotorcontroller. Figure12.30showsthefourservomotorcontroller. This maybepurchasedasakitfromImagesSIInc., oryoucanhardwirethecir cuitandprogramthechipyourself.


PicBasicProprogram
Manualcontroloffourservomotorsusing4SPDTswitches
MicrocontrollerPIC16f84
Declarevariables
b0varword b1varbyte b2varbyte Variableforpauseroutine.
Useb1toholdpulsewidthvariableforservo1
UseB2toholdpulsewidthvariableforservo2

+5V Servo Motor 4

+5V Servo Motor 3

+5V Servo Motor 2

+5V Servo Motor 1

+5V R1 4.7K X1 4MHz

+5V
R9 10K R8 10K

+5V
R7 10K R6 10K

+5V
R4 10K R5 10K

+5V
R2 10K R3 10K

13 12 11 10 9 8 7 6 3 2 1 18 17

U1 14 VDD RB7 RB6 MCLR' 4 RB5 16 RB4 OSC1 RB3 15 RB2 OSC2 RB1 RB0/INT

C1 .1F

SW4

SW3

SW2

SW1

RA4/ITOCKI RA3 RA2 RA1 PIC 16F84 RA0 VSS 5

Figure12.30 Schematicoffourservomotorcontroller.

RoboticArm b3varbyte Useb3toholdpulsewidthvariableforservo3 b4varbyte Useb4toholdpulsewidthvariableforservo4 b5varbyte Variableforpauseroutine Initializeservomotorvariables


b1=150 b2=150 b3=150 b4=150 start:
Outputservomotorposition
pulsout pulsout pulsout pulsout portb.7, portb.6, portb.5, portb.4, b1 b2 b3 b4 Sendcurrentservo1positionout
Sendcurrentservo2positionout
Sendcurrentservo3positionout
Sendcurrentservo4positionout
Startuppositionservo1
Startuppositionservo2
Startuppositionservo3
Startuppositionservo4

205

Checkforswitchclosures
ifporta.0=0thenleft1 ifporta.1=0thenright1 ifporta.2=0thenleft2 ifporta.3=0thenright2 ifportb.0=0thenleft3 ifportb.1=0thenright3 ifportb.2=0thenleft4 ifportb.3=0thenright4 Issw1leftactive?
Issw1rightactive?
Issw2leftactive?
Issw2rightactive?
Issw3leftactive?
Issw3rightactive?
Issw4leftactive?
Issw4rightactive?

Routinetoadjustpausevalue(nom18)togenerateapprox50Hzupdate
b0=b1+b2+b3+b4
b5=b0/100
b0=15b5
pauseb0
gotostart
Routinesforservomotor1
left1:
b1=b1+1 ifb1>254thenmax1 gotostart
right1:
b1=b11 ifb1<75thenmin1 gotostart
max1:

Increasethepulsewidth
Maximum2.54milliseconds

Decreasethepulsewidth
Minimum.75millisecond

206

ChapterTwelve b1=254
gotostart
min1:
b1=75
gotostart
Routinesforservomotor2
left2:
b2=b2+1
ifb2>254thenmax2
gotostart
right2:
b2=b21
ifb2<75thenmin2
gotostart
max2:
b2=254
gotostart
min2:
b2=75
gotostart
Routinesforservomotor3
left3:
b3=b3+1
ifb3>254thenmax3
gotostart
right3:
b3=b31
ifb3<75thenmin3
gotostart
max3:
b3=254
gotostart
min3:
b3=75
gotostart
Routinesforservomotor4
left4:
b4=b4+1
ifb4>254thenmax4
gotostart
right4:
b4=b41
ifb4<75thenmin4
gotostart
max4:
b4=254
gotostart
min4:
Capmaxb1at2.54milliseconds

Capminb1at.75millisecond

Increasethepulsewidth
Maximum2.54milliseconds

Decreasethepulsewidth
Minimum.75millisecond

Capmaxb2at2.54milliseconds

Capminb2at.75millisecond

Increasethepulsewidth
Maximum2.54milliseconds

Decreasethepulsewidth
Minimum.75millisecond

Capmaxb3at2.54milliseconds

Capminb3at.75millisecond

Increasethepulsewidth
Maximum2.54milliseconds

Decreasethepulsewidth
Minimum.75millisecond

Capmaxb4at2.54milliseconds

RoboticArm b4=75 gotostart


end
Capminb4at.75millisecond

207

Figure12.31isaphotographofthecompletedfourservomotorkit. Thecir cuitboardforthiskitwasusedasthemaincircuitboardfortheturtlerobot inChap. 8. Figure12.32isaschematicforthefiveservomotorcontroller. This circuitissuitableforcontrollingourfiveservomotorroboticarm. When you program the 16F873 with the fiveservomotor controller pro gram, make sure the watchdog timer is disabled and the brownout reset is

Figure12.31 Assembledfourservomotorcontrollerkit.

+5V Servo Motor 5

+5V Servo Motor 4

+5V Servo Motor 3

+5V Servo Motor 2

+5V Servo Motor 1

+5V
20 U1 R1 4.7K

+5V
R11 10K R10 10K

+5V
R9 10K R8 10K

+5V
R7 10K R6 10K

+5V
R4 10K R5 10K

+5V
R2 10K R3 10K

SW1

SW2

SW3

SW4

SW5

28 27 26 25 24 14 13 12 11 7 6 5 4 3 2

RB7 X1 RB6 MCLR' 1 RB5 4MHz OSC1 9 RB4 RB3 10 RC3 OSC2 RC2 Vcc RC1 RC0 R12 RA5 10K RA4 RA3 17 RA2 RC6 RA1 Push RA0 VSS Button 8 19

VDD

C1 .1F

Figure12.32 Schematicoffiveservomotorcontroller.

PIC 16F873

208

ChapterTwelve

alsodisabled. Ifthebrownoutresetisnotdisabled, thecircuitmayautomat icallyresetwheneveraservomotordrawsenoughcurrenttomakethesupply voltagedipmomentarily. Thisisnotwhatyouwanttohappeninthemiddle ofaroboticarmoperation, somakesurethatconfigurationbitisdisabled. TheseconfigurationbitsareeasytosetwhenyouusetheEPICProgrammer. SimplygototheConfigurationpulldownmenuanddisabletheseoptions.
PicBasicProprogramforfiveservomotorcontroller
Manualcontroloffiveservomotorsusing5SPDTswitches
MicrocontrollerPIC16f873
adcon1=7 SetportatodigitalI/O Declarevariables b0varbyte Useb0asholdpulsewidthvariableforservo1 b1varbyte Useb1toholdpulsewidthvariableforservo2 b2varbyte Useb2toholdpulsewidthvariableforservo3 b3varbyte Useb3toholdpulsewidthvariableforservo4 b4varbyte Useb4toholdpulsewidthvariableforservo5 b6varbyte Variableforpauseroutine b7varword Variableforpauseroutine Initializeservomotorvariables
b0=150 b1=150 b2=150 b3=150 b4=150 start:
Outputservomotorposition
portb=0 Preventspotentialsignalinversiononreset
pulsoutportb.7,b0 Sendcurrentservo1positionout
pulsoutportb.6,b1 Sendcurrentservo2positionout
pulsoutportb.5,b2 Sendcurrentservo3positionout
pulsoutportb.4,b3 Sendcurrentservo4positionout
pulsoutportb.3,b4 Sendcurrentservo5positionout
Routinetoadjustpausevalue(nom18)togenerateapprox50Hzupdate
b7=b0+b1+b2+b3+b4
b6=b7/100
b7=15b6
pauseb7
Checkforswitchclosures
ifportc.3=0thenleft1
ifportc.2=0thenright1
ifportc.1=0thenleft2
Startuppositionservo1
Startuppositionservo2
Startuppositionservo3
Startuppositionservo4
Startuppositionservo5

Issw1leftactive?
Issw1rightactive?
Issw2leftactive?

RoboticArm ifportc.0=0thenright2 ifporta.5=0thenleft3 ifporta.4=0thenright3 ifporta.3=0thenleft4 ifporta.2=0thenright4 ifporta.1=0thenleft5 ifporta.0=0thenright5 gotostart


Routinesforservomotor1
left1:
b0=b0+1
ifb0>254thenmax0
gotostart
right1:
b0=b01
ifb0<75thenmin0
gotostart
max0:
b0=254
gotostart
min0:
b0=75
gotostart
Routinesforservomotor2
left2:
b1=b1+1
ifb1>254thenmax1
gotostart
right2:
b1=b11
ifb1<75thenmin1
gotostart
max1:
b1=254
gotostart
min1:
b1=75
gotostart
Routinesforservomotor3
left3:
b2=b2+1
ifb2>254thenmax2
gotostart
right3:
b2=b21
ifb2<75thenmin2
Issw2rightactive? Issw3leftactive? Issw3rightactive? Issw4leftactive? Issw4rightactive? Issw5leftactive? Issw5rightactive?

209

Increasethepulsewidth
Maximum2.54milliseconds

Decreasethepulsewidth
Minimum.75millisecond

Capmaxb1at2.54milliseconds

Capminb1at.75millisecond

Increasethepulsewidth
Maximum2.54milliseconds

Decreasethepulsewidth
Minimum.75millisecond

Capmaxb1at2.54milliseconds

Capminb1at.75millisecond

Increasethepulsewidth
Maximum2.54milliseconds

Decreasethepulsewidth
Minimum.75millisecond

210

ChapterTwelve gotostart max2: b2=254 gotostart min2: b2=75 gotostart Routinesforservomotor4 left4: b3=b3+1 ifb3>254thenmax3 gotostart right4: b3=b31 ifb3<75thenmin3 gotostart max3: b3=254 gotostart min3: b3=75 gotostart Routinesforservomotor5 left5: b4=b4+1 ifb4>254thenmax4 gotostart right5: b4=b41 ifb4<75thenmin4 gotostart max4: b4=254 gotostart min4: b4=75 gotostart end

Capmaxb2at2.54milliseconds

Capminb2at.75millisecond

Increasethepulsewidth Maximum2.54milliseconds

Decreasethepulsewidth Minimum.75millisecond

Capmaxb3at2.54milliseconds

Capminb3at.75millisecond

Increasethepulsewidth Maximum2.54milliseconds

Decreasethepulsewidth Minimum.75millisecond

Capmaxb4at2.54milliseconds

Capminb4at.75millisecond

Figure12.33isaphotographofthefiveservomotorcontroller. Theroboticarmservomotorscanplugrightontothethreepositionheaders on the main board. However, to separate the control board from the robotic arm, Iusedfive24inservomotorextensions. Oncewired, eachSPDTswitch controlsoneroboticarmservomotor(seeFig. 12.34). Whenusingtheroboticarm, Inoticedthearmmovetooquicklyformeto performfinemovements. Sotoslowitdown, Iaddedadelayroutine. Thisfol lowingprogramisidenticaltotheaboveprogram, withtheexceptionofthe delayroutine(s).

RoboticArm

211

Figure12.33 Assembledfiveservomotorcontrollerkit.

Figure12.34 Finishedroboticarmandfiveservomotorcontroller.

212

ChapterTwelve Slowspeed
Manualcontroloffiveservomotorsusing5SPDTswitches
MicrocontrollerPIC16F873
adcon1=7 Declarevariables
b0varbyte b1varbyte b2varbyte b3varbyte b4varbyte b6varbyte b7varword s1varbyte s2varbyte Useb0asholdpulsewidthvariableforservo1
Useb1toholdpulsewidthvariableforservo2
Useb2toholdpulsewidthvariableforservo3
Useb3toholdpulsewidthvariableforservo4
Useb4toholdpulsewidthvariableforservo5
Variableforpauseroutine
Variableforpauseroutine
Unassigneddelayvariable
Assigneddelayvariable
SetportatodigitalI/O

Initializeservomotorvariables
b0=150 Startuppositionservo1
b1=150 Startuppositionservo2
b2=150 Startuppositionservo3
b3=150 Startuppositionservo4
b4=150 Startuppositionservo5
s2=4 start:
Outputservomotorposition
portb=0 Preventspotentialsignalinversiononreset
pulsoutportb.7,b0 Sendcurrentservo1positionout
pulsoutportb.6,b1 Sendcurrentservo2positionout
pulsoutportb.5,b2 Sendcurrentservo3positionout
pulsoutportb.4,b3 Sendcurrentservo4positionout
pulsoutportb.3,b4 Sendcurrentservo5positionout
Routinetoadjustpausevalue(nom18)togenerateapprox50Hzupdate
b7=b0+b1+b2+b3+b4
b6=b7/100
b7=15b6
pauseb7
Checkforswitchclosures
ifportc.3=0thenleft5 ifportc.2=0thenright5 ifportc.1=0thenleft4 Delayvariable

Issw1leftactive?
Issw1rightactive?
Issw2leftactive?

RoboticArm ifportc.0=0thenright4 ifporta.5=0thenleft3 ifporta.4=0thenright3 ifporta.3=0thenleft2 ifporta.2=0thenright2 ifporta.1=0thenleft1 ifporta.0=0thenright1 gotostart Routinesforservomotor1 left1: s1=s1+1 ifs1=s2then b0=b0+1 s1=0
endif
ifb0>254thenmax0 gotostart
right1:
s1=s1+1
ifs1=s2then
b0=b01 s1=0
endif
ifb0<75thenmin0 gotostart
max0:
b0=254 gotostart
min0:
b0=75 gotostart
Routinesforservomotor2
left2:
s1=s1+1
ifs1=s2then
b1=b1+1 s1=0
endif
ifb1>254thenmax1 gotostart
right2:
s1=s1+1
ifs1=s2then
b1=b11 s1=0
endif
ifb1<75thenmin1 Issw2rightactive? Issw3leftactive? Issw3rightactive? Issw4leftactive? Issw4rightactive? Issw5leftactive? Issw5rightactive?

213

Increasethepulsewidth

Maximum2.54milliseconds

Decreasethepulsewidth

Minimum.75millisecond

Capmaxb1at2.54milliseconds

Capminb1at.75millisecond

Increasethepulsewidth

Maximum2.54milliseconds

Decreasethepulsewidth

Minimum.75millisecond

214

ChapterTwelve gotostart
max1:
b1=254
gotostart
min1:
b1=75
gotostart
Routinesforservomotor3
left3:
s1=s1+1
ifs1=s2then
b2=b2+1
s1=0
endif
ifb2>254thenmax2
gotostart
right3:
s1=s1+1
ifs1=s2then
b2=b21
s1=0
endif
ifb2<75thenmin2
gotostart
max2:
b2=254
gotostart
min2:
b2=75
gotostart
Routinesforservomotor4
left4:
s1=s1+1
ifs1=s2then
b3=b3+1
s1=0
endif
ifb3>254thenmax3
gotostart
right4:
s1=s1+1
ifs1=s2then
b3=b31
s1=0
endif
ifb3<75thenmin3
gotostart
max3:

Capmaxb1at2.54milliseconds

Capminb1at.75millisecond

Increasethepulsewidth

Maximum2.54milliseconds

Decreasethepulsewidth

Minimum.75millisecond

Capmaxb2at2.54milliseconds

Capminb2at.75millisecond

Increasethepulsewidth

Maximum2.54milliseconds

Decreasethepulsewidth

Minimum.75millisecond

RoboticArm b3=254 gotostart min3: b3=75 gotostart Routinesforservomotor5 left5: s1=s1+1 ifs1=s2then b4=b4+1 s1=0 endif ifb4>254thenmax4 gotostart right5: s1=s1+1 ifs1=s2then b4=b41 s1=0 endif ifb4<75thenmin4 gotostart max4: b4=254 gotostart min4: b4=75 gotostart end Capmaxb3at2.54milliseconds

215

Capminb3at.75millisecond

Increasethepulsewidth

Maximum2.54milliseconds

Decreasethepulsewidth

Minimum.75millisecond

Capmaxb4at2.54milliseconds

Capminb4at.75millisecond

IntheaboveprogramvariableS2isassignedavalueof4. Toincreasethe speed of the servomotors movement, decrease this value. To slow down the servomotormovement, increasethisvalue. IncreasingtheLiftingCapacityoftheRoboticArm SubstitutingthetoptwoHS322servomotorsconnectedtothegripperwith two HS85MG servomotors can increase the lifting capacity of the robotic arm. TheHS85MGservomotorsaresubstantiallysmallerandlighter, while producingclosetothesametorqueastheHS322servomotors. Thedownside isthattheHS85MGservomotorscostabout3timestheamountoftheHS 322 servomotors. Do not try to substitute the HS85BB servomotor for the HS85MG. The HS85BB uses plastic gears, which will strip pretty quickly. TheHS85MGincorporatesmetalgearsthatlast. TousetheHS85MGservomotorsintheroboticarm, substitutethetopHS 322bracketforanHS85MGbracket. Inadditionyouneedtoordertheser vomotorgripperthathasbeenmodifiedtouseanHS85MGservomotor.

216

ChapterTwelve

AddingaRoboticArmBase Theweakestlinkintheroboticarm, asitstandsrightnow, isthebaseservo motor. Thebearinginthebottomservomotorissubjectedtoallthestressand weight of the entire arm as it turns and lifts any object. We can greatly improveuponthissituationbyaddingasecondbearingthatremovesmostof thestressontheservomotorssmallbearing. Toincorporatethissecondbear ing, weneedtobuildasmallbase. Itriedanumberofdesigns. TheonethatIfeelworksbestismadeprimarily from3/4inthickhardwood. Thefollowingdrawingsshowthefivepiecesneeded to make the base. Figures 12.35 and 12.36 show the wood blocks needed for mountingthebaseservomotor. Figures12.37and12.38showthesidesforthe base. Figure12.39isametalbaseplate. Thetwoservomotorblocksaremount edtothebaseplate, usingwoodscrewsthroughthebottom. Theservomotoris mountedtothewoodblocks(seeFig. 12.40). Nextthesidepiecesaremounted tothewoodblock(seeFig. 12.41). Weneeda0.40in, lengthof1indiameter wood dowel. To this piece of wood we center and attach a round servomotor horn, usingtwosmallwoodscrews(seeFig. 12.42). Thetopoftheservomotor hornshouldbesandedflattoremovethesmallliparoundthecenter. Thewooddowelisfittedontothebaseservomotor(seeFig. 12.43). Nextthe 3insquarebearingisplacedonthesidestoensureeverythinglinesupprop erly. Thewooddowelshouldbecenteredinthebearing(seeFig. 12.44). Mount thebearingtothesides, usingfourwoodscrews. Atopplateforthe3insquarebearingisshowninFig. 12.45. Thisplateis mounted to the bearing using four 632 plastic machine screws and nut.
1.5

Material 3/4 - thick hardw ood 1.0 All holes1/16 diameter

.555 .158

Semicircle 3/8 diameter .945 Top

C/L .375

Bottom

.375

1.125

All dimensions in inches


Figure12.35 ServomotorblockA.

1.5

Material 3/4 - thick hardwood All holes 1/16 diameter

1.0 Side

.555 .158

.945 Top

C/L .375

Bottom

.375

1.125

All dimensions in inches


Figure12.36 ServomotorblockB.

Material 3/4 - thick hardwood

3.5

1.7 Side

.228 .216

2.8 All holes 1/16 diameter Top

.5

3.0

.375

Bottom

All dimensions in inches


Figure12.37 SideblockA.

217

Material 3/4 - thick hardwood

3.5

1.7 Side

.228

2.8 All holes 1/16 diameter Top

.534 .5 3.0

.375

Bottom

All dimensions in inches


Figure12.38 SideblockB.

1/8 - 3/16 aluminum or CRS .5 3.0

.375

1.129

1.879

2.625

.696 All holes diameter, countersunk on bottom. All dimensions in inches.


Figure12.39 Baseplate. 218

3/ 16

3.119

RoboticArm

219

Figure12.40 Assemblingservomotorblocksandservomotortobase.

Figure12.41 Attachingsidestobase.

220

ChapterTwelve

Figure 12.42 A 1in 0.40in

wooddowelwithroundservomo torhorn.

Figure12.43 Attachingaservomotorhorntoservomotorbase.

When the top plate is secured to the bearing, the top of the wood dowel shouldberightunderneaththetopplate. Placethebottomservomotorbrack etoftheroboticarmontopofthetopplate. Securetheservomotorbracket (andtopplate)totheunderlyingdowelthroughthefourcenterholesinthe topbearingplate(seeFig. 12.46). Thetopsectionoftheroboticarmisfittedtothebaseservomotorbrack et. ThefinishedroboticarmisshowninFigs. 12.47and12.48. Inthepic ture note the use of the smaller HS85MG servomotors connected to the gripper.

RoboticArm

221

Figure12.44 Attach3insquarebearingtobase, checkforalignment.

1.69 1.32

.219 .219

1.32 1.69 Material: Aluminum 3 3 .042 thick

1/ 8

Center holes dia.

5/ 32

Corner holes dia. All dimensions in inches

Figure12.45 Topbearingplate.

Figure12.46 Attachtopbearingplate, servomotorbracketto 3insquarebearing.

Figure12.47 Finishedrobotic

armwithbase(rightside).

222

RoboticArm

223

Figure12.48 Finishedrobotic

armwithbase(leftside).

PartsList
Roboticarm

(3)HiTecservomotors(HS322HD) (2)HiTecservomotors(HS475HB) (5)Servomotorbracketassemblies (1)Servomotorgripperassembly (1)Baseboard (5)12or24inservomotorextensions


Base

ServomotorblocksAandB Baseplate BasesidesAandB

224

ChapterTwelve

3insquarebearing Topbearingplate 1indiameter 0.40inwooddowel Plasticmachinescrewsandnuts, woodscrews AvailablefromImagesSIInc. (seeSuppliersatendofbook).


Fourservomotorcontroller

(1)PIC16F84 (1)4MHzXtal (2)22pFcapacitors (4)SPDTPCmountedswitcheswithcenteroffposition (8)10k, 1/4Wresistors (1)4.7k, 1/4Wresistor (1)0.1F, 50Vcapacitor 5Vpowersupply(regulated) KitavailablefromImagesSIInc. (seeSuppliers).
Fiveservomotorcontroller

(1)PIC16F873 (1)4MHzXtal (2)22pFcapacitors (5)SPDTPCmountedswitcheswithcenteroffposition (11)10k, 1/4Wresistors (1)4.7k resistor (1)0.1F, 50Vcapacitor 5Vdcpowersupply KitavailablefromImagesSIInc. (seeSuppliers).

Chapter

13
BipedalWalkerRobot
Inthischapterwewillconstructandprogramabipedalwalkingrobot(seeFig. 13.1). Bipedalrobotsmorecloselyresemblehumansbecausetheyusetwolegs towalk. Bipedalismisanecessarysteptocreatingadvancedrobotsthatcan workandfunctioninhumanenvironments. Theheartandmindofthisrobot arethe16F84microcontroller. Themicrocontrollerwillbeprogrammedusing thePicBasic(orPicBasicPro)compiler. Muscleformotionisgeneratedusing aseriesofeightHS322servomotors, fourservomotorsforeachleg. Ihavenottakenanyshortcutsinbuildingthisbipedalrobot, meaningthis robotisatruebipedalwalkerrobot. Thiscriteriondemandsthattherobotbal ance itself on one leg in order to lift the other leg to initiate walking. This action is accomplished using independent ankle, knee, and hip movements. Thisbipedalrobotdoesnothaveoversizedfeetorfootpads. Thiseliminatesthe typeoflowtechnologytiltingbipedalwalkerthatusesoversizedfeettokeep therobotfromtippingoverwhenmovementproceedsfromonelegtotheoth er. You may have seen this type of bigfoot walker; the older units have a motoractivatedcamthatrisesandmovesonelegaftertheother. LatelyIve seenservomotorpoweredtiltingbigfootsontheloose. To see a movie of this bipedal robot walking, go to the Internet to the fol lowingpage: www.imagesco.com/catalog/biped/walker.html. Mydesigncallsforusingfourservomotorsineachleg(seeFig. 13.1). Theini tial walking gait programmed into the robot resembled that of the flamingo bird. Thisparticularbirdhasareversekneejoint. Ifthatbirddoesntbringa clearenoughpicturetomind, perhapstheImperialwalkerfromtheoriginal StarWarsfilm(s)willsuffice. Naturehasevolvedathreejointedlegformostwalkinganimals. Although itmayappearthatourroboticleghasfourjoints, becauseithasfourservo motors, itisessentiallyathreejointedleg. Thereasonisthatourfirstandsec ond servomotors, starting from the bottom of the leg, form a twodirectional ankle. Itisimportantthattheanklecantiltthefoot, lefttorightaswellas
225

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

226

ChapterThirteen

Figure13.1 Bipedalrobotready

towalk.

forwardandbackward. Humanshavetwodirectionalankles; thisrequirestwo servomotorstoreplicateinourleg. Sothethirdservomotorisconsideredthekneejoint, andtheforthservomo torthehipjoint. A QuestionofBalance? When we walk, we receive constant feedback from our leg muscles and feet suchasstretch, tension, andload, inadditiontohavingtiltandbalanceinfor mationpresentfromourinnerear. Removethisphysicalfeedbackinformation and remove any visual clues, and it becomes much harder to walk. Imagine howmuchharder, ifnotimpossible, itwouldbetolearnhowtowalkwithout sensoryfeedback. Thislackoffeedbackisadilemmaforrobotics. Itispossibletoprograma bipedalwalkerrobottowalkwithoutfeedbackandasenseofbalance. Todoso, exactpositioncontrolandmovementsaremeasuredforeachlegservomotor action, eachactionsequenceisprogrammedintothemicrocontroller, thepro gramisinitiated, andthesequencerepeatedtoachieveawalkinggait.

BipedalWalkerRobot

227

Figure13.2 FlexiForcepressuresensor.

Thisbruteforceprogrammingworks, butitisnotadaptive. Ifanyweightonthe robotshifts(batterypackmoves)orifyouhavetherobotcarryaweight, anything thatchangestherobotscenterofgravity, thentheprogramwillneedtobeadjust ed. Alittlesensoryfeedbackmayhelptherobotwalkandbemoreadaptive. A LittleFeedback Feedbackcomesinmanyforms. ThesensorIwouldincorporateintothisrobot isapressuresensor. Iwillbeplacingapressuresensoronthebaseofeachfoot pad. The sensor could tell the microcontroller when there is no pressure (weight)onafoot. Thiscouldbeusedtoadaptivelytilttherobotuntilthereis noweightontheoppositefootpad. The sensor is a FlexiForce pressure sensor (see Fig. 13.2). (FlexiForce is a trademarkofTekscan, Inc.)Thisparticularsensorismadetodetectpressure from0to1lb. Althoughthefinalweightoftherobotmaybeslightlymorethe sensortopweight, Ifeelitsabetter(moresensitive)choicethantakingthe nextsensorthatmeasurespressurebetween0and25lb. The pressure sensor is a variableresistor type. As pressure increases, its resistance drops. Since we are using the sensor to determine when there is zeroweightonaleg, wedontneedtoperformanA/Dconversiontoreadvary ingpressure(weight). Insteadwecanuseanopampandcomparator. Theop amp converts the resistance change in the sensor to an electric change. The comparatorissettotriggeronzeroweight. Theoutputofthecomparatorcan bereadbythemicrocontrollerasasimplehighlowsignal. Thisbipedalrobotdoesnotuseanyfeedback, soitisnotadaptivetoshift ingweightloads. Ihaveprovidedthisfeedbackinformationincaseyouwish toadvancethisbasicbipedalwalkeronyourown. Servomotors ThisbipedalwalkerutilizescommoninexpensiveHiTecHS322HD42oztorque servomotors. Othermorepowerfulservomotorsareavailable, suchastheHS 425 and HS475, and they will increase the weightcarrying capacity of the robot. However, these more powerful servomotors also require greater electric current. Sothebatterypackwillneedtobeincreasedproportionally. Therobot, asitstands, iscapableofcarryingitsown6Vbatterypackandcircuitry.

228

ChapterThirteen

Figure13.3 Servomotorbracketsneededforoneleg.

ServomotorBrackets ThisrobotusesthesameservomotorbracketsasoutlinedinChap. 12. Thatinfor mationwillnotberepeatedhere. InFig. 13.3thebracketsneededforonerobot iclegareshown. Youneedtwosuchsetsofservomotorbrackets, eightinall, to buildthisbipedalrobot. Theservomotorhornsusedontheseservomotorbrack etsareincludedwithallthecompatibleHiTecservomotors, suchasHS322, HS 425, HS475, andHS35645. Thesebracketsmayalsobeusedwithsimilarsize Futabaservomotors, butyoumayhavetopurchasethehornsseparately. Footpads ThefootpadsfortherobotareshowninFigs. 13.4and13.5. Igluedrubbergas ketmaterialtothebottomoftheplasticfootpadtomakethepadnonskid. The footpads provide a larger surface area that makes it easier for the bipedtobalanceandwalk. TheyareattachedtothebottomUbracketofthe bottomservomotor. Iarbitrarilychosetomakethefootpadsize1.5inwide 4inlong. Icutoutthissizerectanglefrom1/4inthickacrylicplastic. The locationoftheservomotorbracketonthefeetisshowninFig. 13.4. Youwill noticethebracketisnotcenteredontheplasticfoot; itislocatedatoneside towardoneend(consideredtheback). Drillfour1/8indiameterholesinthe plasticthatlineupwiththefourholesontheUbracket. Eachdrilledhole mustbecountersunkonthebottomofthefoot, sothatthemachinescrew headwillnotprotrudefromthebottomofthefoot; seesideviewandclose upofFig. 13.4andfinishedfootpadinFig. 13.5. Thiswillallowthefootto lieflatagainstthefloor. Ontheprototypethecornersofthefootpadsaresquare(seeFig. 13.5). I plantoroundthecornersofthefootpads, sotheywillbelesslikelytocatch onsomethingandtriptherobotwhenwalking. Thefootpadsareattachedto theUbracketusingfour440machinescrews, nuts, andlockwashers.

Outside Edge

Servomotor Bracket Placement

4.0 in

Top View: Left and Right Foot

Front

1.5 in

Material: 1.5- 4.0-in Transparent Plastic


1/4-

Outside Edge

Side View

Bracket Plastic Close-Up Countersunk hole (see text)


Figure13.4 Diagramoffootpad.

Figure13.5 Pictureoffootpad.

229

230

ChapterThirteen
Material 1/8 1 4 aluminum Hole size 5/32 dia.

C/L

1 C/L

1 All dimensions in inches

Figure13.6 Aluminumhipbar.

The bottom of the acrylic plastic feet can be slippery, depending upon the surfacematerialthebipedalrobotiswalkingon. Igluedsoftrubbersheetgas ketmaterialtothebottomoftheacrylicfeettocreateanonskidbottomsur faceforthefeet. Ifjustthefrontandbackofthegasketmaterialaregluedto theplasticfoot, asmallflatpocketiscreatedinthecentersectionofthefoot. Thisflatpocketisidealforlocatingaflatsensorthatcouldbeslidinbetween thegasketmaterialandtheacrylicplastic. Althoughwewillnotbeusingany flatsensorinthisrobot, itcouldbecomeafuturemodification, andyoumay wanttoleavethisoptionopenwhengluingthegasketmaterialtothefootpad. IhavefoundthisrobotbipedwalksandbalancessoeasilythatIbelieveits possibletoreducethesizeofthefootpadsorremovethementirely. Thisidea isopenforfutureexperimentation. Thehipbarthatconnectsthetopservomotorbracketsofbothlegsisshown inFig. 13.6. Thebasematerialis 1/8inthickaluminumbar1inwide 4in long. Markacenterline(C/L)acrossthewidthandthelength, asshowninFig. 13.6. FromthewidthC/Lmarkanotherline1inawayfromtheC/Loneach side. Nextusethebaseoftheservomotorbrackettomarkthefourmounting holes. AlignthebracketontheleftsidesothatanX fromthedrawncenter linesiscenteredintherightmosthole. Markthefourholeswithapencil. Align thebracketontherightsidesothatanX fromthedrawncenterlinesiscen teredintheleftmosthole. Markthefourholeswithapencil. Punch the center of each hole with a hammer and punch. Drill the punch holes with a 5/32in drill. Clean each hole to remove any burrs with a file or deburringtool. Assembly Whenyouassembletheservomotorstotheservomotorbrackets, centereach servomotorbeforeattachingtheservomotorshafttothehornbracketassem

BipedalWalkerRobot

231

Figure 13.7 Bipedal robot with allservomotorscentered.

bly. Thewalkingprogramexpectstheservomotorstobealignedinthisway. If acenteringservomotorsignalissenttoalleightservomotors, therobotwalk erwillappearasshowninFig. 13.7. Thisisnotthestartpositionofthewalk ingprogram. Schematic Figure13.8istheschematicofourbipedalwalkerrobot. Toachievemaxi mumtorquefromtheservomotors, Ineededtorunthemat6V. Torunthe PIC16F84atcloseto5V, Iincorporateda1N4007diode. Theaveragevolt agedropacrossasilicondiodeis0.7V. Soatpeakpowerfromthebatteries (underload)themicrocontrollerwillreceiveabout5.3V, whichiswithinthe voltagerangeforthismicrocontroller. Aphotographoftheprototypecircuit isshowninFig. 13.9. ThebatterypackIusedisbelowthecircuitboard. It holdsfourAAbatteries. IusedasmallpieceofVelcrotosecurethebattery pack to the hip bar. I secure the circuit board by using two small elastic bands(seeFig. 13.10).

232

ChapterThirteen

+6 V To Servo # 7 To Servo # 6 To Servo # 5 To Servo # 4 To Servo # 3 To Servo # 2 To Servo # 1 To Servo # 0


13 12 11 10 9 8 7 6 3 2 1 18 17

+6 V
14

U1
4

VDD
RB7 RB6 RB5 RB4 RB3 RB2 RB1 RB0/INT RA4/TOCKI RA3 RA2 RA1 RA0 VSS 5 MCLR OSC1

R1 4.7 K X1 Reset Switch

Servo Motor 0

16 4.0 MHz

OSC2

15

Caps 22 pF

PIC 16F84

Figure13.8 Bipedalrobotschematic.

Figure13.9 Topviewofprototypecircuitboard.

The fourAA battery, 6V power supply only lasts a short time. The bipedal robotappearstobeabletoliftmoreweightthanIplacedonit, soyoumaybeable toaddasecond6Vpowersupplyandincreasetheuntetheredwalkingtime. In anycaseIonlyusethebatterypackfordemonstrations. Formostdevelopment

BipedalWalkerRobot

233

Figure13.10 Sideviewofcircuitboardandbatterypackattachedtorobot.

workyoumaywanttobuildanexternalregulatedpowersupplyforthebiped, as Ihave, andtetherthepowersupplytotherobot. Keeptheunusedbatterypack ontherobot, soyouwillnothavetocompensatefortheadditionalweightwhen demonstratingtherobotswalkingabilityusingthebatterypack. Program When the robot is assembled, you may have to adjust the program slightly. Therewillbeslightvariancesinyourservomotorpositionsascomparedtomy prototypeduetosmallvariancesintheconstruction. Youonlyneedtoaddor removeonelineintheentireprogramtomakeadjustments, andthelineis:
gotohold

The hold subroutinekeepstheservomotorslockedintheirlastposition. The robotstaysfrozen, givingyouplentyoftimetolookoveritsposition. Thisistheprocedureforusingthatonelineandadjustingtheprogram. You place that line after each robotic movement. Check the position, adjust the movementifnecessary, checkagain, andadjustifnecessaryuntiltheposition isperfect. MovementisadjustedbyvaryingtheY1andY2numbersineach movement. Icannotimaginethevariancebeingmorethat5pointsoffwhat theprogramisshowing. There are 15 movements to check. I would advise letting the robot step through each movement; you will see if there is a problem. The robot may eithertriponitsfeetorloseitsbalance. Ifthathappens, youknowyouhave toadjustthatmovement. Butyoumustworkitthroughmovementbymove

234

ChapterThirteen

Figure13.11 Frontviewofrobot.

ment. Ifyoujusttrytoletthewalkerwalk, itwillbehardforyoutodetermine whichmovement(ifany)iscausingaproblem. The first thing to check is the start position of the robot. Write the goto hold linerightafterthecommand Gosub servoout. Therobotshouldbe level, standinginapositionshowninFigs. 13.11and13.12. Ifadjustmentsarenecessary, youneedtomakethemintheinitializevari ables section. Onceyouaresatisfied, removethegotohold lineyouwrote intheprogram. Placethegotohold lineattheendoftheFirstmovement. Checkposition, adjustifnecessary, thenmovethegotohold linetotheend oftheSecondmovement. Continueinthismanneruntilallmovementshave beenchecked. The way the program is written, the robot will take three steps and then stop. YoucanchangetherangeofB(10)toincreaseordecreasetheamountof stepstaken.
SubroutinesM1,M2,andM3

ThesubroutinesM1, M2, andM3aredelayroutines. Theseroutinesslowthe servomotormovement, sothemovementissmooth. Withouttheseroutinesthe

BipedalWalkerRobot

235

Figure13.12 Sideviewofrobot.

servomotorswouldjerkintopositionsoquicklythatthemotionwouldtopple therobot. ThereasonforthreeroutinesisthatIwanttoaffecttwoindependent servomotormotionsatthesametime. Thenumberscontrollingtheservomotor positionscouldbeboth(1)decreasing(M1,)andincreasing(M2 ,)and (2)increasinganddecreasing(M3 ,). Henceweneedthethreesubroutines tohandlethemotion.
Bipedalwalkerprogram
Declarevariables
x1varbyte
x2varbyte
y1varbyte
y2varbyte
lpvarbyte
Declarearray

236

ChapterThirteen bvarbyte[12]
Initalizearrayvariables
b(0)=148 b(1)=121 b(2)=204 b(3)=126 b(4)=150 b(5)=178 b(6)=101 b(7)=180 b(8)=0 b(9)=0 b(10)=0 b(11)=0 start:
Holdingloopthatholdsuprightposition3secondsbeforemoving
b(8)=b(8)+1
gosubservoout
ifb(8)<180thengotostart
b(8)=0
forb(10)=1to3
Legmovementsforonewholestep

Firstmovement
x1=0 x2=4 y1=129 y2=135 lp=106 gosubm1

Secondmovement
x1=5 x2=6 Take3stepsforward
Resetloopcounter
Rightankle(vertical) Rightankle(horiz.) Rightknee Righthip Leftankle(vertical) Leftankle(horiz.) Leftknee Lefthip Counter Counter Counter Dummyvalue

Servomotor0
Servomotor4
Tiltrightankle(horiz.)
Tiltleftankle(horiz.)
Loopcounter

Servomotor5
Servomotor6

BipedalWalkerRobot y1=2 y2=70 lp=140 gosubm3 Thirdmovement x1=4 x2=7 y1=150 y2=160 lp=75 gosubm3 Fourthmovement x1=1 x2=5 y1=132 y2=200 lp=90 gosubm3 Fifthmovement x1=6 x2=0 y1=85 y2=140 lp=96 gosubm2 Sixthmovement x1=0 x2=4 y1=167 y2=169 lp=80 gosubm2 Seventhmovement x1=6 x2=5 y1=101 y2=178 lp=95 gosubm3 Leftankle(vert.) Leftknee Loopcounter

237

Servomotor4 Servomotor7 Leftankle Lefthip Loopcounter

Servomotor1 Servomotor5 Straightenankle Straightenankle Loopcounter

Servomotor6 Servomotor0 Leftknee Straightenankle Loopcounter

Servomotor0 Servomotor4 Tiltankleleft Tiltankleleft Loopcounter

Servomotor6 Servomotor5 Tiltknee Tiltankle Loopcounter

238

ChapterThirteen Eighthmovement
x1=2
x2=1
y1=244
y2=104
lp=140
gosubm3

Ninthmovement
x1=3
x2=7
y1=140
y2=180
lp=80
gosubm2

Tenthmovement
x1=1
x2=2
y1=121
y2=204
lp=150
gosubm3

Eleventhmovement
x1=0
x2=4
y1=129
y2=135
lp=150
gosubm1

Twelfthmovement
x1=5
x2=6
y1=217
y2=70
lp=144
gosubm3

Thirteenthmovement
x1=4
x2=3
y1=133
y2=126

Servomotor2
Servomotor1
Rightankle
Rightknee
Loopcounter

Servomotor3
Servomotor7
Righthip
Lefthip
Loopcounter

Servomotor1
Servomotor2
Rightankle
Rightknee
Loopcounter

Servomotor0
Servomotor4
Straightenrightankle
Straightenleftankle
Loopcounter

Servomotor5
Servomotor6
Leftankle
Leftknee
Loopcounter

Servomotor4
Servomotor3
Leftankle
Righthip

BipedalWalkerRobot lp=66 gosubm1



Fourteenthmovement
x1=6 x2=5 y1=101 y2=178 lp=144 gosubm3

Fifteenthmovement
x1=0 x2=4 y1=148 y2=150 lp=115 gosubm2

nextb(10)
Loopcounter

239

Servomotor6
Servomotor5
Leftknee
Leftankle
Loopcounter

Servomotor0
Servomotor4
Leftknee
Leftankle
Loopcounter

Nextstep

hold: Holdposition
gosubservoout
gotohold

servoout:
Outputservomotorposition(s)
portb=0 Preventsignalinversion

Rightleg
pulsoutportb.0,b(0)
pulsoutportb.1,b(1)
pulsoutportb.2,b(2)
pulsoutportb.3,b(3)
Leftleg
pulsoutportb.4,b(4)
pulsoutportb.5,b(5)
pulsoutportb.6,b(6)
pulsoutportb.7,b(7)

Sendcurrentservo1positionout
Sendcurrentservo2positionout
Sendcurrentservo3positionout
Sendcurrentservo4positionout

Sendcurrentservo5positionout
Sendcurrentservo6positionout
Sendcurrentservo7positionout
Sendcurrentservo8positionout

pause5 5milliseconddelaytogenerate50Hzsignal
return Toservomotors

240

ChapterThirteen m1:
b(8)=b(8)+1
ifb(9)=2thenm12
b(9)=b(9)+1
gotom13
m12:
b(x1)=b(x1)1
b(x2)=b(x2)1
b(9)=0
m13:
ifb(x1)<y1then
b(x1)=y1
endif
ifb(x2)<y2then
b(x2)=y2
endif
gosubservoout
ifb(8)<lpthenm1
b(x1)=y1
b(x2)=y2
b(8)=0
b(9)=0
return

m2:
b(8)=b(8)+1
ifb(9)=2thenm22
b(9)=b(9)+1
gotom23
m22:
b(x1)=b(x1)+1
b(x2)=b(x2)+1
b(9)=0
m23:
ifb(x1)>y1then
b(x1)=y1
endif
ifb(x2)>y2then
b(x2)=y2
endif
gosubservoout
ifb(8)<lpthenm2
b(x1)=y1
b(x2)=y2
b(8)=0
b(9)=0
(positiveincrement(s)+,+)
(negativeincrement(s),)

BipedalWalkerRobot return

m3: b(8)=b(8)+1
ifb(9)=2thenm32
b(9)=b(9)+1
gotom33
m32:
b(x1)=b(x1)+1
b(x2)=b(x2)1
b(9)=0
m33:
ifb(x1)>y1then
b(x1)=y1
endif
ifb(x2)<y2then
b(x2)=y2
endif
gosubservoout
ifb(8)<lpthenm3
b(x1)=y1
b(x2)=y2
b(8)=0
b(9)=0
return
(positivenegativeincrement+,)

241

GoingFurther Therearemanyareasforimprovement. Oneofthesimplesttasksyoucan perform is to reduce the loop counter (LP) variable in each movement. I exaggeratedthisnumbertoensurethattheservomotorsgottotheirproper position. ThewalkinggaitusedinthisrobotwasthefirstoneIdeveloped. Iamsure thereismuchroomforimprovementforanyonewhowantstotakethetime anddevelopone. Inaddition, youcantrytoprogramcompletelydifferentwalk ing gaits. Right now the robot used two reverse knee joints. I looked at the robotstanceusingonereversedkneeandoneforwardknee. Itappearstohave betterbeenbalancedthanthecurrenttworeversekneebipedstance. Inthe future I may try to develop a gait using a forward and reverse knee stance. Thiswouldmostdefinitelybearoboticgait, sinceIdontbelievethereisany animalthatusesbothareverseandaforwardkneelegforlocomotion. Thisis anotherareayoumaywanttoworkon.

242

ChapterThirteen

Turningrightandleft

Asthebipedalwalkerstands, itcanonlywalkforward. WhileIwasdevelop ingthewalkingprogram, Ihappenedacrossaninterestingaccident. Oncer tain occasions the robot would pivot to the left or to the right. I plan on developingthisaccident toseeifIcanuseittoturntherobottotheleftand right. Ifyouwanttoattemptthis, herearethebasicinstructions. Tomakethe robotpivot, firstraiseoneleg. Ontheraisedlegtiltthehorizontalankleser vomotorslightly, andthentilttheverticalankleservomotorupslightly. Next placetheweightbackdownontheraisedleg; therobotwillpivotastheweight shifts. Turningtherobotinthismannermustbeaccomplishedincrementally. Trytoturnittoomuchatonetime, andtherobotwilltopple. Finallywithalittlework, youshouldbeabletomaketherobotwalkback ward. Imentionedadaptivewalkingandbalancecontrol. Weusedalleightpinsof portBonthePIC16F84, butthePIC16F84stillhasfiveunusedpinsassigned toportA. Thesepinscouldbeusedforprogrammingoptionssuchasadaptive balancecontrol, orarun/walkswitch, perhapsaforward/backwardswitch, or evenaturnleft/rightsensor. So you see, we have only scratched the surface of playing with this biped walker. Thereismuchonecandoandlearnfromthisproject. PartsList (8)HiTecservomotors(orsimilarsizeandtorqueservomotor)(HS322) (8)Servomotorbrackets (2)1/4in 1.5in 4inacrylicplastic (1)PIC16F84(4MHz) (1)4.0MHzXtal (2)22pFcapacitors (1)Diode(1N4007) (1)6VAAbatteryholder(flat) (8)Threepositionheaders(forconnectingservomotorstocircuit) Plasticscrewsandnuts, Velcro, prototypingbreadboard, elasticbands

Chapter

14
ColorRoboticVisionSystem
Therobotwewillbuildinthischapterwillbecapableoflookingatandseeing anobject(ortarget)andfollowingthatobject. Iftheobjectgetstooclosetothe robot, therobotwillbackawayfromit. Chooseabrighttargetthatwillhave good contrast with the background environment. Colored objects are fine; a bright red or yellow ball works fine. For my tests I used a 2.5in square of orangeconstructionpapertapedtoastiffwire. Oneofthemostdifficultareasinroboticstodayisthecreationofanartifi cialvisionsystemforarobottosee. Teachingarobottoseeisnotsimplyacase ofconnectingavideocameratoacomputer. Theelectronicrepresentationofan imagecreatedbyavideocameramustbepresentedinawayacomputercan lookat andinterpret(see)theimage. To gain an understanding of the processes involved, lets examine how a computermightlookatasimpleblackandwhiteimage. Wemustfirstdefine theresolutionofthepictureimageinpixels. Forourdiscussionletsassumea lowresolutionpictureof80 143pixels. Atthatresolutionourcomputermust lookat11,440pixels(80 143 11,440). Eachpixelofthepicturecanbeany tonalityofgraybetweenpureblackandpurewhite. Wenowhavetodetermine howmanydifferentshadesourcomputercandifferentiatebetweenpureblack andpurewhite. Ifwewantedeachpixeltoberepresentedbyasinglebyte(8 bitnumber), therewouldbe256shadesofgray, includingpurewhite(0)and black(255). Thecomputerwouldlookateachpixelandassignanumberbetween0and 255dependinguponitstonality(grayness). Afterthecomputerassignednum bers to each 11,440 pixels, it transformed the basic image into a numbered representationitneedstolook attheimage. Thesoftwarethatlooksatanimageandinterpretsvisualfeaturesisappro priatelycalled imageprocessing. Robotistsovertheyearshavegleanedsome techniques for helping computers to see. One technique is called edge detec tion. Herethecomputerlooksthroughtheimage. Youprogramthecomputer
243

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

244

ChapterFourteen

Figure14.1 FieldofviewfromCMUcamera.

sothatanypixeldarkenoughtobea200numberorlargerisapossibleedge, andyouchangethatpixeltopureblack, number256. Anynumberlessthan 200 probably isnt an edge, and the computer changes those pixels to pure white, number1. Whatisleftisasimplifiedrepresentationofthepicturethat canbemoreeasilyanalyzed. Thesameprocessusedforedgedetectionmayalsobeusedtodetectpartic ularcolorsinanimageorthecontrastbetweencolors. Onceanobjecthasbeen detected, throughcontrast, color, oredgedetection, theprocessingsoftwarecan assign location parameters to the object within the image and field of view (FOV)ofthecamera. InFig. 14.1wehavearepresentationoftheFOVfromtheCMUcamerawe willbeusingandafewoftheimageprocessingparametersavailable. Oncean objectisdetectedbythecamera, wecanreadtheseimageprocessingparame ters in real time from the serial communication port of the camera. We use theseparameterstotrackanobjectinthecamerasimagespaceandtomove ourrobotaccordingly. CMUCamera TheCMUcamera(seeFig. 14.2)wasdevelopedatCarnegieMellonUniversity (CMU). The CMU camera uses an SX28 microcontroller interfaced to an OmnivisionOV6620CMOScamerachip. TheSX28microcontrollerdoesmuch oftheimageprocessingforus. Wecommunicatewiththecameraviaastan dardRS232orTTLserialport. AfewoftheCMUcamerafeaturesareasfollows: Tracksuserdefinedcolorobjectsat17framespersecond Findsthecenteroftheobject

ColorRoboticVisionSystem

245

Figure14.2 FrontCMUcamera.

Gathersmeancolorandvariancedata Resolutionof80 143pixels Serialcommunicationat115,200, 38,400, 19,200, and9600Bd Demomodethatautomaticallylocksontoanddrivesaservomotortotrack anobject

SerialCommunication Asstated, wecommunicatetotheCMUcameraviaaserialinterface. Wewill createaserialcommunicationlinkbetweentheCMUcameraandbothaper sonalcomputer(PC)andthePICmicrocontroller. WewillfirstlookatthePC communicationtotheCMUcamera. Figure14.3isasimpleWindows98program. ItallowsyoutotesttheCMU cameraandtheserialcommunicationlink(portnumberandbaudrate). You canadjustthePCsbaudrateandserialportthroughdropdownmenuitems. This program may be downloaded without cost from this website: http://www.cmucam.com. BeforeyoustarttheWindowsprogram, youneedtosetuptheCMUcam eras baud rate. Figure 14.4 shows the back of the CMU camera, where the male header is located to place various jumpers. The baud rate is selected usingjumper2andjumper3onthebackoftheCMUcamera:

246

ChapterFourteen

Figure14.3 BasicserialWindowsPCcommunication

program.

Figure14.4 BackofCMUcamerashowingbaudratejumpers.

ColorRoboticVisionSystem

247

Baudrate 115,200 38,400 19,200 9,600

Jumper2 Open Set Open Set

Jumper3 Open Open Set Set

For PC communication I recommend using the 115,200Bd rate. Use this baudratebecauseonceyouhaveyoursimplecommunicationupandrunning, youcanswitchovertoamoresophisticatedWindowsprogramtoevaluatethe CMUcameraparameters. Withthebaudrateset, connecttheserialcabletotheCMUcamera(seeFig. 14.5). ConnectaDB9pinserialcablefromthePCtothecamera. Starttheprogram. Set theprogramsbaudratetomatchtheCMUcameras baudrate. SettheserialporttotheoneyouconnectedtotheCMUcamera. If yourcomputerhasmultipleserialports, youmayhavetotrydifferentCOMM portstofindoutwhichoneisconnectedtothecamera. Totestaport, settheserialporttoCOMM1. TurnontheCMUcamera. Thefollowingmessageshouldbedisplayedwhenthecameraisturnedon:
cmucamV1.12
:

Figure14.5 PCserialcableconnectiontoCMUcamera.

248

ChapterFourteen

If you do not see this message, turn off the camera, set the serial port to COMM2, and test again. Continue in this manner until you find the right COMM port. If you dont see the message with any of the COMM ports on your computer, you may have the baud rate set improperlydoublecheck. Onceyouseethemessage, youbegintocommunicatewiththeCMUcamera. ToturnonthecamerasgreenLED, enterthecommandl11 andhitReturn. ToturnoffthegreenLED, enterthecommandl12 andhitReturn. Onceyouhavethecommunicationlinkworking, youarefinishedwiththe firstprogram, anditistimetomoveontothemainVBapplicationprogram. VBApplicationProgram TheVBapplicationprogramisincludedontheCDROMwiththeCMUcamera. The applicationallowsyoutoseehowtheCMUcameraimagesdifferentscenesor targets. ThecurrentVBapplicationisntstable; however, bythetimethisbook goestopress, anewer, (hopefully)morestableapplicationprogramwillbeavail able. Thesimpleapplicationweusedbeforeprovidedthecorrectportnumberthat youwillneedtoallowthisprogramtofunctionproperly. Thebaudrateusedonthis programisfixedat115,200. SomakesuretheCMUcameraissetat115,200Bd.

Figure14.6 WindowsPCprogram.

ColorRoboticVisionSystem

249

Figure14.7 WindowsPCprogramshowingframedump.

Toviewtheimageproperlyfromthecamera, hitthe180 option(seeFig. 14.6). SelecttheproperCOMMportnumberandopentheport. Turnonthe camera. You should receive the CMUcam V1.12 message. Hit the Dump Framebuttonandwait. Itcantake10sforthesoftwaretodumptheframe. TheimageshownintheDumpFramewindow(seeFig. 14.7)isasimpletar getIconstructed. Thistargethelpedmecalibratethecamerasfieldofview. Thetargetisa2.5insquareoforangepaper(seeFig. 14.8), heldatadistance of12infromthecameralens. Ialsousedthistargettoreadtheimagepro cessingparametersfrommyPICprogram2asImovedthetargetleft, right, up, anddown. Iassembledtheseimageprocessreadingsinasmalltable; more aboutthislater. Youshouldusethisopportunitytofindagoodtarget. Placetheobjectyou wanttouseasyourtargetinfrontofthecamera, anddoaframedump. You arelookingtoseethattheobjectshowswellintheimageandhasgoodcon trastwiththebackground. Youcanalsoseehowmuchspacetheobjecttakes upintheimage. Thiswillgiveyouanideaofhowcloseyoushouldholdthe objecttothecamera. Onceyouhaveyourtarget, youcanstartusingthecommunicationportfor issuingcommandstotheCMUcamera. TryturningthegreenLEDonandoff

250

ChapterFourteen

Figure14.8 TargetusedforcalibratingCMUcamera.

asbefore. Youcanusethiscommunicationporttoimplementmorechalleng ingcommandsandseetheresultsonthescreendump. Hereareafewcommandsyoumaywanttotry: Turnonautolightadjustment. Thiscommandtellsthecameratoadjustto the ambient lighting. When you use this command, do not have your object/targetinfrontofthecamera. Thecommandiscr1844. Nowpress theReturnkeyorSendbutton. Wait 10 to 20 s for the camera to complete its ambient light adjustment. Thenenterthiscommandtoturnoffautolightadjustment: cr184419 32. NowpresstheReturnkeyorSendbutton.
This next command I found particularly useful. It turns on a fluorescent
bandfilterwiththeautolightadjustment: cr4571844. Nowpressthe ReturnkeyorSendbutton. YoucanfindothercommandsintheCMUmanual. InterfacingtheCMUCameratoaRobot Thefirststepininterfacingthecameratoarobotistoestablishcommunica tionbetweenthePICmicrocontrollerandtheCMUcamera. RemovetheDB9 serialcableusedforcommunicatingwiththePC. ThecamerahasaTTLseri aloutputnexttothejumpers(seeFig. 14.9). BeforewecanusetheTTLseri al input/output pins, first we remove the MAX232 IC from the back of the CMUcamera.

ColorRoboticVisionSystem

251

Figure 14.9 Back of CMU showing TTL serial communication

jumpers.

Note: AtanytimeyouneedorwanttoreconnecttheCMUcameraserial interface to a PC, you will need to place the MAX232 chip back onto the board. PlugtheTTLcableontotheappropriateheaderpinsontheCMUcamera. Figure14.10istheschematicwewillbeusing. Youdonotneedtoconnectthe twoservomotorsforourfirsttwoprograms. PIC16F84Runsat16MHz OneimportantnoteabouttheCMUschematicyoumustbeawareof. ThePIC 16F84usedinthiscircuitisa20MHzversionoperatingat16MHzwitha16 MHzcrystal. Ineededtojumpupinspeedbecausethe9600Bdcommunica tionisrunningatthelimitofthecapacityof16F84at4MHz. Tokeepthebaud ratetimingaccuratewhenwechangeclockspeeds, weenterthecommand
defineosc16

Thisinformsthecompilerthatwearerunningat16MHz. Thecompilerauto maticallyadjuststheserialcommandstokeepthebaudrateaccurate. Program1 ThisfirstprogramestablishesacommunicationlinkbetweentheCMUcam eraandPIC16F84microcontroller. ItturnsthegreenLEDontheCMUcam eraonandoff. Youshouldnotproceedtothemoreadvancedprogramsuntil youhavethisprogramfunctioningproperly.

252

Figure14.10 Mainrobotschematic.

ColorRoboticVisionSystem

253

Whentheprogramstarts, itbeginswitha5scountdown. Ifyoulookintothe countdownloop, youwillseethattheprogramissuesaresetcommandeach timethroughtheloop. Ihavefounditnecessarytosendafewresetcommands beforethecameracommunicationlinkbecomesresponsive.


PICtoCMUtest
SendserialinformationtoCMUcameratrue
defineosc16
xvarbyte
yvarbyte
recdatavarbyte[10]
trisb=0
portb=0
pause1500
seroutportb.1,6,[CMUProgramV1]
forx=0to4
y=5x
portb.3=1
seroutportb.1,6,[254,192,Startingin,#y]
seroutportb.2,2,[RS,13]
pause500
portb.3=0
pause500
nextx
seroutportb.1,6,[254,1,ResettingCam.]
seroutportb.1,6,[254,192] Movetosecondline
seroutportb.2,2,[RS,13]
gosubdisplay
pause1000
start:
TurngreenCMULEDon
seroutportb.1,6,[254,1,GreenLEDOn]
seroutportb.1,6,[254,192] Movetosecondline
seroutportb.2,2,[L11,13]
gosubdisplay
pause1000
TurngreenCMULEDoff
seroutportb.1,6,[254,1,GreenLEDOff]
seroutportb.1,6,[254,192] Movetosecondline
seroutportb.2,2,[L12,13]
gosubdisplay
pause1000

254

ChapterFourteen gotostart
display:
serin2portb.0,84,20,error,[strrecdata\4]
forx=0to4
serout2portb.1,16468,[,#recdata[x]]
recdata[x]=32
nextx
pause1000
return
error:
Noacknowledgment
seroutportb.1,6,[NoACKCont.]
pause1000
return

Program2 ThissecondprogramdisplaysontheLCDthemajorimageprocessingparame tersavailablefromtheCMUcamera. Thisprogramjustfitsintothe1Kmem ory space of the PIC 16F84. If you add a programming line or a couple of letters or spaces in any of the LCD displays, the program will not compile, becauseitwillexceedthePIC16F84memorylimit. Keepthatinmind, ifyou encounteranerror, whencompilingthisprogram.
Incandescentorfluorescentlighting

WhenIfirststartingworkingwiththeCMUcamera, Iwasworkingunderflu orescentlighting. ThecamerawasnottrackingitstargetaswellasIexpected. GoingthroughtheliteratureIhadonthecamera, Ifoundafluorescentfilter. I incorporatedthefilterintomyprogram, andthecamerastartedtrackingbet ter. Theprogramusesthefluorescentfilter; itisinthefollowingline:
Turnonfluorescentbandfilterandautolightingadjust
seroutportb.2,2,[CR4571844,13]

Ifyouareusingfluorescentlighting, youcanleavethislinealone. However, if yourlightingisincandescent, changethecommandlineto


seroutportb.2,2,[CR1844,13]

Obviouslythisprogramismoresophisticatedthanourfirstprogram. Itdis playsthetypeSdatapacketandthendisplaysthetypeMdatapacketina loopforrealtimeobjecttracking. Letsfirstlookattheinformationthatispro videdinthetypeSdatapacket.

ColorRoboticVisionSystem TypeSDataPacket Displayedprogram parameter RM GM BM Rdev Gdev Bdev Item Rmean Gmean Bmean Rdeviation Gdeviation Bdeviation Description Themeanredfoundinthecurrentwindow Themeangreenfoundinthecurrentwindow Themeanbluefoundinthecurrentwindow Thedeviationofredfoundinthecurrentwindow Thedeviationofgreenfoundinthecurrentwindow Thedeviationofbluefoundinthecurrentwindow

255

HeresalistingoftheinformationthatisprovidedinthetypeMdatapacket.
TypeMDataPacket Displayedprogram parameter MMX MMY LCX LCY RCX RCY pix conf mx my x1 y1 x2 y2 pixel confidence Item Description Themiddleofmassxvalue Themiddleofmassyvalue Theleftmostcornersxvalue Theleftmostcornersyvalue Therightmostcornersxvalue Therightmostcornersyvalue Numberofpixelsinthetrackedregion Numberofpixelsinareacappedat255

Itstimetochooseanobject/targetifyouhaventdonesoalready. Program2 needs an object to lock onto, too. When the microcontroller runs, it displays informationontheLCDscreen. Duringthe10sautoadjustperiod, thecamera shouldjustbelookingatthebackground. WhenLED1(seeschematic)starts toblink, placeyourobject/targetinfrontoftheCMUcamera.
CMUparameterdisplayprogram
ByJ.Iovine
defineosc16
recdatavarbyte[10]
xvarbyte
trisb=0
portb=0

256

ChapterFourteen pause1500
seroutportb.2,2,[RS,13]
seroutportb.1,6,[CMUTestProgram]
pause1000
seroutportb.2,2,[RS,13]
seroutportb.1,6,[254,1]
ResetCMUcamera
seroutportb.2,2,[RS,13]
gosubdisplay
TurngreenCMULEDon
seroutportb.2,2,[L11,13]
gosubdisplay
portb.3=1
Turnonfluorescentbandfilter&autolightingadjust
seroutportb.2,2,[CR4571844,13]
gosubdisplay
seroutportb.1,6,[AutoAdj.]
pause10000 seroutportb.1,6,[254,1]
pause50
Turnoffautolightingadjust
seroutportb.2,2,[CR18441932,13]
gosubdisplay
TurngreenCMULEDoff
seroutportb.2,2,[L12,13]
gosubdisplay
portb.3=0
Forx=0to10 portb.3=1
pause250
portb.3=0
pause250
nextx
BlinkredLEDtotellusertoreadytarget
Hold10seconds

Setpollmode1packet
seroutportb.2,2,[PM1,13]
pause100
Setrawdata
seroutportb.2,2,[RM3,13]
pause100

ColorRoboticVisionSystem TrackwindowcommandlooksatcenterofCMUwindow
Grabsdataandsendsthemtotrackcolorfunction
Track:
seroutportb.2,2,[TW,13]
GatherthesstatisticspacketfromTWcommand
serin2portb.0,84,[strrecdata\8]
DisplaydataonLCDscreen
seroutportb.1,6,[RM,#recdata[2]]
gosubhold
seroutportb.1,6,[GM,#recdata[3]]
gosubhold
seroutportb.1,6,[BM,#recdata[4]]
gosubhold
seroutportb.1,6,[RDev.,#recdata[5]]
gosubhold
seroutportb.1,6,[GDev.,#recdata[6]]
gosubhold
seroutportb.1,6,[BDev.,#recdata[7]]
gosubhold
pause2000
main:
Sendcommandtrackcolor(withnoarguments)
WilltracklastcolorgrabbedbyTWcommand
seroutportb.2,2,[TC,13]
GatherthemstatisticspacketfromTWcommand
serin2portb.0,84,[strrecdata\10]
DisplaydataonLCD screen
seroutportb.1,6,[MMX,#recdata[2]]
gosubhold
seroutportb.1,6,[MMY,#recdata[3]]
gosubhold
seroutportb.1,6,[LCX,#recdata[4]]
gosubhold
seroutportb.1,6,[LCY,#recdata[5]]
gosubhold

257

258

ChapterFourteen seroutportb.1,6,[RCX,#recdata[6]]
gosubhold
seroutportb.1,6,[RCY,#recdata[7]]
gosubhold
seroutportb.1,6,[Pix,#recdata[8]]
gosubhold
seroutportb.1,6,[Conf,#recdata[9]]
gosubhold
gotomain:
display:
serin2portb.0,84,20,main,[strrecdata\3]
forx=0to3
serout2portb.1,16468,[,recdata[x]]
nextx
hold:
pause500
serout2portb.1,16468,[254,1]
pause40
return

Whentheobjectiscaptured, theprogramfirstdisplaystheSdatapacket. Thenitgoesintothemainprogramloop, capturinganddisplayingtheMdata packet. Using this program, I constructed a data table that shows how my camera tracked my object/target. In the following table, n/c no change. Althoughthisisnt100percentaccurate, Iignoredsmallchangesoflessthan afewpointsineitherdirection. Thereasonsarethat(1)Idontwantanyone getting bogged down focusing on small changes and missing the important mainchangesand(2)whenImovedatargettotheleftorright, Ididntkeep the height exactly in line. I just moved the target over and kept the height approximatelythesame. Obviouslythiscausedminorfluctuationsthatcanbe ignored.
DataTableX(LeftandRight) Parameter MMX MMY LCX Target 2inleft 67 n/c 53 Target 1inleft 57 n/c 45 Target centered 45 74 33 Target 1inright 35 n/c 23 Target 2inright 20 n/c 4

ColorRoboticVisionSystem LCY RCX RCY PIX CONF n/c 80 n/c 144 31 n/c 70 n/c 150 215 47 58 102 163 232 n/c 53 n/c 162 142 n/c 28 n/c 162 39

259

Fromtheabovetablewecanmakeageneralobservation: Asthetargetmoves fromlefttoright, MMX, LCX, andRCXdecrease. Thereverseisalsotrue; as thetargetmovestotheleft, MMX, LCX, andRCXincrease.
DataTableY (UpandDown) Parameter MMX MMY LCX LCY RCX RCY PIX CONF Target 2inup n/c 31 n/c 7 n/c 57 153 246 Target 1inup n/c 52 n/c 26 n/c 80 157 233 Target centered 45 74 33 47 58 102 163 232 Target 1indown n/c 98 n/c 71 n/c 125 164 237 Target 2indown n/c 116 n/c 96 n/c 143 116 181

Fromtheabovetablewecanmakeageneralobservation. Asthetargetmoves up, MMY, LCY, andRCYdecrease. Thereverseisalsotrue. Astheobject/tar getmovesdown, MMY, LCY, andRCYincrease.
Servomotorsforrobot

ThisrobotwewillbuildusestwoHS425servomotorsmodifiedforcontinuous rotation. Theprocedureformodifyingtheseservomotorsforcontinuousrota tionwasdiscussedinChap. 8. Onceyouhavethemodifiedservomotors, itis essentialthatyoudeterminethepulsewidthsneededforslowforward, slow backward, andstop. Figure14.11isaschematicforacircuityoucanusealongwiththefollow ingPicBasicProprogramtodeterminethepulsewidths. Thepulsewidthis shown in real time on the LCD display. You change the pulse widths up or downbyusingtheSPDTswitch. Itisessentialthattheswitchusedinthiscir cuithaveacenteroffposition.
Continuousrotationservomotorcalibration
SerialcommunicationtoLCDdisplayis2400baudinverted
xvarbyte

260

ChapterFourteen

Figure 14.11 Servomotor schematic for determining pulse widths for slow forward, slow backward, andstop.

yvarbyte
pause1500
seroutportb.1,4,[ServomotorTest]
pause1000
seroutportb.1,4,[254,1]
pause20
x=150
main:
pulsoutportb.0,x
ifporta.1=0then
x=x+1
endif
ifporta.0=0then

ColorRoboticVisionSystem x=x1
endif
seroutportb.0,4,[254,1,,#x]
gotomain

261

HerearethepulsewidthnumbersIneededfortheservomotorsIusedinmy prototyperobot.
Function Stop Slowbackward Slowforward Rightservomotor 167 160 174 Leftservomotor 169 176 162

Notethatthenumbersrepresent10sincrementsintime.
Sothe167usedintheprogramisequalto1.67ms.

Program3 Thefollowingprogramisforourtrackingrobot. Itusesinformationfromthe Xdatatabletotrackanobject/targetfromlefttoright. ThePIXpixelparame terisusedtodeterminerangeoftheobject. Iftheobject(PIXgetstoolarge) comestooclosetotherobot, therobotwillbackawayfromtheobject. Everythingstatedaboutprogram2alsoappliestothisprogram. Keepinmind thelightingfluorescentorincandescentandremembertokeepthetargetout ofthecamerasFOVwhenitisadjustingfortheambientlight. Againthispro gramjustfitsintothePIC16F84; soifyouaddanythingtotheprogram, evena fewspacesinthedisplay, youstandagoodchanceofitsnotcompilingproperly.
CMUtrackingprogram
ByJ.Iovine
defineosc16
recdatavarbyte[10]
xvarbyte
confidvarbyte
trisb=0
portb=0
pause1500
seroutport.1,6,[CMUPrg.]
seroutportb.2,2,[RS,13]
pause1250
ResetCMUcamera
seroutportb.2,2,[RS,13]

262

ChapterFourteen gosubdisplay
TurngreenCMULEDon
seroutportb.2,2,[L11,13]
gosubdisplay
portb.3=1
Turnonautolightingadjust&fluorescentbandfilter***
seroutportb.2,2,[CR4571844,13]
gosubdisplay
seroutportb.1,6,[AL] pause20000 Turnoffautolightingadjust
seroutportb.2,2,[CR18441932,13]
gosubdisplay
TurngreenCMULEDoff
seroutportb.2,2,[L12,13]
gosubdisplay
portb.3=0
Setpollmode1packet
seroutportb.2,2,[PM1,13]
pause100
Setrawdata
seroutportb.2,2,[RM3,13]
forx=0to10 portb.3=1
pause250
portb.3=0
pause250
nextx
BlinkredLEDtotellusertoreadytarget
Autolightingadjustment
Hold20seconds

portb.6=1 TrackLEDon
TrackwindowcommandlooksatcenterofCMUwindow
Grabsdataandsendsittotrackcolorfunction
Track:
seroutportb.2,2,[TW,13]
pause2000
portb.6=0 main:
TrackLEDoff

ColorRoboticVisionSystem portb.3=1
Sendcommandtrackcolor(withnoarguments)
WilltracklastcolorgrabbedbyTWcommand
seroutportb.2,2,[TC,13]
GatherthemstatisticspacketfromTWcommand
serin2portb.0,84,[strrecdata\10]
confid=recdata[9]
ifrecdata[2]>50andconfid>20thenleft ifrecdata[2]<40andconfid>20thenright ifrecdata[8]<175andconfid>25thenfwd ifrecdata[8]>200andconfid>25thenbwd seroutportb.1,6,[254,1,S] portb.3=0
pulsoutportb.4,668 pulsoutportb.5,676 pause18
portb.3=1
gotomain
left:
seroutportb.1,6,[254,1,L,#recdata[2]]
forx=1to7
pulsoutportb.4,696 pulsoutportb.5,676 pause20
nextx
gotomain:
right:
seroutportb.1,6,[254,1,R,#recdata[2]]
forx=1to7
pulsoutportb.4,668 pulsoutportb.5,648 pause20
nextx
gotomain:
fwd:
seroutportb.1,6,[254,1,F,#recdata[8]]
forx=1to7
pulsoutportb.4,696 pulsoutportb.5,648 pause20
next
MMX MMX PIX PIX

263

Stop
Rightservostop
Leftservostop

Rightservoforward
Leftservostop

Rightservostop
Leftservoforward

Rightservoforward
Leftservoforward

264

ChapterFourteen gotomain:
bwd: seroutportb.1,6,[254,1,B,#recdata[8]] forx=1to7 pulsoutportb.4,640 pulsoutportb.5,704 pause20 nextx gotomain: display:
serin2portb.0,84,20,main,[strrecdata\3]
forx=0to3
serout2portb.1,16468,[ ,recdata[x]]
nextx
pause1500
serout2portb.1,16468,[254,1]
return

Rightservobackward Leftservobackward

Robotconstruction

Bythetimethisbookgoestoprint, thisartificialvisionrobotwillbeavailable asakitfromImagesSIInc. VisittheCMUcamerawebsiteathttp://www.cmu cam.com. We begin by assembling two part As of the standard servomotor

Figure14.12 Twoservomotorbrackets, partA, assembled.

ColorRoboticVisionSystem

265

brackettogether(seeFig. 14.12). AfrontUbracketismadetoassembletothe frontofthetwopartAs(seeFig. 14.13). TheinsidewidthofthefrontUbrack etisthesameasthewidthoftheCMUcamera, approximately2.125in. The frontUbrackethasaholenearthefrontfortheshaftofthefrontwheel. There areholesnearthetopfrontoftheUbracketalso, notshowninthefigure.

Figure14.13 BracketswithUbracketassembled.

Figure 14.14 Robot base with servomotors, wheels, and multidirectional

frontwheel.

266

ChapterFourteen

Figure14.15 Finishedrobot.

Nextweassembleourtwoservomotorsandfrontwheelontothebaseassem bly (see Fig. 14.14). The wheels for the servomotors are the same type of wheelsusedinChap. 8. Thefrontuniversalmultidirectionalwheelisthesame oneusedintheBraitenbergvehiclesinChap. 9. TwosmallLshapedmount ingearsaremadetoattachtheCMUcameratothefrontoftheUbracket. I constructed the entire circuit on a PIC Experimenters Board. I changed theXtalontheboardfrom4.0MHzto16MHz. Powerforthecircuitmaybe obtainedfromanexternalpowersupplyoranonboardbatterypowersupply. ThefinishedrobotisshowninFig. 14.15. RunningtheProgram Whenyoufirstruntherobot, youmaywanttohaveitliftedsothewheelsdont touch. Itsaloteasiertocheckoperationandfunctionwithouthavingtorun aftertherobot. Usetheexperienceyougainedwithobject/targetsusingpro gram2. TheLEDD1flashesaftertheautolightadjustmenttosignalyouto putthetargetinfrontofthecamera. TheD1LEDalsoflasheswhentherobotisinthestoploop. Iincludedthe flashingLEDbecauseitsnotalwayseasytoseetheLCDdisplay. TheprogramreadstheMMXvaluefromtheCMUcameraanddetermines whethertherobotshouldturnleftorright. Youcanadjustthesevaluestosuit yourparticulartarget. Donotmakethegreaterthan()andlessthan()val uesofMMXtooclose. Ifyoudo, therobotwillquiverleftandrightconstantly. If you find the robot constantly overshooting when it turns to the left or right, youcanreducetheloopvalue(x)intheseturnsubroutines.

ColorRoboticVisionSystem

267

GoingFurther Obviously, wehavejustscratchedthesurfaceofplayingwiththeCMUcamera. OnefeatureIdidnthavetimetoimplementwasanupanddowntiltservomo torthatusestheMMYparameter. Thisinvolvesaddinganotherservomotorto therobot, butwouldallowtherobottofollowatargetasitmovesupanddown. IquicklyapproachedthememorylimitofthePIC16F84. IfIhadhadmore time, Iwouldhaveimplementedit, usinganotherPICmicrocontrollerwitha littlemorememory. ThePIC16F628isportBcompatiblewiththe16F84and hastwiceasmuchmemory(2048bytes). Latest updates and information on the CMU camera can be found at http://www.cmucam.comorhttp://www.cmucamera.com. PartsList CMUcamera (2)Servomotors(HS425) (2)PartAservomotorbrackets
16MHzPICExperimentersBoard
(2)Servomotorwheels PIC16F84, 20MHz
16MHzcrystal
(2)22pFcapacitors (2)330, 1/4Wresistors 4.7k, 1/4Wresistor Multidirectionalwheel Aluminumsheetmetal, shaft, plasticscrews, andnuts AvailablefromImagesSIInc. (seeSuppliersatendofbook).

Thispageintentionallyleftblank.

Suppliers

ImagesSIInc. 109WoodsofArdenRoad StatenIsland, NY10312 (718)6988305 (718)9826145(fax) www.imagesco.com JamecoElectronics 1355ShorewayRoad Belmont, CA94002 (800)8314242 (800)2376948(fax) www.jameco.com JDRMicrodevices 1850South10thStreet SanJose, CA95112 (800)5385000 (800)5385005(fax) www.jdr.com

269

Thispageintentionallyleftblank.

Index

Aluminum, 90
Aluminumhipbar, 230
Applicsdirectory, 22
AutoCodeCompletion, 23
Behaviorbased(neural)architecture, 8386
Behaviorbasedrobotics, 86, 87
Berger, Hans, 87
Bigfootwalker, 225
Binary, 6568
Binarycountingprogram, 7172
Binarynumbertable, 66
Bipedalwalkerrobot, 225242
assembly, 230231
feedback, 227
finishedproduct(photographs), 234, 235
footpads, 228230
movie, 225
partslist, 242
pivoting, 242
possibleimprovements, 241242
program, 233241
schematic, 231233
servomotorbrackets, 228
servomotors, 226, 227
turningright/left, 242
(Seealso Hexapodwalkers)
Bit, 65
Bookmarks, 24
Braitenberg, Valentine, 125
Braitenbergvehicles, 125141
backwheels, 129131
CdSphotoresistorcells, 133, 136137
firstvehicle, 128141
frontwheels, 131132
graphs(transferfunctions), 127
neuralI/Orelationships, 126
partslist, 141

Braitenbergvehicles(Cont.):
photographoffinishedvehicle, 140
secondvehicle(avoidancebehavior), 141
sensorarray, 137139
16F84microcontroller, 139
testing, 139, 141
Breadboard, solderless, 4950
Brooks, Rodney, 86
Buildingintelligence, 8386
button, 7275
Byte, 65
Camera(see Colorroboticvisionsystem)
cd, 16
cd.., 17
cd\, 17
CdSphotoresistors:
Braitenbergvehicles, 133, 136137 Waltersturtle, 109110
Centerpunch, 89, 90
CMUcamera, 244245
CodeDesigner, 2335
connectEPICprogrammingboardto computer, 33
EPICprogrammingboardsoftware, 3334
features, 2324
freeversion, 24
partslist, 35
settheoptions, 2533
softwareinstallation, 25
CodeDesignerLite, 24
Coldrolledsteel(CRS), 90
ColoredPicBasicsyntax, 24
Colorroboticvisionsystem, 243267
CMUcamera, 244245
finishedproduct(photograph), 266
improvements, 267
incandescent/fluorescentlighting, 254259

271

Copyright2004TheMcGrawHillCompanies. Clickherefortermsofuse.

272

Index

Colorroboticvisionsystem(Cont.): interfacingCMUcameratorobot, 250251


partslist, 267
program1, 251254
program2, 254
program3, 261264
robotconstruction, 264266
runningtheprogram, 266
serialcommunication, 245248
servomotorforrobot, 259261
16F84runsat16MHz, 251
VBapplicationprogram, 248250
Compiler, 2
installingPicBasic, 1112
installingPicBasicPro, 1218
PicBasic(PicBasicPro), 24
using, 7
Components(see Partslist)
Connectedspeechrecognitionsystem, 168
Consumables, 5
Continuousspeechrecognitionsystems, 168
copy, 16
Countingprogram, 7172
Creationofintelligence, 8386
CRS, 90

dir, 16

DOScommands, 16
DOSprogramming, 3748
compile, 3943 EPICprogrammingboardsoftware, 4448 programmingthePICchip, 4344 DOSprompt, 17
DOSwindow, 17
Drill, 90
Edgedetection, 243244
8bitnumber, 65
ElmerandElsie, 88
EPICProgrammer, 3
EPICProgrammersoftware/hardware, 3
EPICprogrammingboardsoftware, 3334,
4448
EPICprogrammingcarrierboard, 4, 5
ExperimentersBoard(see PICExperimenters
Board) Expertsystem, 8386 Finishedproducts(see Photographsoffinished products; Projects)
Firmware, 5
Flashmemory, 5
FlexiForcepressuresensor, 227

Hammer, 90
Hexapodwalkers, 143164
center(tilt)servomotor, 154155
construction, 148164
electronics, 158159
legpositioning, 152153
linkage, 154, 155
microcontrollerprogram, 159164
mountingtheservomotors, 151152
movingbackward(backwardgait), 146147
movingforward(forwardgait), 145146
partslist, 164
photographoffinishedrobot, 161
robotbase(diagram), 149
robotlegs(diagram), 150
sensors, 155158
servomotors, 144, 145
tripodgait, 143144
turningleft, 147148
turningright, 148
(Seealso Bipedalwalkerrobot)
Highlevellanguage, 2
HiTecHS322HDservomotors, 227
HiTecHS425BBservomotor, 9097
HiTecservomotorhorn, 189
HM2007speechrecognitionintegratedcircuit, 165
HS85MGservomotors, 215
HS322HDservomotors, 227
HS425BBservomotor, 9097
Imageprocessing, 243
(Seealso Colorroboticvisionsystem)
ImagesSIInc., 269
ImitationofLife, An (Walter), 88
Input, 72, 7778
input, 7778
Installation:
CodeDesignersoftware, 25
EPICsoftware, 1922
firmware, 7
PicBasiccompilersoftware, 1112
PicBasicProcompiler, 1218
Intelligence, 8386
Isolatedspeechrecognitionsystems, 168
JamecoElectronics, 269
JDRMicrodevices, 269
Labellistbox, 24
Layeredbehavioralresponses, 8586
LCDdisplay, 5456, 6065
Leggedwalkers, 143
(Seealso Bipedalwalkerrobot; Hexapod
walkers)

Index

273

Lineerrorhighlighting, 23
LivingBrain, The (Walter), 88
MachinaSpeculatrix, 88
MachineThatLearns, A (Walter), 88
md, 16
Metalworkingtools, 8990
MicrochipTechnologyInc., 1, 2
Microcontroller:
defined, 1
features, 1
16F84, 56
whyused, 12
microEngineeringLabs, Inc., 2, 4
Models(see Projects)
Neural(behaviorbased)architecture, 8386
Nibbler, 89, 90
Output, 7071, 7778 output, 7778 Partslist, 89
bipedalwalkerrobot, 242
Braitenbergvehicle, 141
CodeDesigner, 35
colorroboticvisionsystem, 267
hexapodwalker, 164
roboticarm, 223224
speechrecognitionsystem, 182184
testingcircuit, 79, 81
Waltersturtle, 123124
path, 16
Pavlov, Ivan, 87
Pavlovsdogsstimulusresponseexperiment, 87
peek, 7577
Photographsoffinishedproducts:
Braitenbergvehicles, 140
colorroboticvisionsystem, 266
hexapodwalker, 161
roboticarm, 222, 223
speechrecognitionsystem, 179181
Waltersrobot, 122
PicBasic, 2
PicBasiccompiler, 24
PicBasicProcompiler, 24
PicBasicPro/PicBasicsoftware
packages/manuals, 3
PICchips(PICmicrochips), 2
PICExperimentersBoard, 5665
builtinLCD, 6065
experiment(prototypingarea), 5860
LCDdisplay, 5456, 6065
testcircuit(Waltersturtle), 111

PICExperimentersBoard(Cont.): use, 5658


PICmicrochips, 2
PICprogrammingoverview, 24
PIC16F84circuit, 109
PIC16F84microcontroller, 56
poke, 70, 71
PortAregister, 69
PortBregister, 67
Portregisters, 6570
Pressuresensor, 227
Programmingcarrierboard, 4, 5
ProgrammingthePICchip, 7
Projects:
bipedalwalkerrobot, 225242
Braitenbergvehicles, 125141
colorroboticvisionsystem, 243267
finishedproducts(see Photographsof
finishedproducts)
hexapodwalker, 143164
roboticarm, 185224
speechrecognitionsystems, 165183
Waltersturtle, 87124
(Seealso individualsubjectheadings)
QuickSyntaxHelp, 23
Redo/undo, 24
Registers, 65
poke, 70, 71
port, 6570
portA, 69
portB, 67
TRIS, 68
TRISA, 68, 69
TRISB, 67, 68
Roboticarm, 185224 addingabase, 216220 assemblymultipleservomotorassemblies, 189192
finishedproduct(photograph), 222, 223
partslist, 223224
servomotorbrackets, 185189
servomotorcontrollers, 199215
servomotors, 197199, 215
Roboticarmgripper, 193
Roboticarmgripperassembly, 195
Servomotor:
bipedalwalkerrobot, 226, 227
centeringprogram/circuit, 7880
colorroboticvisionsystem, 259261
hexapodwalker, 144, 145
photographof, 79

274

Index

Servomotor(Cont.): roboticarm, 197199, 215 Waltersturtle, 9097 whatitis, 78 Servomotorbracketkit, 186 Servomotorbrackettravel, 187 Servomotorhorn, 189 Shears, 89, 90 Sheetaluminum, 90 Sixleggedwalkerrobot, 143164 (Seealso Hexapodwalkers) 16F84PICmicrocontroller, 56 Solderlessbreadboard, 4950 Speakerdependentspeechrecognitionsystem, 167168 Speakerindependentspeechrecognitionsystem, 168, 172173 Speechrecognitionsystems, 165183 applications, 167 circuitconstruction, 168169 clearingtrainedwordmemory, 172 components, 165166 finishedproduct, 179181 listening/speechunderstanding, 167 microphone, 181 partslist, 182184 programmingspeechrecognitioncircuit, 177178 16F84microcontrollerprogram, 176177 softwareapproach, 167 speakerdependent/speakerindependentsystem, 167168, 172173 speechinterfacecontrolcircuit, 173176 stylesofspeech, 168 testingrecognition, 172 trainingthecircuit, 169172 voicesecuritysystem, 173 wirelessrobotcontrol, 181 Speechsoftware, 167 Stainlesssteel, 90 Standaloneservomotorbracketassembly, 191 Standardbasedexpertprogramming, 8386 Statementdescription, 23 StatementHelp, 23 Subdirectory, applications, 22 Suppliers, 269 TestingthePICmicrocontroller, 4981 accessingportsforoutput, 7071 button, 7275 countingprogram, 7172 input, 72 input/outputcommands, 7778 LCDdisplay, 5456, 6065 partslist, 79, 81 peek, 7577

TestingthePICmicrocontroller(Cont.): PICExperimentersBoard, 5665 (Seealso PICExperimentersBoard) registers(see Registers) schematicsoftestcircuit, 5053 servomotors, 7879 (Seealso Servomotor) solderlessbreadboard, 4950 troubleshootingthecircuit, 54 Tilden, Mark, 86 Tripodgait, 143144 TRISAregister, 68, 69 TRISBregister, 67, 68 TRISregister, 68 trisx.x, 70 Turtlerobot(see Waltersturtle) Undo/redo, 24 VehiclesExperimentsinSyntheticPsychology (Braitenberg), 125 Vise, 90 Walkerrobots(see Bipedalwalkerrobot; Hexapod walkers) Walter, WilliamGrey, 8788 Waltersturtle, 87124 attachingbumpertorobotbase, 101103 behavior, 120121 bumperswitch, 104106 centerofgravity, 100101 drive/steeringmotors, 90 equipment, 8990 fudgefactor, 121 handedness, 123 lightintensity, 121123 modesofoperation, 88 mountingsteeringservomotor, 107108 observedbehavior, 8889 partslist, 123124 photographsoffinishedproduct, 122 photoresistor, 109111 power, 119120 program, 115119 schematic, 114118 sensorarray, 112114 servomotor, 9097 sheetmetalfabrication, 9798 shell, 99100 sleepmode, 119 WindowsversionofEPICsoftware, 8 wink.bas circuit(solderlessbreadboard), 53 wink.bas program, 45

xcopy, 16

ABOUTTHEAUTHOR
JohnIovineistheauthorofseveralpopularTABtitlesthat explorethefrontiersofscientificresearch. Hehaswritten HomemadeHolograms: TheCompleteGuidetoInexpensive, DoItYourselfHolography; Robots, Androids, and Animatrons: 12IncredibleProjectsYouCanBuild, consideredacultclassic; KirlianPhotography: AHandsOn Guide; FantasticElectronics: BuildYourOwnNegative IonGeneratorandOtherProjects; and AStepintoVirtual Reality. Mr. IovinehasalsowrittenextensivelyforPopular Electronics, Nuts&Volts, ElectronicsNow, and otherperiodicals.

Thispageintentionallyleftblank.