EXPERimENTS EVIL GENIUS

M' I ' OREN YOUR HEAD, ADD THE CONTENTS OF THIS BOOK STIR WITH YOUR IMAGINATION, AND BUILD SOME GREAT TAB WAITAKERE LIBRARIES ROBOTICS

886605 7 PRINTED CIRCUIT BOARD IT1YKE PREDKD INCLUDED MASSEY LIBRARY

123 Robotics Experiments for the Evil Genius 123 Robotics Experiments for the Evil Genius

MYKEPREDKO

McGraw-Hill New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Seoul Singapore Sydney Tdronto Library of Congress < 'ataloging in-Publication Data

Predko, Michael. 123 robotics expeiiments for the evil genius / Mvke Predko./ p. cm ISBN 0-07-141358-8 1 Robotics 1. Title: One hundred twenty-three robotics exeriments for the evil genius. 11. Title: One hundred twenty-three robotics experiment' for the evil genius. Ill Title.

TJ2T1.P73 2003 629.8'92—dc22 2003066532

Copyright © 2004 by The McGraw Hill Consnipanies. Inc. All rights reserved. Printed in the United States of America. Except as permitted under the United States C opyright Act of 1976. no part of this publication may be reproduced or distributed m any form or by any means, or stored in a data base or reti ieval system, without the prior written permission of the publisher. I 2 3 4 5 6 7 8 9 0 QPD/QPD 0 9 8 7 6 5 4" 3

P'N 141359-6 PART OF ISBN 0-07-141358-8

The sponsoring editor for this hook was Judy Buss and the produc lion superv isor was Pamela A Felton. It wav set m Times Ten by Mat Alfister Publishing Services, LLC.

Pruned and hound by Quehecor/Dubuque.

This book is printed on recycled,acid free containing a minimum of 50 percent recycled de-inked fiber.

McCIraw-Hill books are available at special quantity discounts to use as premiums and sales promo tionx, or for use in corporate training programs. For more information, please write to the Director of Special Sales, McC it aw Hill Professional, Two Penn Plaza, New York, NY' 10121-2298. Or contact your local bookstore.

Information contained in this work has been obtained by The McGraw Hill Compa¬ nies, Inc ( McGraw Hill") from sources believed to be reliable However, neither McC iraw- Hill nor its authors guarantee the accuracy or completeness ol any informa lion published herein,and neither McGraw-Hill nor its authors shall be responsible tor any errors, omissions, or damages arising out of use of this information. Ibis work is published with the understanding that McGraw-Hill and its authors are supplying information but are not attempting to render professional services. If such services are required, the assistance ol an appropriate professional should be sought. o o Contents ■■ MB MBI BMi BBS BM BM Hi MB BBB H Mi £| (D 3 ft Mvke’s Rules of Robotics ix Experiment 15 Resistors and Voltage Drops 44 Section One Introduction to 1 Experiment 16 Current Measurement and Ohm's Law 46 Experiment 1 Toilet Paper Roll Experiment, 17 Kirchoff’s Voltage Law M android 2 and Series Loads 48 Experiment 2 Pipe Cleaner Insect 5 Experiment 18 Variable Resistors 50 Experiment 3 LEGO Mobile Robots 7 Experiment 19 Kirchoff’s Current Law and Parallel Loads 53 Experiment 4 Cardboard Arm 10

Experiment 20 Thevinu.Cs Equivalency 55 Section Two Structures 15 Experimi NT 21 Power 57 Experiment 5 Cutting Plywood 17 Experiment 22 Batteries 59 Experiment 6 Strengthening Structures 20 Section Four Magnetic Devices 63 Experiment 7 Finishing Wood 22 Experiment 23 Electromagnets 65 Experiment 8 A Gaggle of Glues 24 Experiment 24 Relays 67 Experiment 9 Nuts and Bolts 25

Experiment 25 Measuring the Earth’s Experiment 10 Soldering and Splicing Magnetic Field 69 Wires 28 Experiment 26 Direct Current ( DC) Experiment 11 Assembling the Included Motor 71 PCB 31 Section Five Drivetrains 75 Section Three Basic Electrical Theory 35 Exerimenf 27 Motor-Driven Crane 77

Experiment 12 Electrical Circuits and Experiment 28 Pulleys Added to Switches 37 Ciane 79

Electrical Circuits and Experiment 13 Experiment 29 Switch DC Motor 40 Switches MI Bridge" 80

Experiment 14 Voltage Measurement 41

Contents V Contents vi Contents Experiment 44 Experiment 43 Section Seven Experiment 31 Experiment 45 Section Eight Experiment 42 Experiment 41 Experiment 39 Experiment 38 Experiment 37 Experiment 36 Experiment 34 Experiment 40 Experiment 35 Experiment 33 Section SixSemiconductors Experiment 32 Experiment 30 Experiment 47 Experimeni 46 555 Chip Stepper Motors Robot Chassis Differential Drive Muscle Wire 555 ButtonDebounce Transistor Motor Transistor Sensor White/Black Surface Optoisolator Lockand Changing anLEDs Light-Seeking Robot Motor Control Key Multisegment LEDs Brightness Different ColorLEDs R/C ServoControl Blinking LEDs H-Bridge LED LightingControl NPN TransistorandTwo- (LEDs) Bipolar PNPTransistor Driving aMotorwith Light-Emitting Diodes Diodes Optoelectronics Our Friend,the 107 121 133 114 .112 104 124 117 109 102 128 126 131 91 88 85 82 99 97 95 93 Experiment 49 Experiment 50 Section Nine Experiment 57 Experiment 55 Section Ten Experiment 52 Experiment 51 Experiment 48 Experiment 66 Experiment 63 Experiment 62 Experiment 61 Experiment 60 Experiment 54 Experiment 53 Experiment 65 Experiment 64 Section TwelveSequentialLogic Section ElevenPowerSupplies Experiment 59 Experiment 58 Experiment 56 Circuits Digital Logic TIL “NOP'Gate Sound-Level Meter Code PracticeTool Line FollowingRobot Full DFlipFlop from theNORGate CMOS TouchSwitch Electronic Stethoscope Basic TransistorOscillator Buzzers Audio Electronics Flops Supply Switch ModePower Zenet Diodes XORs andAdders Common l.ogieBuilt Sum ofProductCircuits Basic GateOperation Edge-Triggered Flip Bipolar Transistor-Based Linear PowerSupply Mickey MouseLogic Pull-,y ps/Pu11-Downs RS FlipFlops 139 151 173 183 189 179 155 145 177 170 161 158 153 175 168 163 135 187 185 166 141 148 143 Contents Experiment 67 Flip Flop Reset 191 Experiment 85 Creating Simple Program I .oops 232 Experiment 68 Parallel Data 193 Experiment 86 Conditionally Looping 233 Experiment 66 Traffic Lights 194 Experiment 87 ’■Power Off" Experiment 70 Shift Registers 198 Application 235

Experiment 71 Christmas Decoration 200 Experiment 88 Conditionally Executing Code 236 Experiment 72 Random Movement Robot 203 Experiment 89 Advanced Conditional Execution 238 Expf riment 73 Counters 205 Experiment 90 l Ring the “for" Loop Expi riment 74 Schmitt Trigger Inputs in Your Application 236 and Button 1 )ebounce 207 Experiment 9] Sa\ ing Code Space Experiment 75 PWM Generation 209 t Ring Subroutines 242

Section Thirteen Learning to Section Fourteen Interfacing Program Using the Parallax I lardware to the BASIC BASIC Stamp 2 213 Stamp 2 247

Experiment 76 Loading BASK ' Stamp Experiment 92 Controlling an LED 246 Windows Editor Software on Your PC’ 214 Experiment 93 Cylon Eye 250

Experiment 77 Connecting the PCB Experiment 94 Hitachi 44780-Controlled and BS2 to Your PC I iquid Crystal Display 252 and Running Your First Application 216 Experiment 95 Musical Tone Output 254

Experiment 78 Saving Your Applications Experiment 66 Electronic Dice 256 on Your PC 218 Experiment 67 Keypad Input 257 Experiment 79 The “Hello World!” Application Explained 220 Experimen r 68 Resistance Measurement 256 Experiment 80 Variables and Data Types 222 Experiment 66 PWM Analog Voltage Output 261 Experiment 81 Number Data Formats 224 Experiment 100 R-2R Digital-to- Experiment 82 ASCII Characters 226 Analog Converter 262

Experiment 83 Variable Arrays 228 Section Fifteen Sensors 265

Experiment 84 I Ring Mathematical Experiment 101 bLiza. the Snarky Operators in the Computer 267 Assignment Statement 230

Contents vii Contents Section Sixteen Experiment 104 Experiment 103 Experiment 102 vi i Experiment 108 Experiment 106 Experiment 111 Experiment 109 Experiment 107 Experiment H)5 Experiment 112 Experiment 110 Experiment 114 Experiment 113 Sensors Displays Multiple Seven-segment Sound Control State Machine Differential Light RCtime LightSensor DC MotorControl Servos Controlling Multiple Drivers Base withH-Bridge R/C ServoSetup Explained Programming [R ObjectSensors Robot “Whiskers” Robot Base Remote-Control Car Random Movement Robot MothExample Mobile Robots Contents 287 273 283 280 278 275 271 289 294 292 303 300 298 296 Experiment 115 Section SeventeenNavigation Experiment 116 Experiment 118 Experiment 117 Experiment 121 Experiment 120 Experiment 119 Experiment 122 Experiment 123 About theAuthor Acknowledgments Index PBASIC Reference Stepper MotorControl Wall FollowingRobot Comma nications Infrared Two-Way Programming Parallax’s “GUI-Bot” Measurement Line-Following Robot Interface Robot Artist Hall EffectCompass Ultrasonic Distance NMEA GPSInterface 319 343 341 335 357 305 31 1 308 324 321 314 332 330 326 Myke's Rules of Robotics

Myke's Rules of Robotics

throughout Sis book, I will be keeping to my 10 6. The faster a robot runs, the more impressive it rules of robotics: is.

1. Start small. 7. Object detectors should detect objects far enough away from the robot so that it can 2. Design everything together. stop before damaging the object or itself.

3. Jerkiness in a robot is not a selling point. 8. Complexity adds weight.

4. Protect your drivetrains from the environ¬ 9. Weight adds weight ment. ID. If the robot isn't doing anything, it shouldn't 5. Keep the robot’s center of mass in the center be expending any energy. of the robot.

Myke's Rules of Rubntics 1 X Section One Introduction to Robots

When you think of the term “robot,” what comes to actions automatically. 3 a person w ho works mind? Ihe following are some definitions that mechanically and efficiently but insensitively attempt to explain what a robot is: The Canadian Oxford Dictionary, 1998

Humans are the ultimate generalists, with a form A true robot is a machine that can be “taught,” designed by millions of years of evolution to programmed like a computer, to make different respond to a very wide variety of circumstances. The kinds of motions and perform a variety of jobs. ... science and technology of robotics is usually Machines that do one job only and cannot be concerned with building machines to perform a retrained" are not true robots, either. The New Book of Knowledge, 1998 much smaller number of tasks within a specific set of problems, such as inspection or assembly parts on Robotics A field of engineering concerned with production lines. Such lobots generally have a much the development and application of robots, as well as simpler form They often consist of a jointed arm computer systems lor their control, sensory with a gripper or other devices that work like a hand feedback, and information processing, there are and a microprocessor that functions like a brain. many types ol robotic devices, including robotic Encyclopedia of Technology and Applied Sciences, 1994 manipulators, rohot hands, mobile robots, walking Robot “A reprogrammable multifunctional robots, aids for disabled persons, telerobots, and manipulator designed to move material, parts, tools microelectronomechanical systems. or specialized devices through various programmed The McGrow-Hill Encyclopedia of Science A Technology, 8th Edition motions for the performance of a variety of tasks." Robot Institute of America. 1979 A robot is a mechanical device that operates automatically. Robots can perform a wide variety of Now, here we go on a more detailed examination tasks. They are especially suitable for doing jobs too and explanation ot robots, which, to coin a boring, difficult, or dangerous for people The term definition, are fully automated machines which may robot comes from the Czech word robota, meaning respond to external stimuli as well as to internal drudgery. Robots efficiently carry out such routine commands which have been prerecorded It is tasks as welding, drilling, and painting automobile important to note that we have here the term body parts. “robot." which is different from android, or droid for The World Book Encyclopedia, 190$ short, or from humanoid another term associated with these machines. A robot is a machine that performs a task The Complete Handbook of Robotics, 1984 automatically The robot’s actions are controlled by a microprocessor that has been programmed for the Robot Any mechanical device that can be task. The robot follows a set of instructions that tell programmed to perform a number of tasks involving it exactly what to do to complete the task. manipulation and movement under automatic World Book s Young Scientist 2000 Control. Because of its use in science fiction, the term

robot suggests a machine that has a humanlike robot /'ro:bot'n I a machine with a human appearance or that operates with humanlike appearance or functioning like a human. 2 a machine capable of carrying out a complex series of

1 Experiment 1 — Toilet Paper Roll Mandroid 2 would beabiped,thesameashumans.Abipedcon¬ that aresimilartoours. can createmachinessimilar to ours,musthavebodies was feltthataliens,evolved to thepointwherethey clusion waslargelybasedonthescientists'familiarity sists oftwoarmsandlegsarrangedsymmetrically ied rangeoftasks.Carrying this lineoflogicfurther,it around averticallme.lhereasoningbehindthiscon¬ likely bodyshapeanalienfromspacewouldhave tion, arecapableofcarrying outanastonishinglyvar¬ die resullothundredsofmillionsyearsevolu with theirownbodies:Recognizingthathumans,as In the1050s,scientistsdetemunedthatmost different situationsitmayencounter.Twocommon with someartificialintelligencesothatitcanreactto very littlephysicalresemblancetohumans. capacities: inactualitymodernindustrialrobotshave arc tasksforthemtoperform types ofrobotsareagentsandspiders. more tasksrepeatedly,withspeedandprecision. human intervention.Typically,arobotisendowed Robot Australian RoboticsandAutomationAssociation A robothasthreeessentialcharacteristics: ITiere areasmanydifferenttypesofrobotsthere matically. After beingprogrammed,itoperatesauto¬ variety oftasks. It possessessomeformofmobility. It canbeprogrammedtoaccomplishalarge (2) Aprogramthatrunsautomaticallywithout (1) Adevicethatrespondstosensoryinput. A robotisamachinedesignedtoexecuteoneor 1E3 Robotics Experiments for the EvilGenius AP DictionaryofScienceandTechnology Toilet PaperRollMandroid Experiment 1 w hatis?coni Webopedia the definitionsabove. ent typesofrobotsexist,eachonemeetingsome people havewidelydifferentandoftenconflicting a robotisandhowitsupposedtowork.Different designing andbuildingasimple bipedrobotoutof start designingandoperating robotsBecausewe sense becausewearecomfortablewithusingour robot liketheTerminatororRobbyRobot.Using should look.Ifyouwereaskedwhatarobot you’ve neverheardofmeorthisbook. over theworldanditfails,whenauthoritiescome, many oftheskillsandmuchknowledgetocre¬ the differenttypesofrobotsandintroduceyouto ideas ofwhatarobotisanditisn't.Manydiffer¬ have asuccessfultormtofollow (ourown),let'sstall bodies tomovearoundand manipulateobjects. using thesamebodytypesaswehavemakesalotof look like,youwouldprobablythinkfirstotabiped through whentheyarethinkingabouthowrobots ate yourownrobots. the logicofscientists1950s,buildingrobots Clearly, noonesingledefinitionencompasseswhat Tins lineotthinkingisessentiallywhatpeoplego Just rememberthatifyoucreatearobottotake As thisbookisaboutrobots. I’msureyouwantto In thefollowingpages.Iwillinvestigatesomeof through inaction,allowahumanbeingtocome as suchprotectiondocsnotconflictwiththeFirstor beings exceptwheresuchorderswouldconflictwith harm, Second Law. the hirstLaw. 2. Arobotmustobeytheordersgivenitbyhuman 3. Arobotmustprotectitsownexistenceaslong J. Arobotmaynotinjureahumanbeing,or, Isaac Asimov toilet papex rolls, pipe cleaners, and some glue. ()nce are important to other people). I shouldn’t have to Experiment 1 — Toilet Paper Roll Mandroxd. this robot has been built, you can perform the book’s say this, but you should wait tor toilet paper rolls to first experiment for yourself—seeing how a biped become available: don’t expedite the process of robot would transition from standing straight up to getting bare toilet paper rolls. I don’t want to get any walking forward. Once we have done this, we can angry emails from parents saving that one day they start experimenting with other actions humans per walked into their bathroom and found enough toilet form. paper lying on the floor to fill 10 rolls. The mandroid for this experiment consists of a ()nce you have the cut pipe cleaners to size using a skeleton of used toilet paper rolls that are connected sharp knife, cut one of the rolls into two smaller cylin¬ using pieces of pipe cleaner that have been glued to ders, each piece 1 inch (2.5 centimeters) long.The the inside of the toilet paper rolls. If the toilet paper longer piece will become the •‘back" of the robot with rolls are analogous to the bones in your body, then the small cylinder being the robot’s “pelvis.” On the pipe cleaners are the connective tissues and your another toilet paper roll, cut a ring about 0.75 inches (2 joints. In the plan view (Figure 1-1), note that I have centimeters) long: this will become the robot’s “head.” specified locations for the pipe cleaners so that the W ith the other eight rolls of toilet paper, you are skeleton can move (or articulate) the same way that ready to start assembling the robot using some kind your body can Because we are following a human of paper or wood glue. Model airplane cement, epox¬ model very closely, we can expect to be successful and ies. and contact cements are not appropriate for this be able to go on to other experiments with this robot, task You may want to try using a cyanoacrylate such such as having it walk over to an object and pick it up. as Krazy Glue to hold down the pipe cleaner pieces Note that for 1 he different pipe cleaner joints, before using the paper or wood glue. Personally, I you'll see that I took into consideration their place¬ would discourage doing this as you will probably end ment so that the robot would be capable of moving in up gluing y ourself to short pieces of pipe cleaner and the same manner as a human being. empty toilet rolls. After other people see this, it will To build the robot, I cut 10 2.5-inch-long (6.4 cen¬ be hard for them to think of you as an “Evil Genius” timeters) pieces of pipe cleaner and collected 10 old with any kind of seriousness. toilet paper rolls.To cut pipe cleaners. I used a set of On each toilet paper roll, put down a 1 inch (2.5- wire clippers- don’t use scissors (especially ones that centimeter) bead of glue along the inside to affix one

“Shoulder' “Neck” and "Spine"

“Torso' and ' Pelvis” cut from a single roll. “Pe'vis” is 1” (2.5 cm) Long. “Hoad" is cut from a single roil and is 1 2 "(3 cm) long

Figure 1-1 Toilet paper robot plan

bection Dne Introduction to Robots 3 Experiment 1 — Toilet Paper Roll Mandroid. come upwiththemotionrequiredtowalkwithout of daysorsofromwhenyoustarted),willhavea glue themtothetorso.onesideatatime,avoid other 1.5inches(3.8centimeters)outsidetheroll end ofapiecepipecleaner.Push1inch(25cen¬ could supportitselfstandingup.itisverydifficultto going throughlheeffort.Evenifyouhadarobotthat with howyouwillmakeilwalk. the collectionoftoiletpaperrollsinasetposition. cleancr, youcandrawafewconclusions.Thefirstone port therobotsothatyoucanstaitexperimenting ing togetarobotlochangefromstandingstraightup having thegluerun.Whenyouarefinished(acouple leave itlodryforanotherday.Therewillbe0.5 a day. make surethatitissecure.Oncethisdone,leave When youhavepushedthepipecleanerdowninto timeters) ofpipecleanerinti'theglue,leaving the pipecleanerswith.but1wantlotellyoutoavoid You mightbethinkingotmaterialsyoucouldreplace is thatpipecleanersarenotrigidenoughtosupport have thevexingproblemofdetermininghowtosup¬ ingly looselyconnectedemptytoiletrolls,similarto try togetitlostandup to walkingforward.Withtheglueonyourrobotdry, model robotthatlooksliketheoneinFigure1-1. between thetworolls.Oncepieceshavedried, inches (1.25centimeters)ofpipecleanerjoint toilet paperrollusingexactlythesameprocessand timeters) oftheexposedpipecleanerintoanother the rollsoftoiletpaperandpipecleanerstodryfor the glue,putsomeglueontopofpipecleanerto 4 the pileIendedupwith(Figuie1-2).Youwillalso Chances areyouwillendupwithaheapofseem¬ Looking atthisheapofpaper,glue,andpipe Next, repeattheprocessbygluing1inch(2.5cen¬ As Iindicated.wouldliketoexperimentwithtry 1E 2 Robotics Experiments for the EvilGenius year orsotoprogramyourselfstandupandwalk the robotfallingover.Rememberthatittookyoua incredibly challengingtaskinwhichlarge,well- robots. Stairs areaparticularlyvexingproblemforwalking figure outhowtoturnandwalkoveruneventerrain. aspect oltheproblem—alongwithit.youwillhaveto forward, andinyourcase,youhadallthenecessary sights atthebottom. and actslikeahuman,butforrightnow,let’ssetour a robot.Onedayyoumaybuildrobotthatlooks essary skillstobuildthedifferentcomponentsusedin looking atthemfromthebottomup,gainingnec¬ to changethewayyoulookatrobotssostart ning tohavesuccess.Withthisinmind,1wouldlike funded companiesandlaboratoriesarejustbegin¬ roboticists asthe“HolyGrail”ofrobotics—itisan and walklikeahumanbeingisconsideredbymany equipment tobeginwith.Walkingforwardisjustone building yourownrobots Figure 1-2Notanauspiciousbeginningto Designing amobilebipediobotthatcanstandup Xperiment 2 — Pip© Cleaner Insect w Experiment 2 Pipe Cleaner Insect

In the first experiment in this book, I gave you some By going to a lower life-form with four legs, we idea how difficult it is to create a robot based on the have solved the problem of being unstable when human form l mentioned that there would be prob¬ standing up. but we still have a problem of move¬ lems getting the robot to walk, but didn't go into ment. Let's look for a lower life-form that ean move detail because I didn’t know of a way to get the robot on multiple legs, but is always stable.The obvious to even stand reliably. Before starting to work on animal that meets this requirement is the bug If you actual robots. I think that it is important to come up observe the motion of an ant (cockroaches are too with a platform that is stable (it ean stand up reliably) fast), you will see that at all times, the ant has at least and then investigate how the robot can move or three legs on the ground. As I show in Figure 1 3, manipulate objects. w hen an ant moves forward, two legs on one side When looking for ideas or a better understanding and one leg on the other are pushing it forward of how' to approach a problem, you will often find, the while the other three legs are getting into position to answer by looking at nature and seeing how different take over and move the insect forward. animals (and even plants) respond to the same chal¬ The legs must be hinged and driven in such a way lenge. If we want to look at a stable platform capable that they can move up and down and back and forth. of movemenl and moving objects, then we will proba¬ Moving the lower leg up and down pushes the insect bly look through different multilegged animals,This off the ground, and moving back and forth is used to should be an obvious simplification of the robot plat either propel the robot or move the leg into position form. As a child, you were able to learn to craw 1 on to propel the insect. Figure 1-4 shows a mechanical all fours much sooner than you were able to walk analog of an insect leg with the side-to-side motion Looking at animats that can walk around on all provided by a hinge joint on the side of the insect, fours and manipulate objects similarly to humans, the and the up-and-down motion accomplished by mov¬ obvious animal to me is the elephant. It can move ing the lower leg up and down. around on ils legs and manipulate objects using its When referring to robot arms and legs, each trunk.The problem with the elephant fand any four¬ dimension the limb can move in is called a degree of legged animal) is its dynamic and unstable motion. freedom. Although this simple insect leg only has two As the elephant walks, it transfers mass between its degrees of freedom (up/down and back wards-for¬ different legs so that it never quite falls over. Imple¬ wards). you will find that other robots have limbs menting this motion in robots is not terribly difficult, with as many as eight degrees of freedom to allow but it has the problem of the robot falling over if it them to perform complex tasks. were to stop abruptly or with one leg left in the air ITie insect is always stable (its center of gravity is As a simple test of this statement, get down on always in the center of at least three legs), and if it your hands and knees and craw l across the floor, were to stop for any reason, it wouldn’t fall over stopping abruptly with one arm or leg in the air because it is always stable, unlike the four legged ani¬ Depending on what you are holding up when you mal. Along with forward movement being casih stop, you will either fall onto your side or your face. implemented, changing direction for an insect is also Initially, it might be difficult for you to tall over; you quite simple. This is why insect-based robots (some¬ will automatically compensate for the lifted limb and times called insectoids) are more popular than ones move your body’s center of gravity so that you are based on cats, dogs, or elephants. stable on three limbs You might want to conduct this You can very easily investigate the properties of experiment over a gym mat to make sure you don't the insect-based robot by building a simple model for hurt yourself.

- * Section One Introduction to Robots 5 Experiment 2 — Pipe Cleaner Insect cleaner thatwaspresentoneachsideandthenglued direction,causing adifferentialforceontheinsect are stored),andpushedapipecleanerthroughthe |cgS ,nasimilarmannerasmovingforward,but yourself. Formyprototype.Iusedhalfofthebottom 6 hole. OnceIhadthesixlegs(madeoutofthree instead ofmovingillthreelegsinthesamedirection, in thesideofeggcarton(ineachwellwhereeggs Turning theinsectisaccomplishedbymoving pipe cleaner“legs.”Tocreatethelegs.Ipokedholes strate howaninsectmovesforwardquiteeasily, of aneggcartonand,usingwhiteglue,mountedsome 1 -6showingthemotionloraninsect,youcandemon¬ you canseeinFigure15are stiicilyfordecoration.w^iyourpipecleaner and eggcrateant pipe cleaners).Ievenedouttheamountof the singlelegononesidemovesinopposite with themotionoflegs. Using Figures1-3andneedfortherobottosupport itselt.Dependingon dry. Onceithasdried,youcan st.irtexperimentingshouldseetwoofareas ofconcern.'Thefirstisthe the legsintoeggcartonwells.Theantennaethat and turningit.Thiscanbeveryeasilydemonstrated Figure 1-3Insectmovement \ou willfiiidthatittake adayforthegluetoReviewingmodelrobot you’vejustbuilt,you Surface MovingForwardtoPush Shaded LogsonSurface,Pushing Next. insect Forward.WhiteLogsoff 123 Robotics Experiments for the EvilGenius Move 1 Figure 1-5lhecompletedrobotinsect to PositionDriveInsect. to SurfaceandPushingInsect Lifted upandMovedBacktoPosition Forward LegsPreviouslyonSurface Legs PreviouslyoffSurfaceLowered Move 2 how the robot is implemented, this could be a major concern as the weight ot the robot may be more than K what the legs (and the mechanisms that drive them) can handle. Ihe second is the apparent complexity of the robot -you are probably feeling like there could (D be an easier way of developing a mobile robot. h H* 3 (D Shaded legs on left side push to the rear while the shaded leg on the 2 right side pushes forward. The white legs are above the surface, preparing to continue the turn c+

Figure 1 6 Insect turning 00

V-l Experiment 3 'm LEGO Mobile Robots y) oO

In the pre\ ious pages. I have looked at some different seen in Figure I 7, the "right” wheels (closest to the types of legged mobile robots. In presenting these dif¬ axis of the turn I w ill have to be at a sharper angle s ferent types. I have also noted that they have some than the "left'' wheels. (Actually, when you look at fairly significant concerns that go with them in terms Figure 1-7,you will see that all four wheels are actu tr of complexity. Thinking about it, you may come to ally turning through a slightly different radius curve.) H' the conclusion that basing robots on some kind of Most cars have an offset built into the steering gear life-form is not the best way to design them, and pieces (known as linkages) that automatically turn (D maybe wc can look somewhere else for inspiration. the wheels at the required angle.This can be built In our modern society, many different moving into a robot, but you will have to work through the W devices do not follow the human, animal, or insect proper angles of the linkages to be successful. O form that was discussed previously in this section. For tr example, virtually HX) percent of the cars on the road Front Wheel Tracks o are built using the same platform consisting of four rt wheels, two of which are driving and two are steering. (/) For most modern (front-wheel drive) cars, the steer¬ ing wheels are also the driving wheels. Left Wheel Making the use of the car platform very attractive Angle is the ability of many different model remote-control (12 Degrees) (R/C) cars to be converted into a robot format. Later m this book, I will discuss my experiences trying to convert a prebuilt car product into a base for a mobile robot. It you want to build a car platform from scratch, you will discover two different problems that have to Rear Wheel Tracks be overcome when you want to turn the vehicle, fhe Figure 1-7 Car turning first one has to do with the steering wheels. As can be

Section One Introduction to Robots 7 Robot designers use two common solutions to this when the robot is turning. In the diagram of a car in a problem.The first is to just use a single steering tui n (Figure 1-7), you can see that the inside wheels wheel. By doing this, the robot base is known as a tri¬ have a smaller radius than the outside wheels.This cycle for obvious reasons. ITie second solution to the smaller radius means that the inside wheels have to different angle on the steering wheels is to mount go a shorter distance in the same amount of time as both of them on a single bar, like a toy wagon. Using the outside wheels. In a car. the solution to this prob¬ a few pieces of LEGO, you can build a model of a car lem is to build in a differential, which is a special type robot with wagon steering, like the one shown in Fig¬ of gearbox that changes the speed of the different ure 1-8. driving wheels depending on the angle of the turn. A For ihe examples in this experiment, I bought a differential could be built into a robot, but a much LEGO Creators kit. which costs less than $10. If you simpler solution is to just drive one w heel have any LEGO toys in your home, chances are you For many robot designers w ho want to create a CO will have enough parts to build the example robot steered robot, the tricycle platform, with the steered -p models in this section without having to buy anything wheel being driven (the other two wheels are allowed o else. \\ hat you need is four wheels with axles to turn freely) is the optimum choice. attached to LEGO blocks, a vertical hinge (or small, rQ For other robot designers, after looking at the o round pieces of I ,E GO that will allow a block to extra complexity of turning the wheels, they question poor), and a few LEGO blocks to hold the model P6 the need for steering wheels at all In Figure 1-9,1 robot together. have built a simple LEGO robot with only two This method works reasonably well, but can result wheels. 0) m the robot tipping over when turning sharply, and it This is the simplest robot that you can build and it can have difficulty running over rough surfaces. Ihe is known as a differentially driven robot because the •H second issue with the car-based mobile robot is the two wheels should be capable of moving independ¬ X difference in speeds between the driving wheels ently so the robot can turn. With this robot model, a 2

O 8x6 Flat “Top” O Side View U» m m ^

4x2 Front I ro 6x2 “Spine' 4-> c ) p DOC r o Front View ooo | o 4x2 Squares ■ n n k i i-» n . e w with Axels | -|—’ Round *H r o *—- u - Steering M Bearing

8 1E1 Robotics Experiments for the Evil Genius Top View Experiment 3 — LEGO Mobile Robots o o o o 3 O' o o o o O o o 600o : . 3 3 0 0 0 OOO o o OOP o o

lJ0 o o o ooo B _ Ufi ooo OOOGOOOO O O O O O Oooo O o o o o o O Q / o o o o o o 4x2 Axel 8x6 Flat Blocks Base \ Three 10x2 Flat Chassis

Figure 1-9 Two-wheel, differentially driven Lego robot

you can place your fingers on the wheels and see how the base for the actual mobile robots I work through the robot moves with the wheels both going in the later in the book. same direction, as well as turning the robot by turn¬ An evolutionary step for the differentially duven ing the wheels at different rates or even turning the robot is the tracked differentially driven robot, which wheels in different directions. uses tracks like a military tank or bulldozer. This type It you look at different robots on the Internet,you of robot handles uneven surfaces very well (which is will discover that 90 percent or more of the different whv it is used for tanks and bulldozers), but it can robots that have been built at home follow this for¬ have a lot of resistance to movement. This is espe¬ mat. Of the different robot body types investigated so cially true when you are trying to turn the robot. far. this is the simplest and least expensive to imple¬ To minimize the robot's turning resistance. I feel ment— its only real problem is that it does not handle the optimal solution is to have two driving wheels on changing or uneven surfaces well. each side of the robot (both linked to each other). It is very easy to develop circuits and software to You can build this robot very simply using the LEGO control the motion of the two wheels of this robot, pieces you’ve used for the previous example bases as and I will be using the differentially driven robot as shown in Figure 1-10.

Top View

10x2 Flat 4x2 Axel “Chassis" Blocks

Figure 1-10 Design for a four-wheeled LEGO cart

Section One Introduction to Robots 9 Experiment4 4 — Cardboard Arm per) asasetofweldingtongs.Thepaintingrobot's job thatithastodo.Theweldingrobotisdesigned These robotsareusuallydesignedtooperatefrom So farIhavediscussedmobilerobots,robotsthatcan gripper isactuallyapaintsprayer.Theassembly would discoverthateachoneiscustomizedforthe simply pickingupandmovinganobject.Ifyouwere assembling parts.Noneoftheseoperationsinvolve see robotspainting,welding,drivingbolts,and some kindofbase(itcanmove)andpicksomething robotics researchistheoperationofrobotarms. move aboutundertheirowncontrol.Anotherareaof of thesecases,specializedhardwareisaddedtothe with its“hand”(alsoknownasanendeffectororgrip¬ to examinetherobotsusedassemblecars,you similar totheCanadarmonspaceshuttle. robot forittoperformthedesiredfunction. robot hasanairwrenchforitsendeffector.Ineach were togointoanautomobilefactory,youwould tic definitionofarobotarm.Youknowthatifyou move objectsprobablyseemslikeanoverlysimplis¬ ment. youwillbuildasimplemodelrobotarmthatis up andmoveittoanotherlocation.Inthisexperi¬ 10 Figure 1-11/Imodelrobot armthatyoucanbuild Saying thatarobotarmcanjustpickupand 12 3 Robotics Experiments f 0rthe EvilGenius Pipe Cleaner Base Joint” “Elbow’ Pipe Cleaner 4 5”l.ong “Upper Arm” 4'- Long Forearm”-. Pipe Cleaner "Gripper’ Experiment A Cardboard Rrm similar toahuman. the robotmovestoolstoworkarea.Byimple¬ shown withabasejoint,elbowandtwo pieces, andusingtourpiecesof2.5-inch-long(b.4 the corefromarolloffaxpaper,cutitintotwo experiment.The differenceinthisrobotisthatIused with thetoiletpaperrollbipedrobotinfirst ple robotarmmodelinmuchthesamewayyoudid menting themanufacturingprocessusingthis to bepickedupbytherobotarm’sgripperandthen used toperformmultipletasks,thetoolsaredesigned centimeter) pipecleaner,Igluedthemtogetheras methodology, therobotarmisworkinginamanner similar towhatisshowninFigureI-12,andtried the piecesofpipecleanerintothem,andletthemdry II shapedpiecesforthegripper. pipe cleanerbasejointandmovedtheaimaround, for adayorso. (2.5 centimeters)otwhiteglueintotherolls,placed In somemanufacturingsettingswhereonerobotis In Figure1-11,1haveoutlinedhowtobuildasim¬ When thegluehaddried,1thenhelddowntilt- Like thetoiletpaperrollbipedrobot,Tput1inch move means increased complexity of the joints and Section One — Introduction to Robots the requirement for stronger actuators (the mecha¬ nisms that move the parts of the arm). The work defines all the places that the end of t he robot arm can reach. To specify the "X" position within the work envelope for the two axis of freedom, you could use the formula below:

ArmX = (UpperAr-mLength x Cosine (UpperArmAngle)) + (ForeArmT.ength x Cosine (ForeArmAngle * UpperArmAngle))

Calculating the “armY” position is exactly the Figure 1-15 Three-dimensional robot arm same, except sines are used rather than cosines. Note that to get the correct position at the end ot the arm, the angle the forearm is at must also take into move to objects and see what was involved in the account the upper arm s angle. Hopefully, this for¬ process. mula does not scare you off—I gave it because ! In many teal robot arms, this is similar to the wanted to show that the position at the end of the process that is used to record oi program their move¬ arm can be fairly easily calculated using basic ments. For these robot arms, a human guides the arm trigonometry. (either directly or using some kind of remote control) I’m sure that my definition of a robot arm was dis¬ to the various locations where the arm is needed. Hus appointing to you—especially when you compared it method is quite fast and reasonably precise. to what your own arm and hand can do.This is a The problem with this method is that it is not prac¬ good opportunity for you to consider your arm and tical for many rohot applications.'lire classic example hand and think about just how amazing they are. of something that cannot be programmed this way is Your brain is able to command your arm and hand to the Canadarm used with the special shuttle. This move to a specific location in space, in a specific man ¬ robot arm cannot '■upport itself under Earth's gravity, ner, without having any visual feedback. let alone carry any kind of payload. In this , the motion ot the aim must be worked out mathemati¬ cally, usually by computer. To illustrate what I mean, let’s look at a two For Consideration dimensional robot arm that consists of a long upper arm and a short forearm (Figure 1 13). As 1 have When I am asked by people how they can create drawn the arm, the upper arm can turn about 45 their own experiments, I am surprised at how few degrees from the shoulder while the upper arm can people understand that in a well designed experi turn ISO degrees around the elbow This range of menu the results are seldom a surprise. The stereo¬ motion has resulted in the strangely shaped work typical cloaked scientist mixing chemicals at random envelope that is drawn under the arm on the diagram. before he comes up with something interesting is a When a robot arm is described, each direction a myth that many people believe. A properly designed part can move in is described as a degree of freedom. experiment is used to test a theory or hypothesis, not For the robot arm shown in Figure 1-13. it has two to see what happens when something is done arbi¬ degrees of freedom one at the shoulder and one at trarily. the elbow. Your arm has seven degrees of freedom To illustrate what 1 mean, consider the experi (three for your shoulder, one for your elbow, two for ments performed 150 years ago by many reputable your wrist, and one for your hand opening and clos¬ scientists trying to discover w hat air is made up of. ing). I he more degrees of freedom a robot arm can As you are probably aware, a bit more than

Section One Introduction to Robots 11 Section One — Introduction to Robots out andcannotberemovedwithtechniqueslikecen- trace gaseswereinthehopesoffindingsomething ments performedweremadetounderstandwhatthe percent consistsofdifferenttracegases.Theexperi or soismadeofoxygen,andtheremaining]2 hydrogen at-252.7C,andhelium-268.6C.Just carbon dioxideat—78.5C,chlorine-34.5 gen boilsat-1dS.SCelsius(C).oxygen-182.8C, gases inairwasdemonstrated. of workbeforeamethodextractingthedifferent and thedifferentgasesinitaredistributedthrough¬ ingenious. Airisactuallyasolution(likesaltwater) that wasvaluableornew. three quartersofanismadenitrogen.20percent Figur e1-13Horizontalrobotarmmotion scientists performingthemdidnotthinkaboutwhat as areferencepoint,absolutezeroisat-273C. edge. airwascompressedtothepointwhereitlique¬ terfuging orheating.Itactuallytookahundredyears collected inandbreathedthem in.fileassumption was goingtobeproducedby theexperiment,sothey thing elsewasallowedtoescape.Forexample,nitro¬ to collectwhatboiledofforwasleftafterevery¬ fied, andthenitwasheldatdifferenttemperaturesto it willbecomeaverycoldliquid.Usingthisknowl¬ made wasthatbecauseairwas safeforpeopleto let thedifferentgasesboiloff,allowingscientists 12 tested themb\openingthe thegasseswere How thedifferentgaseswereextractedwasquite You mayknowthatifyoucompressagasenough, The problemwiththeexperimentswasthat 123 Robotics Experiments for the EvilGenius be safe. small luestoburnintensely,andlargeconcentrations we knowthatchlorineisadeadlycorrosivepoison, breath, thedifferentgassesthatmadeitupmustalso of carbondioxidewillstopaperson'sbreathing. ments weretakingplace),pureoxygenwillcause hydrogen explodesoncontactwithflame(remember together inan,thedifferentgasesarequitebenign, selves (andtheirlaboratories)andallowedthemto able todevelopexperimentsthatprotectedthem (which iscalledahypothesisortheory)thatpoten¬ parts ofaircouldbedangerous.Withtheguess and thepropertiesofdifferentgassesthatmadeil them.The compositionoftheEarth’satmosphere bly) withoutcomprehendingwhatwashappeningto tists performingtheseexperimentsdied(oftenhorri light bulbshadn'tbeeninventedwhentheseexperi¬ but bythemselves,theycanbeverydangerous.Today presented inthisbookhave thefollowingsixparts: better studythedifferentgasses. tially dangerousgaseswereintheait.scientists iments thatcouldfail(likethefirstoneinthisbook), reviewed, anditwasguessedthattheconstituent up weren'tunderstooduntiltheexpeiintentswere 1 amgoingtomakesurethe restoftheexperiments 1. Statementofexperiment's purpose.Thisisa Unfortunately, thisassumptioniswrong.Mixed To avoidgettingintothetrapotdevelopingexper¬ It shouldn'tbesurprisingthatmanyofthescien¬ simple statement,morethan atitlebutnot Work Envelope Range of Forearm complete description of what's going to format I’ve used in this book isn’t going to cut much Section One — Introduction to Robots be done. ice with them. 2. Theory behind the experiment. This is a state¬ An important tool for any experimenter is a neat, ment of what the expected results are well-laid-out notebook. Going back to what your and why. teachers have been telling you, they have probably 3. Bill of material (equipment or apparatus been harping on the importance of a notebook for found in the “Parts Bin" and “Tool '). years. Notebooks are invaluable for storing ideas, cir¬ This is the list of equipment needed for (he cuit diagrams, formulas, or plans for the future. As experiment. you work through this book, 1 recommend that you keep a notebook alongside it and use it to save 4. Procedures. These are the different tasks needed to carry out the experiment I will important points, the observations of vour own include assembly drawings and circuit dia¬ experiments, or ideas that you can use later. grams for the experiment in this section The experiments m this section are somewhat

5. Results (or observations). This is quite simply willy nilly and I’m sure they don’t measure up to what 1 saw (and I would expect you to see). I what you are expecting tor the book. Rather than will include photographs of the completed calling them experiments, I would be more comfort¬ experiments as well as quantitative measure¬ able calling them model tests because they do not fit ments of what was seen. into my idea of what an experiment is and how it is conducted. Model is an excellent term for what was 6. Conclusions. This is a discussion of any lessons learned and suggestions of what can be done done in this sec tion because the models demonstrate next. the concerns regarding different robot types. Hie pur pose of this section is to show- you that you can test These six parts w ill be similar to how a high school out your own ideas for robots simply and inexpen science teacher would like experiments to be organized. sively. Formatting the experiments will help you to organize As I go forward in this book, I will be endeavoring your Ihoughts and understand exactly what you want to to make the experiments much more rigorous and get out of the experiment. It also allows other people to robust, and I’ll reflect how experiments are actually repeat the experiment and test the results. Finally, the conducted when robots are being developed. results should support the conclusion Whereas the experiments in this chapter took mini¬ You may find that your teacher wants you to write mal thought to create, the experiments throughout up experiments in a specific format Remember that the rest of the book will have much more up-front if you want to get good marks in the course, write up work done on them to make sure that they work reli¬ your experiments in the format your teacher wants. ably and can be used as a basis for later experiments Telling your teacher that you’re just following the or robot projects.

Section One Introduction to Robots 13 Section Two Robot Structures

At the start of the previous section, t demonstrated book for information on the body's joints, you can 1 hat creating a robot based on the human form was see a basic finger joint is built like the one shown in difficult .(“.nontrivial” in engineering teims). I he first Figure 2-1.1 have simplified this diagram to show the robot experiment started with a somewhat skcleton- most important pieces of the joint to more clearly like structure that was connected with flexible joints. illustrate what they are doing. When the robot was stood up. it promptly collapsed T)ic purpose of the finger joint is to allow the mus in a heap I explained that this form of robot is unsta¬ clcs to change the angle at which the two bones of ble and requires a series of muscles to keep it upright the finger meet. Muscles can only shorten (contract), along with the skeleton and joints. After doing this. so lo change the bones' angle, one of them must I then worked through a number of different forms contract, as shown in Figure 2-2. To straighten out the that would be better suited to a robot, ending up with two bones, the muscle on the opposite side of the a small car like form that had no moving narts other joint must then be commanded to contract and the than its wheels.The first section explained why robots other allowed to relax. To reproduce this action you look the way they do. but it did not explain how Ihey might be thinking of something like a solenoid, which were manufactured. I will discuss later. In the first section. I used a variety of simple mate¬ ITie muscles arc not connected directly to the rials to make up the robot forms. These materials bones. Instead, both the muscles and bones arc con- really weren't optimal as they took a long time to harden and were not very mechanically strong. In this section. I would like to investigate the different mate¬ Bone Ligament “Stops rials that robots are built from, along with some of the science behind robot structural design. When you ( Bone Bone have finished this section, you will have the basis foil ) some ot the robots I work through in the later experi¬ Cartilage Siriovial Fluid ments as well as a basic understanding of which Tendons materials and products are best suited for youi own robots. Figure 2 1 lhe anatomy of a finger joint To avoid getting into a ehicken-and-egg argument, I want to look at an already existing structure we can use to model our robots. The obvious one is the human body Although you might be reluctant to con sider the human body tor this role because of the results from the first experiment, you should realize that smaller parts of the body (call them subsystems if you will) can be used as a guide for building a robot. Bottom Muscle Has lhe parts of the human body that are of the most Contracted interest to robot designers (or roboticists) are the Figure 2-2 Bottom muscle contracting to hem! ones that can move. When looking at an anatomy finger

15 Section Two — Robot Structures ing upwithaconnectionbetweenthetwobonesthat surface andisbuiltintothebonetoallowfor will allowthemovement.InFigure2-1.takealookat sinovial fluidwhileinthehinge,andoilisusedtomini¬ aligned. Finally,the“bonestops"arefeaturesthat together andkeepthecartilageoftwobones as sinovialthud.Iheligamentspulithebones but theyarcseparatedbyathinfilmofliquidknown bones doesnotcomeintocontactwithoneanother, bones torubtogethereasily.Ihecartilageofthe first partisthecartilage,whichhasasmooth,hard the jointsectionitself;itismadeoffouipaits.Ihe other isonlyhalftheproblem.Iheearn¬ of themuscletopassoverbendingjointwithout connected tothem. pm providethesamefunction.Finally,metalof ments, andthecurvedmetalpiecesencasinghinge finger jointarcanalogoustoamechanicalhinge. bone ismgdesignedfor.Thesedifferentpartsofthe keep thehonesfrommovingatananglethat taking upalotofspace. nected byathinlengthoftissueknownastendon. 16 known asactuatorsorsolenoids)pullthefishingline can contract,wecouldcreateamechanicaldevice extensions builtintothefingerjoint. far inonedirection,exactlyanalogoustothebone mize friction.Thefingerjointisheldtogetherbyliga reason itisknownasabearing,Tominimizethefric¬ moves) whenoneofthecontractingdevices(also wood, somefishingline,andacoupleofdevicesthat hinge isformedinsuchawaythatitcanonlymoveso tion ofthebearing,fingerjointislubricatedusing applied tothejoint,asdoeshingepin.andforthis ure 2-3).Thejoint'sanglechanges(orthejoint that istherobotequivalenttoafingerjoint(seeFig¬ Ihe tendonisverythinandstrong,allowingtheforce Using thehingealongwithacouplepiecesof Moving theangleoftwobonesrelativetoeach Ihe cartilageservesasasurfacethatbearstheforce lEd Robotics Experiments fortheEvil Genius can pushorpuli,suchasahydraulicram.Inthisjoint, simpler andcheapertobuildthanusingtwo depending onwhatpartofithasfluidforcedintoit. wood pieces(bones)byhingedrigidconnections given tothedifferentpartsofafingerjointprobably actuators. Creating ajointusingsingleactuatorcanbebit (called pushrods)andcanexpandorcontract, the actuator(muscleanalog)isconnectedto structure discussedinthisintroductionalongwith sinovial fluid.Thegears,wheels,andthemechanical cates themotorisactuator,andaxlebearing wheeled robot,butyoucanfindstrongsimilaritiesto do notseemliketheywouldapplythatwelltoa that haslegs(likeweuse),Ipushedtheideaofrobot previous section.Insteadotrecommendingarobot a feedbackmechanism(knownasreflexes)isusedto immediately cometomind.Thefirstis,inarealjoint, mechanical jointanalogsandthewheelanalog. bits holdingeverythingtogetherarethetendons. allows partstomovesmoothlylikethecartilageand the fingerjointmodeljiresentedhereFigure2-4indi¬ that movedonwheels.ThemechanicalanalogsIhave how positionfeedbackworks. introduce youtoradiocontrolservos,willsee indicate thecurrentpositionofjoint.WhenI Figure 2-3Mechanicalanalogtofingerjoint This mechanicaljointcouldalsouseadevicethat Table 2-1liststhedifferentpartsoffingerjoint After goingthroughthis,probablytwoissues I hesecondquestioninvolvestheresultsfrom Muscle Table 2-1 Honor base materials Bearing Gears

(Cartilage & xperiment 5 — Cutting Plywood (Tendons) Sinovial Fluid) Motor Mechanical Wheel Hold Down Wheel (Tendon) Finger Joint Ffnalog Rnalog Runing Bone Connecting pieces Base Motor (Muscle) Surface Muscle Actuators Motor (Bone) Beating Tendons Fishing line/push Rods drivetrain/ Hold-Down wheels (Ligament) Robot Structure Ligaments Hinge body Mounting pieces (Bone) Cartilage Pin Bearing

Sinovial fluid Oil lubricant Bearing lubrican* Figure 5-M WheeUdrivetmm system with the same part functions to the finger joint identified

Experiment 5 Cutting Plywood

Parts Bin Tool Box 12- by 12-inch sheet-, of Saw fox cutting plywood 3/16-inch aircraft plywood

When looking at different materials commonly used various types can have depending on the cut type and for robot framework, I came up with Table 2-2. The where ihc piece was taken from the tree. Choosing first two criteria, availability and cost, are self- the propei wood for a specific application requires a explanatory. Strength is the material’s relative lot of knowledge and makes wood suboptiinal, in my strength anti its resistance to being damaged. Cutting opinion, for use in a robot’s framework. ease is how easy it is to cut down stock into a desired Plywood consists of a number of thin sheets of shape: the harder a material is (its strength), the wood arranged in different orientations and glued harder it is to cut. Stability is how well the material together under a press to create a strong and durable keeps its shape (and precision) over time and use. product, as shown in Figure 2-5. In the ease ot ply¬ “Vibration Resistance" is a measurement of the abil wood. different types and cuts of wood arc chosen for lty of the material to maintain its function when the the application.The strongest and most durable type robot is running. Will it crack or lose its shape as the of plywood is known as aircraft plywood and can be robot runs over an uneven floor? found in small quantities at a hobby store.

When paying a visit to a local hardware store, you fil()FR4 is commonly used for making printed cir¬ will probably discover literally hundreds of different cuit boards (P(’Bs). It is built by compressing materials to choose from. Looking at Table 2-2. you'll fibers together with an epoxv binding them together. see that for many of the different categories. I have GIO refers to the glass fibers and epoxy mixture, and given wood the w idest possible range of ratings. The maintains its dimensions despite changes in temp- different ranges are due to the different types of eratuie. I R4 indicates that it has fire resistant wood available and the different properties that the

Section Tuuo Rcbot Structures 17 Experiment 5 — Cutting Plywood Table 2-2Materialcharacteristics Materia! and iseasytoform,butdifficult todrillormachine Ot these.1wouldonlyrecommendusingfoamboard compressed anilgluedtogether),cardboard,and clear) canbeusedtomake for anattractiverobot. precisely (available inartstores),asitsurviveswellovertime foam board(cardboard-claddedpolystyrenefo3m). can befoundforpenniesatsurplusstores. people useoldPCBsfortheirrobots,becausethey G10FR4 isdifficultandexpensive,althoughmany ucts. includingparticleboard(woodchipsandfibers tormulation 4builtintoitFindinglargeblocksof Figure 2-5Plywoodconstruction 18 G10FR4 Steel Wood Card board Aluminum Plywood Plexiglas Foam board Particle board You canconsideranumberofpaper-basedprod You canalsoconsiderplastics. Plexiglas(especially Top ViewSide 1E 3 Robotics Experiments for the EvilGenius Good Excellent Good Good Excellent Excellent Good Good Excellent Fair RvailahilitM Layer View Fair Good Good Excel Good Fair Good Fair Good Poor Coat Top Layer Vlidd'e Layer Layer Bottom Wood Grain Direction Indicator Good Excellent Excellent Excellent Poor-exeellcnl Fair Fair Poor-fair Fair-good btrength Poor fair excellent formakingcoversandbodiesrobots.1 “vacuum formed”intointerestingshapesandis Polystyrene usuallycomesinthinsheetsandcanbe your robotmoreandmore,thelikelihoodofcracks vibration resistance.Yonwillfindthatasyouuse demonstrate thestrengthofplywoodinnext shown inFigure2-6.Thethreelargerectangleswill could hopetofindonthisplanet. ered thatplywoodisaboutasboringanythingyou is what1willbeusinginthisbook.Beforegetting can usewhenyouarecreatingyourownrobotandit appearing intheplasticincreases. tend toavoidplasticsbecausetheyusuallyhavepoor experiment. from ahobbyshopforlessthan$5)intothe10pieces tacts aboutit.Afterdoingabitofresearch.1discov¬ plywood alongwithsomeofthemostinteresting into theexperiment.1wantedtocoverhistoryof and willcreateastripthatis aswidethelengthof cut willbe4,75inchesfrom the edgeofplywood way tocuttheplywoodinto theshapesinFigure2-6. in thisbook,whereasthefourstripswillbeusedto be usedasthebasesformobilerobotspresented 12 pieceof3/16-inchaircraftplywood(available the PCBincluded wallthebook. Ihe orderotthecutsisshown inFigure2-7.Thefirst Poor- fair Excellent Excellent Fair- good Poor Fair Poor-excellent Good-excellent Poor fair Fair good Cutting Ease Plywood isprobablythebestbasematerialyou For thisexperiment.1wouldlikeyoutocuta12by Ibis experimentconsistsoffiguringoutthebest (iood-excellenl Excellent Excellent Excellent Poor-excellent Good Good Poor Poor- fair Stability Poor Good Ciood Fair Excellent Resistance Poor Poor Excellent Poor Excellent Poor Vibration w 1 Z. X

(D > H Three H’ §75* x 3.5”—H 3 CD j 3 3.5" | 1 Figure 2-7 Order of cuts to 3/16-inch plywood \ / / *—4.75"— \ \ / , CD Six 12” x 1”

Figure 2-b Cuts to 3/16-inch plywood for ) experiments Cut - Plywood Stock Dimension o Material Taken c Try different saws (such as a hacksaw, coping saw. Away by Saw rt jig saw. Dreniel tool, sabre saw. table saw, band saw. Cut Line ct circular saw, or a miter saw) and find which one works H* best for you To cut plywood, 1 use a miter saw with a 3 12-inch circular blade. It is an expensive tool, buf 1 can iQ specify the cut angles that I want with accuracy. Figure 2-8 Plan for lost material from previous Depending on your means, you may only be able to cuts when marking your cut lines. use a handsaw, but make a note to yourself to try some of the other options listed here. H* reason, you should be measuring and marking your Note: If you arc using a power tool make sure you K cuts after the previous one has been completed. It have been propeily trained and are supervised when t you mark the position of the cuts in the wood before¬ you are using it O hand. you will discover that almost all your pieces, When you cut the plywood, you will find that o except for the first one, will be cut incorrectly With some of the material is lost in the cuts, as shown in some experience, you will learn to compensate for p- Figure 2-8. This means you will have to cut to the out¬ lost material when you are cutting, but for now, meas¬ side Of the cut line to make sure the final piece is not ure and mark your cuts Just before doing them to smaller (by the width of the cutting blade). For this make sure they are as accurate as possible

Section Tuuo Robot Structures 19 Experiment 6 — Strengthening Structures can strengthenapieceofplywoodbytwotothree of intherobots.Inthisexperiment.1wanttolookat physical propertiesandwhatwecantakeadvantage Now thatwehavedecideduponusingplywoodfor do this. mend thatyoudesignyourrobotswithouthavingto orders ofmagnitude(100to1,000times),1recom¬ because althoughIamgoingtoshow'youhow to strengthenit.Thisexperimentissomewhatironic, how strongplywoodactuallyisandwhatcanbedone the robotstructuresinthisbook.Iwanttolookatits three ofthesedifferentproperties,tryoptions: wood bypressingonitisknownascompression. pull thepieceapart.Tryingtomakeasmallerof bending thestripinmiddle.Tolookatfirst be appliedtoanobject.Tensionconsistsoftrying 20 strength againstbending,set uptheapparatusshown in Figure2-10.Placetwobricks (orlengthsof2X4) Tw istingiscalledtorsion.Finally,youcanalsotry • Fullingthepiece«»fplywoodapartYoumay • TwisttheplywoodThiscouldbedoneeither • CompressingtheplywoodYouand Figure 2-9show'sthefourdifferentforcesthatcan To testandquantifythestrip ofplywood’s should grabanendolthestripandpull. want togetsomeonehelpyou.F.achperson cracking (althoughthiswilltakealotof the stripwithjustonetypeofforce. without bendingit.Theideaistojusttest push againstthestrip.Tinsshouldbedone helper fromthepreviousstepshouldtryand force). by twopeopleorjustyourselfandsomething like abenchvise.Stopifyoubegintohear 123 Robotics Experiments for the EvilGenius Four stripsof12-by1- by 3/16-inchaircraft ous experiment plywood cutinprevi¬ Strengthening Structures Experiment 6 saw thescalegoto9pounds or4.1kilogramsbefore strip. As1slowlyincreased the forceonstrip.1 scale. Ifoundthat1hadameasuredweightof5 them. Recordtheweightofbricksandstrip. on ahomescalewiththestripofplywoodbetween pounds (2.3kilograms)for2bricksandtheplywood with yourfoot,watchingtheindicatedweighton Applying 4poundsofforce issurprisinglysmalland the stripstartedtomakecracking soundsandbreak. bathroom scale Figure 2-9Structuralforces Figure 210Measuringbendingforceusinga Force --hH-Force Force -1--1>1orce Next, slowlypressdownonthecenterofstrip Compression Force _ZZ□ Torsion Tension force Wood clamps Carpenter's glue Force Twisting Sample Material Bricks/2x4s Scale Bathroom Bending much less than would have been required for any of the forces to break the strip. To summarize the results, we can say that the ply¬ wood strip is extremely resistant to tension and com¬ pression, resistant to torsion, and not very resistant to bending. With ihis information, let’s create a different form tor the plywood to see if we can increase its resistance to bending forces. You might be confused by what is happening in this experiment Thinking about it, you might be inclined to look at the bent strip of plywood like the cable shown in Figure 2-11. As a force pushes down on the cable, the different elements experience more Q\ Bending tension. In reality, when the plywood is bent, the dif¬ Force ferent libers (or material particles) that make up the structure are having an asymmetric force applied to them.This asymmetric force breaks the fibers at the microscopic level by shearing them apart, resulting in in the strip breaking. An important rule to remember is ct that the larger the bending movement the strip is h allowed, the greater the shearing force applied to the (D individual fibers and the easier they will break. 3 Ihe approach 1 used to find this better shape is to I-beam shape using carpenter’s glue. When I built my iQ take advantage of the strengths of the plywood strip ft plywood 1 beam, I first glued the bottom piece to the to overcome its weakness. In this case. I want to ere vertical support and clamped the assembly together 3* ate a shape that will use the excellent tension and CD compression properties of plywood to overcome the at the two ends and the middle. After waiting a day 3 poor bending quality. for the glue to harden. 1 then glued the top piece on and again clamped it together and let i! harden Tlic shape I decided to use should not be a surprise overnight. 3 if you have ever seen a building put up. I decided on the I-beam shape (shown in Figure 2-12) because it Repeating the experiment with the two biicks and the scale, 1 found that I could not break the I beam, will convert the incoming bending force to compres¬ sion (on the top) and tension (on the bottom), as even when I stood on it (and I am 200 pounds or 91 in shown in Figure 2 13. rather than the shearing. kilograms, which is 50 times more force that what was rt required to break a single piece of plywood). 1 was You can build a simple I beam to test using three h amazed at the strength of the I beam. strips of plywood and gluing them together in the d You might wonder what would happen if you siin o ply glued three pieces of plywood together, flat side rt Force Due to to flat side, essentially creating a thicker piece of ply¬ Gravity wood. You may expect to get a similar gain in bend¬ d ing resistance as the I beam created here. If you were h to try it, you would discover that the bending resist¬ (D ance would be increased, but in a very linear fashion. in Force of Gravity You would find that two pieces of plywood would Converted to have essentially twice the bending resistance of a sin¬ Tension gle piece, three pieces would have three times, and Fiqure 2-11 Coble bending while suspended between two points

Section Tujo Robot Structures 21 Experiment 7 — Finishing Wood 22 over thecourseofafewdays.Itwillallowyoutocre¬ functional benefitsof ate finishedpiecesolplywoodthatwillhavethe advantages overusingunpaintedwoodinyour quickly andeasilyfinishpiecesofwoodnotonlyto and seenwelldesignedrobotsthatotherpeoplesaid wood ontherobot.I'vebeentoseveralrobotmeets greater themovementofwood, see thatallofthemarequiteshortbecausethe simply becauseitisnotneededWhenyoulookatthe robot’s structure. make therobotlookbetter,butalsotoprovideafew the robotInthisexperiment.1willshowyouhowto erable effortwentintothedesignandconstructionof piece ofwoodthatgavetheappearanceconsid¬ the onlydifferenceIcouldsecwasanicelyfinished also seenrobotsthatwereobviouslyquitepooryet received manyaccoladesontheirappearance,and looked asiftheywerejust“throwntogether."Ihave Nothing seemstobeabiggerturn-offwhenitcomes robot structuresIhavecreatedforthisbook,you'll to homebuiltrobotsthanbareplywoodorother tage ofitinanytherobotspresentedthisbook needed tocreateone,Iamnotgoingtakeadvan¬ from an1-beamshapeandthesmallamountofeffort » Eliminatingtheduston thesurfaceofply¬ Despite thephenomenalgainsinbendingstrength The processwillrequireafewminutesoltune inating thelibersalsoallows formoreeffec two-sided tapeattachment and removal.Elim¬ wood, allowingforaneffective surfacetor live glueand tape bonds. 153 Robotics Experiments fortheEvil Genius Three 4.75-by3.5-inch Two stripsof12-by1- by 3/16-inshaircraft aircraft plywcoccut ous experiment plywood cut.inprevi¬ pieces of3/16-inch in previousexperiment Experiment 7 Finishing Wood aerosol canof indoor/outdoor(ormarine )acrylic should buyanaerosolcanof primer(grayisalways cleaned up.Fromanautobody supplyhouse,you go asefficientlypossible:thisiswhyyouwillsee shearing forceonthefibers.Bykeepingpiecesof very littlemessoccursandno brusheshavetobe that youwillneedsothepaintingoperations will bequitesurprising.Ihavetriedtolisteverything probably seemtobequiteobvious,whereasothers ol thematerialslistedatbeginningofthissection will beusedforrobotbaseslaterinthisbook.Some nificantly. Bykeepingthepiecesshortandwide,I the wood’sresistancetobendingforcesincreasessig¬ force isdistributedovermorearea),youwillfindthat my firstchoice),andfroma hardware store,buyan items iniheli«tlikebottlecaps. experiment alongwiththreepiecesofplywoodthat painted plywoodstripsthatwillbeusedforthenext pieces ofplywoodusedtortherobot’sstructures. don't havetoworryabouthavingstrengthenthe plywood relativelyshort(aswellaswidesothatthe Tool Box • Allowingpencilandinkmarkingsforcorrec¬ • Eliminatingsplintersandminimizingsurface • Smoothingthewood’ssurfaceandreducing At theendofthisexperiment,youwillhavetwo I tendtouseaerosolpaint;whenproperlyused, gets moistorwetoverrime. splintering whendrillingintothewood. tions onthesurfacetobeeasilywipedoff. the liftedfibersthatappearwhenwood Acrylic marineaerosol Autobody primeraerosol Old clothrag Old newspaper caps 220-grit wet./drycandpa- Per paint in your favorite color (I use Krylon®). Person¬ the sanding step (along with sanding the ends of the Experiment 7 — Finishing Wood. ally. 1 like to use red, as it catches the eye and isn’t wood and wiping it dow n with the damp rag) before overwhelming. If there is a blemish in the wood or applying another coat of primer After the second your work, it hides it quite nicely. coat is put down, let it dry, sand very lightly, and wipe Set up a painting area in a garage or another well down again. ventilated area by laying down newspaper both on Now you are ready to apply the paint. Shake the the floor as well as vertically. Next, lay down the but can according to t lie instructions and spray the ply¬ lie caps to be used as supports for the materials you wood strips, putting on a thin, even coat. You will are going to be painting over the newspaper. You probably find that the paint will seem to be sucked don't have to use bottle caps: scraps of wood or other into the wood and the surface will not be that shiny. detritus can be just as effective Just make sure that This is normal. Once the paint has dried, lightly sand when you are painting something that the supports again, wipe down with a wet cloth, and apply a are smaller than the perimeter of the object being thicker coat ot paint finished. You will want to finish the ends of the ply¬ When this coat has dried, you'll find that ihe sur¬ wood and don’t want to end up with paint flowing face of the plywood is smooth and shiny Some of the between the plywood and the support. grain ot the wood is still visible, but it is not that Lightly sand the surfaces of the plywood you are noticeable You do not have to sand the paint again; going to paint. When finishing the two strips, I just flic plywood is now ready to be used in a robot. painted 6 inches (15 centimeters) on one end. You Once you have done the two strips, you can finish may also want to sand the edges of the strips more tlie three rectangular pieces ol plywood the same aggressively to take off any loose wood that could way.The difference will be that alter each painting become splinters. Once you have finished this, mois¬ step, instead of going ahead and sanding, you should ten the rag and wipe it over the surface you have turn the piece over and use primer or paint on the sanded to pick up any loose dust. other side. Sand both sides and then apply the next Shake the can of primer following the instructions layer. When 1 am painting pieces like this. I usually printed on the can. Usually, a small metal ball is spray twice a day (to make sute the primer or paint is inside the can. and you will be instructed to shake it thoroughly dry), which means it takes me four days until the ball rattles easily inside. .Start with the two to produce the finished wood. 1 suggest you plan plywood strips and place one on the bottle caps sup¬ ahead and finish as many pieces a« 1 think are porting the surface to be painted. Spray about 0 required at one time. When y>'U are painting the rec inches of the strip, starting at the supported end. tangulat pieces of plywood, remember to paint the Most primers take 30 minutes or so to dry. Check the edges as well.The acrylic paint will help bind the instructions on the can before going on to the next edges of the plywood together, minimizing the step of sanding and putting on new coats of paint or chance that you will gel a splinter from the wood. pi inter. Ihe two partially painted strips of wood will be After the first application of primer, you will prob¬ used in the experiment that follows and the three ably find that the surface of the wood is very rough. fully painted rectangular pieces will be used as the I his is due to the cut fibers in the wood standing on mounts for the mobile robots presented later in the end after being moistened from the primer Repeat book.

Section Tuuu Robot Structures 23 Experiment 8 — A Gaggle of Glues are notfastenedtogetherverywell.Partoftheprob¬ ing problemswithlightbackgroundnoiseortherun code thatcan’tworkintheactualenvironment(caus¬ when arobotisbroughtouttorcompetition?Most What doyouthinkisthenumberoneproblemIsec 24 discussing thedifferentkinds andtestingthemouton do researchatalibraryorontheInternet. which applicationstheyarebestsuitedforIfyou ent gluesandnotmuchmoreaboutthemotherthan ent gluesandmechanicalfasteners(discussedinthe andfastenersfortherobots. ture (likeonethatbreaksduringuse),butthe falls apartorbreaksbecausethedifferentelements ning surface),butwhat1usuallyseeisarobotthat people wouldthinkofthingslikedeadbatteriesor the twostripsofplywood: glues andwhytheybehavethewaydo,youcan interested infindingoutmoreaboutthedifferent ment containsaprettyskimpyexplanationofdiffer¬ plywood fromthepreviousexperiments.Thisexperi glue work,usingthetwopartiallyfinishedstripsof of gluesthatareavailable.Inthisexperiment,1would overwhelming problemistheuseofinappropriate lem istheuseofanunsuitablematerialforstiuc- like toexaminehowanumberofdifferenttypes next experiment)canbechosenfrom.Ilielistinthe Parts Binisjustasmallfractionofthetotalnumber • (fluesworkbestwhenthey areattachingtwo I shoulddiscussafewpointsaboutgluesbefore 11ns isnotsurprisingbecauseaplethoraofdiffer¬ pieces ofthesamematerial together.Insitua¬ tions wheredissimilar materialsareattached. 123 Robotics Experiments for the EvilGenius Two 12-hy1-by3/16- aircraft plywood tially finiehed inzh pieceofpar¬ R GaggleofGlues Experiment 8 comments 1haveaboutthem Thesegluesarereason- glues, thematerialstheyare bestsuitedfor,andany stronger thanthematerialitself glue andthebonditformswithmaterialmustbe tion. IhavecreatedTable2-3. whichliststhedifferent in thePartsBintshouldbe used forwhichapplica¬ Tool Box • (fluesarechemicalsandassuchshouldbe • Gluesdonotdry;theycureorharden. • “Solvents”areusedtothinglues,increase • Thelayerofgluebetweentwoobjectsis • Gluecanalsobeknownas“.” • Thebesttestofaglueistouseitattachtwo • Youcannotreactivategluesbysoakingajoint To helpyouunderstandwhich typeofglue(listed The lastpointisausefulruleandstatesthatthe called the“joint.” handled withcaretoensurethatnoopportu as describedinthenextexperiment. use amechanicalfastener(likenutandbolt) doesn’t break,buttheattachedmaterialdoes. cure,and ihenpullthemapart.Dieglueis in waterortheglue’ssolvent. their curinglime,ortowashgluesfromsur¬ with theinstructionsandwarninglabels. robot. Makesureyoureadandarefamiliar burned orgluedtodifferentpartsofthe appropriate fortheapplicationifjoint representative objects,wailtortheglueto faces. nity existsforyouorotherstobechemically vreldbond Carpenter's glue Kiazy Glue®/Loct.ite® Hot. gluegun Contact cement Five minuteepoxy Small woodclamps Two-sided tape Solvents Table2-3 Glues and their best materials Mounting tape, 1 would caution you against using hot Experiment 9 — Nuts and. Bolts glue (dispensed from a hot gun) because it does not

Glue Materials Comments hold as well as the other glues. It also does not handle vibration very well and can leave long, sticky strings. VVeldboiul Wootl/PCR Excellent for tying down loose wires and insulat¬ 1 his experiment is quite simple: Using the two ing POBs. strips of partially finished plywood, test out and doc- Solvents Melts plasties together. umenl the appropriateness of the different glues on

Krazy Glue/ Metal/ Best for locking nuts. both the finished and unfinished portions of the Loctite wood. 1 hen document the results in a table. A suc¬

Carpenter's glue Wood Unfinished wood. cessful glue is one in which the joint doesn't break, but the material being held together does. Five-minute epoxy Everything Very permanent. The idea of gluing yourself (or somebody else) to Contact cement Flat, porous Good for bonding materials paper/laminate to wood. something like a table might seem funny, but there is a real danger of causing an injury if a caustic glue is Two-sided tape Smooth surface Good for holding components on (he used or attempts to pull the glue off are taken with¬ robot structure. out reading the warning on the package or con¬

Hot glue gun Everything Not recommended. sulting a doctor first. Always remember that glues are chemicals and can cause serious problems. Follow the instructions on the package to make sure the glues are used correctly and any required solvents are on hand for cleanup. ably inexpensive and can be found in virtually all After carrying out this experiment. 1 found that hardware stores. carpenter’s glue was best for in finished wood, and As staled in the table, I only use Kra/v Glue to two-sided tape was most convenient for finished prevent nuts from loosening on bolts. Also, two-sided wood. You'll probably find that five-minute epoxy tape is excellent for mounting battery packs and ser¬ can glue anything to anything. You will be surprised vos on robots. For best results. I recommend that you at how ineffectual the other glues are when gluing use 3M Scotch Super Strength (5 pounds) Exterior strips of wood.

Experiment 9 Nuts and Bolts

In this experiment, I would like to talk about using needs to be said, but you don t understand the princi¬ nuts and bolts as the primary removable fasteners ple upon which they are based. you will use when you are creating your robots. When I use the term fastener, f am referring to a Chances are you have used them in numerous prod¬ device that will hold two pieces of material together. ucts and toys, and you probably feel like not much In the previous experiment,you tried out a number of different glues on finished and unfinished wood to

Section Tuuo Robot Structures 25 Experiment 9 — Nuts and. Bolts 26 initially andthenloosenasthe nutisnolongerincon to reversethenut.stiffness wouldalsobepresent down andthematerialiscompressed,nutbecomes vibration andstress. cal fasteners(includingrivets,staples,screws,and tact withthematerialbeing held together harder toturn.Youshouldalso noticethatifyouwere noticed thatthenutslipsoneasily,butasyouturnit should bechosensothatitextendsthroughthemate¬ symbol hasthehorizontalbarsthatindicate will furtherdiscusswashersattheendofthisexperi¬ to lessenthechancematerialwillbedamaged.I the forceappliedbynutandboltonmaterial one andahalfthreads. threads (themetalstriprunningaroundtheshaftof rial) andmanyofthemwillloosenovertimedueto once (removalmaydamagethefastenerormate¬ other fastenersshowninFigure2-14canonlybeused would likeyoutofocusonthenutandboll.The two piecesofmaterialtogetherbutallowyoutoeas ment, 1wouldliketoexplainhowanutandbolthold ment andexplainhowtheycanbeusefultoyou. rial. throughanywashers,andpastthenutforatleast the boltscrewedintonut).Thebolt'slength holding twopiecesofmaterialtogether.Thebolt nails, asshowninFigure2-14),butforyourrobotsI ily takethemapartYoucanconsiderothermechani¬ purposes theywerebestsuitedfor.Inthisexperi¬ better understandhowthegluesworkedandwhich Figure 21UDifferentmechanicalfasteners Figure 2-15showsasideviewofnutandbolt When youputonanutandbolt,haveprobably Washers areroundpiecesofmetalusedtospread 12 3 Robotics Experiments for the EvilGenius Nail Nut and Bolt pretension, asshowninFigure2-16Astheboltunder¬ will continueuntilitisimpossible toturnthenutany more.The forceduetofriction isdefinedbythefol¬ fastener the greaterpretension,andmore becomes aviciouscycle:themorenutisturned, ent directionthantheturningofnutAs tion thenutexperiences. goes pretension,theforceitappliesonthreads shaft ofthebolt.Thetechnicaltermlorthisiscalled lowing formula: the harderitistoturnnutduefriction.This friction experiencedturningthenutincreases.This* the pretensionforceonthreadsisincreased, increases, causinganincreaseintheamountoffric¬ to thematerialtogether,andplacingtensionon Figure 2-15Differentpartstonutandholt The pretensionforceonthethreadsisinadiffer¬ Fhe reasonthenutbecomeshardertoturnisdue. Screw Rivet Threaded Bolt “Head” Experiment 9 — Nuts and Bolts Nut and Bolt Forces on the Nut

Ihis equation says that F ^ (the pretension Sharp Angle Acute Angle force) is multiplied hv a constant to give you the nut’s frictional force. Remember that thi'' friction works in both directions,both when you tighten the nut as well as loosen it To demonstrate how this force works, 1 could have come up with an experiment that measures the pre¬ tension of the bolt as well as the amount of force needed to turn the nut. but I wanted to come up with

something simpler that would be fun for you as well. Friction Duo to Gravity To do this, build a house of cards (Figure 2-1,7). Figure 2-18 Friction holding a card upright when Ihe suiface of a playing can! is quite slippery. the frictional force due to gravity downward is When you place a card on it at a very sharp angle greater than the sideways force due to gravity (close to being perpendicular to the card), the friction of the card, which is a function of the force of gravity, will hold the card upright despite it trying to slide the with a drawing that shows what happens when the bottom of the card.This is shown in Figure 2 18 along card is at a more acute angle. In the left drawing of Figure 2-18, the amount of sideways friction due to gravity is greater than the sideways force. The increase in Iriction due to the increased force of gravity in the card on the left in Figure 2-18 is exactly the same as the increase of friction on the threads of the nut. For many applications, simple tightening the nut and bolt causes enough friction to prevent the nut from loosening. Cases occur, however, when a bit of help is needed Figure 2-19 shows the three most common washers you will work with, Ihe flat washer is simply Lm AI a ring of metal that is used to spread out the force of \ the nut and bolt as well as protect the material from being damaged by them (especially when the nut and bolt are being tightened). Figure 2-17 A house of cards showing how the force of gravity can increase frictional force

Section Tijlid Robot Structures 27 Experiment 10 — Soldering and Splicing Wires joint hasgoodelectricalcharacteristics. 28 is broughttoitsmeltingpointandthenpressed welding orbrazinginwhichthematerialbeingjoined applied byapplyingheat.Solderingisdifferentfrom normally atin-leadmixturecalledsolderandis if youwanttobeablecreateyourownrobotsis good tousecmwoods,plasties,andlaminates(suchas washer hasanumberofbentteethinsideitthatwill vide thesametunetionasflatwasherhutalso ing orbrazingresultsinastiong bond,andasolder together withorwithoutInterposing material.Weld¬ This interposingmaterialforelectroniccircuitsis of twopiecesmetalwithaninterposingmaterial. “soddering;" the“Iissilent)isprocessofjoining the abilitytosolder.Soldering(normallypronounced One ofthemostimportantbasicskillsyouwillneed PCB materials). rial providingmorefriction.Ibistypeofwasheris twist whenbeingtightenedand“bite"intothemate¬ known as“lock*"washers.Th$internaltooth-lock help toholdthenutinplace.Forthisreason,theyare Figure 2-19Differenttypesofwashers View View Side Top The othertwowashersshowninFigure2-19pro¬ Flat Washer 1 ?3 Robotics Experiments for the EvilGenius Wire sections 1/8-inch—diameter heat Soldering andSplicingUUires shrink tubing Split-Lock InternalTooth Washer cock Experiment 10 be usedonlyonmetal.Ifyoudonotwanttousea of thenutonbolt.Thesplit-lockwashershould pretension ofthesystemandincreasingfriction create abondbymeltingthe solderbetweentwo expert oramachinist’stexttofindoutwhatkindof robot thatisveryheavy,youshouldconsultwithan that therobotwillbreakdownandyouhaveto washer usedisnotthatimportant;theworstcase byist robotapplications,thetypeofnut,bolt,and bolts, andinothercasesletyoudecide.Formosthob¬ place (whilestillbeingremovable). drop otKrazvGlueonthethreadstoholdnutin pushes againstthenutasitistightened,addingto region showninFigure2-20.This copper-soldermixis der takesplaceandisknown astheintermetallic pieces ofcopper,amixing thecopperwithsol¬ experiment. technicalities beforeattemptingtosplicewireinthis the solder.Youshouldbeawareofafewsoldering and mechanicalbond.Ifyouwanttobreaktheeon der. whichflowedoverthem,forminganelectrical per havebeenraisedtothemeltingpointofsol¬ nuts, bolts,andwashersshouldbeused. tighten thenutsup.Ifyouareworkingonapowerful lock washer,youcanalwaysusesomethinglikea nection betweenthetwopiecesofcopper,justmelt pieces ofcopper.Theedgesthetwocop¬ Tool Box The split-lockwasher,actslikeasmallspringand Although theideabehind solderinghereisto In theexperiments.1willspecifysomenutsand Figure 2-20showsthecross-sectionoftwojoined Clippeis/wire strippers Matches Flat workstation Soldering iron/soldering 60/40 fluxcoresolder station Experiment 10 — Soldering and Splicing Wires Solder "Fillet' lead in solders is not a healtli concern it you make sure

! • You solder in a well-ventilated area. Solder • You do not smoke while soldering (cigarettes and lead fumes can create cyanide gas).

\~ ) • You w ash your hands after soldering. 'Intermetallic Regions The copper should be as clean as possible for sol¬

Figure 2-2D Solder joint cross-sections der to adhere to it. this should not be a big problem because new parts will have clean wires or, if you are connecting wires, they have been protected in a plas¬ actually an alloy (a mix of metals),often with greater tic sheath (called insulation).To further ensure that strength and a higher melting point than the copper solder will stick to copper, most electronic solder or solder. The goal of soldering is to apply heal for comes with a weak, heat-activated acid called flux the minimum time possible to create a good joint and that cleans oft copper oxides and debris. Many differ¬ keep the intermetallic region as narrow as possible. ent types of flux are available, with rosin being the Tinning is accomplished by heating up a piece of type of flux vou should buy. Acid flux is used for copper and applying a thin layer of solder over the plumbing applications, and no-clean fluxes (rosin flux copper to inhibit corrosion. You will find that many is cleaned using water or isopropyl alcohol) should be wires and electronic components are pretinned to avoided, as the residue from one joint can affect the minimize the possibility that the copper will corrode, solderabilily of another. which will make soldering more difficult You can tell To apply solder, you will need a soldering iron, and if a wire or component is tinned because it will be a a suitable one for digital electronics can be purchased gray or silver color, rather than the expected copper for around $20. A a low-end soldering statio consists color. of a small lightweight soldering iron connected to a Solder is made up of a tin-lead mixture of varying base that controls power to the iron as well as the percentages, and when solder is specified, the tin con¬ heat on its lip. When you are soldering, the soldering tent is specified first (40/60 solder is made up of 40 iron s tip should be wiped on a wet sponge periodi¬ percent tin and 60 percent lead). Some solders have cally to clean off any burned flux or excess solder. silver added to them, but silver does not improve the Your soldering iron's tip will look something like joint's ability to pass electronic signals* it has been Figure 2-21. An insulated grip contains a heating ele¬ added to improve the joint’s mechanical characteris¬ ment and a removable tip that has been pretinned. If tics. Solder with silver added to it is not required for the tinning at the end of the removable tip is lost any applications presented in this book. Eutectic sol over time or if you can't get it clean, replace the tip. tier has a low melting point and is used for surface- Do not try to file the tip down and then re-tin it your mount electronics (not discussed m this book). self. When you file the tip, you will expose the copper Lead-free solders are available and the electronics of the tip and it will pollute the solder and result in industry is changing toward having all electronic the alloys I warned you about. devices use lead-free solders by 2010. Currently* lead- W hen you choose a soldering iron, make sure you free solders are difficult to find anil use with conven¬ get one designed for electronics assembly. It should tional electronic parts. I recommend that you work be rated at 30 watts or so. A higher watt rating isn't with standard electronics 37/63 or 40/60 solders (with better and can accidentally damage electronic cir¬ rosin llux cores) until you can be sure that the cuits. A lower-watt rating may not result in satisfac¬ components you are working with are designed for tory solder joints. A 30-w att iron or a solder station is lead-free solders. As I write this (mid-2003), very few ideal. Make sure a metal support for the iron keeps components are designed for lead-free solders. Ihe the tip away from the workbench surface.

SeLtiun Ttun Robot Structures 29 Experiment 10 — Soldering and Splicing Wires 30 Figure 2-22Splicingtwo wiresusingsolder will meltapieceofsoldeiortouchspongeto table. Ifyouaren'tsureifthetipishot,don’ttestitby ful withthematalltimes,andputdownona from solderingwilljustsaythatyouarestupid. in battlemaysavthatyou’reheroic,scarsreceived hear itsizzle.Rememberthatalthoughscarsreceived using yourfingerorotherpartsofbody.Seeifit metal supporttomakesuretheydon’tburnyour Figure 2-PISolderingirontip Soldering ironsgethot.somakesure\ouarecare¬ 123 Robotics Experiments for the EvilGenius Step 12 Bringing WiresTogetherSoldering Step 3 Fitting HeatShrink puff ofsmokewhenthesolderispressedtoiron. should looksomethinglikestep2ofFigure2-22and This isthefluxvaporizingwhenheatapplied.When stripper toolorasharphobbyknife.Strip1/4-inch scraps ofstrandedwirearebroughttogether.Baring shown inFigure2-22,Thisisanexcellentlow-cost of Figure2-22.Asitsnameimplies,heat-shrinktub merge thestrandstogetherasIhavetriedtodo. or strippingwiresisaccomplishedbyeitherusinga you fromruiningthePCBthatcamewiththisbook. way oflearningbasicsolderingskillsanditwillkeep iment withtryingtosplicetwowirestogether,as applied toit. ing eoniractswhenheat(likethatfromamatch)is the solderedspliceusing.L/8-inch-diameter(3mil¬ the suifaceshouldbeshiny,notdull.Oncewires few secondsandapplythesoldertoit.Theresult the ironishot.holditagainstjoinedwiresfora melt whenittouchestheiron.Youmayalsoseea testing itwithapieceotsolder.Waitforthesolderto (6 millimeters)ofinsulationfromthewiresandtryto are solderedtogether,youcanprotectandinsulate limeter) heat-shrinktubing,asshowninsteps3and4 In stepIofFigure222,thebaredwiresfromtwo Step 4-FinishedSplice Next, wailforyoursolderingirontoheatupby With thetheoryofsolderingbehindus,let’sexper¬ Experiment 11 — Assembling the Included. PCB Experiment 11 Assembling the Included PCB

Tool Box Book PCB Soldering iron/soldering station Two 220 v 16-pin resis¬ tor Dual In- line Pack¬ 60/40 flux core solder age s (DIFs) Matches Two C.C1 |j.F capacitors Clippers/wire strippers of any typ.e Screwdriver for 4-40 CKN9C09 momentary push¬ screws button switch

Twenty-foue-pin, 0 600-inch sockets

Single-row, 32-pin PCB mount socket

PCB mount, female 9-pin D-Shell connector

Keystone 1294 9-volt battery connector

Short (3.5 inch or 82-mi11iraeter) br eadboard

Two i/4—inch ( 6.5-mj. 11 imet.er) 4-40 fiat head screws and nuts

To make it easier for you to learn how to design your into the P( B and how you would use them when you own robots,a PCB has been included with the book are designing your own robot, 'the Parts Bin descrip¬ that, after soldering, can be used to explain and tion of the parts should be enough for you to go out demonstrate basic electronic concepts. It also serves as and buy the parts, even if you’ve never worked with a base for mounting your robot’s control electronics. electronics before. If you are unsure, ask someone After assembly of the Pt’R (which means adding the working at the store, but make sure you have the electronic components listed in the Parts Bin af the book and the PCB with you. start of the experiment ), the PCB will provide you with In the previous experiment, I introduced you to the basics of soldering and m this experiment I w ill • A 9 volt battery connector to power your experiments, expand on them and have you solder pin through hole (PT H) components to the PCB. As the name • A breadboard that is used to temporarily wire implies, a pin passes through a hole in a PCB (the circuits. hol"| is known as a via).The hole is plated with cop¬ • A socket for a Parallax BASIC Stamp 2 (BS2), per (or copper with a thin solder tinning), and after the controller used for in the experiments pre¬ inserting the pm into the hole, the two are bonded sented in this book. together using a soldering iron and solder,as shown • A set of current-limiting resistors to protect in Figure 2-23. When you have completed the solder the BS2's input/outpat (I/O) pins. joint and are about to cross section it. you should see something that looks like Figure 2-24.Hie solder • A programming interface for the BS2. more than fills the hole, but instead of forming a cir¬ Certain terms in the list of parts and features built cular shape, it forms the conical fillet shown in the diagram, and it should be shiny. When you first start into the PCB may be unfamiliar to you. Don’t worry if something is confusing to you: as you work through soldering PTH components, you will find that the the experiments, you will gain an understanding of shape may be more rounded lhan conical and the fin¬ these parts and features, including why they are built ish is dull and crinkled

Section Tujo Robot Structures 31

PCB PCB. turn everything over and start soldering the c pins as described previously. You might w ant to first ■H solder two corner pins to hold the DIPs rigidly. If the DIPs ride up. bv pressing down on them while hold¬ Figure 2-20 Good solder faints ing the soldering iron to the othei side, you can push them down onto the PCB. Once the DIPs are in and the corners are soldered down, you can go ahead and When I am going to solder, l usually turn the sol¬ solder the rest of the pins (Figure 2-26). CO dering iron on and let it heat up for 15 minutes (like a When you have finished with the lesistor DIPs, watched pot never boiling, a watched soldering iron w you can solder in the 24 pin 0 600-inch socket and the takes forever to heat up).To make a FI II solder momentary on switch. When soldering in the socket, < joint, I apply the hot iron to the pin and PCB for remember to match any indentations or markings at about a second (you should see some residual solder the end of the socket with the marked indentation on I flowing from the tip to the pin and the P(’B) and the PCB. As for the switch, you should notice that then touch it with solder. Your first attempts might one side is longer than the other and if you follow not look great, but you can fix them bv touching the this, the switch will go m easily and be oriented in the joint with the soldering iron for a few seconds with¬ right way. out solder. I’m sure you will be a pro after getting Next, insert the two 0.01 |xF capacitors into the -p through the first few joints in this experiment PCB.The wires running from the capacitors should To start off, insert the two 16-pin resistor DIFs into G be 0.100 inches apart (2.54 millimeters) and should the top of the PCR as shown in Figure 2-25. The top a) slide easily into the holes marked Cl 1 and 02 on ot the PCB is the side that has the white markings on the PCB. After insetting the component wires into S it. Component markings will be covered in more •HI the PCB, turn it over, letting the components rest detail later in the book, but the two DIPs should have u against the tabletop (they will be the same height as an indentation at one end and maybe a circle or the resistor DIPs) and solder in the leads. After sol¬ 0) square printed on the top by one of the corner pins. dering the wires, clip them to the same length as the Pu Push the Dips into the PCB’s RPl 220 and RP2 220 resistor DIP pins. X positions with the end indentation matching the ua

32 123 Robotics Experiments for the Evil Genius You’re almost done! The last piece of work is to add the breadboard. It should have a piece ot double¬ w sided tape on its back so that you can attach n to the X PC B. as shown in Figure 2-27. When 1 added the breadboard, I turned it so that the side with (he red single-row socket. First, clip off eight pins from one working on the circuits, I suggest you get a piece of to end and then soldei the endpins to the P( 'B. While antistatic matting to work on or place the PCB on to holding the PC B and connector, touch the iron to (he one of the plywood robot bases that you cut and fin¬ (D soldered pins to make sure the socket is exactly per¬ ished in this section, using I-inch standoffs (available pendicular to the PCB. Once you are satisfied, you from electronics stores). can then solder the rest of the pm. It is pretty easy to solder in the final two compo¬ H- nents. the 9-pin female D-Shell connector and the 9 volt battery connector. The D-Shell connector should d have metal tabs th.it tit thiough the large holes on either side ol the J3 connector that lock it in.These tabs should be soldered to the PC B along with the ct connector pins. d* The 9-volt battery connector has two tabs that are (D soldered into holes in the PCB, and the connector is held in place with two 4-40 screws and nuts. Ideally, M the screws should be countersunk to allow a 9-volt d battery to sit in the connectoi without being pushed Q out. Although I put in four holes for holding the bat¬ M tery connector, you really only have to use the two Figure 2-27 Completed PCR with breadboard in holes away from the battery contacts. place d p-(D PL ►d o to

Section Fujo Robot Structures 33 Section Three Basic Electrical Theory

When I was a kid. a very popular theme for an For some reason, nobody (and this includes the episode of a TV show was to have two heroes (or the special effects crew responsible for explosives) seems anil a wisecracking terrified bystander) defuse a to hav e told any Hollywood screenwriters that they bomb. The process of amateurs defusing a bomb could cut either wire leading from the fuse to the det¬ invariably follows after they discover an armed bomb onator and the bomb would be safe. As I will show in where either a fake one was expected or a live bomb this section, electricity must flow in a closed circuit- was expected somewhere else. After discovery of the in the TV shows then, once one of the wires was cut. bomb, the reluctant amateur ordinance disposal current couldn’t flow from the fuse to the detonator experts (ODEs) go through a complicated process of and back to set it off. opening up the bomb (careful to avoid anv booby- The bomb's fuse is represented by the switch and traps) only to be confronted with two wires. These the battery. Electricity is produced by a power sourcc wires are used to connect the fuse (the part of the (usually a battery ), and when the switch is closed, bomb with the timer, optional remote control electricity flows through the wires to the "detonator” receiver, and any booby trap sensors) to the detona and then back to the battery. lor (the part of the bomb that causes the high explo¬ The detonator can be thought of as a “load;” its sive to blow up). The bomb usually looks like it is purpose is to convert the electrical energy into some wired something like Figure 3-1. thing useful. In an actual detonator, electricity pass¬ With the booby traps behind them and the bomb’s ing through it causes a wire to heat up and a small components exposed, the heroes are always faced heat-activated charge in the detonator explodes. with the dilemma of which of the two wires leading When the detonator’s charge explodes, the shock of to the detonator to cut (adding to the tension, just this explosion sets off the high explosive of the bomh. before they make their decision and cut a wire, the It is not widely known by most people, but high show cuts to commercial ). Somehow they know that explosives do not go oft when they arc exposed to by cutting the wrong wire, the bomb would explode, extreme heat—they may burn fiercely, but they will but by cutting the right wire, the bomb would be not explode. It is the shock of the exploding detona¬ defused and safe. tor charge that sets them off. It should go without saying that throwing a stick of dynamite, or anv thing else you might find that is labeled “explosive” onto a fire to see what will hap¬ pen is not a good idea. Many dilferent kinds of explo¬ sives. as well as different products (such as aerosol hairspray). will explode and/or throw off binning materials if exposed to high heat When I discuss explosives in this section, it is for your edification, not as an invitation tor you to experiment with them. In case you didn’t get it the first time;do not place items labeled “explosive” (or that have an explosive warning symbol) onto a fire or other heat source. Figure 3-1 Block diagram of a bomb circuit

35 Section Three — Basic Electrical Theory of whatelectricityisandhowdifferentvaluesit some referencesinwhichthestarsaregiventask can becalculatedandmeasuredinacircuit. wires providingthepathforelectricitythrough 36 about: to defuseanexplosivedevicetheyknownothing treated inTVshowsandmovies,thefollowingarc expand onthisbasicruleandgiveyouabelteridea writers donotunderstand.Inthissection,Iwill is thebasicelectricityrulethatHollywoodscreen¬ switch andthecircuitaredescribedasbeingclosed, come together(astwowiresheldtogether),the same astwowiresheldapart.Whenthecontacts electricity cannotflowthroughthecircuit.Thisis within theswitcharenottouchingoneanotherand you willsecthatthedifferentpartsof“bomb on aschematicdiagramareusedtorepresentthe and electricitycanflowthroughthem. and setoffthebomb. this istheclosedcircuitIhatrequiredtoallowelec¬ when thereisapathforittofollow.Theblacklines tricity toflowfromthefuse’sbatterydetonator block diagram”arelinkedtogetherinaclosedloop— in thebomb’scomponents.IookingatFigure3-1. the powersource'spositiveconnectiontoitsnegative In caseyoudon’tbelievemeabouthowbombsare When aswitchissaidtobeopen,thecontacts Benjamin Iranklinsaidthatelectricityflowsfrom Ihe needtotaclosedcncuitforelectricitytoflow Short Fuse” Hogan's Heroes“AKlink,aBomband 1E3 Robotics Experiments for the EvilGenius or itwaswiredincorrectly,wasn'tthetypeof good laughbecausethebombturnsouttobeadud, bomb thatwasmeanttodestroythings. panic. Afterwards,everyoneisokayandenjoysa wrong wireiscut,whichresultsinafewmomentsof shows, you’llseethatinvirtuallyeverycase,the shows. Whatisamazingthatwhenyouwatchthese ally followedthesamelinesforeachofdifferent defusing processonTVwasverysimilarandgener¬ At thestartofthissection,Inotedthatbomb¬ seemed tohavedefuseatleastonebomb Barney Miller“LadyandtheBomb” Laverne andShirley—“TheRighttolight” every threeorfourepisodes) to befair,inMissionImpossible,theteam tain” A/M S*H—“TheArmy-NavyGame” bomb thattheyaretryingtodefuse. up abuildingbycuttingthew-rongwirein Lethal Weapon3—RiggsandMurtaughblow¬ FT?/—“Time Bomb’ Get Smart!—“StakeoutonBlueMistMoun¬ Ironside “NotwithaWhimper,butBang" Remington Steele—'Preni11tinSteele" Mission Impossible—“TimeBomb”(although experiment 12 — Electrical Circuits Experiment 12 Electrical Circuits and Switches

Assembled printed cir¬

cuit board (PCR)

Resistor with brown, black, and red bands

Light-emitting diode (LED), any color

Single-Pole Double-Throw (SPDT) switch toolbox

Introducing this section. I presented, in a rather grams. 1 usually mark the positive side of the power explosive (excuse the pun) manner, the concept of source with the + symbol to avoid confusion, but if electrical circuits. Electricity must follow a closed cir¬ you look at a circuit, remember that the end with the cuit. For this experiment, the nature of an open and longer line is the positive connection to the battery. closed circuit w ill he demonstrated—a light will he The positive connection ol the battery conies out of turned on using electricity provided by a battery. the Vin connections and the other (negative) connec¬ Every electrical circuit has three parts to it. Elec¬ tion of the battery is w ired to the Vss connections. In tricity is provided by a power source and passes the later experiments, 1 will explain positive and nega¬ through conductors (wires) to the load.The load con¬ tive as ii relates to electronics, as well as explain what verts the electrical energy into some oilier form and the connections Vin, Vdd, and Vss on the PI B mean. performs work with it. A load can be a simple light, a Hie electricity coming from ihe battery is passed microcontroller (such as (he BS2 presented later in along wires from the connector to the components on the book), an electric motor, or a combination of parts. the breadboard From these w ires, the electricity In this experiment. 1 will use the PC’B that came passes through the switch (Figure 3-3) to the resistor with the book, soldered together (assembled, as dis¬ (Figure 3-4) and then to the LED (Figure 3-5) before cussed in the previous section) with a battery, along returning to the battery. Wires are usually made from with a tew electronic devices to create a light that you copper and may have another metal over them to can turn on and off. ITie circuit that you will build is resist corrosion. To prevent wires in different circuits shown in Figure 3-2. (or different parts of the same circuits) from touch¬ ing, the unused portions of the wire are wrapped (or In Figure 3-2 I have used the conventional dia¬ clad) m a plastic sheath, known as insulation.The gram (the series of different-length parallel lines) to indicate the 9-volt radio battery power source placed in the clip built into the P( B, In my schematic dia¬ Outside View Inside Operation

Figure 3 2 First circuit showing switch control of electricity Figure 3-3 Switch appearance Resistor Lead Resistor Body Resistor Lead LED (Figure 3-5) is the acronym for light-emitting (wire) diode, and it can be pronounced either as the word rn n n rhyming with bed or as three individual letters. LEDs V a \_y are semiconductor devices known as diodes that emit light when electricity passes through them in one Value Bands’ Tolerance Band direction. I discuss diodes in more detail later m the

Value Bands Should Bo Brown Black and Red, book. Right now. I just want to introduce them as a from the End of the Resistoi to the Center very inexpensive, reliable, and easy-to-use alternative to standard lightbulbs. Figure 3 - M Resistor appear mice The breadboard is know n as a prototyping system w and allows you to quickly and easily wire circuits -p together. As you can see in Figure 3 6, a breadboaid consists of a matrix of holes in which rows or columns P Flat on Side of Diode of them are interconnected.To wire a circuit, you will V Indicates Polarity and have to place a component’s pin or w ire into one of Direction of Current Flow u the holes in the breadboard and then either put in a wire or another component into a hole that is con¬ nected with '.his one. u Leads Connecting LED to Circuit The different parts of the circuit are wired on the breadboard as 1 have shown in Figure 3-7. Hie polar H Figure 3-5 LED appearand ity or orientation (the direction the component goes (d in) doesn’t matter tor the resistor or the switch, but it u wires used in this application are part of a bread docs for the LED. The battery's polarity also matters, board wiring kit that you will need to build the exper¬ but the PCB-mounted clip ensures the battery is iments in this book. wired correctly. The pin on the flat side of the LED is *P the switch is a device that btings two wires connected to the Vss holes in the PC B’s connector. O together to allow electricity to pass from one to When you build your breadboard circuits, it is a good idea to keep the components’ wires as short as possi¬ 0) another Figure 3-3 shows a Single-Pole Double- ble and pressed against the breadboard. For simple rH Throw (SPDI) switch looks like. In the description, circuits, such as the one in this experiment, this is not. U4 the poles are the number of circuits that can be switched and the throw is the number of connections critical but ii will be for the more complicated exper¬ iments presented later in the book. that can be made in the circuit I went with the SPOT switch simply out of convenience: it is a lot easier to When you have put together your circuit, il should find a breadboard mountable SPD F switch than it is look something like Figure 3-8. CM to find a breadboard-mountable SPST switch (the symbol for which is used in Figure 3-2).Ter use the SPOT switch as a SPST switch, connect the middle Interior Connections Fxtcrior -P pins (called the common terminal) to one of the out¬ C side pins. <1) Fhe resistor (Figure 3-4) is probably the most 6 basic, true electronic device that you will work w ith *H In this section I go into detail explaining how resis tors work, how their value is specified, and how they are used in an electrical circuit. For now, just select a 0) resistor with a brown, black, and red stripe (or band) to painted on it Figure 3-6 Breadboard with interior connections shown to

38 LET) Robotics Experiments for the Evil Genius nD nnnnn nnnnn Dn DD nnnnn nnnnn nn DD nnnnn nnnnn on m DD Dnopn □□□□□ nn w

Figure 3-7 l ii st experiment wiring Figure 3-8 What lha first wiring experiment looks like on a breadboard

When you move the switch's slider hack and forth you should see the LED light when the switch is in You can demonstrate the operation of the switch one position and not in the other. When the LFD Electrical Circuits in a more concrete fashion by taking out the switch lights, the connection within the switch is made and and using a length of wire that you can pull out of the the circuit is said to be closed with electricity (lowing breadboard and put back in to show w hat happens around it. When the switch is in the other position, when the circuit is open and closed. Once you have the connection is broken and electricity cannot flow the LED lighting when the switch is closed and turn around the circuit. In this case, the circuit is described ing off when the switch is open, you can go on to the as being open. next experiment. I will use this circuit (or its base) for If the LED does not light, then check vour wiring the next few experiments. (especially the orientation of the LED) and try another battery in the socket.

Section Three Basic Electrical Theory Experiment 13 — Circuits and. Switches cuit showninFigure3-10,One ofthetwoLEDswired the T.EDconnectedtoresistor willalsolight. that itisconnectedto.When oneoftheseLLDslights, switches allowelectricityto flow throughthewires into theswitchconnectionwill lightwhenthetwo SPOT switchescanbedemonstratedbyusingthecir quite ahitofcomplexcircuitrytocontrol. venient touseandprobablyseemliketheyrequire of theotherswitch.ITietwoswitchesareverycon¬ anymore soyouturnitoffbychangingtheposition switch. Attheendofhall,youdon'tneedlight 40 ity cantlowthroughthecircuit. necting wires,thereisanopencircuitandnoelectric¬ switches areclosingtheconnectionstodifferentcon¬ necting wiresandthecentralconnections.When switches eloseacircuitbetweenoneofthetwocon¬ switches totherestofcircuitandoutsidecon¬ the lighton,youchangepositionofnearest you haveasinglelightcontrolledbytwoswitches.It ous experimentworks,amiexplainhowaseemingly explaining whatelectricityisandhowitworks.Iwant Figure 3-9,withthecentercontactconnecting ment. TheseswitchesarewiredasIhaveshownin you areatoneendofthehallandwanttoturn magical switchinyourhomeworks. actually) attheflipofaswitch.Beforegoingonand tacts connectingthetwoswitchestogether. like theonethatyouusedinpreviousexperi¬ to goback,examinehowtheswitchusedinprevi electrical circuitthatturnsonandoffalight(anLED In ihepreviousexperiment.Idemonstratedasimple Chances are,inyourhome,probablyahallway, In actuality,theyjustrequiretwoSPOTswitches As showninFigure3-9.electricityflowsonlyifthe the movementofelectricityinacircuitwithtwo 1 ?3Robotics Experiments fortheEvil Genius Electrical CircuitsandSuuitches Assembled PCBwithbat¬ Resistor withbrown, Three LEDs,anycolor Two SPDTbreadboard mount switches black, andredbands tery Experiment 13 for electricity Figure 3-11isthewiringdiagramforthiscircuit. back andforthinanefforttoseehowtheswitches indicating thatthereiselectricitypassingthroughit. Figure 3-10SPDfcontrol oftwodifferentpaths Figure 3-9SPDIlightcontroloperation - 9-Voll Tool Box . Youshouldspendsometimeflippingtheswitches I Through Bottom Throuqh Top Flow Nc Electricity Electricity Path Flowing Electricity Path Flowing Battery LTTl 1- ► Wiring Kit SW1 syvi Electricity Flow Electricity Flow --p. - JfL- _n t TD SW2 sw z Experiment 14 — Voltage Measurement work (you might also want to compare the operation □ □ □ □ □ □ □ i □ □ □ □ □ □, of a dual-switch light control in your home to con¬ □ Ho dfl t5 □ _p □ □ □ □ □ □ □ n—□ °am vince yourself the circuit works in the same way). □ □ □ □ □ □ ? □ □ □ □ □ □ □ □ □ □ & □ □ □ d—d □ □ □ □ It will probably be difficult for you to “see” Figure □ □ □ □ □ □ □ □ □ □ □ 3-10’s circuit in Figure 3-11 ’s wiring diagram.This is □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ because 1 tried to come up with a wav that the LEDs □ □ □ □ □ □ □ □ □ □ □ □ □ □ could be in line without requiring extra wires. When □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ you design your own breadboard circuits, you will □ □ □ □ □ □ □ □ □ □ □ □ □ □ find that some methods will make the circuit easier □ □ □ □ □ □ □ □ □ □ □ □ □ □ to wire but obfuscate its operation. If you are con □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ fused by the wiring diagram, then I suggest that you □ □ □ o □ □ □ □ □ o □ □ □ □ trace it out with a highlighter to see the paths for □ □ □ □ □ □ □ electricity or try wiring it on your own and do not Figure 3-11 Wiring diagram for SPDTswitch follow Figure 3 11. being used to select different electricity paths Despite the simplicity of this circuit it actually provides quite a sophisticated function; it allows con¬ trol over a light from two physically different loca¬ tions. This can be implemented a number of ways, but the method shown here is probably the most elegant.

Experiment 14 Voltage Measurement

Tool Box Assembled PCB with Wiring kit battery Digital multimeter (DMM) Resistor with brown, black, and red bands

LED, any color

In the previous experiment. 1 said that the LED lights any form (except as lightning), which means it does¬ when “electricity” passes through it. It is not an accu¬ n’t have mass. Although you probably know it can be rate term, but to help you get through the first experi¬ used to create a magnetic force, it doesn’t seem to ment in electricity, 1 wanted to keep the number of have any force that you can perceive or measure. new concepts to a minimum. What you should have When you were in grade school, you probably gotten from the previous experiment is that electric¬ read about Benjamin Franklin's experiment with liv¬ ity must How in a circuit for the circuit to work. ing a kite in a rainstorm—after the kite was hit by In this experiment, I would like to look a bit lightning, Franklin touched a tncial key that had been deeper into w hat electricity is. Electricity is a form of tied to the line and got a shock. This shock was the energy and is capable of performing “work.” If you same as to the static electricity shock that you get have taken introductory physics, then these two from shuffling your feet over a carpet and touching a words should set oil something in your head energy door handle. At the tune, touching things that were and work imply a force acting on a mass.This is prob¬ thought to have electricity was the accepted test to ably confusing ter you because electricity doesn’t have detect electricity: It you got a shock., it was there.

Section Three Basic Electrical Theory 41 Experiment 14 — Voltage Measurement Figure 3-12Aswimming poolwatersystem lowest energylevel).Itthecatchbasinhasacrackin 42 13 3Robotics Experiments for the Evil Genius the wateratdifferentpoints.InFigure3-12,1have open inanelectricalcircuit. not beabletoperformanykindofworkforvery work asitflowsdowntothebottomcatchbasin(the ferent pointsbutwecanmeasurethepressureof long. Acrackinthecatchbasinissameasan li sothatwatercouldleaknut.thenthesystemwould top oftheswimmingpoolisathighestenergy some kindofpressureappliedtoit. level. Ihisenergyisallpotential,anditcanperform draws thewateragaintocontinueprocess. downward tothebottombasinwherepump to waterinaswimmingpoolsothatitcanmove ing toalevelofthewaterinpool,flows upwards mapipe(asshowninFigure3-12).Afterris¬ applied toanelectricalcircuitusingapowersource. that electricitywouldnotmoveunlesstherewas so theforcebecomespressure(whichisdefinedas stop working.Tomovewateryouhavetoapplysome force overarea).Usingthismodel,itwasrealized the forcewouldhavetobespreadoutoveranarea, force onit—becauseofthefluidpropertieswater, all thewaterinasystemleakaway,will moving inacircuit,theelectricityisreused,ifyoulet tem andwaterwillstopflowinginit).Aspartof block apipe,youhaveeffectively"‘opened'thesys¬ water inaclosedsystem(ifyoudamupriveror electricity, oneofthemostimportanttheories Franklin postulatedwasthatelectricityflowslike 1 Ins.isanalogoustousingapumpapplypressure We cannotmeasuretheenergyofwateratdif¬ As 1haveshowninFigure3-12.thewaterat Electrical pressureiscalledvoltageandit Along with'proving”lightningwasmadeupof Difference Pressure Pool, HalfMax Halfway down D;fference Max Pressure Pump Outputs-J CM LB.asinl—<3) Bottom,Zero Pressure Difference Side View • tomorethan$500.I’mgoingsuggestthatyou Hold theDMM’sblackprobeconnectedtocir ment’s instructionswillexplainhowthisisdone). done thisandtheLEDislit,setyourDMMtomeas¬ ple circuitshowninFigure3-14,consistingofaresis¬ experiments mthisbook. ure voltagesinthe“20-voltDC”range(theinstru tor andI.F.Donthebreadboard.Whenyouhave are nicetohavebutnotrequiredforanyofthe transistor betas,andcountthefrequencyofasignal Features suchastheabilitytotestdiodes,measure ability tomeasurevoltage,current,andresistance. 3-13. YoucanbuysimpleDMMsanywherefor$5 device calledavoltmeterisused.Allhoughsimple take advantageof.Youshouldjustbelookingforthe unit willprovideyouwithfeaturesthatcannot you haveaccuracyproblems,andamoreexpensive resistance. InDMMslessthan$20.youmayfindthat accuracy thatshouldbeabletomeasurecurrentand buy oneforabout$20. a digitalmultimeter(DMM)liketheoneinFigure voltmeters areavailable.Iamgoingtoaskyouget To measuretheelectricalpressure(orvoltage),a electrical circuityoubuiltmthepreviousexperiment. approaches thepressureatbottomofpool. you descendlowerinto,thepool,pressure different fromthatatthebottomofpool,andas the topolpool,waterpressureisquiteabit pressure ofthewateratbottompool.At the pressureofwateratdifferentpointsto pool.To takethesemeasurements,1amcomparing put pressureindicatorsatdifferentdepthsofthe The swimmingpoolisactuallyverysimilartothe l orthisexperiment,youwillhavetobuildthesim¬ For $20.youwillgetaDMMwithreasonable t=G Top- Difference Pressure Max □ p p p p p p p p p p p □ □ p p p p p □ p p p p □ 0 ppppd □ □PPP □ n-g&SkTTnrfl ppp o o LCD Display □ □ PL'PPP p p p p p □ □ P'OOP O O O P P □ p p u □ □ □ noooo o o a p nppp^ □ O O P o □ o a or p p©) P P P P o p p eriment 14 — Voltage Measurement □ p □VS H □ PPPOP p p □ p p SAp □ PPPOP □ □ p pl*^>p PPOPP □ □ p p pbA PPOPP □ □ □ p PPP P u PPOPP O O □ □ DPPPP O P □ □ □ a □ p p □ □POP □ POOP □ □ □ p PPOPP P P P P o □ o □ p □ □pop □ POPP □ o POPDP o □ o o □ □ o □ POOP D □ □ D D □ o □ □OOP PPPOP □ o PPPOP PPPOP □ o p □ p p p PPOPP □ p □ □ p p p PPOPP p o p p O P p P P □ POOP □ o □ p p □ □ □ □ p □ p □ a o o p □ 0 p P P P □ □OOP p □ p p □ □OOP □ p □ p p p o

Figure 3-15 Measuring the battery's voltage

P □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ p □ □ □ □ □ 'J □ oq^i f\ooo □ □ COOP Table 3-1 Voltage measurements for the LEU SSS&j □ O □ P □ p p l Placo DMM probos and battery in this circuit as shown (- positive” is red and “ negative" is black) □ □ □ □ Ol0| □ □□□□ Voltage □ □ □ □□ P P P P P □ □ □ □ □ P P P P p Point Measured Comments □ O □ □ □ p □ P p □ □ □ □ O □ □ POPP □ □OOP P P P P P Battery 9.25 Ihe s imc at either the battery □ □ □ □ □ PPOPP □ □ □ □ □ p p p p □ or across both the rcsi'tor and □ □ □ □ □ DPPPD □ □ □ □ □ □ PPDP LED □ □ □ □ □ n p p p p □ □ □ □ □ p p p p p □ □ □ □ □ □ p p p □ LED 2.01 □ □ □ □ □ p p p p p □ □ □ □ □ p p p □ p □ □ □ □ □ p p p p p

Figure 3-14 Measuring the voltage across the basin at the bottom of the pool in the water example. LCD When measuring water pressure or voltage, there must be some bottom reference that can be used to cult's negative connection (Vss shown in Figure compare the values. In an electrical circuit, the nega¬ 3 14); then measure the voltage at the two different tive output of the power source is normally used as points in the circuit as shown in Figure 3-14 and Fig¬ this bottom reference. Instead of the term bottom ure 3 15 using the DMM. reference, the word ground (abbreviated to Gnd or sometimes referred to as Vss as on the PCB) is used In Table 3-1,1 have listed the voltages that I meas¬ for electricity.The ground is the point in the circuit ured in a prototype circuit where there is no electrical pressure (it has a voltage These results are similar to what would be seen of “0”) and. if something was connected to the when measuring the water pressure relative to the ground, it would be unable to do any kind of work.

Section Three Basic Electrical Theory Experiment 15 — Resistors and Voltage Drops tion isaforcethatresistsmotion,convertingthe selves arequitesmallphysically,sotheirvalues ohms andaregiventhefisymbol.Resistorsthem¬ of resistancetoelectricity.Theunitsare energy islost.italmostalwaysconvertedintoheat created nordestroyed;ifsomeislostinthepipe,then thermodynamics statesthatenergycanneitherbe energy ofthemovingwaterintoheatIhefirstlaw does nottravelinapipeeffortlessly.Ihesubtly how electricityworks,youshouldrealizethatwater ing formulaandaredefined inTable3-2. indicated onthembyaseries ofcoloredbands ferent partsareavailable,offeringdifferentamounts component fordoingthisiscalledaresistor,anddif¬ why theapproximationofthembeingperfectis typically haveaverylowlevelofresistance,whichis called superconductors,everythingwillresistthe (called resistance)toelectricitymovingthrough that conductorsareperfect,theyoffernofriction it mustbeconvertedintosomeotheiform.When the waterexperiencesmovingthroughpipe.Fric¬ ot themotionofwaterwouldcauseapressuredrop pipe andtheexit,youwouldfindthatrestriction Using thewateranalogytocontinueexplain be changedtomoresuitable.Themostcommon made. them. Thisisactuallynottrue;excepttormaterials impedes thepassageofwaterrunningthroughit. If youweretomeasurethepressureatinletofa 44 movement ofelectricitythroughthem.Conductors The handsspecifytheresistance usingthefollow When wearedealingwithelectricity,assume In manyelectricalcircuits,energyhasto Ihis pressuredropiscausedbythefrictionthat 123 Robotics Experiments fortheEvil Genius Assembled PCBwith Three resistorswith Resistors andVoltageDrops orange bands brown, black,and breadboard Experiment 15 culate theresistorsusedinthisexperimenttobe Table 3-2Resistorbandcolorcoding Color Orange Green Yellow Red Black Silver Gold White Gra> Motel Blue Brown Resistance =((Brownx10)+Black) Using theformulaandcolorchait,youcancal Resistance =((Eand1ColorValue Band CotarValue = 10,000Ohms = (10+0)x10’Ohms N/A N/A x lo°“na‘Ohms x 10}+(Band2Color 5 2 0 4 3 9 8 6 7 1 Ohms Value) }x10Band3Cc,lorv*ju« Wiring kit DMM 0.05% 0.25% 0.5% 0.1% Tolerance N'A N'A N/A N/A 10% 2% IS, 5% Most resistois offer 5 percent tolerance and this is For the energy to increase, an energy source, such as experiment 15 — Resistors and Voltage Drops more than acceptable for the circuits piesented in a battery, would have to be inserted into the circuit this book and the ones that you will work with. In To further investigate the behavior of voltage in a practical terms, you will find that most resistors ha\e circuit with resistors, measure the voltage across each a tolerance of 1 percent or less they are specified as resistor using the DMM probes as shown in Figure being 5 percent as the absolute worst case by the 3-17. You should find that the voltage across each manufacturer. resistoi is approximately the same and is one-third To demonstrate the operation in an electrical cir the voltage applied by the battery. In doing this, you cuit and how it affects the electrical pressure or volt¬ are mcasuiing the voltage across each resistor. age, build the circuit shown in Figure 3-16 and Finally, measure the voltage across two resistors as measure the voltage across the resistors. In your first 1 have shown in Figure 3-18.This voltage should be test, set your D\1M to “Voltage" (the 0- to 20- volt two-thirds of the total voltage applied to the circuit. range) and place the black probe at the negative or As I will explain later in this section the voltage Vss voltage and place the red probe at the four points across a resistance is proportional to its fraction in noted in Figure 3-16 and record the voltages. the total circuit. These two resistors have two-thirds When you have recorded the voltages, you would of the resistance in the circuit, so it should make have found that the voltages changed evenly from sense that they have two-thirds of the voltage drop in zero to the applied battery voltage at each resistor the circuit. step.This is analogous to measuring the pressure of water as it travels down a pipe. Each resistor behaves similarly to a length of pipe in which the water pres¬ Measurement #1 sure drops Just as the pressure reduction in a length - 1-Volt of pipe is called a drop, the voltage reduction through —_ Battery each resistor is called a voltage drop. You should Measurement #2 notice that none ol the voltages measured in Figure 3-16 is greater than the applied battery voltage; they are either less than or equal to the battery’s voltage. Measurement #3 lire voltages being less than or equal to the applied voltage should not be a surprise especially considering the comments 1 made at the start of this Figure 3-17 Measuring voltage drops across experiment. II the voltage increased, then the energy individual resistors of the electricity would have increased, which should be impossible due to the first law of thermodynamics.

Figure 3-16 Measuring voltages in a dram relative to ground

Section Three Basic Electrical Theory 4 5 Experiment 16 — Current Measurement age). Tohelpdefinehowelectricity behaved,Ben¬ at all.Infact,theprevailingtheoryofelectricitywas defined, thenatureofatomwasnotunderstood jamin Franklinpostulatedthat thisfluidmovedfrom some kindofelectricalpressure (whichwecallvolt materials anditcouldbemoved bytheapplicationof that electricitywasafluidexistedincertain know nasnegativeelectricalcurrent. more positivelocation.Thismovementofelectronsis and theywillmoveawayfromtheforcetowarda electrical pressure(calledvoltage)isexertedonthem 2 trillion(?.x10)planetsintheMilkvWaygalaxy. charge isthecoulomb,anditconsistsof1.60219X the positiveteiminalofapower souicetothenega¬ than thereareplanetsinourgalaxy. One coulombhasabout8.IKK)timesmoreelectrons how bigitactuallyis.considerthatthereareabout (your scientificcalculatorcanprobablydoexponents are andhowmanyinanobject,lhebasicunitof atoms, itishardtounderstandjusthowsmallthey electric current.Whenwetalkaboutthesizeof by electricforce(voltage)toproduceelectricity. cules ofwater,nowilistimetolookatwhatmoved were discussed,theforcewasappliedtomole ent devicesintheeircutWhenwaterexamples the differentvoltagedropsexperiencedbydiffer¬ to thebase10of40ormore).Togiveyouanidea to water.Aspartofthis,youshouldbefamiliarwith (voltage) andhowitcorrespondstopressureapplied 4 6 negatively chargedsubatomicparticles,makeup You shouldnowbefamiliarwithelectricalpressure I0|u electrons.Thisexponentmaynotseemverylarge When electricitywasfirstbeingunderstoodand To minethefreeelectronsinametal,negative As youareprobablyaware,electrons,which 12 3Robotics Experiments for-theEvil Genius Current MeasurementandOhm'sLauu Assembled PCBwith 1,000 !tresistor(brown, 10,000 1!resistor breadboard bands) black, redbands) (brown, black,orange Experiment 16 circuit Thisimpliesthatavoltage/current/resistance one-tenth thecuirentthrough the1,00011resistoi tive (theterms“positive”and“negative”beingcom¬ mula: relationship existsthatissimilar tothefollowingfor¬ the currentthrough10,000 11resistorcircuitwas measurement was8.84voltsandthecurrenttluough resistor inplaceofthe1.00011resistor.Myvoltage and measurethecurrentpassingtluoughit.Imeas measure 0to20milliamperes(niA)ofcurrent measured 8.89volts).Then,settingyourDMMto voltage acrossthe1,00011resistorandrecordit1 circuit asshowninFigure3-19.Firstmeasurethe observed andmeasuredusingyourDMM,wiredina to thevoltageappliedcircuit. open circuitexists),thentheelectronswillbunchup the positiveterminalofpowersource.Ifposi¬ for ustofollow. as thedefinitionofelectricalcurrent.Workingwith acceptance ofFranklinstheoryelectricitytravel¬ terminals tothepositiveterminals,butdue Actual electricalcurrentmovesfromthenegative lhe resistorwas0.90mA. ured 8.93mA. in theconductoruntiltheircollectivevoltageisequal tive terminalofthepowersourceisnotpresent(an are simplytoosmallforustoseeandmovefast ling frompositivetonegative,wearestuckwiththis pletely arbitrary).Unfortunately,thiswaswrong. (explained inyourDMM’smanual),breakthecircuit this conventionisn'ttooonerousbecauseelectrons Tool Box The mostpositivelocationinanelectricalcircuitis Looking attheseresults,youshouldnoticethat Next, repeattheexperimentusinga10,00011 Hie movementofelectricalcurrentcanbe QMM Wiring kit DMM Set to Read W Voltage X

ft) h H- 3 3 rt

JS

Figure 3-19 Measuring voltage across a current as well as through it n Current = Constant x Voltage/ circuits. You might want to remember it using a c Resistance mnemonic like

You can test this by placing a different battery h Twinkle, twinkle, little star. (with a different voltage output) into the circuit and a> Voltage equals eve times are. repeating the measurement. No matter how many 3 different ways you test this (with different resistors r+ Another way of remember Ohm’s law is to use the and batteries), you will find that the previous formula “Ohm s law triangle."This tool will return the for¬ is true. mula for any of the three parts when you place your This is a basic rule ot the universe known as Ohm’s finger over one of the three symbols. In Figure 3-20,1 ance was named the ohm in his honor Find I = ? 3 To simplify the application ot the law. the Systeme (D International (SI) units for voltage, resistance, and 3 current were chosen so the formula does not need a rt constant. Replacing voltage with the symbol “V,” resistance with the symbol "R" and current with the symbol “i." Ohm's law can be written out simply as i ' V = i x R Result I = Understanding and remembering this formula is critical if you are going to work with electronic Figuro 3-20 Ohm’s law triangle example

Section Three Basic Electrical Theory 47 Experiment 17 — Kirchoff s Voltage Law I current thatflowsthroughit.IIthesestatementsdo ance inthecircuit,youwilldecreaseamountof current increases.Similarly,ifyouincreasetheresist¬ ohms, and"M”isusedformillionsofohms.This ohms. Youwillfindthatmostresistorsyouwork experiments againtomakesurethattheseconcepts you increasethevoltage(electricalpressure), can visualizewhathappenswhenelectricalcurrentis and itgetstediouswritingthemoutas1.000SIor wilh areeitherinthethousandsormillionsofohms, because youmustbeabsolutelyclearonitwhen1 are clearillyourmind. them, thenyoushouldgobackandworkthroughthe flowing inacircuit.Itshouldseemobvious(hata'' With abasicunderstandingofOhm’slaw1,1thinkyou resistances, thesymbol“k”isusedforthousandsof not makesensetoyouandcannotvisualize 48 Figure 3-91 Different waysofaddingloads toanelectricalcircuit IJX)O.O(K) SI.Ibsimplifythewritingdownoflarge So far,Ihavebeenreteriingtoresistorsinunitsof I ampushingyoutounderstandthisconcept Kirchoff sVoltageLaidandSeriesLoads L 23 Robotics Experiments for the EvilGenius Series O Assembled PCBwith V— V_

a> Sa

Pa

Fi

ti

te y

te

Is

a

c

r 1

i are in this section, we can look at how each type of the circuit In Figure 3 23.1 show a circuit in which Experiment 17 — Kirchoff's Voltage circuit works without worrying about complications there are three resistors—to the right of each resistor brought by other components. 1 present the formula for the voltage drop across it. In this experiment I will be investigating what hap¬ lhe voltage drop is the fraction of the resistance to pens when you put resistors in place serially. The the total resistance in the circuit, lhe current is the analogy of adding resistors in series is similar to the same at every point in the circuit because there is situation shown in Figure 3-22 in which a pump is nowhere, other than the circuit, to flow. Using the driving water through a pipe to work a water wheel. voltages across each resistor in Figure 3-23. the total voltage across the resistors is: Increasing the length of pipe is one wav of adding resistance to a system; adding resistance will result in less water flow in the entire system and a drop in out¬ put water pressure (at the water wheel load). Adding = V X R1/(R1 + R2 + R3) + V X more pipe (resistance) to the circuit is the same as R2/(R1 + R2 + R3j + V x R3/IR1 adding another resistor to a circuit that is driving a + R2 + R3) load like the one I show in Figure 3-22. lhe longer = V x

.R = R + R equivalent original added uring the current through the system, you will have to break the connection and set your DMM to 0 to 20 Therefore, the equivalent resistance will always be milliamperes. larger than any of the single resistances summed together,'This is an important fact to remember when Looking at these results. I can use Ohm’s law to you are calculating series resistance* (such as on a confirm that the total load resistance is 3.2k (lk test). added to 2.2k). lhe impact of each series resistance is propor¬ tional to its value relative to the total resistance of

Figure 3-23 Voltage drops across different series Figure 3 ??. Increasing resistance in an electrical resistors t in nit

Sprtion Three Basic Electrical Theory 49 Experiment 18 — Variable Resistors Tlie secondmostbasicelectricalcontrol(afterthe Table 3-3Circuitmeasurements shouldn't betoosurprising,astheyarecommonly over acircuit,potentiometer providesyouwiththe give you“onand“off*(also calledbinary)control used indifferentelectronicdevices.Whereasswitches resistors work,andtheideaofavariableresistor tiometer. Youshouldbefairlycomfortablewithhow mechanical switch)isthevariableresistororpoten¬ tors. youshouldseethatthevoltageratiosoftwo 50 control isusually referredtoasananalog control. Measurement Results between full"onandcompletely “off.”Thistypeof ability tosetacontrolan arbitrary position 2.2k resistorvoltage602V Current 2.73mA Battery voltage8.77V I kresistorvoltage2.74V (Checking thevoltagedropsacrosstworesis¬ = 3,201!)-3.2k = 8.77V/27.4mA 12 3 Robotics Experiments for the EvilGenius Nine-volt battery Assembled PCBwith Twenty -fourinches 10k PCBmountpot.en- 100 1!resistor breadboard 22- to24-gauge wi re clip t. iometer stranded copper (6C centimeters)of Variable Resistors Experiment 18 potentiometer (oftenabbreviatedtojustpot)isoneof resistors inthisciicuitcanheexpressedasthe by thetotalresistance. applied voltagemultipliedbytheirvalueanddivided material shown alongwiththewiperconnected toit. sentation ofthepotentiometer withtheresistive potentiometer (Figure3-26) isafairlyaccuraterepre¬ operator orsome,device.The schematicsymbolofa across aresistivematerialunder thecontrolofan rotary potentiometer;acopper"wiper”ismoved conic upwithonmyown.Figure3-25showsatypical the fewthatlookslikesomethingIwouldhave manufactured. 1findthatthevariableresistoror Figure Scriescircuitwithtestpoints Tool Box - Battery - 9-Volt When llookathowdifferentelectronicpartsare Through Ikand2.2kResistors Battery HeretoMeasureCurrent Break Connectionfrom9-Volt < ? Wiring kit. DMM Hobby knife Standard HEpencil 2 2k Positive Negativt Across the1k Measure Voltage Resistor Across the2.2k Measure Voltage Resistor from graphite (a form of carbon), the same material as is used in resistors and many types of potentiome¬

Resistor ters. You can demonstrate the operation of the vari¬ Detriment 18 — Variable Resistors Contacts able resistor made from the pencil lead by placing your two DMM probes on the lead, setting the DMM to read resistances, and moving the probes back and Figure 3 25 How a potentiometer is built forth across the lead. You should see the resistance increase as the two probes move farther apart (which Competent Reference is expected because there is more resistive material between the two probes). If the resistance goes infinitely high on your pencil lead, then you bare a crack in it. If this happens,you should try to expose the lead in another pencil. I found it took me three attempts to get the results shown in Figure 3-28. I lie potentiometer can also be used to output changing voltages as can be demonstrated by wiring Figure 3-26 Potentiometer/variable resistor the PCB’s 9-volt battery (with a loose battery con¬ symbol nector) to the extreme ends of the exposed pencil lead. Next, set your DMM to measure voltage and place the. black probe on the negative connection and Potentiometers are specified by the following the red probe onto the peneil lead (Figure 3-29). As three characteristics:

• Resistance of the material between the two Pencil for Experimentation contacts. The wiper resistance is assumed to be negligible and is used as a "tap1' into the resistive material. Wood Cut Away to Expose "Lead” Inside

• Whether the resistive material in the poten¬ Actual Results Showing “Lead” Exposed tiometer increases in resistances linearly (resistance changes evenly along its length) or logarithmically ( the resistance changes accord¬ ing to a function like 10

• How much power the potentiometer can han die. As I will discuss later in this book and show why in this experiment, potentiometers are not well suited to control powei being passed to loads. For this reason and because small potentiometers are much cheaper than high-power potentiometers, I only use poten¬ tiometers that can handle very miniscule amounts of power.

You can make your own potentiometer by remov¬ ing the wood on one side of a simple HB pencil (not a colored pencil crayon) and exposing the lead inside, Figure 3-28 Measuring varying pencil lead as I show in Figure 3-27. The lead of a pencil is made resistance

Section Three Basic Electrical Theory 51 •H -P Signal 100 Voltage Out Positive Negative Signal Equivalent Circuit as Potentiometer Measure Voltage Position Changed Out Signal Experiment 19 — Kirchoff's Current Law

Experiment 19 Kirchoffs Current Lauu and Parallel Loads

Tool Box

Assembled PCR Wiring kit

lk resistor DMM

2 2k resistor

Looking at loads in a series, the addition of the resist¬ Using Ohm’s law. we can calculate the equivalent ances of the loads to make up a single, equivalent resistance: load should seem quite intuitive. Using the example of the lengthened pipe, the added resistance of the ^equivalent ^tntal length ot pipe is quite naturally added to any resist¬ = 10 volts/7 amps ances already in the system and increases the total = 10/7 ohms = 1.43 ohms resistance of the system. With this in mind, you might think that the equivalent resistance of two resistors in Rather than jumping to the decimal value of the parallel (Figure 3-34) is just as intuitive. equivalent resistance, take a look at the fractional When you first try to figure out what is the equiva¬ value for the resistance, The numerator of the frac¬ lent resistance, you will probably hit a roadblock Irv¬ tion is the product of the two resistances and the ing to visualize what is happening in the circuit. denominator is the sum. With this information, you Going to the water analogies, it may help to think of can generalize the equivalent of two parallel resist¬ the two resistors as two pipes in parallel passing ances (A and B) to water over a greater amount of area: this reduces the R = (R X B )/(R + R ) resistance, but the equivalent resistance is not intu¬ txzuivalmn t a B A B' itively obvious. Looking at a circuit that has three or more resis¬ To calculate the equivalent resistance ot the two tors in parallel (such as Figure 3-35). and performs resistors in Figure 3-34, knowing that the voltage the same analysis (starting with the current through drop is the same across each resistor, we can find the each resistor, adding them up, and calculating the current flowing from the 10-volt power source using equivalent resistance), you would discover that the Ohm’s law general formula for the equivalent resistance is the following: i, . = 10 volts/5 ohms 5 ohm R = 1/( (1/R ) + (tl/RJ = 2 amps equivalent. * 1 1 t + . . . (1/RJ) . = 10 volts/2 ohms i 2 ohm

= 5 amps

Cotsl 5 ohm 2 ohm i = ? =2+5 amps

= 7 amps

With the work done so far. looking at Figure 3-34, Power 10V you should be comfortable with the concept that the Source — sum of the currents passing through the branches of the parallel circuit is equivalent to the total current provided to the circuit. Figure 3-3M Two-resistor test circuit

Section Three Basic Electrical Theory 53 Experiment 19 — Kirchoff's Current Law experiment, 1cancalculatetheexpectedequivalent ol 701.3ohms. cuit Asexpected,thecurrentsthroughllietworests any accuracyerrorsinyourDMM. values oftheresistorsthatyouareusingaswelt value, justasIwas.Thisdifferenceisduetotheactual percentage pointortwoofffromthecalculated parallel resistanceoftheIkand2.2kresistorstobe This allowsmetocalculateanequivalentresistance tors matchthetotalcurrentprovidedbybattery. matches thecalculatedequivalentresistance. 5 4 yout calculatedequivalentresistancewilljustbea in atablelike'lablc3-4.Usingtheresults,calculate using thecircuitinFigure3-36andrecordresults the equivalentresistanceandseehowcloselyit Figure 335Multipleresistorequivalency Chances arethatwhenyouruntheexperiment, I singtheformulacameupwithearlierinthis In thisexperimentIwouldliketotestanalysis Hie tablecontainsthevalues1readlronimycir eguivaient 123 Robotics Experiments for the EvilGenius 2.(10*) /3.2103)ohms= 687.5 ohms (lk x2.2k)/(Ik+2.2k) (x* *V/f**V smallest resistorintheparallelcircuit.Thisobserva age lawandOhm’slaw,isvitallyimportantto Kirchoff’s amentlawthislaw,likevolt¬ tion isusefultorememberwhencalculatingthe resistance ofparallelresistorsisalwayslessthanthe of currentpassingthroughthecircuitisknownas through aparallelcircuitisequivalenttotheamount is reasonable. resistance ofaparallelcircuittoknowifyouranswer Table 3-4Rnalyisresults remember andunderstand. Figure 3-36Two-resistortestexperimentcircuit Measurements An importantobservationisthattheequivalent Hie statementthatthesumofcurrentspassing 4 18mA 9.25 soils 9.02 13.19 mA Experiment 20 — Thevinin s Equivalency

Experiment 20 Thevinin's Equivalency

In cases where you have a combination of series and plify working with the values later, and to allow parallel resistances, you might be a bit overwhelmed myself to mentally to check the results and make sure hv what you see. In basic electronics courses, you are they made sense. For example, when calculating the often given a circuit like this one and asked to calcu¬ value of “VI” (in Figure 3 38). 1 know that it will he late the equivalent resistance of the circuit, the volt¬ less than halt the power source voltage because the age across different resistors in the circuit, and the voltage drop at the 1 k resistor across the top of the currents through the different parts. The problem circuit schematic diagram will be greater than the really is not difficult when you use the rules for com¬ drop across the other three resistors. The calculated bining series and parallel resistances. value of 2/5 V is less than half the applied voltage, so The process of simplifying a collection (or inmitively, 1 know that my calculations are m the network) of resistances into a single resistance is right direction. known as Thevinin’s equivalency, which states that all With the equivalent resistance worked out,you loads in a circuit can be reduced to a single equiva¬ can now work through different parameters in rhe lent one. rhe first step in reducing a circuit is to com¬ circuit as in Figure 3-38. Io carry out this analysis, you bine all scries resistances as I have shown in Step 1 of will have to use Ohm’s law along with Kirchoffs volt¬ Figure 3-37. Next (Step 2), the parallel resistances are age and current laws. combined. These two steps are repeated until you To test out the calculations that I made, 1 would have the single resistance. I kept the result in a mixed like you to build the circuit that has been presented fraction format when I solved the equivalent resist¬ here. Once you have done this, power it up, create a ance rather than convert to a decimal number, to sim¬ table like Table 3-5. and record your results in the

-vVv Ik Equivalent __5__ Resistance 3 Y

Step 1. Step 2 Repeat Step 1 and Eliminate Eliminate Step 2 until There Series Resistances Parallel Resistances Is a Single Resistance

Figure 3-37 Reducing the complex electrical load to a single equivalent resistor

Section Three Basic Electrical Theory 55 Experiment 20 — Thevinin's Equivalency 56 values intheTtievinequivalentcircuit Table 3-5Comparingcalculatedtomeasured percentage pointasminewas. and i.3)wasaccuratetowithinthesamefractionofa and lk.Youcouldexpandthecheckstomakesure 3-38 bvmultiplyingbytheactualbatteryvoltage(V) parameters listedinthetable.Comparethesevalues to testequivalentresistance that eachvalue(voltagesacrossthedifferentresistors to thepredictedvaluesthat1derived:fromFigure Figure 3-38Electrical.circuitwithcomplexload Measurement Formula i2 VI it v Battery 123 Robotics Experiments for the EvilGenius 2/5NV1Iaw/lk 2 ‘5X^|Ja(,cry 8.85 Volts 9 Volt Battery VsHue WV Ik 12 Expected < 3.54 mA 5.31 mA ? 54V Value Ik •V2 i3i • VI 3.52 volts 3.52 mA 5.29 mA FtCtual Ik Ik Value circuit areinbalance. gauge. can indirectlymeasuretheresistanceofstrain changing itsresistance)thathadaresistancevar¬ between thetwovoltagedividers.Theammeterwill when theratiosoftwovoltagedividersareequal. behave likeavoltagedividerandnocurrentwillflow resistance.The resistorsoneachsideofthecircuit when youaretryingtomeasureminutechangesin one showninFigure3-39. experiment, Icreateda“Wheatstone”bridgelikethe multiplier. Ifyouhadastraingauge(whichisglued formula showninFigure3-39tofindoutwhatthe measure theirresistance,andusethesevaluesforthe zero, lbentakeRl.R2,andR3outofthecircuit, read zerowhentheresistorsintwohalvesof In Figure3-39,youcanseethatIputanammeter Mil. Inthiscase,R3wouldbe10ohms.Byadjusting Wheatstone bridgewithR2andRIatavalueofI resistance difference50,000timesbyusingthe ied between10to20ohms,youcouldboostthe to astructureandoutputsthestrainit’sunderby unknown resistance(Ru)is. have toadjustR1untiltheammeterisdisplacing R1 untilnocurrentflowsthroughtheammeter,you Figure 3-39Wheatstonebridge I The Wheatstonebridgeisaveryusefulcircuit When Iwasfirstdesigningthecircuitforthis If theammeterdoesnotreadzero,thenyouwill Ihe Wheatstonebridgebehavesasaresistance R2 R3 When NoCurrentFlowis Ru =R1*R3/R2 In theAmmeter Experiment 21 — Power

Experiment 21 Power

Tool Box Assembled PCB with Wiring kit

breadboard Jogging shoes 100 !*, 1/4-watt Stopwatch resistor

lk, 1/4-watt resistor

As you become more capable in electronic circuit When you have moved a mass some distance, you design, you will take the power used by ihc applica¬ can be described as having performed some work on tion into account more and more. For most basic- the object or added some energy to the object.The applications. you do not need to keep track of power, unit of SI work or energy is the joule and has the but as you begin to work with more and more com units newton meters (literally, force X distance). plcx applications (especially when you are working The rate at which energy is being pul into a system with robots), the importance ol keeping track ol is called power and is given the label watts (IV), which power in the circuit becomes more important. Units has the units kg X m2/s\ I’m sure you’ve heard the in the electrical (as well as physical) arenas have term watts, but it is probably something that you have been very cleverly specified in the .SI measurement difficulty in visualizing what it actually is. James Watt, system to allow a simple conversion of units between one of the inventors of the steam engine, defined the the different fields to help us understand and relate term horsepower as the standard amount of power power levels. output of horses pumping water out of a mine. Today Power is the product of force times velocity and one horsepower is defined as 746 watts. can be expressed quite simply as the following: To help you get a feeling for horsepower, try a simple experiment; measure a flight of stairs followed Power = F x v by the amount of time it takes you to run up it. Atter where torce is measured in newtons (kg X m/s2) and doing this, enter the units into one of the two formu¬ velocity is in m/s. Force is defined using the formula: las below to find out how much power was exerted running up the stairs: F = n. x a

where “m” is the mass of an object and “a” is the Powei = Weight (lbf) x Height (ft) x acceleration the object is experiencing. If you arc 1.356/Time up staiis (s)

familiar with ihe English measurement, system, you = Weight (N) x Height (m)/Time may refer to your weight as being some number of up stairs (s) pounds.This is not correct, but the truth is somewhat confusing. Pound is a measurement of mass (how Mv mass is around 200 lbm (90 kg, which becomes much matter an object has) and should have the a weight of 890 N), and I was able to run up 10 feet (3 abbreviation Ihm. Where things become contusing is meters) of stairs in 7 seconds. Using these values in that a pound of mass exerts a pound force (Ibf) when the formulas above, 1 found I expended about 378 in a standard gravitational field (32 ft/s2 or 9.807 watts or about 0.51 horsepower.This is surprisingly m/'s2). There is no kilogram of force in SI; the SI unit large and when you test yourself. I’m sure that you of force is called the newton (A).To convert a weight are able to output at least 0.25 horsepower, which in pounds to a force in newtons, you should use the also seems strangely large. The confusion lies m your conversion vision of a horse—chances are you are visualizing a big strong beast. When Watt defined the horsepower. 1 lbf = 4.45 N L Section Three Basic Electrical Theory 57 04 CD u o S

Experiment-» 21 joules/s orkgXm"/slwhichisidenticaltotheunits 58 you won'thavetroubleholdingapenorpencil. pads ofyourfinger,andifyouaccidentallyburnit, touch thecomponentwithtopofyourfinger, ally bequitewarm.ThisiswhyIindicatedthatyou with thelkresistor,but10012resistorwillactu¬ your linger.Youshouldnotnoticeanydifference with thebook,buildcircuitshowninFigure3-4U source, usingthebreadboardonPCBthatcomes isn’t dissipatingasmuchpowerthe10012resistor power beingforcedintothem;thelkresistorjust top ismuchmoresensitivetoheatthanthetipsor about 30secondsandthentouchitwiththetopof immediately apparent. touch thebreadboardreasonwhywillbecome of theresistorsasshortpossibleso resistor. 1recommendthatyoudonotcliptheleads and wireitusingfirstalkresistorthen10012 for wattsgivenabove. plying thetwovaluestogetherresultsinaquantity rent (i)hasbeengiventheunitscoulombs/s.Multi¬ fed horse. a fractionofthepoweryoung,healthy,andwell- been debilitatedbyanillnessandcouldonlyputout using thefollowingformula: horses weregeneialhattheendoftheirlivesoihad he usedthescrawnyworkanimalsofhisday.TTiese To testtheabilityofabatteryascircuit’spower Voltage (V)hastheunitsjoules/coulombandcur¬ Actually, bothresistorswarmupbecauseofthe After wiringtheresistorinfobreadboard,wait In directcurrentelectricalterms,powerisdefined p =vx1 1 d3 Robotics Experiments fo*" the EvilGenius sinking andiscommonlyusedformicroprocessors, generally beinga1/2wattormore)isknownasheat Providing moresurfaceareatoacomponentthat more surfaceareatodissipatethepowerover(and much largerthana1/4-wattresistor,sothatthereis standard 1/4-wattresistorthat1useprimarily watts. The10011resistorisdissipating10timesas dissipating 0.081wattsandthe10011resistor,0.81 tors byknowingtheappliedvoltage;lkresistoris be usedtoexpressitinanumberofdilfercnlways: Going backtotheformulaforpower,Ohm’slawcan like theoneinyourPC. produces asignificantamountofheat(“significant” have acorrespondinglylowersurfacetemperature). throughout thebook.A1-wattresistorisphysically rated fordissipating1wattolpowerinsteadofthe much powerasthe1kresistor,whichiswhyit amount ofpowertheresistoristurrr.ngintoheat. is. WhenIsaydissipatingpower.amindicatingthe this situation,1wouldspecifytheuseofaresistor noticeably hotterthanthelkresistor.Normally,in Figure 3MGResistorpowertestexperimentcircuit Source Power We cancalculatethepowerusedbytworesis¬ p =vxi = I2XR = v2/r 9 V R from Resistor as Heat Power Output Experiment 22 — Batteries Experiment 22 Batteries

Tool Box

Assembled PCB with Wiring it breadboard DMM 100 11, 1-watt Stopwatch resistor

Nine-volt inexpensive carbon battery

Nine-volt alkaline battery

Nine-volt NiMH battery

Power for robots almost always comes irom onboard lightest, and cheapest robot for a given set of require¬ batteries. Some robots use photovoltaic cells, but ments. I do want to caution you about one thing: it is these robots store power in capacitors or batteries very easy to design "down" your robot to the point before passing it to electronics or motors. Other where it does not fulfill the original requirements robots are powered externally and have power cables because of the attractiveness of using the smallest running to the robot. I tend to discourage these types possible components. of robots because keeping the cord separate can be When choosing batteries, the choice is between difficult, and every time I sec a robot that has a wire alkaline radio batteries, nickel metal hydride running to it. I can't help but think of something from (NiMH)/nickel-cadmium (NiCad) rechargeable bat a Far Side comic strip. A very small number of robots teries, and lead-acid (motorcycle or car) rechargeable are powered by fuel cells and internal combustion batteries. For all your robot projects. I recommend motors. that you use NiMH batteries instead of NiCad batter¬ When choosing the method of powering your ies because they are less toxic for the environment. robot, you will have to make the decision on how to The correct choice of battery is important because it power the motors and any control/peripheral elec will affect the following: tronics. Many robots have two battery packs, one for • Size and weight of the robot the motors and one for electronics The reason for using two battery packs is to minimize the power • Cell voltage fluctuations experienced when the motors are fumed • Operational life of robot on and off. • Speed of movement A single battery pack minimizes the cost and weight of the robot. You will find that as you mini¬ • Cost mize cost and weight in your lobot. something amaz¬ • Recharge time ing happens. A single battery pack means the overall weight of the rohot is lowered, w hich means that Different battery types output different voltage •-mailer motors are required. Smaller motors are usu¬ levels per cell and discharge at different rates. Lithium ally cheaper and require less current, which means a cells provide relatively high voltage, but usually low smaller battery. A smaller battery weighs and costs current. For carbon- and alkaline based batteries, you less than a larger one allowing you to use a smaller can expect 1.5 volts per cell or more, Rechargeable motor... battery cells (such as NiCad and NiMH) output 1.2 Ihis loop of decreasing costs and weights is known volts per cell. As is shown in Figure 3-41, rechargeable as a super-effect and will help create the smallest, batteries tend to output a constant voltage, whereas

Section 1 hree Basic Electrical Theory 59 Experiment4 22 — Batteries ances. Youcanusuallyfindoutwhatabattery’s pensive batteriestendtohavehighinternalresist about usingthesebatteriesinrobotsbecauseinex¬ will tindthattheirabilitytosourcecurrentdrop. 60 internal resistanceisbyreadingthedatasheetfor will saythatyoushouldonlybuycheapcarbonbat¬ cheaper robot. ance otthebatterywillresultinasmaller,lighter,and possible motorisused,minimizingtheinternalresist¬ appear whenasinglebatterypackandthesmallest passed tothecontroller.Likesuper-effectsthat the outputisaffectedbyvoltagetransients,resulting up (duetopowerbeingdissipatedwithinthem),you lost withinthebatteries.Oftenwhenbatteriesheat battery type’sinternalresistance.Thehigherthe very similar.Thisistiue,butIwanttocautionyou hattcries becausetheA-Hratingbetweentwois teries insteadotexpensivealkaline(orrechargeable) in increasedneedsforfilteringthepowerbeing motors andadisproportionateamountofpoweris internal resistance,thelesscurrentavailablefor parameter forchoosingthebatterytobeusedis Figure 3-MOTheeffectof batteryresistanceinarobot The higherinternalresistanceabatteryhas.themore robot, itisimportanttorememberthatthecritical decreases linearlyastheyareused. the outputofsingleusecells(carbonandalkaline) Often people(describingthemselvesas‘‘experts’’) When consideringdifferentbatteriesforuseina 12 3 Robotics Experiments for the EvilGenius controller andmotor of amulticellbattery Robot circuitconsisting Idealized Circuit Actual Circuit V Controller expanded with Ceils in internal resistors battery model Multicell internal series with resistances sentative ofasinglebattery.Inthe“EffectiveCir- although yougenerallyvisualizethecircuitasbeing what isspecifiedintheirindustrialcustomercatalogs. battery availableonthemanufacturer’swebpageor across aloadisinverselyproportionaltothecurrent voltage acrosstheinternalbatteryresistanceswill the currentdrawnfrombatteryincreases, cuit" showninFigure3-42.1havelumpedthe diagram witheachbatterysymbolandresistorrepre¬ the “IdealizedCircuit.”‘‘ActualCircuit”is ances isillustratedinFigure3-42.Mostbatterypacks increase. AccordingtoOhmslaw.thevoltagedrop internal resistancestogethertoclearlyshowthatas used mrobotsconsistofmultiplecellsinaseries,and Figure 3-MIDifferentbatteryoperations The problemwithveryhighinternalbatteryresist¬ and motor(s) external tocontroller to showvoltagedrop resistance combined Multicell battery Effective Circuit drawn through it.This means that as more current is Section Three — Basic Electrical Theory drawn through the battery’s internal resistance + increases, the effective voltage output drops. power IE 100 When you look around, you will find that the low¬ Source-E est internal resistance batteries available are either premium alkaline radio battery cells or rechargeable batteries designed for high-current applications. As a Figure 3-M3 Battery power life experiment c irettit potential source for robot applications!-the 9.6-volt NiCad batteries used for remote-control electric rac¬ voltage stays closest to 9 volts for the longest period ers have very low internal resistances and can be of time anti falls off sharply instead of providing mar¬ bought fairly inexpensively with chargers.The experi¬ ginal power (which is actually an advantage in most ment that I would like you to perform is quite simple applications). to see if you can reproduce Figure 3-41 using an inexpensive carbon battery, a moderately expensive alkaline battery, as well as a rechargeable NiMH bat¬ tery. These batteries will be used with the book’s PCB For Consideration in the circuit shown in F igure 3-43.

To lest these assumptions, I recorded the life of The math dial was used to calculate different values a carbon, an alkaline, and a fully charged NiMH in this section should not have been new to you. nor battery; then J recorded and plotted the results in should it have been very difficult. What will probably Microsoft Excel (Figure 3-44). The results essentially be a new experience for you is understanding what match what I have stated here except for the carbon the values mean and whether or not they are reason¬ battery, which had a large initial voltage loss. After a able. Toward the end off this section. 1 will explain bit of research 1 found that this was due to a conver¬ more about the different values and what kind of sion of battery materials close to the electrodes ranges you should expect them to be in within the battery, increasing the resistance within the All electrical measurements are in SI units. SI is an battery. From Figure 3-44, it appears that the NiMH agreed to standard set of measurements for different battery would be the best choice because the output quantities. Most countries around the world utilize SI

Time NiMH Alkaline Carbon 0 9 02 9.08 8 24 Battery Life Graph 5 8.69 8 44 7.02 10 8 62 8 32 6.57 15 8.61 8 22 6 37 20 8 62 8 12 6.3 25 8.61 8 04 6 28 30 8 61 7 96 6.25 35 8.6 7 9 6.23 40 8 59 7 83 6 19 45 8 55 7 78 6 16 50 8 53 7 73 6 09 55 8.5 7 67 6.05 60 8 46 7 62 5 98 65 6.4 7.58 5.93 70 8.34 7.52 5.86 75 8 27 7.46 5.79 80 8.18 7.43 5 73 85 8.05 7.39 5 67 90 7.86 7.36 5 61 95 7.63 7.33 5.56 100 7 22 7.3 5.49 105 6.3 7.28 5.43 110 3.3 7 25 5 37 115 1.88 7.22 5 31 NiMH Alkaline Carbon 120 7.19 5.25

Figuie 3-44 Graph of actual battery life by type

Section ThreB Basic Electrical Theory 51 cu •H Q) 0) X a M Q-* Batteries 62 cal otitsperiodasshownin Figure3-45.Inthisdraw¬ occasionally secs.Ifyouareworkingonanexperi¬ onds (millisecondsormsecs]millionthsofseconds made amistake. lionths ofasecond(nsecs),thenyouhaveprobably ment inthisbookandacalculationworksouttobil¬ in thisbook,youwillseesignaltimesmsecsand (microseconds orpsecs).Formostprojectspresented microwave outputfrequency(9.192.631.770oscilla¬ of 10(forexample.It)tothepower1is"decea"), exponent of10andaddtheappropriatepietix. you merelyhavetomultiplyordivideby10some ing. Ihaveshownarepeating signalthattakes‘Tf’ they areoftenlistedintermsofthousandthssec* normally listedwithprefixesgreaterthanone.but tions masecond)ofcesiumatom.Secondsarenot but Ididn'tplacethisinformationinthetablebecause thing"). Mostmetricprefixtablesincludeeverypower things, youactuallyhave1kilo-something(or“ksome- to thegalleon)seempositivelysimple] makes learningthewizardmoneyusedinHarry to theton(anImperialactuallyweighs2,240and stones tothehundredweight,and20hundredweight quarts makeagallon,and8gallon*bushel values. 1rememberasakidlearningthattherewere it isnottypicallyusedinforelectronics. not 2,200poundsasmostpeopleassume).Allthis ounces makesapound,14poundstothestone,8 chain, 10chainstoafurlong,and8furlongsmile. on powersof10allowsforsimplemanipulation Potter bookseries(29knutstoasickleand17sickles In termsofimperialvolume,2pintsmakeaquart,4 easy manipulationintodifferentunits.Beingbased quantities. deviation, thesecountriesuseSIunitsforelectrical still relyontheimperialmeasurementsystemfor United States,Canada,GreatBritain,andAustralia) Imperial weightmeasuresareevenstranger;16 units oflength,volume,mass,andforce.Despitethis units toreverything,butsomecountries(notably,the 12 inchestoafoot,3feetyard.22yards To convertSIunitsintoamoreconvenientfoods I singTable3-6,ifyouhave1(XX)metricsome¬ A secondisaSIunitthatdefinedasthe The waySIquantitiesarethoughtoutallowfor The frequencyofasignalisdefined astherecipro¬ 123 Robotics Experiments for the EvilGenius quency ofmillihertz,thenyou shouldknowyouhave of ahertz(ifyoucalculate signaltohaveafre¬ made amistake). quencies ofseveralhundred toamillionorsohertz 2.5 kHzrange.Inthisbook,youwillseesignalfre¬ can probablyhearfrequenciesol12kHzorgreater, (Hz. kHz,andMHz).Youshould neverseefractions but spokenwordsgenerallyfallwithinthe1(H)Hzto in therangeof100Hzto2,500(or2.5kHz).You 0.002 seconds),itsfrequencywouldbecalculatedas the signaltorepeatiscalleditsperiod. units of1dividedbyseconds.Mostaudiosignalsare seconds torepeat.Thelengthoftimenecessaryfor frequency Figure 3-45Repeatingsignalshowingperiodand Multiplier Pouter Table 3-6Converting51units W to1' 103 Hr ur The SIunitforfrequencyishertz(Hz)andhasthe So. ifyouhadasignalwithperiodof2msecs(or / / X.. Frequency =1/Period Signal '’i Prefix mega peta giga tera \^_y kilo = 5001/seconds = 1/2(10~3)seconds = 50Chertz = 1/2msecs Symbol Frequency =-^4^ M G p k r . Period Multiplier Prefix PoLuet to-'2 10 15 10" 10 v Hi l ... femli) micro nano pico milli Symbol Ill P 11 a f Section Four Magnetic Devices

When we talk about something being difficult or non- intuitive ( that is. not immediately obvious), we usu ally refer to it being “backwards” in some way. Colloquially, we use terms like “upside down," “inverted," and “18(1 degrees out of phase” to describe tilings that are difficult to learn, hut we do not use terms to describe these things as being side¬ ways (as in perpendicular or d() degrees out of phase). I lind this surprising because the most diffi culty I had in visualizing something when I was a uni¬ versity student was magnetic fields and how they interacted with current-carrying wires. Basic magnetism is quite easy to understand. In Figure 4-1, a magnetized piece of metal (called a per nianent magnet or just a magnet) has lines of force Figure M-l Bar magnet showing line of force running from the “north” pole (or end) to the between the poles “south” pole. The lines of force (also called the mag¬ netic field) can be altered when a piece of a magnetic through nonmagnetic material. In the case of having metal (normally iron) is placed into the lines ot force. a piece of iron close to a magnet, the iron provides a Just as an electrical current travels through the path for the magnetic tields to travel through l he path of least resistance, magnetic fields are most effi¬ magnetic field travels through the iron and draws it cient when they travel in a magnetic material (usually closer, so the magnetic field is smaller (and more iron) or have a minimal distance to travel when going efficient).

Lines of Magnetic Force pulling magnets together

Figure M-2 Two bar magnets interacting

63 Q •H 0) 0) CO o Section Four — Magnetic > 64 current-carrying conductor with thecurledfingers passing through. at thevisibleendofwirewherecurrentis dot attheendofwirewherecurrentcomesout using theright-handrulesimilar tothesingle-wire (like anarrowhead).InFigure4-3,1havedrawnX rent isgoingin(suchasanarrow’sfeathers)anda to placeaciossattheendofwirewherecur¬ show thedilectionolmagneticfield. 4-5 showsthedirectionofcircularmagneticfield in Figure4-4.Themagnetic field canbepredicted increased byusingmultiple wires formedinacoil,as in thedirectionofcurrentandyourcurledfingers pens whencurrentflowsthroughthewire.Thethumb thumb awayfromyourhandrepresentswhathap Using youirighthand.Curlingyourfingers,pointthe wire. Thedirectionofthecurrentcanbepredictedby electrical currentpassesthroughaconductor.Figure that isproducedwhenacurrentpassedthrough design forcenturies. in water(oralcohol)hasbeenthecompass’basic its Northpolewillbeattractedtotheearth's screwdriver sothatitwillpickupandholdscrews(so hole (andviceversa).Suspendingafloatingmagnet the magnetizedcompassneedleisplacedoncork, they willnotfall)byrubbingitwithamagnet.When become magnetized.Manypeoplewillmagnetizea dle inthesamedirection,causingneedleto direction severaltimeswillarrangeatomsinthenee¬ nonsteel pan. putting itonacorkfloatinginwaterheldby a magnetinthesamedirectionseveraltimesand can bemadebyrubbingasteelneedle(ornail)with stronger untiltheironisincontactwithmagnet closer tothemagnet,forcedrawingifingrows make yourselfasimplecompass.Acompass repel andunlikepolesattract(seefigure4-2)to advantage ofthepropertiesthatlikemagnetpoles and ittakesalotofefforttopulltheironoff. a magnet,theforceofmagnetcanbedetected but canbeeasilycounteractedAstheironisbrought The magneticfieldcanbeconcentrated and When drawingcurrentinawire,theconventionis Circular magneticfieldsareproducedwhenan Rubbing theneedlewithmagnetinsame When youwereyounger,mighthavetaken l'hi'' iswhvwhenapieceotironheldawayfrom 123 Robotics Experiments for the EvilGenius connection, buttheconductor causesthelinesof netic fieldsattempttofollow thesamenorth-to-south cross onthesmallcirclein centerofthepage. conductor isgoingintothepage,asindicatedby manent magnet.Thecurrentflowingthroughthe carrying conductorbetweenthetwopolesofaper¬ the permanentmagnetarid the conductor.Themag¬ applied onthewire.Figure45showsacurrent netic fieldswillinteractandcauseaforcetobe rent-carrying wireinamagneticfield,thetwomag¬ complex whenyoumixthetwo.Ifplaceacur¬ difficulty infiguringoutwhathappensbecomesmore tromagnet shouldseemquitestraightforward.The fields ofconsiderablestrength. is calledanelectromagnetandcanproduceelectrical netic field,resultinginamuchstrongerforceonthe magnetic objects.Acoilwrappedaroundametalbar iron) inthecoil,strengthofmagneticfield being thedirectionofcurrentincoiland the coilcanbeincreased.Thisconcentratesmag¬ thumb beingthedirectionofmagneticforce. carrying acurrent carrying acurrent Figure 4-4Magneticfieldsgeneratedbyacoil Figure 4-3Magneticfieldsgeneratedbyawire Figure 4-5showsthelinesof magnetismforboth The operationotapermanentmagnetandanelec¬ By placingabarofmagneticmaterial(suchas Current flowingthroughWire Magnetic FieldsGeneratedby Wire Through the Passing Wires Coil of Lines of Fields in Magnetic components of these forces will cancel each other out Experiment 23 — Electromagnets and the horizontal forces will become dominant. You N can predict the direction of the force by using your / l 'A;. Magnetic Lines of Force left hand with the first two lingers and thumb at a Direction of right angle to each other. If the direction of the mag¬ Force O') App;ed netic field is your first (or index) finger, and the to Wire 7'j) direction of current in the conductor is your middle finger, the force applied to the wire is in the direction of your thumb This is known as the “left hand rule." You shouldn't be surprised to find out that the

Figure M-B Magnetic fields with a current-carrying horizontal force exerted on the wire is very small. The wire between them amount ol force can be increased by increasing the current passing through the conductor or by increas¬ ing the strength of the magnetic field ( this can be magnetic fields to hend so that the lines coming from accomplished by moving the poles closer together). the north pole of the permanent magnet are drawn to Another way of increasing the force is to add multi¬ the right side of the conductor. This movement of ple conductors. lines causes a force on the wire that doesn't draw it For a traditional (rotary ) electric motor, this side¬ toward either permanent magnet pole but sideways ways motion caused w hen a conductor is in a mag¬ between them. netic field cannot be easily taken advantage of Ihe direction of force is surprising, but the reason because it would require one pole to be in the center should become obvious, rhe circular magnetic fields of the motor with the other outside. A more practical coming from the current-carrying conductor have implementation ol this behavioi is known as a linear both a north and a south pole that will be facing the induction motor and has been proposed many times poles of the permanent magnet Ihe like poles will in the past for levitating (frictionless) trains. repel but the unlike poles will attract. The vertical

Experiment 23 Electromagnets

Tool Box

Three-inch (8-cent irpe- Two C batteries with ter) steel nail clip

Twenty feet (6 meters) Miscellaneous nails, of 22-cauge stranded nuts belts, and washers copper wire Miscellaneous coins Elastic band

Probably the coolest thing ever done with an electro¬ leaves. While being driven to the airport, he is mur¬ magnet was in the lames Bond movie Goldfinger. dered by Goldfinger's bodyguard (“Oddfob”), and Ihe title character. Auric Goldfinger, has created a both him and the car he was murdered in (a I .incoln plan to roh the gold depository in Fort Knox. Ken¬ Continental Mark 11 with the gold payoff in the tucky, requiring the aid of organized criminals. After trunk) are crushed into a cube a yard (I meter) outlining his plot,one of the mobsters rejects the idea across. The cube is picked up by an electromagnet as being impossible and asks for his payoff and and dropped into a pickup truck and returned to

Section Four Magnetic Devices 65 Experiment 23 — Electromagnets pick upsteelobjects,asshowninFigure4-8. 66 objects youfindlyingaround.Youshouldthat will besurprisinglystrong.AttachthetwoCcellsto are notaffectedbymagnetic fields. whereas coins,madefrombrass, copper,andsilver, bolts, andwashersarecommonly madefromsteel, ers, nuts,andboltsbutwillnot affectmostcoins.Nuts, the electromagnetandtestitoutwithdifferentmetal netic fieldthatflowsthroughthenailandallowitto magnetic fieldoftheotherloopstoproduceamag¬ around eachlooponthenailthatcombineswith When powerisappliedtothewirewrappedaround come outatthesameend.Isecuredloosewires core becauseitwillbeeasiertowraparoundthenail. the electromagnetwilleasily pickupstandardwash the nail,currentwillcauseamagneticfield using asmallelasticband(seeFigures4-6and47). wire inanyparticularorder.Theonlysuggestionlhave is tomakesurethetwowirescomingfromnail Don’t worryaboutbeingneatorputtingtheloopsof magnet fieldthesamewaynormalsteelwill. are magneticmaterialsandwillnotconcentratethe made fromstainlesssteelorbrass,neitherofwhieh of wirearoundasteelnail.Makesurethenailisnor¬ solution totheproblemotpickingupacrushedcar. cube.'fhe electromagnetisactuallyquiteanelegant or notdifferentpartswillsupporttheweightof sideration oftheshapefinalproductorwhether cube, thecarwouldhavemanysharpedgesand nails aremadefromsteel,youmayfindonethatis mal steelusingapermanentmagnetAlthoughmost to pickupallthemetalincrushedcarwithoutcon¬ produce amagneticfieldoncommand,willapplyforce the electromagnet.Afterbeingcrushedintoasmall 40-year-old movie)bringstearstomyeyes. be difficulttopickup.Theelectromagnet,whichcan ing abrandnewonedestroyed(eventhoughit’s tul. IalwayslovedtheContinentalMark11andsee¬ also considerthescenetobealmostobscenelywaste reclaimed. Goldfinger sothatthegoldincarcouldbe That’s allthereistitmakinganelectromagnet To startofftheexperiment,wrap20feet(6meters) I recommendusingstrandedwireratherthansolid What thisscenedemonstratesistheversatilityof Ihc magneticfieldproducedbytheelectromagnet Ibis isagreatvisualscenedespitebeingillogical.1 12 3 Robotics Experiments for the EvilGenius Figure 4-8Electromagnet inoperation Figure 4-7Electromagnetcross-section Figure 4-6Thecompletedelectromagnet with Wire Wrapped Iron Nad ' NodhPole" Electromagnet’s Force comingfrom Lines ofMagnetic inside it Current Wire showing Direction of Electromagnet s Force goinginto Lines ofMagnetic 'South Pole" Experiment 24 — Relays

Experiment 2 4 Relays

Tool Box

Two 3-inch (8-centime¬ Nme-vclt battery with ter) steel nails clip

Twenty feet (6 meters) Soldering iron of 22- gauge stranded Solder copper wire

Elastic band

Twelve inches of 24- to 28-gauge strandea copper wire

SPST or SPDT switch

Light-emitting diode (LED)

Ik resistor

Two C batteries with clrp

Throughout the book. I emphasize that 1 do not think passes through the electromagnet, the wiper is pulled you should work with relays in your robot projects down to make a connection to the “Connection when (or really any electronics projects). Foi now. I will dis¬ Coil Active.” Although I have shown that only one cuss the operation of the relay and show' you how to wiper is in the relay depicted in Figure 4-9,1 should build one using the nail electromagnet from the pre¬ point out that multiple wiper circuits’ relays can con¬ vious experiment. Relays have two properties that trol more than one device by the same relay. will be important to understand as I explain more Ihe action of the wiper against the two contacts is complex electronics. exactly the same as the action of the switch wiper in ITie electronic symbol for the relay (see Figure the single-pole double-throw (SPDT) switch. It allows 4-9) is a good representation of how it is built. The connections if the relay’s electromagnet is active or relay consists of an electromagnet that moves a not. When the electromagnet is off, the wiper is con¬ “w iper,” which has a piece of steel bonded to it. A nected to one contact. When the electromagnet is on wiper is a steel and copper connection that is and active, the w iper is pulled away from the one attracted by the coil and provides a method of pass¬ contact and touches another. ing current between it and either the “Connection By using the electromagnet built in the previous when Coil is Inactive” or “Connection when Coil experiment, you can build the simple relay test circuit Active.”The wiper is normally pulled to the "Con¬ shown in Figure 4-10. Fhis circuit consists of the elec¬ nection when Coil is Inactive” when no current is tromagnet pinvered by two C batteries and con¬ passing through its electromagnet. When current trolled by a simple series switch The wiper for this circuit is actually another nail Wiper connected to an LED. a lk resistor, and the positive (Pulled by Connection when Coll is Inactive Electromagnet) connection of the 9-volt battery. Io simplify building Common (Connected to ''wiper’ ) Coil - in the circuit, the steel nail core of ihe electromagnet is Power J Connection when Coil Active In " the contact, which is made when the electromagnet is Electromagnet active and pulling m the wiper. (with Steel Core) With a few modifications, this cncuit could be Figure M-9 Labeled relay symbol used as quite an impressive science fair project.lire

Section Four Magnetic Devices 67 Experiment 24 — Relays 2x X"-S- 68 BatteriesT___ I cuits, whichisausefulpropertywhencreatingrobots. completely separatefromthedrivingcircuit.Thisis household orotherhigh-voltageACcircuits. important forapplicationscontrollingthingssuchas voltage andcurrenttodrivehigh-voltage/currentcir¬ rent circuit.Isolationmeansthatthedrivingcircuitis circuit are(1)isolationand(2)theabilitytocontrola per hingewiper. net. Also,usecopperboltsforthecontactstocop¬ steel bohthatwouldbeattractedbytheelectromag¬ high-voltage/current circuitfromalow-voltage/cur¬ another nail,youcoulduseacopperhingewith electromagnet canbemountedinawoodenframe the core)withwiperheldbelowInsteadof (which is:why1suggestyouuseasteelnailorbollfor Figure M-10Simplesimulatedrelaycircuit wrapped nail Built fromwire Electromagnet Tlie twoimportantfeaturesthatrelaysbringtoa This isolationofcircuitsallowswithalow- 123 Robotics Experiments for the EvilGenius A. /Nail Bare Steel I-V\A- Ik Battery 9-Volt case, youshouldmakeamentalnotetocomeback The digitallogic(andanalog)circuitspresentedlater this circuitdiagramforlaterreference. your currentlevelofknowledge,andilthisisthe motor fromlogiccircuits.Thiscircuitmaybebeyond to controlarelayfromsimplelogiccircuitandis exactly thesameaswhatwouldbeusedtocontrola a resistancethatwillaffecttheoperationofmotors. will seethattheydohaveadefinitevoltagedropand the relay’scontacts.WhenIintroducetransistors,you ers: theverysmallvoltagedropandresistanceof designing yourownsolid-stateelectronicmotordriv¬ cussed, butyouwillappreciatethemwhenare cal forbeingabletocreaterobots. power signalstocontrolhigh-powerdevicesarecriti¬ rents ofevensmallhobbymotors.Devicesthatallow in thebookrunwithmuchlowervoltagesandcur¬ Figure M-llControllingarelay’soperation Two otherrelaycharacteristicsarerarelydis¬ Figure 441isthetransistoidrivercircuitrequired Power Relay Connection whenCoilActive Connection whenCoilisInactive Common (Connectedto'wiper') Experiment 25 — Measuring the Field. Experiment 25 Measuring the Earth’s Magnetic Field

Tool Box

Assembled print ed Wiring kit. circuit, board (PCB) with Clippers breadboard Knife Compass

Twelve to 20 inches of 22- to 26-gauge stranded wire

lk potentiometer

C battery

When you use your digital multimeter (DMM) to test elements very easily; you may have heard that it is the voltage, current, or resistance in a circuit, you called the noble metal. This name does not come must remember that this instrument is the result of from it being used in royal crowns, it comes from the literally millions of person-years of experimenting inability other elements have in combining with gold and theorizing the nature of electricity and how it is except under extreme conditions. The last properly of measured. In Ben Franklin’s day, the test for electric¬ gold that makes it ideal for this type of experiment is ity was touching a circuit and seeing if a spaik was its malleability. Gold can be pounded into very thin produced. This touch test for electricity only detected sheets only a few atoms thick. fairly high levels of electricity (to produce a spark, a Electroscopes arc difficult for the modern hobby¬ potential of 1,500 volts or more is required).This test ist to build and use. As you would expect, finding suit is obviously not very accurate and potentially very able gold leaf is difficult, but you would be surprised dangerous. An European scientist repeating at how hard it is to find other materials that can be, Franklin’s kite experiment was electrocuted when he used in its place. Normal household aluminum foil touched the key. cannot be used because it is too thick and heavy. I Over time, different theories were postulated as to have seen some sample electroscopes built using the what was electricity, and to test these theories, differ¬ plastic foam “peanuts” used for protecting items din¬ ent experiments were performed, with the apparatus ing shipping. You could try to build your own electro¬ used actually becoming tools to better understand scope using the foam peanuts, but remember that what was happening. A very early example of this they tend to hold static electricity and are actually a was the electroscope (see Figure 4-12). which consists considerable risk to the different electronic parts of a copper plate connected to a circuit and to a piece of gold leaf, or a thin sheet of gold. When the copper plate would be connected to an electrical circuit, both Voltage it and the gold leaf would repel due to similar Source" v Thin sheet of changes on the fixed and hinged gold leaf. The gold Gold Leaf that leaf, being very light, would be moved by the charge. is Hinged at top Gold leaf has a long and distinguished career in Fixed science (it being central to Rutherford’s experiment Copper ^Uke Charges on the nature of matter), because gold has some use¬ Plate on Copper and Gold pushing Gold ful properties. Tirst of all, it is an extremely good con¬ Away ductor. Secondly, it docs not react with other Figure M-12 Early electroscope

Section Four Magnetic Devices 69 W i!) x a risnent 25 — Measuring the Field. sure thaiIkeptthecoilofwireandcompassasfar cific locationcanbefound.Doingthistakesabitof 70 Tlie potentiometerlimitsthetotalcurrentpassedto rent, thestrengthofearth'smagneticfieldataspe¬ wrapped withwire Figure M-ldAmmetermode fromacompass PCB forihisexperimentandfoundthatIhadtomake the coilofwirearoundcompass.1usedbook’s potentiometer tothecircuit,asshowninFigure4-14. work, butyoucandoitquiteeasilybyaddingaIk movement oftheneedletoaknownamountcur cost. Withabitofwork,aftermeasuringtheamount electricity inacircuitbecauseofitssimplicityandlow netic field. powered coilismuchstrongerthantheearth’smag¬ duced byjusttwoorthreeturnsofwire.ACcell how quicklythecompassneedlemovedwith around thecompassasitalignsitselfwithmag compass, asshowninFigure4-13.Thenorientthe stranded wirewrappedtwoorthreetimesarounda sure thefoamisdisposedofandnotadangertoelec¬ magnetic fieldtoindicatethepro¬ netic fieldproducedbvthewires.Iwassurprisedat becoming perpendiculartothewireswrapped compass sothatNorthisparalleltothedirectionof pass-based ammeter.Tobuildthisdevice,usea ment devicethatyoucanexperimentwithisthecom tronic devices. bare endsofthewire. menting withthefoampeanutelectroscope,make the wrappedwire,andconnecta9-voltbatteryto used inthisbook'slaterexperiments.Afterexperi¬ Many earlyscientistsusedanammetertodetect A muchmoreusefulhistoricalelectricalmeasure¬ You willfindthatthecompassneedlesnaps, 123 Robotics Experiments for the EvilGenius acting onthecompassneedle: degrees). IcancalculatetheF.arthsmagneticfield resulting compassdirection.Rearrangingtheformula for thetangent(andknowingof20 magnetic fieldis.InFigure4-15.1havedrawnoutthe of thecoil’smagneticfieldsothat1coulduse Faith’s magneticfieldwiththecoil'sand trigonometry tofigureouthowpowerfultheEarths the current,thatIusedthreeturnsofwire,and Ohm’s law.Ihadacurrentdrawof770mA.Knowing of thepotentiometerandwire(1211).Applying volts inmyexperiment)andmeasuredtheresistance compass, whichisinsidethecoilofwire,sothatNorth symbol "FTandisinunitsofTeslas”)definedby 1.039(10’’) Tesla. ter, lfoundthatthemagneticfieldinsidecoilwas that thecoilwas2inches(5.08centimeters)indiame¬ is inparallelwiththecoilofwire,puta9-voltbattery where p(|isthepermeabilityofvacuumand away fromthe9-vollbatteryaspossibletoensurethat then measuredthevoltageat9-voltbattery(9.25 until thecompassisonlydeflectedby20degrees.I into itsdiponthePCBandadjustpotentiometer the current(inamperes)throughwire,andris the followingformula; any ironinthebatterydidn’tthrowcompassoff. the radiusofcoilinmeters.Whenarranging 1.257(10') N/A2.Nisthenumberofturnswire,i magnetic field Figure 'TIM(iraiiitomeasuretheearth's Earth's magneticfield =Coil'smagnetic £ield/tan(20) 1 startedwithNorthperpendicularlothedirection Hie magneticfieldproducedbythecoil(given = 2.86(10-*)Tesla = 1.039(10s)Tesla/0.364 B =}i0xNi/(r11.18) Ik enough forCompass of Wirelarge to Fitin two orthreeLoops Ibc accepted value for the Earth's magnetic field Experiment 26 — Direct Current (DC) Motor is about 5( 1 O ' i Tesla, so my measured and calculated value is a little more than half the value.This may seem like a large error, but I’m amazed 1 got as close as 1 did with the crude equipment I used. W hen I per formed the experiment, 1 did it in the kitchen of my house; I might have gotten a more accurate result if 1 were to repeat it outside with no metal or power lines around. Of course. 1 might end up with a less accurate result because of my placement of the wire coil Figure M-15 Trigonometry <>J the perpendicular around the compass, the charge in the battery, oi due nwgnctu jnids to a variety of factors. It would be interesting to measure the Earth’s magnetic field in different loca¬ tions while keeping the apparatus as constant as pos¬ sible to see what kinds of deviations are found.

Experiment 26 Direct Current (DC) Motor

Small DC motor

9V or C battery

Sheet of cardboard

One of this book’s goals is to create experiments that compressed together as much as possible to save you can conduct on your own and that would pio- space. Keeping the various magnetic parts as close duce results lor use in later experiments. For the most together as possible is an advantage because it allows part, I think I have succeeded, except for one device, the motor to run more efficiently. the electric motor. 1 have not been able to come up An electric motor can be considered to consist of a with a design for this machine that is both simple to number of electromagnets that can be switched on build anil that could be used in later experiments. and off according to the position of the electromag¬ Ibis is surprising, especially considering that a direct net rotor, as shown in Figure 4-18. t have drawn the current (DC’ f motor only consists of a few different motor as hav ing three electromagnets, ( this is com parts (see Figure 4-16). mon for most DC motors, as I will explain below), Figure 4 17 shows the different parts of a small and in the left drawing, electromagnet 1 is pointing electric motor The armature consists of the motor’s upwards with electromagnet 2 producing a south pole driveshaft and the parts that have been mounted on and is drawn to the permanent magnet’s north pole. it The different parts have been spread out so they Electromagnet 3 produces a north pole, is repelled can be easily identified, but when you look at an from the permanent magnet’s north pole, and is actual armature, as in Figure 4-17. its parts have been drawn to the permanent magnet's south pole.

Section Fnur Magnetic Devices 71 Experiment 26 — Direct Current (DC) Motor Electromagnet on Electromagnet on 72 Figure 4-16DCelectricmotorparts Figure 4-17loyelectricmotordisassembledtoshowdifferentinternalparts Figure 418Three-rotorDC electricmotoroperation Bearing Armature Armature Rear with FrontBearingMagnetsArmatureEnd 123 Robotics Experiments: fortheEvil Genius Battory HousingPermanentMotorEndCapwith Initial PositionwithForces M PermanentMagnet I PermanentMagnet ' "North"Pole "South' Pose Indicated h~ Dnvoshaft commutator contactsontheaxleaswelltheirrela- continues todrawtheelectromagnetsperma¬ permanent magnet'ssouthpole.Asthemotor’saxle pole andtsturnedoff.Electromagnet3isstillproduc¬ used todrivewhateveritisconnectedto. and 2havechangedoperationtoensurethataforce has turned60degreesinFigure4-18,electromagnet1 ing anorthpoleandcontinuestobedrawnthe tromagnet 2isfacingthepermanentmagnet’snorth net Iisturnedonandproducingasouthpole.Elec¬ motor's axlehasturned60degreesandelectromag¬ the electromagnetsispassedoutofmotorand motion oftheaxlealongwithtorquecreatedby nent! magnetsandprovidetorqueontheaxle.The In Figure4-18.1havemarkedthepositionof In thedrawingonrightofFigure418. with ChangesinElectromagnet 60 DegreesLaterPosition Forces Indicated lion to the motor's two brushes. Note that in the Eight Cutouts, 45 Degrees Experiment 26 — Direct Current (DC) Motor example only two ot the commutator contacts are Apart touching the brushes. This is not always the case. For the angles between the examples presented in Figure 4-18, all three contacts will be touching the brushes. One thing that has not been discussed is the prop¬ erty of the motor that causes it to turn in only one direction according to the direction in which current is flowing.To indicate how the motor will run. by looking at the end cap of the motor you will see it is marked with both a + symbol bv one wiring connec¬ tion and by a flat side on the axle bearing (Figure 4-19). Most small motors run anywhere from 2,000 to 4,(XX) RPM. and it is difficult to see the direction in Figure M-?D Cardboard fan disk to test motor which the motor is turning.To make the direction operation easier to observe, I used the fan disk show n in Figure 4-20 was made out ot cardboard. When you make the fan disk, you should use a compass and protractor to make it as even as possible and make sure the center is accurately identified. Eight fan blades are bent from the cut cardboard. Using this fan disk, you can tell which direction the motor is turning from the direction in which air is being blown by the motor.

Before testing the motor with a battery, measure Figure M-21 Circuit to test the DC electric motor and record its resistance using a DMM (one of my motors had a resistance ot 0.9 fl). Once you have done this, press the fan disk onto the motor's axle and motor. The reason for the higher effective resistance test it using the circuit shown in Figure 4 21. Measure is due to the “reluctance’' of the sw itching electro¬ the voltage across the motor, as well as the current magnets. When a coil is turned on or off. its effective through it, and calculate the resistance using Ohm’s resistance becomes very large until current is flowing law. With 7.2 volts applied and 0.3 amperes being smoothly in the motor. drawn, this works put to 24.311.This calculated value As a final aside, a simple electric motor was first is much greater than the resistance of the stopped shown on the TV show Bcakman’s World. It is what I would call a single electromagnet motor because the electromagnet can only be energized one way. The Positive motor is simple to build but is quite complicated to Indicator get running, and it usually only runs for a few seconds Flat Spot on (in one direction) before jumping out of its cradle. If \ End Cap you are interested in building it, you can find the ® instructions at http://electiomcs.howstuflw orks.com/ |\ Bearing framed.htm?parent=m©tor.htm&url J 0 http://fly.hiwaay.net/- palmer/motoi. htn.il.

Positive Negative Terminal Terminal

Figure >-i-19 Polarity indicators on motor end cap

Section Four Magnetic Devices Section Five □rivetrains

Electric motors are the most popular method of caus¬ at 2,000 RPM (somewhat slow for a small motor) ing motion in robots, even though they are not very and the nubs are 0.25 inches (6.35 millimeters) in efficient and can be somewhat difficult to use in dif¬ diameter, fhe robot would move about 52 inches ferent situations, especially when they are compared (133 centimeters) per second. This is quite a bit to other devices such as faster than an adult’s walking speed and would allow the robot to cross a 10-foot (3-meter) room in • Internal combustion motors (gas and diesel) just over 2 seconds. A small robot moving at this • External combustion (steam) motors speed is very hard to control and will probably » Hydraulics spend a great deal of time crashing into different things because it cannot detect objects tar enough • Muscle wire away to stop or turn away from them.

To allow electric motors to perform the same tasks A question might be asked about how to slow as the devices listed above, they will have to have down the motors electrically, and this is possible, but mechanical attachments to make them more useful in to do that,you will have to significantly cut down on different situations.These mechanical attachments the amount of current being passed to the motors As consist of devices such as axles, couplings, gears, and you decrease the current to the motors, you do not wheels, and rather than using the clumsy term motors get as much torque (rotational force) from the and mechanical attachments, 1 am going to refer to motors In this type of robot where the nubs are the motor and hardware that drive the robot or per¬ small, you will find that a lot of force must be applied form some kind of action using the term drivetram from the nubs to the^surface the robot is running on to get the robot to move. If you decrease the amount The simplest robot drivetram that I can imagine is ol torque,you will find that the robot will move shown in Figure 5-1 and consists of motors with some unpredictably (one side will turn while the other kind of small sticky nub placed on the ends of their doesn’t) or not move at all. Another solution to this shafts. I always cringe when I seen a robot built with problem is to “blip’’ the motors periodically, and this this configuration. Even though it will move the is the usual solution—the robot's controlling elec robot, it can be tricky to set up, and it does not handle tronics determine the timing between each motor any surface other than one that is perfectly flat and being turned on quickly. This isn’t a terrible solution, smooth. 1 have seen wheel nubs used for the robot but you have a robot that can only run on a very flat design in Figure 5-1 made out of small w ashers that and level surface. snuglv lit over the motor’s axles, or made from sec¬ tions of hot glue gun sticks that have been melted onto the axles. The reason why 1 ciitige when I see a robot like this because it is so limited. Small electric motors tend to run at several thousand revolutions per minute (RPM) and running them continuously is impossible. This may not be immediately obvious, but consider the case where the motors are turning Figure 5-1 Mechanically simple robot drivetrain Section Five — Drivetrains —-in citherofthesecases,thedifferencesinsizes 76 transforming rotationspeed andtorque becomes thefollowing: and isspecifiedinpounds-inchesorNewton-meters. plied b\theladiusatwhichforceismeasured, dealing withrotatingcomponents,butas1indicated, Figure 5-2Gearsmeshing togetheranil II rotationismeasuredinRPM,thepowerequation gears. ThisisanimportantpointandonethaiIwill gear’s radius,diameter,orcircumferenceusedinstead rotational forceistorquehastheunitsofmulti¬ take advantageofinthissection. cles thatareincontactandnoionlytermsoftwo and torqueisaccomplishedusinggears(Figure5-2) power wastheproductofforceandvelocity: because thisallowsyoutothinkintermsoftwocir¬ that radius,diameter,orcircumferencecanbeused I hogearsaretakenintoaccount.wanttopointout the gears.Thisequationcouldbemodifiedwith speed ofrotationalongwiththenumberteethin that canbothchangethedirectionoflotationaswell and becontrolledverysimply.Thischangeinspeed which willallowtherobottorunoverunevensurfaces doing this,largerwheelscanbeusedwiththerobot, speed themotorrunswhileincreasingitstorque.By as changethespeedandtorqueofmovement. the book.Ipresentedconceptthatmechanical sPeedLar3ex #TGethiargo=SpeedSman#Teethu When 1introducedtheconceptofpowerearlierin In Figure5-2,1havepresentedanequationofthe I hismayseemtobeabittrickierwhenyouare I hebestsolutiontothisproblemisreducethe P -TorquexRotationalSpeed P =FXV 153 Robotics Experiments fortheEvil Genius . Gear“Teeth" speed whileprovidingasmallamountoftorque. electric motors—theygeneiallyiunataveryhigh is onethatcriticalforrobotsworkwithsmall we canequatethepoweroltwoandhnd torque atthelargergear rate, andassumingthatnopoweiislostinthesystem, power isbeingdrivenintothesmallgearatsome speed ofihelargergearcanbecalculatedasthefol¬ of rotationtogearsize,ifwehaveasmalldriv¬ third thespeedofsmallergear.Knowingthat lowing: ing onethathasthreetimesthenumberofteeth, motion orelectricalpower. The abilityofgearstotransformspeedandtorque So thespeedoflargergear’soutputisone- Going backtotheoriginalformulaequatingspeed Speed = 3xTorque^.. Torque =Speedy,xTorque./ Power, = It ismeasuredinwattsassingledirection = sPeeds^nHrer

Tool Box Miscellaneous K'NEX Kits (see text)

Motor drive kit (see text)

Thread

Although I find it hard to agree that remote-control shoulder, one at the elbow, three at the wrist [twisting “robots” (such as BattleBots) fit the description of a is a degree of freedom 1. and the last being the ability true robot. I have to agree that the technology used to open and close your hand). Most robot arms have to build them is applicable tor autonomous robots. three or more degrees of freedom, so the crane is not Saying that remote control devices are true robots an unlikely device to consider as a robot analog. could be similar to accepting that motor-driven The crane that I would like to play around with is cranes (such as the construction cranes you sec assist¬ the single-degree-of-freedom crane that I built out of ing in the creation of buildings) could also be called miscellaneous K’NEX parts. It uses a motor taken robots. I find cranes useful in explaining the opera¬ from a K'NLX “Kart Racer” (Figure 5-4). If you are tion of different robot parts because they cannot run not familiar with K’NEX. I suggest that you buy a off the table or bench you are working on and cither sample experimenter’s kit—K’NEX is a building tool smash into a million pieces or run under a couch. that consists of various rods and connectors that ran A typical consti uction crane has three degrees of be put together to create quite light, fairly strong, freedom (a< shown in Figure 5-3). Degree of freedom large structures. A nice feature of the different rods is the term used to describe a movement that does that make up the kit is that they are measured so tri¬ not affect other movements. I he crane can turn the angular structures can be built along with square and boom left or right (one degree of freedom), move the rectangular ones very easily. Most of the experi¬ hook up or down (second degree of freedom), or menter’s kits consist of instructions for building dif¬ move the hook toward or away from the center of ferent creations (ranging from sculptures to moving the crane (third degree of freedom). For comparison, you arm has seven degrees of freedom (two at the

Boom with Counterweight

Hook Support Motion Motion

Hock 3 Support

Figure 5-3 Different motions of axis of movements possible for a construction crane

Section Five Dri vet rains 77 objects such as circus rides or simple vehicles), along has a good assortment of gears and w heels. Building with a plethora of parts (including gears and wheels) structures is probably not as intuitive with K’NEX as that will give you a great deal of flexibility in coming it is with other building kits. For this reason 1 suggest up with your own designs. that before you create something new, look through I used the Kart Racer gray motor as the crane’s instructions for something that is similar to what you “winch" that pulls the sewing thtead because it can want to build and start from there.The “crane*’ used drive the K’NF.X shafts directly (without having to in this experiment started life as a “windmill," and hack any parts to fit onto a motor dnveshaft). This after removing the sails and modifying the base. I had motor can be cut open to give you access to the motor most of the design for the crane completed. wiring, and using the different gears and motors that Looking at the other different building kits avail¬ are available in the different kits, you can very easily able on the market. I categorize their strengths and 0) create a complex drivetrain of your very own. weaknesses in Table 5-1.1 have limited the list to just c Please do not feel that you have to use exactly the K'NEX, LEGO, and Mechano. although similar (ti same parts that I did when building your crane, this products are compatible to these and have similar u design is by no mean* the most efficient, and depend¬ characteristics. One thing you will notice is that these u ing on your skills and the parts you have on hand, kits are fairly pricey, especially if you are looking for you could probably come up with something better. specific parts. You w ill find it a good idea to either buy a parts kit and try to work within it, or collect K'NEX is ideal for this ty pe of experiment, better G pieces (garage sales are excellent places to find than 1 EGO or Mechano because it is well suited to building large, open structures such as a ciane. and it *H

M Bible 5-1 Various building kits P I Product Description Rdvantages Disadvantages Best Robot Replications

M K'NLX Rods and eonncclors Large structures, lightweight. Poor bending strength/ Differential drive robots (Good O Good selection of gears iigtditv. motor/gear/wheel integration). and wheels that integrate Not intuitive to build Prototype robot arms. •P easily with product. without experience. O Difficult to find motors 2 and paits. LEGO Interlocking bricks Strong small structures. I urge structures will be Prototype mobile robots. Intuitive/fast to work with heavy .'may not be very “MindStornis" strong. provides excellent robot Complex structures may base and sensor set be weak r- Widely available parts. Motors/gears generally designed for specific Cs| products.

Mechano Melal/plastic girders Very strong. Fewer predefined kits Poorly Suited for complete 4-> held together by small Intuitive to work with. than K'NEX and LEGO. robots, but individual parts can outs and bolls Par Is can be easily adapted Heavy. be integrated into robots very G to work in other structures. Nuts and bolts hurl effectively and easily 0) when stepped on. G ■H U

78 1E3 Robotics Experiments for the Evil Genius Experiment 28 — Pulleys Added to Crane Experiment 28 Pulleys Rdded to Crane

Crane from previous experiment

Four small tireless K'NEX wheels

Miscellaneous K'NEX Parts

Depending on the motor you used with your crane sity of common stone (Earth has a density of 4,500 or the amount of charge left in the batteries,you will kg/ml which was the basis I used for this value). probably discover that the crane does not have a lot Fifty kg of force (*‘kgf\) is probably acceptable for a of lifting power. I found that the stock configuration modern man hut for an Egyptian slave, it is proba¬ ol the crane would not lift two “C” cells what was bly optimistic. In any case, 8,000 men pulling up the needed was some way of increasing the power of the obelisk is an unreasonable number and something crane. One of the obvious ways of doing this is to has to be done to lower it to something more man¬ increase the gear ratio between the motor and the ageable. winch (what the thread winds itself around). This w ill The solution is to double up the ropes using a work, but gears and the structure needed to support device called the pulley, which will effectively multi them are heavy and complex. ply the amount of force each slave could exert on the As 1 will do throughout this book, when I am con¬ obelisk.The operation of the pulley is shown in Fig¬ fronted with a problem like this one, I will go back ure 5-6 a motor pulling a weight upwards on a sin and look at how the problem was handled histori¬ gle cable will have to exert enough force to lift 1

Motor Supporting Motor Supporting Motor Supporting Slave Full weight 1.'2 Weight ' 1/4 Weight

Figure 5-5 Raising a large obelisk using nwsde Figure 5-5 Changing'force to raise an objectusing (slave) power a puuey

Section Five Dr i vetra i-ns 79 Hopefully, you do not think that this force multi plication conies fiee as with everything in life, when you change one thing, it affects something else. In this case, the length of rope or cable that is moved is increased with the number of tunes it is looped

X So. it it required 1 pound of force pulling for 1 foot using a rope looped around 3 pulleys, the force applied on the object would be 3 pounds and the Figure 5-7 K’NEX crane pulley detail U object would travel of a loot. o In this experiment, you can demonstrate the -p increased power (and decreased speed) of adding a amount of weight the crane can lift four limes. After o pulley to your crane. If (he crane was built out of making this modification, you can test out this asser¬ K'NEX, the top of the crane and the hook would be tion by trying to lift heavier objects if. like my crane, modified to look like Figure 5-7. In this case, 1 have yours could not lift two “C” cells, you should find that u looped the thread around two wheels at each end, with the pulley added to if. it can now comfortably lift Q making a four-pulley crane and increasing the six or seven. X

-P Experiment 29 •H Switch DC Motor "H-Bridge” C/3 Tool Box Assembled PCB with Wiring kit.

breadboard Rotary tool Crane from previous Soldering iron as experiments Solder eg Dual "C." battery clip Heat shrink tubing Two Single-Throw Double- -P Throw (SPOT), PCB- mountable switches C Q) Previously, 1 showed how the direction a DC motor allowing the motor to turn in the same direction. For £ turned in was controlled by the direction that current robot applications, the simplest way of changing the •HI flowed through it. By changing the direction of the direction a shatt turns in is to change the direction of u current flowing through the motor, the direction it the current flowing through the motor. a turns changes. For most applications, motors only If you were to think about the problem for a few a* have to turn in one direction;even it they are minutes, you might come up with a circuit like the x required to reverse, their motion is often passed one shown in Figure 5-8.This circuit provides two w through a gear box that changes the output while battery packs, one of which is selected at any tune

SO 123 Robotics Experiments for the Evil Genius Experiment 29 — Switch DC Motor H-Bridge Motor

Figure 5-8 Using two butteries to control motor operating direction

and allows current to cither flow into the motor or out of it This type of switch has been used in some robots but has a problem that should be quite obw Figure 5-9 H-Bridge motor driver ous; the battery pack that powers the direction that the robot runs in most of the time (normally for¬ ward) will be run down much quicker than the other Motor battery pack. Tire main advantage of the circuit in Figure 5-8 is that it only requires one switch.

Another advantage is that there is only one switch Current Hows voltage drop—this is not an issue when mechanical Through Switches and switches are used, but it can be a problem for elec¬ Bypasses Motor. This tronic swatches. Can Burn out Wiring The motor control circuit that is most commonly Or Motor used to control the direction of a DC motor is called Power Supply- the “I I-Bridge” (Figure 5 9). By closing the switches catercorner from each other, you can control the direction of the motor. As I will discuss later in the book, turning the motor on or off, as well as how fast it is turned on and off, can be controlled easily using simple electronic devices. The H-Bridge allows a sin Figure 5-ID H-Bridge motor driver operating gle power supply to be used to control the direction a incorrectly DC motor turns in and can generally be built quite inexpensively. lem; by elosing the two switches on the same side of T he H-Bridge has two main concerns that you the H-Rridge, you have created a short circuit.This should be aware of. The first is that the motor current short circuit will burn out the motor wiring, the II- must always pass through two switches. When physi¬ Bridge switches, or the power supply. The best that cal switches are used, this is not a problem, but there you can hope for is that the battery's charge will be will be situations when electronic switches are used seriously depleted. Care must be taken ttt your motor with low-voltage batteries where there may not be a control circuits and software to ensure that this con¬ sufficient amount of voltage for the motors to run dition can never happen. properly. If you have used the same K’NEX hardware as I The second concern is quite subtle and is one that have to build your crane, you might have figured out > you must be aware of at all times, The motors will by now that the switch on the gray motor will com¬ turn when one switch on either side of the II Bridge mand the rnotoi to turn in one direction or the other is closed. If both switches on the same side of the 11- and is probably wired internally as an 11 -Budge. Bridge are closed (Figure 5-10), you will have a prob- Rather than taking this on faith, for this experiment I

Section Five Drivetrains 81 Experiment 30 — Differential Drive Robot switch andthesmallPCBthatitismountedon motor Hbridgecontrol 82 gauge solidcorewiretoallowmethemotor exposing theDC'motorwires,Isolderedonsome24- would likeyoutodisconnectthewiresleading used arotaryDremeltool).Afterpullingoutthe Figure 5-1.1BreadboardwiringforcraneDC to thebook'sPCMbreadboard. DC motorinthegrayboxbycuttingitopen(I Motor straps(seetext) Double sidedtape Four 1-inch(2.54- Eight. 1-4005-mch(1-ceniimeter) Misc nutsandDolts(see text) Two axles(seetext) Two wheels(seetext) Two smalltoymotors Furniture glideacorn nut, LEDor centimeter) standoffs screws clothes hook(seetext) 153 Robotics Experiments for the EvilGenius Differential DriveRabatChassis Assembled PCEwith Four AAbatteryholder Four PCBmountSPDT Switch withsolderlugs | ng 1 a□ breadboard switches a □ o □ □ a □ □ a □ c = □ a □ □ a □ n □ □ a □ □ □ a □ □ L-c.jap.-qja .qq.bs.Qi nxLnnun_rmnnn □ o□□□□□ □□□□□ □□□□□ □□□□□ □□□□□ □ □□Do—-rf □ L-iL-h a 2h(O)t□ rVp P-y\u_tpr~n nan uj*—~*q.□D ofTn ao□oua □ njia □ QCLa □IfljoipD njflja □(*]□□ nfji|c □□□□□ □□□□□ □□□□□ □□OD □□□□□ □□□□□ □□□□□ □ D0□□O !?°Crane Motor’° Experiment 30 □ o □ n d a a □ D □ □ □ □ 3 □ □ □ □ 3 n 3 □ □ □ □ a □ □ a □ □ 5-1,1. Forthiscircuit.1havewiredtwoSPDTswitches cover thatitworksidenticallytothesingleswitchof connected. with thewiperconnectedtoDCMotorcontacts breadboard aspartotthecircuitaccordingtoFigure were tocontinueopeningupthegraybox.youwould direction, nocurrentcanflowinthemotors.So.ifyou both SPDTswitchesaresetinthesamedirection, the originalwithoneimportantexception:When being achanceforbothsidesofthelI-Bridgetobe ative voltageforeachsideofthemotorwithoutthere device (asinthiscase),thereisnocurrentflowand understood thatifthereisnovoltagedropacrossa flow. I’mpointingthisoutbecauseitisnotoften probably seethatinthecenterposition(off),thereis motor stops.Whenbothswitchesareinthesame the devicewon'twork. no actualconnectiontothemotors,socurrentcan Too1 Box ihis willallowyoutoselecteitherapositiveorneg¬ When thisisdone,youcanwirethemotorto Once youhavewiredthecircuit,shoulddis¬ Misc. screwdrivers/pli¬ Glues/adhesives Wiring kit Soldering iron ers Experiment 30 — Differential Drive Robot When I present actual robots in the rest of this book, keeping the wheels and center of mass as close to the I will be primarily working with the differential drive center of the robot as possible, the amount ot change platform that I introduced to you in the first section. in force on the casters is minimized, allowing the The simplicity ot this type ot robot allows for simple robot to run easily over different surfaces (see Figure building as well as easier circuit and software devel¬ 5-14). lliis is important when the robot is expected to opment, although you should be aware of a few run over carpets or from one surface to another. It a things to make the assembly and operation of the lot of force is on the caster, you may find that the robot as simple as possible. As I work through the robot will stall at the caster if too much force is being chassis. I will cross reference the design decisions to placed upon it and less weight is placed upon the my 1.0' Rules of Robotics." wheels (Figure 5-15). I feel that the ideal layout for the differential drive When a robot’s wheels are placed at one end and robot is the one shown in Figure 5-12; the robot is as the center of mass is located elsewhere, corrections short as possible with the wheels centered and the may be required between the sensor/control input center of mass at the center of the robot. In Figure and the wheel commands. In the best possible situa¬ 513,1 have marked casters at the two ends of the tion. the sensors would be placed directly above the robots; the castors are wheels or smooth plastic that wheels (at the robot's center) so that the robot could allow the front or rear of the robot to slide on the turn and follow the sensor input without the require¬ running surface easily. ment for any kind of correction caused bv inadver¬ The center of mass is often called ihe center of tent body movement due to the wheels. gravity, but I prefer to refer to say mass lathei than The purpose of this experiment is to add a battery gravity w'hen talking about robots because it reminds connector, power switch, wheels, and motors to one me that the inertia of the robot when it starts or stops will change the amount ot force on the casters. By Stopped and Following Turning a Path Center of /Robot Followinq Path Assembled Book PCB

Finished Plywood Base

r (2 54 cm) Axis Following Standoffs

ideal differentially driven robot Wheel and Four "AA" Battery Pack Figure 5-1M Motor Drivetrain Power Switch motion

Figure 5-12 What the differential drive robot with

PCB will look like Center of Stopped and Following Robot NOT Turning a Path Following Path Predictably. There’s a Top View Side View Robot’s Possible Weight on^ Difference Wheels Between Sensor and Front Commands and Caster. Movement Resulting in More Friction During Robot Turning Movement About Axis *■ Path Robot Drive Wheels Is Running On Between Wheels Following

Figure 5-13 Design of ideal differentially driven Figure 5-15 Less than ideal differentially driven robot robot motion and some potential problems

Section Five Drivetrains 83 Experiment 30 — Differential Drive Robot 0.090”-. Motor Axle Diameter 5-16 isasideviewshowinghowthemotoraxle similarly totwogearsandredueesmotorspeedby16 and detail of theplywoodbasesthatyoufinishedearlier.Figure vent hair,lint,anddustfromfoulinguptherobot’s a gearorpulleysystemsealedinboxthiswillpre¬ times orso.Asyouruntherobot,willdiscover drive it.Ihemotorsarestrappeddownusing while leavingenoughspaceforthetwotoymotorsto drivetrain. a cleanenvironment).Tireperfectsituationwouldbe bly asurprisingamountfevenifyouthinkarein that youwillbecleaningthemotoraxle/wheelassem¬ pressed againstawheel—thisarrangementworks Figure 5-16Differentialdrivewheeldimensions parts, youshouldbeabletofindLEGOpiecesthat bolted downtotheplywoodusingtwo6-10bolts port consistsofan1shapedpiecethatcouldbe a Mechanoset(showninFigure5-17).Theaxlesup¬ 84 an LEDtothebottomolrobot.1heultimatecas¬ also useaTeflon-coatedfurnitureslider,orevenglue plastic hookonthebottomofrobot.Youcould toward theAbatterypack.Becauseofthis.Iended on thePCB.1foundthatmyrobotendedupheavy battery bolderwiththemotorsand9volt axle andmountedtotheplywoodchassis. purchased fromacraftstoreandbesupportedby together. Ifworsecomestoworst,awheelcouldbe work justaswellorothertoykitsthatcanbehacked Mechano metalpieces.Insteadofusing tor wouldbesomethinglike afreeswivelingmodel up onlyusingonecaster;1placedawallmountable wood blockthathasbeendrilledouttoacceplabolt airplane tailwheel,butthese canbesurprisingly expensive andlakeupalot more spacethanisavail able onthebottomotrobot. Iheimportantthing The wheelandaxlesupportIusedwastakenfrom Despite tryingtooffsetthemassoffourAA 123 Robotics Experiments for the EvilGenius Wheel 1 270’’Diameter Wheel Speed,butwith than theMotorProvides Resulting inaSlower Divided 14.1times, The MotorSpeedis 14.1 timesmoreTorque 1.27 /0.09=141 pack willbeusedtopowertherobot’smotorsandit on theplywoodusingtwo-sidedtape.Ihisbattery wheels andthemotors,placeAAbatteryholder move andturneasily. about thecastorisitsabilitytoallowrobot running overyourtableoieausingotherproblems. observe whatishappeningwithouthavingtherobot tery pack,youwillbeabletostoptherobotand ihands tothemotorsandyouwillwantstopthem. because therewillbesituationswhereyourcontrol¬ must haveapowerswitchaddedinlinetoturnoff work throughtheswitchsettingstomoverobot that willallowyoutomanuallycontioltherobotand attaching thestandoffsandboltingrobot ling hardwareorsoftwarewillsendinvalidcom power totherobot’smotors.Ihisisveryimportant details together, followFigure5-18towiretwoH-Bridges By poweringtherobotfromaseparate,switchedbat Figure 5-17Differentia!driverobotdrivetrain differentially withtwitchcontrol Figure 5-18Circuittodrive tworobotwheels X ()ncc youhavefiguredoutawaytomountthe Now youarereadytotestouttherobot.After “AA” BatterySwitch 2x -AA Battery Pack "H Bridge” Switches rood Chassis port Boltedto tic Axle/Wheel Left Motor Motor Right forwards, backwards, and left and light. By wiling the is desirable because transistor switches will drop the Experiment 31 — Stepper Motors four breadboard-mountable SPOT switches as I have voltage available to the motors as well as limit the shown, you will not be able to short-circuit the bi- amount of current they will receive. Even with these Bridge by allowing power to pass directly through losses you will still want the robot to move faster the switches and bypass the motors. If you don’t want than you are comfortable with because it is much eas¬ a motoi to tui n, you simply have to set both motor ier to slow it down than to speed up something you switches to cither battery Vcc or Gnd. have already built and gotten running. When the robot runs with just switch control, it should run somewhat faster than walking speed.This

Experiment 31 Stepper Motors

Tool Box

Assembled book PCB with Wiring kit breadboard Scissors Four AA batteries with Krazy Glue clip (see text) DMM Four Dreadboard-raount- able SPDT switches

Five-volt stepper motor

Four-pin breadboard to stepper motor connector (see text.)

Paper

The “stepper motor” is another type of L)C motoi Ib demonstrate the operation of the stepper that is commonly used in robots, and chances are you motor, 1 would like you to build the circuit shown in are not familiar with them even though they are used Figure 5-20 and wire it like 1 did in .Figure 5-21.The in different devices. Stepper motors differ from stan dard DC motors because they lack the commutator Table 5-2 Coil enerqizdtion seouence to move of standard DC motors—steppei motors generally stoooer motor consist of an armature-mounted magnet with two perpendicular coils that can pull or push the magnet Single in to different positions (Figure 5-19). The armature is Step Degrees Coil R Call B generally geared down within the motor significantly, t 0 South Off so that each time l he armature moves (45 to 90 degrees), the output shaft only moves a few degrees 2 45 South North —this gearing increases the torque output of the 3 90 Oil North motor and allows for more precise movements. 4 135 North North To move the stepper motor, the coils are energized 5 180 Norlti Off in a pattern something like the one listed in Table 5-2 6 for the stepper motor shown in Figure 5-19. When 1 225 North South listed the different coil polarities, I could have listed 7 270 Off South how just one coil is energized to move the armature 90 8 315 South South degrees at a time. '! his may be the simplest method of o 360/0 South Off firsl implementing stepper motor control software.

Section Five Drive trains 85 pairs of wires for each coil will be side by side coming from the body of the stepper motor). When you have done this, I suggest that you place the two switches for each coil wire together to simplify the operation of the switch to move the motors. Rather than cut the connectors off of the motors that I had bought, I cre¬ [XW] ated the four-pin connector from two four-pin single Coil "B" row, breakable PCB mountable connectors. When 1 built my test circuit, I cut out a simple Figure Ed-1 9 Stepper motor paper arrow and glued it (using Krazy Glue) to the end of the stepper motor’s output shaft.This allowed

Four "AA” me to observe the operation of the motor easily and Batteries 'Switch 1“ “Switch 2" “Switch 3" “Switch 4’ make sure that I could come up with a scries of switch movements that would move the output shaft in a continuous direction. After you are finished with CO trie experiment, the arrow can be pulled oft the step¬ M per motor's output shaft and any residual glue can be scraped off to return the motor to its original state. 1 O used stepper motors that were specitied for 5 volts of 4J power. This made wiring them to four A A cells quite easy and avoided the need to come up with an alter¬

2 Figure 5-20 Circuit used to test stepper motors native power supply. If you are unable to find 5-volt stepper motors, then you will have to come up with u an alternate battery supply that meets your motor’s

86 123 Robotics Experiments for' the Evil Genius stepper motor in a constant direction. For my experi¬ In the table. 1 have highlighted the single switch Experiment 31 — Stepper Motors mental setup, I created Table 5*3 to record the switch setting change that is needed to move the stepper positions to move my stepper motor in a clockwise motor (the up and down positions are based on the direction, and I recommend that you do the same lor orientation of the circuit in figure 5-21). When you your motor. Note that the “Coil A" and “Coil B" are wiring your circuit and working through switch polarities are simply arbitrary; I put them m as a sequencing, I suggest that you work toward being check to make sure that the switch positions and able to just change one switch at a time for each motor response made sense. If you touch the motor, movement. This will make both the work to move the you will discover that it is quite warm this is a char¬ stepper motor manually easier, but also make it eas¬ acteristic of the stepper motor because current is ier to program a controller to drive the motor. always flow ing through one or both coils.

Table 5-3 Hctual stepper motor eoergizatioo seqjence

Step Coil R Switch ! Switch c Coil B Switch 3 Switch '•/

i Soulli Down Up Off Up Up

n South Down Up South Down Up

Off Down Down South Down Up

4 North Up Down South Down Up

5 North Up Down Oft Down Down

() North lip I low n North Up Down

7 Off Up Up North Up Down

8 South Dow n Up North lip Down

9 South Down Up Off Up Up

Section Five Drivetrains 87 & ■H

40C 70C Temperature 5-25. When I built my test circuit. I started by cutting Figure 5-23 Muscle wire length as related to temperature and bending a piece of piano wire so that it had a straight edge 3 inches (7.6 centimeters) long with two nght-angle bends a half inch (12.5 millimeters) long mA is passing through it. Flexinol comes pre- at both ends.These half-inch-long ends were both stretchcd.so when you are putting it into your appli¬ sanded with 600-grit sandpaper until they were shiny. cation, it should be taught, but not undei more than a I then cut a 1-inch (2.5-centimeter) piece of piano gram (l/16th of an ounce) of tension. You can tind wire and sanded it with 600-grit sandpaper. Ihis sand more information about Flexinol (and muscle wire) ing is to remove any oxidation and provide the best at Dynalloy’s web site at www.dynalloy.com. possible electrical connection. Next, 1 cut a 5 inch You can buy it trom "Mondo- Ironies, the Robot (12.7-e.cntimeter) piece of Flexinol and sanded l-inch Store” at www.mondotronics.com or trom the “Stiq (2.54 centimeters) of each end of the Flexinol lightly uito” Web page at www.sticjuito.com/. The Stiquito is a muscle wire-based robot (and book series) that vou can experiment with. Ihe Stiq¬ uito takes advantage of muscle wire's best features but avoids some of its shortcomings. The good part of muscle wire is its simplicity; as I will show in this experiment, muscle wire can be used to deform a metal rod for use as an actuator with very little work. Figure 5-2Ll Simple electrical circuit to test muscle When muscle wire is activated, it is silent, and as long wire’s ability to shorten and lengthen as it is kept within its operating range, it will work almost literally forever. Muscle wire can be used to create simple insect robots quickly and with minimal effort and cost. A disadvantage of muscle wire is its inability to support a large amount of weight safely. If muscle wire is stretched too far (around 8 percent longer than you started with), it will no longer be able to contract into a shorter length. Normally, muscle wire b prestretched to 3 to 5 percent of its original length. Most robots you will see that are based on muscle wire will have their batteries,controllers, and sensors external to the robot itself. Muscle wire’s actuation is actually quite slow (taking up to a second to contract and then another second to expand), and it cannot be contracted a specified amount; it’s either all or noth- Figure 5-25 Wire muscle circuit allowing current ing. You will probablv find that muscle w ire is some to tloH throu8h a Piece °f mi,scle wire to hend a piece of piano Hire

Section Five D^ivetrains 89 Experiment 32 — Muscle Wire 90 with apaiiofmedium-dutyneedle-nosepliers. wire. ITnsissomewhatofadelicateoperationandit sure youdonotpushtheFlexinolfiompiano nol betweenthetwopiecesofpianowire.Whenthis bent, andsanded,tiewraptheFlexinolaround two half-inchpieces(12.5millimeters)of10-milli¬ could causeittobreaklater).Alongwiththewire,cutconnecteddirectlvabattery,butifvoudothis,you with 600gritsandpaper.WhensandingtheFlexinol,Thespecificationfor0.004-inchFlexinolisthat satisfied withthefitofaluminumtube,crimpit will takeseveraltriestogetitright.Whenyouare ing overthewire,youmightwanttotwistitmake over thepianowirc/FlexinoiWhenplacingtub is done,gentlypushthepiecesofaluminumtubing the endsofeachtwopiecespianowire. meter aluminumtubing. take caretonotsiretchtheFlexinolornickit(whichmusthave180mApassingthroughit.Itcanbe There shouldbe3inches(7.6centimeters)ofFlexi¬ When youhavethetwopiecesofpianowirecut, 12 3 Robotics Experiments for the EvilGenius current-limiting resistor,Ibuiltthecircuitandthen where itwillmeltthroughthetopsurfaceof w'ill findthattheFlexinolwillheatuptopoint nol andotherwiring,a391)resistorwasperfectfor 50 11BecauseIalreadyhad11.611.duetotheFlexi¬ thiough thewire,1neededatotalcircuitresistanceof per inch(2.54centimeter).KnowingthatJwasgoing because theFlexinolthatIusedisratedat3Ohms measured itsresistanceatthePCB’sbatterytermi¬ the experiment. to usea9-voltbatteryandIwanted180mApass nals. Inmycase,itwas11.611,whichisreasonable limiting resistor.Todeterminetherightvaluefor breadboard.To avoidthis,Iaddeda391)current- Section Six Semiconductors

A big science fiction theme in the 1950s and 1.960s heated first. One of the most dramatic transformations was how intelligence was defined and how it mani¬ happens when eggs are heated; the molecules in the fested itself in living organisms.The typical story (as in “white" are changed so that they can easily combine H. Beam Piper's Little Fuzzy) went along the lines of together, turning it from a clear liquid to a white solid. humans colonizing a planet, only to discover that Oxer time, we have discovered many ways in some of the “animals" (hat already lived there show which materials can have their properties changed. In some remarkable capabilities that suggest they are Table 6-1 1 list some of the piopeities that we rou¬ “sentient." Other stories (such as Clarke and tinely change in different materials and a sample Kubrick’s 2001) explored how humans may have product that takes advantage of the property change. become intelligent. Different Star Irek episodes have Transistors and other semiconductors can change explored this issue as well. These stories have died out their ability to conduct electricity (and pass current) over the past 30 years because you can’t really write depending on some external condition. Semiconduc¬ many different plots with this theme. tors usually start as a pure crystal made out of ele¬ In all of the different stories, a simple test is used ment^ like germanium,selenium, or silicon Oallium to determine intelligence. In Little Fuzzy it was the and arsenic can be combined into a crystal (known as ability to talk and use fire. In 200L it was the ability gallium arsenide) that is also a semiconductor. 'Ihese to use tools. I he problem w ith many of these tests is crystals are usually very good insulators, but their that you will find animals on earth that will pass conductivity is usually increased as the temperature them. In terms of “talking" or communicating, many of the crystal increases. By adding different atoms to different species use different methods of communi¬ the crystal (called dopants). the crystals become able cating: for example bees use “dance” to pass along to conduct electricity hecause the new atoms provide information on where food can be found, birds com excess electrons that allow current to flow through inunicate danger by using different cries, and gorillas the crystal. have been taught sign language and can “talk’ to people In terms of tools, the sea otter uses a variety Table 6-1 of tools to gather and open food. Polar bears take advantage of fire to flush out food. Property Change Sample Product

As I was creating the introductions to the different L iquid to solid Glue- sections in this book, I realized something that Gas to liquid Rocket fuel humans do that separates us from animals, and that is the ability to change the properties of a substance. Gas to solid Dry icc

Now, belore you start getting the picture of cavemen Increase tensile strength Carbonized steel with test tubes in your head, try to think about what Element properties Plutonium (produced in is the most basic change that can be made to some¬ nuclear reactor) thing that appears naturally. Electricity from chemicals Batteries If you thought ot cooking, then go to the head of Increase conductivity Copper allovs the class. Early humans probably discovered that meat tasted better and w as easier to digest if it had been Controlled electiical conductivity Transistors

91 Section Six — Semiconductors 92 gram, whichhavesixelectronsintheiroutershell,sil¬ glass arebasicallyjustsilicon),easeofuse,andlow atoms thatcanacceptanelectioneasily. atom withfiveelectrons.Thisleavesaholeinthe six electronsintheoutermostshellandadopant atoms and.dependingonthenumberofelectronsin toxicity. Unliketheatomsusedinexampledia because ofitswideavailability,lowcost(sandand crystal withanincompletebondinoneofthe flow. InFigure6-1,1haveshownacrystalatomwith leave excesselectronsorholesthatallowcurrent their outermostshells,provideincompletebondsthat added veryeasily.Thedopantsreplacethecrystal Figure G-lPureanddopedsemiconductorcrystals crystals formstructuresinwhichdopantscanhe Silicon isthemostpopularbasecrystaltouse As IhaveshownmtheFigure6-1,semiconductor 153 Robotics Experiments for the EvilGenius Pure Crystal V !_ di _d Atom Crystal y semiconductors. electrons initsoutershell,isatypicalPtypesemi can providefreeelectrons.Boron,whichhasthree electron intheoutershellandareknownasdonors) semiconductors (whichuseelementswithanextra ductor isknownasP-typeandusedinthecrystal vertices. because acubeismucheasiertovisualize(anddraw) icon hasfourelectrons1usedanexamplewithsix electrons initsoutershell,isusedtomakeN-type conductor dopant,andphosphorus,whichhasfive than athree-dimensionalstructurethatonlyhasfour trons (andareknownasacceptors),whereasN-type Figure 6-1.PtypeSemiconductorscanacceptelec¬ used todopeasiliconcrystaltheresultingsemicon¬ When anatomwithfewerthanfourelectronsis Experiment 33 — Diod.es

Experiment 33 Diodes

Assembled PCR

1N4148 or 1N914 silicon diode

The most basic semiconductor application is the (photons) as I have shown in the diagram. For silicon diode, which is a device that only allows current to diodes, these photons are in the very deep infrared

pass 111 one direction. I Jsing the water analogies that I range and not visible by the human eye. As I will used earlier in the book, the diode can be thought of discuss in the next section, bv changing the diode’s as a one-way valve. When there is pressure in one material, useful wavelengths of light can be produced. direction, water w ill flow through the valve with just It is important to note that in Figure 6-4, J show a small pressure drop. If the pressure is reversed, the the direction of electron flow and not current flow. As valve closes and no water is passed In this experi¬ I have stated earlier in the book, current flow is in the ment, you will get a chance to see how a diode works opposite direction of electron flow. When you wire in a circuit and learn about some of its characteristics. your circuit, the N-type semiconductor is connected Hie symbol for the diode, along with what the to the negative part of the circuit to pass current, not actual part looks like, is show n in Figure 6-2.The sim¬ the positive as you might think from this drawing. ple band around the diode is used to indicate the In this experiment. I would like you to wire a direction of current How. In schematics, diodes are diode, 10k resistor, and wire into your PCB/bread- given the reference designator “CR 'or' D." board combination as I have drawn in Figure 6-5. rhe One of the first applications for the diode was to voltages and currents within this circuit will be meas¬ convert (or rectify ) alternating current (AC| into ured so you can Understand the operation of a diode. direct current. Alternating current consists of volt¬ The 1N914 and its equivalent part, the 1N4148, arc ages that are both positive and negative, and you can general purpose silicon diodes The term equivalent see how the diode only passes positive voltages and currents in Figure 6-3. Output In a diode, electrons fall from the high-potential N- 0 V type silicon semiconductor to the low-potential P- type silicon (Figure 6-4). As the electrons fall, they ■ lose energy.This energy is converted to light energy

Figure 6-3 Diode rectifying an AC signal

Photons Electrons Flowing from High- to Low- Potential Material

Figure 6-2 Diode symbol Figure 6-M Diode operation

Section Six Semiconductcrs 93 CO CO uj *H -p >1k > 1" 4 4 ◄GSB2E ^EEsnzci rnA rnA Experiment 34 — Light-Emitting Diodes (LEDs) Experiment 34 Light-Emitting Diodes (LEDs)

Parts Bin Tool Box Assembled PCB Assembled PCB

Light-emitting diode DMM (LED), any color Wiring kit lk resistor

In the previous experiment. I mentioned a by¬ table 6-3 LEX) materials and light product property of diodes that is actually quite

useful. When I discussed the actual operation of the Diode Dutput Light semiconductor parts of the diode, I showed that when Color Materials UJavelength

the electrons fall from the high electron potential Infrared Gallium, arsenic 940- 730 n m N-type silicon to the low electron potential P-type Red Gallium, aluminum, 700-650 nm silicon, photons were released. phosphorous In the previous experiment, I went into some Amber Gallium, arsenic, 610 HIP detail to show how the basic electronic laws are not phosphorous violated by the introduction of semiconductors into Yellow Gallium, arsenic, 590 nm circuits. The release ot photons ensures that the diode phosphorous does not violate the first law of thermodynamics Green Gallium, phosphorous 555 nm that energy cannot be created or destroyed The Liiue Zinc. Selenium 480 nm energy lost by the eleclions as they pass from the N- type to the P-type semiconductor is converted into the photons. As I noted, in a standard silicon diode,

these photons are very low energy (long wavelength) L:ght Rays Line Corresponds to "Flat" on indicating LED and not leaily useful. component's base In Table 6-3.1 have listed some of the different

materials used for making LEDs and the different Current Direction light that they output. Most of the materials used in the manufacture of LEDs are quite exotic, which is Actual Part Appearance the reason why LEDs tend to be about 10 or more

times the price of a si triple silicon diode. "Flat" on side of diode Indicates polarity and The I ED itself comes in a cylindrical package that Direction of Current Flow kind of looks like R2 D2, as I have shown in Figure 6-7. The schematic symbol for the LED is similar to that of ihe LED, but with 'light rays" coming off it as Figure 6-7 LED symbol in Figure 6-7.To indicate it* polarity (and the direc¬ tion ot current flow), the LED package has a flat on LEDs behave identically to regular diodes in a cir¬ one side ot the circular base that indicates which side cuit with one important different—they usually is the LED's cathode (negative connection). Tike have a higher voltage drop than silicon (and other diodes. LEDs usually have the reference designators semiconductor) diodes. In this experiment. 1 am “CR" and “D,” but in some cases, you will see the ref¬ going to repeat the previous one but use an LED erence designator “LED" used instead. instead of a 1N 914/1N4148 diode.

Section Six Semiconductors 95 Experiment 34 — Light-Emitting Diodes (LEDs) will burnitout.Decreasingthecurrentlessen will notmaketheLEDbrighter—althoughtoomuch Figure 6-8Circuitfortesting LEDoperation output, butitishardtocontrolthelightoutputlevel. the lkresistorinthiscircuitprovidesjustover5mA (as canbeseeninTable6-4).Addingmorecurrent resistor's value. dependant onthevoltageacrossresistorand still holdsandthecurrentthroughsystemis voltage dropacrossthesilicondiode.MostLEDs rest ofthedata,you'llseethatKirchoffsvoltagelaw the 0.6to0.8voltsofasilicondiode.Lookingat have avoltagedropofaroundtwovolts,instead ence inthevoltagedropacrossIEDversus yout resultsinatablelikeTable6-4, experiment’s stepsaslistedinFigure6-8andfillout should befacingawayfromtheVin.Onceyouhave the circuitwired,LEDshouldlightup. experiment. RememberthattheflatspotonLED store, youwillprobablybeamazedatthenumberof one showninFigure0-7. experiment (andtheonesthatfollow),1recommend different packagesandbrightnesslevels.Forthis different LEDsavailabletochoosefrom.Alongwith there beinganumberofdifferentcolors,willbe meter package,whichhastheflatatbaselike that youbuyabagofthecheapestonescanfind. These areusuallyredoutputandina5-milli¬ Most LEDswilllightwith5inA.ofcurrent.Using Looking overthedata,youshouldseeabigdiffer Once youhavetheLEDlit.repealprevious This isthesamecircuitaswasusedinprevious It yougotoareasonablywellstockedelectronic 1 d3 Robotics Experiments for the EvilGenius except forTest3whenitis inDCcurrent0-2mArange DMM isinDCvoltageC-20voltrange Test 1 iMfmm 9V. Test 2 your owncurrent-limitingresistors. tors builtintothePCBeliminateneedforadding the LEDbeingaddedtocircuit,220liresis¬ mal, butinsituationssuchaswhentheRS2isdriving current-limiting resistorof220to470If.Disopti¬ mize theamountofcurrentrequiredbyapplica¬ no more.Usingthecurrent-limitingresistorwillmini minimized towhatisrequiredlighttheLLL)and tor weteleftoffinthiscircuit,youwouldfindthatthe tion andmaximizetheapplication’sbatterylife. resistor, theamountofcurrentpassedtoLEDis battery's lifewouldbequiteshort.Byputtinginthe cannot sourceenoughcurrenttoburnitout),butthe LED wouldprobablystillwork(the9-voltbattery has effectivelynoresistanceinthecircuit.Ifresis¬ resistor andisrequiredbecausetheLED(ordiode) modulated controlsignalisproducedinmoredetail and Iwilldiscusshowitworksapulsewidth off. Thisisknownaspulsewidthmodulation(PVVM), later inthebook. is byrapidlyturningthepowertoLEDonand The bestmethodofcontrollingtheLEDlightoutput circuit Battery Table 6-4 Voltage 7.tS volts >1k When workingwitha5-voltlogiccircuit.Iuse The lkresistorisknownasacutrent-limiting tlectrical measurementsfnrtheL 1.99 voto Voltage Diode 9V; Test 3 i—- mA Resistor 5 i7voil's Voltage Current 5.36 mA Circuit Experiment 35 — NPN Transistor Lighting Control Experiment 3^ NPN Transistor and Tuuo-LED Lighting Control

Parts Bin Assembled FOB DMM

Two LEDs, any color Wiring kit

Three lk resistors

Two LTX649 NPN transis¬ tors

So far in this hook, when I have been introducing a This is actually a very accurate description of how new electronic component, I have been using a an NPN transistor woiks, but it misses a few impor¬ “water analog” to describe how the component tant points. Flic first is that the water that passes into works using a medium that you should be familiar Hie control pipe is dumped into the exit pipe. It is with. Unfortunately, as 1 start working with more important to understand that the amount of water sophisticated semiconductor components, the appli¬ passing through the laige pipe is dependant on the cability of using water as a demonstration tool amount of water passing through the control pipe hecomes just about impossible.The operation of the the pressure of the water is not important. Finally, a diode can be modeled using a one-way valve as 1 multiplication factor exists between the amount of mentioned earlier, but trying to come up with the water passing through the control pipe and the large transistor water model is quite difficult and some of pipe.The amount of water that can pass through the the most important aspects of the transistor cannot large pipe is proportional to the amount of water be easily observed. flowing through the control pipe. figure 6-9 shows that the transistor consists of a At the other end of the spectrum is the electrical simple valve ihat is controlled by the introduction of model used by engineers and circuit designers to smi water into the control pipe. The water flow in the ulate the operation of a transistor in a circuit In Fig¬ control turns a small turbine that pushes open a valve ure 6 10,1 have shown the simplified small-signal m the much larger pipe. The more water that passes transistor model that is used by the simulation pro¬ through the control pipe, the faster the luibine turns gram with integrated circuit emphasis (SPICE). Phis and the more the valve opens.The more the valve circuit, shows the parasitic resistances built into the opens, the more water passes through the large pipe. transistor control or base as well as the coupling When no more water is flowing in the control pipe, capacitances.The circle with an arrow is called a cur¬ the valve closes automatically. rent source and it will allow a set amount of current, which is a multiple of the amount of current flowing through the transistor’s control (or base) to the exit Source (‘ Collector") Control Current (or emitter).The current passing through the current Turbine Driven Lever to Open source comes from the source or collector and is Valve passed to the emitter. 1 didn't put in Figure 6 10 to Control (“Base”) Current Self Closing “mu Valve Control Base -w-,-1| ■- t Collector Current Rb p Drain Cpi — Rpi (jQ T L (hx hfe Exit ( Emitter”) Emitter

Figure b-9 Transistor water model Figure 6-10 Simplified transistor model

Section Six Semiconductors 97 Collector pointing downwards, the pins are, from left to right, Loitering TO-92 PacKage always emitter-base-collector, or as I remember it. o | ic- jbx I Part u Number “Emitter Before Collector.” 4-> In the schematic symbol shown in Figure 6-11.1 E B C have labeled the current flows in the transistor. In £ Base o "Super Modified” T0-92 simple terms, the amount of current that can pass CJ k_A through the collector to the emitter is the base cur Letterng Part rent multiplied by h The multiplier. h1F, ts often

J T called Beta (or (3) and is specified in the data sheet tp Emitter c : for the transistor. Schematic Symbol C B E To demonstrate the operation of the NFN transis¬ Figure 6-11 NPN transistor symbol with tor. I have come up with the circuit that is shown in parameters Figure 6-12. When there is no current flowing through the left transistor's base, current passes through the lk resistor at its collector and goes to the scare you. As you become more sophisticated in right transistor's base. In this case, the right transistor electronics, this model will be very important to you is turned on and its emitter current turns on its I,E D. and the different parts will be easily recognizable When the left transistor’s base has cuirent passed M and understandable. O to it. the current available at its collector is passed to -P Rather than trying to figure out the best model its LED. In this case, there is no current for the right showing how an NFN transistor works, I am going to (0 transistor's base, so it’s turned off: start otf with no model at all and go straight to its *H If you are familiar with transistors, you might be schematic symbol and different transistor package CO surprised at my choice of the Zetex ZTX649 NPN pinouts with Figure 6 11. a transistors. In many other basic electronics projects cd In Figure 6-11,1 showed the schematic symbol for books, the 2N3904 is used because it is a very inex¬ the transistor wiili the different terminals labeled. pensive and common general purpose transistor. Hie The base corresponds to the control pipe m the previ¬ ZTX649 is somewhat more expensive than the H ous water analog, whereas the collector and emitter 2N3904, but it can handle up to 2 amps of current, correspond to the pipe with the valve. When you are which makes it ideal tor use as a motor driver in looking at the flat side of the transistor with the leads small robots. The transistor has a current amplifica-

No Connection 9-Volt Connection I tO ro -P a

•H M 0 a, Base Current Flow x ui Figure b-12 Two-transistor LED switch operation

98 lEd Robotics Ex peri merits for the Evil Genius Son factor (h,,) of 3(X). which is about twice that of off and 2.2 when the LED was on. You may wonder the 2N.3904. w hy the LED isn’t "slightly” on when it has 1.7 volts After building the circuit, spend some time watch¬ across it, but you have to remember that there isn’t ing the operation of the LEDs and then take out the any current flowing through it For the LFD to light, connection between the left transistor's collector and it must have both a voltage drop as well as current the right transistor’s base and measure the current. flow. I’m pointing this out because this illustrates an When the tight transistor’s LED is on, the current important fact that you will probably forget and have passing to its base is about 6 mA. when it is off, the to rediscover—simply measuring voltages in semi¬ base current is zefp. This should not be surprising conductor cireutts is not always enough to explain because the LED is off. indicating that there is no what is happening. You must always be prepared to current flow measure both the voltage drop anil current through a component to be able to completely know what is You can also look at the voltage ol the l.EDs happening. when (hey are turned on and off. In my circuits. I found a voltage of about 1.7 volts when the LED was

Experiment 36 □riving a Motor with a Transistor

Parts Bin Tool Box Assembled PCB

ZTXS49 NPN transistor Wiring kit

1N4148 or lN9i4 silicon diode

Two C cells with battery clip

Any small toy motor capable of running with voltage inputs of 1.5 to 3 volts

110 () resistor

470 il resistor

Ik. resistor

1 Ck resistor

In the last experiment. I introduced you to the NPN So far, I have described the transistor as just an transistor and discussed some models for its opera¬ NPN transistor—the correct name for the transistor tion. I also gave you a simple formula showing the is the bipolar NPN transistor, and if you were to look relationship between the base current and its collec¬ at the side view of the transistor, you would see, tor current. I also showed how the NPN transistor something like the bar-shaped device with an N-type could be used as a switch, turning one of two LEDs semiconductor at each end and a thin P type semi¬ on In this experiment, I go into more detail about conductor in the middle as in Figure 6-13. the NPN transistor and show how transistors can be When the transistor is turned on, the base current used to control high-current devices like electric draws electrons from the emitter N-type pole, creat¬ motors. ing a conduction region filled with electrons.To

Section Six Semiconductors 99 u o Transistor "Off' -p Depletiori Region1’ a> CO Collector a. Emitter (Positive) N-type N-type (Negative) CO T Positive Base c (No Current) Transistor “On” Negativ m "Depletion Region" Shrinking

M

X! Figure 6 13 NPN transistor operation -P Measuring the 9-volt battery voltage at 8.91 volts •HI and the transistor base to emitter (or ground) volt¬ understand how the transistor works, remember that £ age at 0 79 volts, I found a 8,12-volt drop across the electron flow is the reverse of current flow—as cur¬ 470-ohm baseAmrrent-lifniting resistor and a 17 mA rent is injected into the base,electrons are being u calculated (I measured an actual current of 17.1 drawn from it. o m A) current being injected into the base. Assuming The P-tvpe section of the transistor is very thin ■p that the hFE of the transistor is 300, the current flow and the electrons pulled from the emitter jump to the o ing from the transistor's collector to emitter works collector; these electrons foirn the collector current 2 out to be 5.18 amps. You should immediately recog and the amount of current is based on the amount of nize that the value of 5.18 amps is unreasonable. I electrons being drawn from the base.The larger the m indicated in the previous experiment the ZTX649 base current flow, the larger the collector current ean carry a maximum of 2 amps and, if you look at flow that is possible. As the base current increases in the datasheet for a C alkaline cell, you will see that the bipolar NPN transistor, I he size of the conduction C it can nominally source about 350 mA. Measuring region increases and the collector current has more •H the current drawn by the motor, I found it to be area in which to flow. > about 190 in A. In this experiment. I would like to demonstrate •H Fhe confusion comes from the range where the the operation of the bipolar NPN transistor as a low M transistor is operating. When I have described the current controlled, high-current switch To do this, I Q operation of the transistor, 1 have been doing so in will use the simple circuit shown in Figure 6-14.1 the “linear small signal operating range” as I show in used a 470 U base-current-limiting resistor, but when Figure 6-15. When a large current drain device (like I you test out the function of the circuit, I would like VD you to vary the base resistor using each of the resis¬ tors listed in the Toolbox. Coliector PO Current When 1 ran my tests using an old toy motor, I -P tound that the 47011 base-current limiting resistor C ran tire motor most efficiently. When I put in the larger values for the base-current-limiting resistor, 1 0) S found that the motor would run much slower (with •H less torque) or not at all. \\ hen I put in a 100-ohm base current-limiting resistor I could not detect any U Base difference in motor operation with it or with the 470- CD Current ohm resistor. Thus, I found empirically that the 470- 04 X ohm resistor was the optimum choice tor the motor Figure 6-15 NPN transistor base to collector W that I used. current flow relationship

100 103 Robotics Experiments f or the Evil Oenius Experiment 36 — Driving a Motor with Transistor the motor) is being controlled by the transistor, its operation has moved out of the small signal range and into a nonlinear range (or “saturation region”) where the operation of the transistor cannot be pre¬ dicted as easily. Most simulation tools have the ability to correctly model the operation of a transistor out¬ side of the small signal operating range, but for driv¬ ing small motors. I recommend following (he path that I have used here test out a number of different base-eurrent-limiting resistors until you find the one that seems optimal for your application. When the motor is turned on and off (or even Figure 6-16 transistor motor control waveforms when its armature turns and a new coil is energized), a large induced voltage (called kickback) causes The upper oscilloscope trace is the collector volt¬ noise in your circuit. If you go back to the original age with no diode, showing tip to +/-10 volts of schematic diagram (Figure 6-14). you will sec that I kickback.The lower trace shows the same voltage, suggest that you measure the voltage between the but w ith the diode in place the noise output has transistor’s collector and emitter. With the motor run¬ been reduced to less than +/-5 volts. Hie diode pro¬ ning, I suggest lhat you do this both with the diode in vides this noise filtering by “breaking down” when a place and the diode removed. When I did this. I found large voltage is applied to it. As I described the tran¬ that the collector/emitter voltage was a very constant sistor behaving unexpectedly at extreme conditions 0.030 volts, with if varying by a millivolt. When I so does the diode when a high voltage is applied to it. removed the diode, 1 found that the voltage stayed At some voltage the diode's operation stops and n around 0.030 volts, but varied by as much as 10 milli becomes like a short circuit, shunting current within it volts. To try and confirm what I saw, I took a look rather than passing it back to other parts in the appli¬ with my oscilloscope at the collector voltage (the cation circuit When you arc building any magnetic emitter voltage was "Ground” for the measurement) device contiol application, you should always put in with the diode m place and with it removed. Figure the kickback diodes to protect (he other parts of the 6-16 is an oscilloscope picture of w hat I saw. circuit

Section Six Semiconductors 101 Experiment 37 — Bipolar PNP Transistor Motor Control source (provide)currentratherthansink. grated circuitsIwhichmeanslowcost),high-speed all situations,particularlywhenaswitchisneededto operation, andgoodcurrent-handlingCapability. transistor includeitseaseofmanufactureoninte¬ section.The reasonsforthepopularityofNPN symbol forthePNPtransistorissimilartothatof the NPNtransistorasyoucanseeinFigure6-17.The NPN transistorandhasmanyofthesamefeaturesas for basictransistorlogic,asIwillshowyouinalater many differentelectroniccircuits,anditisthebasis flows arcintheoppositedirectionasNPN.The NPN transistor,butinthePNPcurrent Unfortunately, theNPNtransistorcannotbeusedin exactly thesamewayasNPNtransistor’scollec¬ labeled identicallytotheNPNtransistor’spins,and tor current.Finally,thePNPtransistor'spinsarc PNP transistor'scollectorcurrentiscalculatedin lTie bipolarNPNtransistorisanexcellenttoolfor NPN transistor. they areorientatedinexactlythesamewayas drawn fromthebase,which injects electronsintothe 102 trons arepassedtothetransistor’s collector,with N-type semiconductorofthe transistor.Theseelec¬ some jumpingfromtheemitter’s P-typesemiconduc¬ The PNPtransistorisusedtocomplementthe When thePNPtransistoristurnedon.current 12 3 Robotics Experiments for the EvilGenius Bipolar PNPTransistorMotorControl Assembled PCB Any smalltoymotorcap¬ Two Ccellswrthbattery ZTX749 PNPtransistor Ik resistor 470 !)resistor100k 1N414B orIN911!silicon 110 12resistor10k voltage inputsof15 diode able ofrunningwith clip resistor resistor to 3volts Experiment 37 tor, mthisexperimentIwillcreateasimilarcircuitas normally hasthesameh,.,.asNPNtransistor. the PNPtransistorcollectorcurrentmultiplieris multiple ofthebasecurrent.LikeNPNtransistor, the currentpassedtotiansistor'scollector. tor, Theelectronscomingfromtheemittermakeup parameters transistor ismanufacturedforanNPNtransistor,it known ashr[;orBetaWhenacomplementaryPNP the currentcollectoriscapableofpassinga turned offifthereisnocurrentflowatthebaseand Figure 6-17PSPtransistor symbolwith To demonstratetheoperationofPNPIransis- Like theNPNtransistor,PNPtransistoris Schematic. Symbol Wiring kit PMM Experiment 37 — Bipolar PNP Transistor Motor Control

in the previous experiment, with a PNP transistor that is the complement to the NPN transistor used in the prev ious experiment. In the schematic diagram (Figure 6-18), you can see that I have reversed the position of the transistor within the circuit. To turn on the transistor, instead of connecting the base to a cur¬ rent source (the 9-volt battery in the original circuit), it has to bo connected to a ground source. You will probably notice that it is quite a bit differ¬ ent from the previous experiment, even though it looks similar. It is a good idea to take out all the com ponents out of the breadboard front the previous application and start over rather than trying to mod¬ ify the previous circuit. Although they are similar, some components are in different locations, and it For this reason and the increased difficulty in manu¬ can be a real pain trying to find the mistake. facturing them on integrated circuits, PNP transistors are not as prevalent as NPN transistors in electronics. Like in the previous experiment, you should try PNP transistors are very useful in some applications, the different resistors until you find one that the and in the next experiment, I will be demonstrating motor will run most efficiently. For the motor that I how PNP and NPN transistors can be used togelhei used, the motor ran quite well with the 47011 resistor to create a bidirectional drive for the DC motors that I found was best with the ZTX649 NPN transis¬ tor. I did experiment with other resistors and found Before leaving this experiment, note that I have that the best speed and most torque were produced included a kickback diode in this circuit.The motor by a 220 11 resistor, which may be a bit surprising will pioduce the same large transients under PNP because the ZTX749 is supposed to be the comple¬ transistor control as it will for NPN transistor control, ment of the ZTX649. The difference is that 1 have connected the diode to ground rather than to the current supply, as I did in PNP transistors are not as efficient as NPNs. Ihis the previous experiment. is due to the greater resistance ot P type silicon and the slower speed at which electrons pass through it.

Section Six Semiconductors 103 Experiment 33 — Transistor Motor H-Bridge ferential drivemeansthatyoumusthaveamethodot formats thatcanbeusedtobuildrobots,finallycon¬ drive amotor.Intheseexperiments,Ihaveshown along withshowingyouhowtheycanbeusedto part ofthemotoroperatingspeedcontrol,andare the motorsisabettersolutionastheycostless,canbe have seenanumberofdesignsontheInternetthat running !hemotorsbothforwardandbackward.I kind ofsteeringgear—eachmotorwouldbeusedto cluding thatthedifferentiallydrivenchassiswas how theycanbeusedtocontrolelectricmotorsfor how theNPNtransistorcanbeusedasaswitch, introduced youtotheNPNandPNPtransistors much moreiubust. motors, but1believethatusingtransistorstodrive use relaystocontroladifferentiallydrivenrobot's drive and(urntherobot.Creatingarobotwithdif¬ most efficientbecauseitavoidedtheneedforany robots. Inthefirstsection.1discusseddifferent 1 haveintroducedtransistorsinthissectiontoshow current throughamotorandlettingitrunThePNP pulling asignaltogroundand,bydoingthis,sinking combining thetwot\pesof transistors, youcancreate transistor cansouicecurrent,andinthiscapacity,itis well suitedlorprovidingcurrenttodriveamotorBy forward orbackward. a motordriverihatcanmake aDC'motorturneither 104 Any smalltoymotorcapableolrunning In thepreviousexperimentsinthissection.1have Two 1)cresistors Two 100(1resistors Two Ccellswithbatteryclip with voltageinputsof15to3volts IE3 Robotics Experiments fortheEvil Genius Bin Assembled, PCB Four 1N4148or1N914 Four ZTXS49NPN Two ZTX/49PNP t ransistors transistors silicon diodes Transistor MotorH-Bridge Experiment 38 6-19 isthatcurrentcouldbe drawnfromthePNP requires currenttobeinjected intothebase. be drawnfromitsbase,whereastheNPNtransistor on differently.ThePNPtransistorrequirescurrentto can neverbedrivenbecausethetwotransistorsturn switches onthesamesideareclosed,thenadirect motor driver,inwhichfourswitchescanbeusedto transistor’s baseandbepassed totheNPN transistors ononesideoftheH-Bridgedrivercircuit you cancontrolthedirectionofmotor.Theresult¬ rent-limiting resistor.Byonlyusingtwodigitaldrivers, tors together,asinFigure6-19,throughacommoncur¬ are usedforfilteringanykickbackfromthemotor. vide theswitchingfunctions.Thediodesincircuit of somethinglikeFigure6-19.Thiscircuitusestwo ment theH-Bridgeusingtransistors,youmightthink both switchesonthesamesidewillneverbeclosed. software thatyoucomeupwititmustensure ground. Ideally,theH-Bridgecontrolcircuitryand path existsbetweenthemotor’spowersupplyand easy, althoughonethingtowatchforisthatifboth motor. C'reatingthedrivercircuitforthisisquite control thedirectioncurrentflowsthrough ing circuitlookstobesimple,anditappearsthatboth pairs ofmatchedNPNandPNPtransistorsthatpro¬ A verylargeproblemwiththe circuitinFigure You mightconsidertyingthebasesoftransis¬ I havealreadyintroducedyoutotheH-BridgeDC' If youhavebeenthinkingabouthowtoimple Experiment 38 — Transistor Motor H~Br i d ge 9V 3V 3V I_ 100 ^ 100 ' 9-Volt : 9-Vol! [ZTX749 Vv'v CZTX749 2 1N4148 Battery i 1N4148 X ZTX749 - Battery .•AAAjj d f » 1 — • --- rfMfttnrll i J «—TZTX649 1 ZTX 64 9 LZTX649 ZTX649*} 1N4148 X X 1N4148 X

_LT- 3V Forwards Backwards Ik Control Control Ik a a a_ connectConnect ^onnecrConnect a a a 2xAA - 2x C To drive motor, drive connection to 9V to Turn to 9V to Turn. * H=r Battery ’ Battery Motor Motor - ... Pack on one side nigh and one low ■ Pack Forwards Backwards

Figure 6-19 Obvious H-Bridge transistor motor Figure 6-20 H-Bridge transistor motor control control

circuit shown in Figure 6-20. It is the one that I used transistor’s base. In this case, both of the transistors for this experiment. would be turned on.To make matters worse, this can Ibis circuit provides two terminals that arc used to be a self-perpetuating and amplifying problem; as select in which direction the motor turns. Figure 6-21 more current passes through the transistors, more shows current flowing in the circuit depending on current is available for the bases, which increases the which terminal has voltage applied to it. Ibe only current again, t his process can repeat until the tran¬ drawback to this 11 Bridge is if both motor control sistors or the power supply are burned itself out. terminals are driven or pulled high at the same time This is not to say th.it the problem will always II both teiinmals are energized, then the transistor occur In some situations and with some matched switches on both sides will be turned on at the same pairs of PNP and NPN transistors and motor load, it time and you could burn out your power supply will never happen. Hk problem can be ven haid to and/or the transistor switches. Software written for predict, and you may find that different transistor the interface should make sure that only one termi¬ pairs, resistor values and wiring, battery levels, kick nal has power applied to it at the same time. back diodes, and motors will have an effect on Wiring the application is surprisingly easy; the whether or not it will happen. I have been “bitten” by only thing to watch for is the orientation of the tran¬ this problem once, and to make sure that it ucvci sistors as the PNP transistors will be reversed relative happens again, when I design an 11 Bridge, I use the to the NPN transistors.

Motor Running Motor Running forwards Backwards

Left controlling KPS transistor Right controlling NPN transistor turned on; current through turned on. current through motor travels from left to right motor travels from right to left reversing the direction the motor turns in

Figure 6-21 Operation of the li Bridge motor control

Section Six Semiconductors 105 Experiment 38 — Transistor Motor H-Bridge 106 the motorsthatyouaregoingtouse,thenthiscircuit tor values.Ifyouknowtheoperatingparametersof sistors anddiodesmayhavetochangetheresis¬ 300 mA.thenyouwillhavetochoosedifferenttran¬ for awidevarietyofsmallDCmotors.Ityouare going touseitwithmotorsthatrequiremorethan This H-Bridgecircuitisveryreliableandwillwork i E3Robotics Experiments fortheEvil Genius through thetwocontrollingtransistors’bases—asur¬ can beveryeasilymodeledusingSPICE.Thiswilllet prising amountofcurrentcanpassthroughatransis¬ you optimizethecircuitsotransistorsdonotpass tor's base,causinganunexpectedpowerloss. make surethattherearenotexcessivecurrentdrains more thantherequiredcurrent.Itisimportantto Section Seven □ur Friend, the 555 Chip

When I was a teenager, the most popular chip used at you is the Find (firound) at Pin 1 and the Vcc (Posi by hobbyists (and I wouldn t be suiprised if it was five Power) at Pin 8.These two pins are used to provide also the most popular in commercial products of the power for the part. When you work with chips, you will lime) was the 555 timer integrated circuit or chip. Die find that they do require power, and for chips that arc 555 is probably the most versatile nonprogrammable built from bipolar transistors, such as the 555. you will pait I have ever seen Hundreds of projects have always see Vcc and Cmd pins. used this chip in ways I'm sure the original designer Ihis is stepping a bit ahead, but when you look at never would have thought possible; the original func¬ chips that arc built using MOSFLiT transistors, you tion of the chip was to provide a regular train of will find that positive power is provided to the Vdd pulses. In this section. I will introduce you to the 555 pin and Ground is the Vss pin. This is a convention chip and work through some experiments to show that can be confusing: l tend to mentally convert Vdd how the chip is used in a circuit and how it can be to Vcc and Vss to Ground. Despite the difference in used to create a simple robot. the names for power, the convention of numbering In the previous sections, I have shown you the pins in increasing order counterclockwise from Pin 1 "pinout” of a number of different components—each is still true for MOSFET transistor-based chips one of them ha\ing a unique form factor Ihe 555 is To try and get a better understanding of a chip, usually built into a dual in-line package that is com one of the first things I do is look at its block dia¬ monly used for chips. A dual in-line package is nor¬ gram. In Figure 7-2.1 have drawn out the block dia¬ mally reduced to its acronym DIP and used to refer gram for the 555 timer. to chips that have leads that can be pushed into holes L ike the pinout diagram, I m sure that at first for mounting in a circuit In Figure 7-.1.I have put in glance, the 555 block diagram is quite intimidating an overhead view of the 555 along with a photograph (and maybe even a bit “scary").There should be of an actual 555 chip some things you recognize, but l ‘m sure many things This overhead view of the 555 is the pinout of the don’t make any sense to you at all. When I see a chip and you w ill notice that I have labeled the pins starting at the top left pin, which is indicated by small circle on the chip. Along with this circle, many DIPs have a semicircle molded into the Pin 1 end of the chip Depending on the manufacturer and the part, you may have the small circle or the semicircle or both. Once you have identified Pin 1 on the chip, the pins going in a counterclockwise manner are given increasing pin numbers as I have shown in the figure. This convention is used by all DIPs. regardless of the size, and you will see more of it as I introduce you to different parts in this book. I .ooking at the for each of the pins, most of them do not make a lot of sense What should jump out Figure 7-1 Pinout of555 chip

107 Section Seven — Our Friend, the 555 Chi & 2/3 Vee,ilcannowbeanyvalue(lessthanVcc)that Threshold changes Vtrigto1/2Vcontrol. voltage dividercircuitRatherthanVcontrolbeing circuit designettochangethevoltagelevelsof clue astohowthechipworks. 7-3 IfyouweretoworkoutthevoltagesatVcontrol tations forcomparators,andasIhaveshownmFig¬ a funny-lookingequation.Theseboxesarerepresen¬ to twotriangularboxeswitha“+"andalong the designerwouldlike.ChangingVcontrolalso pin calledControlVoltage.Thisconnectionallowsthe you mayfindconfusingisitsconnectiontoanoutside and 1/3Vee,respectively.Thisisactuallyanimportant and Vtrig,youwoulddiscoverthattheyareat2/3Vcc gram rightoffthebat.Thefirstistransistorat chip forthefirsttime,Ifeelsameway,buttry Discharge block diagramthat1haveseparatedoutintoFigure voltage dividertunningalongtheleftsideof rent toground bottom middleofthediagram.Ihistransistorlooks when thevoltageat“+” inputisgreaterthanthe ure 7-4,thecomparatorsoutputahighvoltagelevel like itiswiredsimilarlytothewaywaswhen know and figureouthowthechipworksfromwhat1do 108 parators tocontinuouslycompare twoexternalvolt¬ voltage atthe"input.The 555 usesthetwocom¬ the transistorisactingasaswitchthatwillsinkcur the motorwascontrolledinprevioussection— Figure 7-2555blockdiagram results toaboxlabeledRSFlip Flop age levelstoVcontrolandVtrig andpassesthe Trigger Voltage Control ()ne apeetofthe555’svoltagedividercircuitthat You shouldrecognizetwopartstotheblockdia¬ ITie voltagesattheVcontrolandVtrigarepassed Hie nextpiecethatyoushouldrecognizeisthe 2 5 6 7- 1 -Gnd 1E3 Robotics Experiments fortheEvil Genius RS FlipFlop “?c=r S Q R O A Reset Trigger When<1/3Vcc. Threshold: When>2/3Vcc. Output High Output Low Discharge TransistorOff Discharge TransistorOn ^ Output voltage, thentheflipflopwill outputahighvoltageat 555 andVcontrolofthevoltage divideroutpulahigh which comparatorlastpassed ahighvoltagetoit.If whichever coilwaslastenergized. the comparatorconnectedto theThresholdpinof tion asthisrelay-baseddevice.Inthe555itsaves wiper thatwillstayinthelastpositionsetby sists oltworelaycoilslaidouthorizontallywitha it asthetwo-coilrelay(Figure7-5).Thedevicecon¬ of thebook,butfornow,Iwouldlikeyoutothink Figure 7-3555voltagedivider Figure 7MComparatoroperation O. whichturnsonthetransistor atthebottomof Voltage Control The 555’sRSFlipFlopperformsthesamefunc¬ I willexplainhowflipflopsworkinalatersection Vcc Vtrig =1/3Vcc Vcontrol =2/3Vcc Vpower The last component that will be new to you is the Experiment 39 — Blinking LEDs triangle with a ball at the end on the lower right-hand 1 Saved High/Low part of Ihe block diagram (Figure 7-2).This compo¬ Voltage nent is known as an inverting buffer and converts a i high input value to a low output and vice versa. Ibis is a fairly complete explanation of how the Figure 7-5 Two-coil relay memory element used 555 works, and I’m sure that you arc at least as con¬ as a simple R-S flip flop fused as you were when 1 first showed you the block diagram ot the chip The individual parts are quite block diagram If the other comparator passes a high easy to understand, but I'm sure you’re mystified as voltage to the RS Flip/Flop, then the voltage at O is to how they work together To fully understand how driven low and the transistor is turned off. the 555 chip works, there is a new type of component that I will introduce you to in the next experiment.

Experiment 39 Blinking LEDs

Assembled PCB

555 timer -hip in 8-pin DIP package

LLD, any color

470-!! resistor

R1 = 33k. resistor

R2 = lOCk potentiometer

0.01 jj.F capacitor, any t yFe

10 jjlF 35-volt elec¬ trolytic capacitor

When I described the operation of the 555 chip. I symbol (Figure 7-6). Figure 7-7 shows different neglected to take into account the components that capacitor packages and the indications that they are would be wired to it. So tar in the book I have intro¬ polarized. duced you to resistors, diodes, and transistors, but I Capacitors store electrical charge, which is meas¬ have not introduced you to any components that are ured in farads. One farad is an extremely large designed to store energy. Resistors, diodes and tran¬ charge It has only been in the last few years that sistors can all change the voltage and current of an capacitors have been created that can store a farad or electrical signal, but they cannot store any energy more; most capacitors store charges in the ranges of from it. millionths or frijlionths of a farad. Capacitors that One of the two most basic electronic devices that store charge in the range of millionths ot a farad are can store energy is the capacitor. Capacitors consist rated in microfarads (pi-) and charges of trillionths of of two metal plates that store energy as an electrical farads are rated in picofarads (pF). Engineers and charge and have the schematic reference “C.” 1 he technicians often refer to microfarads as “mikes” and plates are represented in the capacitor’s schematic picofarads as “puffs.”

Section Seven Our Friend-, the 555 Chip 1C 9 Experiment 39 — Blinking LEDs In somereferences,theSymbolis. number toindicatetheirvalue.Thisvalueissimilar ceramic orelectrolyticcapacitors.Ceramiccapaci¬ digit istheexponentof10withbasebeingin two digitsarethemantissaofvalueandthird to thevaluespecifiedbyaresistor’sbands;tirst voltage Theyaretypicallymarkedwithathree-digit the circuitsaredesignedusingeitherstandard but doesnotletthetwoplatestouch.Inthisbook, picofarads. Forexample,ifyouhuda330pFcapaci¬ tors arcnotpolarizedanddohaveanyrated enhances theamountotchargeplatescanhold two metalplatesseparatedbyadielectricthat manufacture capacitors.Allcapacitorsarebuiltfrom tor, itwouldbemarkedwith 331.Ceramiccapacitors 110 are typicallyavailableinthe rangeofpFsto0.1jliF. Figure 7-7Capacitorappearanceandmarkings plates).They areusuallybuilt inmetalcanswith Electrolytic capacitorsarepolarized andusealiquid Figure 7-6Capacitorsymbol as thedielectric(theinsulator betweenthetwometal (Ceramic Disk Unpolarized or ) Value Stamp (See Text) A numberofdifferenttechnologiesareusedto Capacitor 153 Robotics Experiments for the EvilGenius (Polarized) Tantalum — Indicator + --Polarity + •* Compent Reference Designator ="C" Polarity Indicator Electrolytic (Polarized) ^Cathode) Negalive * Lead Water InOut The productotthevalueofresistorandcapacitor (cathode) indicatorandrangefrom1mFtoseveral constant andisgivenIheGreekletterTau(tJasits water goesupthetower,savingilforlater. night, whenthepump'scapacityexceedsdemand, from ihetowerisaddedtothesupplybygravity.At tower, liketheoneinFigure78,isused.Ifithot excess isbeingpumped.Tohelpthesystem,awater exceeds thecapacityofsystem,orusersdon’tuse tower inacitywatersystem.Normally,is greater itsprice. dielectric. Themoreexoticthedielectric,smaller their valuestampedalongwiththenegativelead change moreslowlythanifitweren'tinplaceatall. and manypeoplearewateringtheirlawns,thenwater very much(suchaswhentheyaresleeping),andan pumped intohomes,butsometimesthedemand the capacitoris.morechargeitcanhold,and tantalum solution,oranelectrolyticsolutionforthe the dielectric,moreexoticdevicesusepolyester,a farads. Basiccapacitorsuseaceramicmaterialfor has avalueof“seconds"andisknownastheRCtime make aresistor-capacitor(orRC)network,asIshow O Volts- in Figure7-9,thevoltageaerosscapacitorwill Figure 79Operationof an RCnetwork Figure 7-8Watertowercapacitoranalogy Input Signal When usedwithacurrent-limitingresistorto A capacitorperforinsthesamefunctionasawater Water Level Pressure Due toInput Output -Vccxe’ W— R . Output=Vccxet/RCSignal Gravity _Across Output Sgnal ■ InputSignal (Voltage Capacitor) symbol.The RC delay is used bv the 555 ehip (and its Experiment 39 — Blinking LEDs built in comparators) to "time" an operation before proceeding. To demonstrate how the RC' network is used with the 555 timer chip to produce a repeating signal, I would like you to build the circuit shown in Figure 7-10. When tliis circuit starts running, the 555 will be an tistable” oscillator w ith the LED Hashing on and off at about once per second. You can change this rate by adjusting the 100k potentiometer that is wired as R? Figure 7-10 555 oscillator circuit As resistance decreases, the LEL) will flash faster and for a shorter period of time. The time the LED is on

(555 output high) is found by the following equation: Vcc

Th.sh = 0.693 x C x (R1 * R2)

= 0.693 x 30 uF x (33k + Rpot)

The time for the LED off is found by using the formula:

Tlow = 0.693 X C X R2

= 0.693 X 1C pF x Rpct

The 0.01 mF capacitor wired to the control voltage Figure 7-11 Electrical signals within the 555 chip pin of the 555 is used as a filter tor the internal volt¬ ages. TTiis capacitor works very similarly to the “water so you can see the changing RC waveform, the out¬ lower;” if the input voltage changes, the capacitor w ill put from the two comparators, and the action of the absoib or release charge to keep the voltage as even RS Flip Flop. as possible. I have covered a lot of material here; don't worry To gel a better idea of how the 555 timer w'orks as if you don't understand everything. Just accept that an oscillator, the following values arc labeled in Fig¬ capaeitois are used to filter out fluctuations in volt¬ ure 7 10: the RC voltage (A), the RS Flip Flop output ages or are used with resistors to delay the time it (R, which is in the inverted 555 output), the “ thresh¬ takes for a voltage output to reach the input level. old” Comparator voltage (C), and the “Trigger" Flow all this works will become clearer as you comparator voltage (D). Figure 7-11 shows the wave¬ go on. forms lor each of these parts marked in Figure 7 10.

Section Seven Our Friendi the 55 5 Chip 111 Experiment 40 555 Button Debounce

Tool Box Assembled PCB Wiring kit

555 timer chip

LED, any color

470-11 resistor

0 R = lOCk resistor o 10k resistor a 0.01 pF capacitor, any type 2 10 |iF 35-volt elec¬ o trolytic capacitor

0 In the previous experiment, along with introducing tor connected to the input pin of the 555 is known as a Q you to the 555 astable oscillator, I have also shown “pull-up'' and it is connected to a button that, when yon a capacitor for the first time. If I were to summa¬ pressed, will connect this line down to ground Tltc rize the important points of the previous experiment, resistor limits the amount of current flow passing G thev would he the following: from the power source to ground and is called a cur¬ O rent-limiting resistor, like a resistor used with an LED. • C Capacitors store charge. -P Die button circuit is actually a small part of Figure -P • Used with a resistor, capacitors can be used to 7-12: most ot the diagram is taken up with an oscillo¬ delay electrical signals. 2 scope picture showing the voltage signal being passed PP • The 555 can oscillate, creating a repeating sig¬ to the input circuit. When a switch closes, the contacts nal with parameters defined by simple formu¬ within the switch do not simply touch and stay IT) las. together: they actually bounce off each other a tew IT) times, resulting in the spiky contact. It this waveform to What I did not note in the previous experiment is is passed to a circuit, it probably would be registered that the resistor and capacitor values used with the as multiple button (tresses because each bounce 555 should be within the following ranges toi stable would be treated as a unique button press. and reliable operation:

10k < n < 14M O

Another basic circuit the 555 is used for is the ■P monostable. In the previous experiment, 1 introduced C you to the astable oscillator, which will run forever: 0 the monostable will only execute once and requires 6 tnggenng. I'm willing to bet that after reading the •H previous sentence, you can think of applications M where an astable oscillator is useiul, but not the 0 monostable. Actually, the monostable is very useful a* for a variety of different applications. x The. typical circuit for a button and its operation is W shown in Figure 7-12. In tins configuration, the resis- Figure 7-12 Oscilloscope picture of a switch bounce

112 123 Robotics Experiments for the Evil Genius By using the 555 timer as a monostable, the Note that in Figure 7-14,1 have drawn the wave¬ Experiment 40 — 555 Button Debounce “bounce” produced by the circuit could be ignored forms bouncing on the switch opening (line A going and a single button press would be registered in the to a high voltage again) When a switch opens, it application. lTie circuit shown in F igure 7 13 shows bounces just like w hen it closed. Secondly, I indicated how the 555 timer will debounce a button input and that the switch is released before the capacitor turn on an l FD for a second each time the button is charges to 2/3 Vcc; when you build the circuit,you pressed. will want to see what happens if you hold the button When the button switch is closed, the pulse output closed longei than the 1 second that the l.F.D i« on. from the 555 timer is determined using the following In the figure, the capacitor does not discharge formula; through the transistor instantly: it has the same expo¬ nential waveform (although much shorter) as the original charging waveform. 1 put in this waveform to indicate that the transistor has a very low resistance, = 1.1 x 100k x 10 pF = 1.1 seconds and it behaves as if a resistor were connecting the capacitor to ground. I’ve “opened up’ the 555 in Figure 7-13. as I did in the previous experiment, with a waveform (Figure 7- One question that you will ha\e is how the button is 14) showing what happens on a button press. implemented. For this experiment (and others that require a button input), I soldered a couple of 22 gauge The 555’s RS Flip Flop is initially reset, and the solid core w ires to a button and covered them in five- transistor that passes capacitor' charge to ground is minute epoxy for strain relict as I show in Figure 7-15. turned on. When the button (A) is pressed and the “Trigger" input receives a low voltage input, its com¬ parator signal (F) goes high, changing the state of the -"Tl illl Button Press ? Li j Button Release RS Flip Flop (C) (and turning on the LED). When the RS Flip Flop Mate changes, the transistor is © \_ turned off and the capacitor charges through the resistor. 'The capacitor charges according to the fol¬ © Debounce Pulse { lowing formula until its voltage reaches 2/3 Vcc. Width = 1.1 x RC . ©

Output = Vcc - Vcc X e :/RC

' First Bounce of * Capacitor When it reaches 2/3 Vcc. the Threshold comparator Switch Starting Charged Capacitor Charging t0 2/3 Vcc (D) goes high and the RS Flip Flop changes state again, tuining off the LED and turning on the transis¬ Figure 7-1M 555 button debounce operation tor that shorts the capacitor to ground, returning the waveforms 555 and the circuit to its original slate.

- 9 -Vott p Battery

LCD

Figure 7-15 Momentary push button with wires Figure 7-13 555 button debottn# circuit soldered to it for wiring to a breadboard

Section Seven Our Friend i the SSS Chip 113 w m X riment 41 — R/C Servo Control on. butitwillappearto“wink”offperiodically.When servos (Figure716)aieexcellentdeviceslorusingin show howyoucanusethe555tolestandcommand of themusearadiocontrol(R/C)servoforturning the capacitorchargesto2/3Vccandbuttonis the circuit.Ifyouholdbuttondownformore is calculatedfortheresistorandcapacitorchosentor surprises untilyouholdthebuttondownlorlonger as yourrobot'sdrivetrain.Inthisexperiment.Iwill and withalittlebitofmodification,theycanbeused robots; theyareinexpensiveandpowerfulactuators, wheels ormovingarmsactuatinggrippers.R/C than asecond,youwillfindthattheLEDstay Hutton willturnontheIKIDforsecondorsothat than asecond.Quicklypressingandreleasingthe robots, youwillprobablyknowthatalargenumber It youhavelookedatanumberofhobbyist-built sists ofasmallplasticboxwith acontrol/poweicable R/C servos. centimeters] long andabout0.8inches[2 centime¬ 114 small vi/e(standardservosare about1.5inches[4 move thecontrolsurfacesof amodel.Despite(heir i unningfromitandanylon arm thatcanbeusedto Trying outtbecircuitshouldnotyieldtoomany As youcanseeinFigure7-16theR/Cservocon¬ 123 Robotics Experiments f othe Evil(lenius Assembled PCB R/C servo Two 0.01|iFcapacitor, Three 100kresistor 2.7M resistor(madefrom Four AAbatteries Servo connector(built Four AAbatteryclip 555 timerchipin14-pin 100k pot. DIP package as Specifiedintext.) any type 2.7V. ft470kresistors) R/C ServoControl Experiment 41 condition fortheRSFlipFlopandoutputfrom 555 islongerthantheexpectedinput. that thelengthoftimeforpulseoutputfrom avoid thisbehavior.youshouldalwaysmakesure tor tyingthecapacitortogroundperiodically.To the FlipPlopisindeterminate,resultingintransis¬ high voltagetotheRSFlipFlop.Thisisaninvalid held down,bothofthecomparatorswillbedrivinga or moreofforce.The\comeinallshapesandsizes for differentapplications.Fortherobotspresentedin ters] deep),servoscanprovide?pounds(1kilogram) Figure 7-16 Hobbyist radiocontrol(R/C) servo Tool Box this book, 1 will be using either standard, low- cost, Experiment 41 — R/C Servo Control general purpose R/C servos, which can be found for less than $10 at large hobby retailers, or “nano” ser¬ vos, w hich cost about $20. R/C servos require a 4.5- to 6-volt power source and generally use between 150 to 300 mA of current when the motor is running. The R/C' ser\o uses a standard three-pin connec¬ tor that is shown with an adapter you will have to make. The three pins are a control signal. Vcc, and Gnd. and if you look at most servos, the cable leading Figurp 7-17 Servo PWM waveform up to this connector consists of w hite (or yellow), red. and black wires.respectively,so that you can identify the purpose of the wires easily.The R/C servo adapter is made from two pieces of three conductor 0.100-inch breakaway header pins that are the "mate” to the sockets soldered to the IT B like you did with the earlier stepper motor experiment. To make the adapter I soldered the short ends of two connector pieces together. When you are building the connectors. I recommend that you get your energy up and build as many of them as you can stand.These connectors are very useful and very easy to lose. For the majority of nonrobot experiments, I have specified the 9-volt battery that is built into the PCB that came with the book. For this experiment and other ones that use an R/C servo or DC motor. I am tor’s output is amplified bv the R/C servo’s “Motor going to specify that you use 4 A A cells. Driver” and the motor turns the arm in the appropri¬ Fhc control signal used to specify the position of ate direction. When the aim is in the same position as the R/C servo’s control arm consists of a 1 to 2 msec specified by the control signal pulses, then the com¬ pulse. When the control signal is a I msec pulse, the parator’s output is zero and the motor doesn't move. arm is at one extreme, a 2 msec pulse moves the arm Looking at what 1 have written here and thinking to the other extreme, and pulses between 1 and 2 back to the two previous experiments,you should be msecs move to a point in between these pulses thinking that the 555 timer is ideally suited to driving should be repeated once every 2d msecs, although if an R/C servo. In the first experiment in this section, no pulses are passed to the servo, the arm will stay at the 555 was used as an astable oscillator, driving a its current position (although it will not offer any repeated negative pulse. In the second experiment, resistance if you w*ere to try and move it). Figure 7 17 the 555 was used as a monostable to output a positive shows an R/C servo control waveform. pulse from a negative input, It should be simple to Figure 7 18 shows you what you get for less ihan wire two 555s, one as an astable oscillator and one as $10. The servo itself consists of a gear-reduced motor a monosiable oscillator, to create a series of pulses that is driving the control arm. the control arm is for the 555.1 would agree with you on all the points mechanically connected to a potentiometer wired as except one, instead of using two 555s. how about a voltage divider. Ihe voltage output from the poten¬ using one 556? tiometer voltage divider is compared against a volt¬ The 556 chip (Figure 7-19) consists ot two 555 age proportional to the length of the incoming oscillators built together. ITns 14 pin chip provides control signal pulse. If the position of the arm is dif¬ the same function as two 555s (one on each side) and ferent than that of the control signal, the compara¬ is ideally suited toi this application. In Figure 7-20.

Section Seven Our Fr iend n the 55 5 Chip 115 Experiment 41 — R/C Servo Control calculated resistorandcapacitorvaluesforasignal not belongerthantheservooperatingpulse(which this timingtomakesurethatthe“low”periodwould that is19.4msecs"high’'and700“low.”Ichose triggered bytheleft555’sastableoscillator. an astableoscillatorandtherightasamonostable you cansee.thatIhavewiredthelefthandcircuitas F iyuie730556■basedservocontrol/testcircuit 116 For theastableoscillatorportionofthiscircuit,I 123 Robotics Experiments for the EvilGenius -Battery —— 4x"AA” delay circuitusingthe100kresistorandpot.’Ihe for theR/Cservo.Icreatedal.lmsecto2.2 out ofa2.2Mresistorand470kresistor.Forthe the previousexperiment).I‘'made"a2.7\1resistor is thesameasholdingbuttondowntoolongin repeats every20msecs. Figure 7-21showsthe1to2mseccontrolpulsethat without anyproblems.Theoscilloscopepicturein timing isslightlyoutofspecification,butyouwillfind monostable oscillatorthatprovidesthecontrolsignal that mostservoswillexecutesignalsinthisrange servo Figure 731Waveformsproduced by556forR/C S) (Scope1.CH15VmS astable output 20 msecperiod V, Sms, 1 uL _,j monostable pulse 1 -2mseclength Experiment 42 — Light-Seeking Robot Experiment 42 Light-Seeking Robot

Parte Bin Tool Box Wiring kit Assembled book PCB Screwdriver Plywood base with DC motet s

556 dua) 5.55 timer chip

Two 21X7*9 PNP transis

Two 0.01 pF capacitors, any type

Two 1,000 pF, 16-volt, electrolytic capacitor

Four 100 !!, l/q-watt resistors

Two 10k, light-depiendant. resistors (CDS cells)

You now have all the information that you need to the robot toward the light source found by the light- build a very simple robot In this experiment, I will dependent resistors (I.DRs). show you how to create a robot that will follow a The light sensors used in the robot are I.DRs that light beam. Ihis robot is very similar to the first light- are made out of cadmium sulfide and are often seeking robot (the “turtle”) created by Dr. Walter referred to as CDS cells. As the amount of light that Grey in the early 1950s. Hie 555 timer provides the falls on the LDRs increases, their resistance drops. control signals for the robot's motors, replacing the For this experiment, I used LDRs that have a resist¬ vacuum tubes used by Dr. Grey, ance of 10k and can fall to as little as 2k when they This robot will use the P( B that comes with the are exposed to a bright light. book,combined with the DC motor base that you The robot presented in this experiment uses this built earlier, and will look something like Figure 7-22. characteristic of 1 .DRs to vary the resistance time In Figure 7-22 1 have labeled some of the most based signal used with 555 that controls the robot important parts of the robot,The wheels are pulling motors. In Figure 7-23,1 have shown the block dia gram of how the 555 is used as an astable oscillator to produce the time-based signals used by the robot. L Empty 9-Volt The I DR, along with a fixed resistor and capaci¬ Niyht LDR Battery Clip tor. is used to produce a series ol low-voltage pulses that are used to turn on a PNP transistor to periodi¬ cally provide current to a DC motor. When I am \ »» * planning to use a 555 timer (or really any time-based signal). I like to draw out the most important parts of the circuit and the expected signals so that I can eas¬ t 0C0 F Capacitors ily visualize what is supposeJ to happen in the circuit, Bahery Pack and hopefully see problems before they become an Left Dnvetrain issue. Left LOR In Figure 7-23. the downward pointing arrow on Figure 7-22 555 robot the left-hand side of the drawing is used to indicate

Section Seven Our Friendi the Sfii Chip rrrTT-r-t-r,TTrrrr ^ o Light 3 § ®! Sensor O o LDP 4 o j i "f- i . Left Motor Pulse Stream 555 555 Output (Nothing over LDR) 1 ; Timer Signal go r Element r* O i i— ° 2. — , 3 Motor 4 Connection Right Motor Poise Stream (Hand over Left LDR) 4 V SO* mS hiftwrig?'* y. *teigs.4. Figure 7-23 Block diagram for robot light -p Figure 7-2M 556 outputs to robot motor driver sensor/motor driver o transistors & 0 the resistances that arc used to produce the high volt¬ Although 1 could have used a 555 timer lor this age portion of the signal As I have pointed out 0i circuit, I decided to use a 556 and take advantage of earlier in this section,, the two seiics resistors make the two 555s built into it. llie schematic drawing for tn up the RC network that provides the high to low the circuit is shown in Figure 7-25. delay. Tire upward pointing arrow indicates that just c Ihis circuit is powered just bv the four AA batter the single, fixed resistor produces the low to high ies in the clip attached to the plywood base. Remem¬ delay.litis is a bit of a mnemonic that 1 use to r* ber to make sure you have an on'off switch for the remember how the 555 works, and it also reminds me 0) AA batteries to make sure that the motors don't start that the time the signal is high is always longer than the larger the resistance in the 555’s RC network, the from what you expect. The lighter (red) motor con¬ longer the delay. nection could go to the PNP providing the current, Using the formulas I presented earlier in this sec¬ but in your actual robot, you may have to connect •H tion, the time the output signal is low is going to be one or both of the black motor connections to the about 0.7 seconds, whereas the lime the output signal PNP transistors for the robot to run in the light is high will be anywhere from more than 10 seconds direction to about a second, depending on how much light falls Looking back to Figure 7-22, the robot should on the LI)R Ihe more light that falls on the I I >R appear to be quite simple,but you should keep a few the more low pulses (which turn on the motor) hap¬ things in mind-The first is that the robot wheels pull tN pen in a given period of time, moving the driven side *r the robot they don't push it. The direction of move¬ ot the robot taster. ment for the robot is from the battery clip to the To create the robot, it has two of these circuits, an 4-5 breadboard on the PUB.This wall give the J DRs the LL)R on each side of the robot used to control the best view of anv lights in front of the robot. Second, C motor on the other. As more light falls on one LDR. before assembling the robot, remember to put in (1) the motor on the opposite side is pulsed faster, turning fresh AA batteries. Although it's not difficult to disas¬ the robot toward the I I)R and the light source. Figure £ semble and reassemble the robot, save yourself a few •H 7-24 is an oscilloscope picture of the outputs of the minutes and make sure the batteries are good. two 555 circuits show ing how the pulses going to the The 10k LDRs, 100 H resistors, and 1,000 pF left motor are happening more f requently than to the 0 capacitors with the motors that 1 have used provided right motor, which had my hand over its LDR (which 04 me with a robot that moves at about one inch per is on the right side of the robot). In this case, the robot second toward a light source, just about perfect for X would be turning to the left as it moves forward w this application. When you build this robot, you might

118 Robotics Experiments for the Evil Genius w X V (D H H-

(u ft

K)

tr Figure 7 25 555-busat light-seeking robot circuit H* iq * want to try other values for these components if your seeking robots in more detail later in the book, but ft motors behave strangely or move too quickly and for now, take a look at how the robot works and see if miss the light. you can establish any rules for it. As a last experi¬ 1 When you get the robot running, try it out in a ment for you to try out, see if you can convert the cn normal room as well as a dark room with a flashlight robot into a Yight-avoieiing robot (it’s actually pretty (!) in one corner I w ill discuss the behavior of light simple; just reverse the LED connections to the 556). CD X H* 2 UQ

o tj o c+

Section Seven Our FrLendi the 55 S Chip Section Eight Optoelectronics

One hundred years ago, the most important argu¬ negatively charged electrode (called a cathode) and ment in science was trying to determine what is light- allowed to travel towards a positively charged target The field was divided into two camps—one that sug¬ (the cross in Figure 8-1). Some of the electrons would gested that light was made up of particles, and miss the target and hit the fluorescent material another that was convinced that light was made up of behind the target,causing it to emit light. Ihe waves. Confusing the matter were the discussions electrons that came from the electrode were known regarding what matter actually was. The final deter¬ as cathode rays, which gave rise to the experiment’s mination of w hat light was changed the course of name: the cathode ray , which is the precursor to human history. today's television set and computer displays. This In the early nineteenth century, matter was result confused many researchers because light was thought to consist of goo that was made up of atoms produced by cathode rays, and not by heat, as was the and electrons that were stuck together. No instru¬ accepted way light was produced; the fluorescent ments were capable of discerning the physical charac¬ material gave off light w hile staying cool. One of the teristics of matter, and this idea seemed like a logical theories of the time was that light particles were part way to view how things were made (especially when of the fluorescent material’s atoms and when the you were confronted with a glass of water or a piece cathode rays stiuck the tluoiescenr material’s atoms, of metal).This model wasn't challenged until the dis¬ the light particles were knocked off. covery of materials that fluoresce, or give off light Max Planck, in 1900, suggested that a unit of light when they are struck by energetic particles. (which he called a quanta) could only be ejected from I he energetic particles that were used m these an atom at a set energy level according to the follow¬ experiments were electrons generated in a vacuum in ing formula: a device like the one shown in Figure 8-1. In this device, electrons were allowed to 'boil off a healed. E » hv Section Eight — Optroelectronics cles hitanyofthegoldatoms. with thenucleusofatomsbeingquitesmallandrcla occasionally particlesweredeflectedbythegoldleaf, of Rutherford’sexperimentwasthathelooking lively farapartsothatwhenthealphaparticlebeam that mattermustbemadeupofmostlyemptyspace and itcamebackhityou.”Rutherfordpostulated if youfireda15-inchshellatpieceoftissuepaper the goldleafUndamagedbyalphaparticles,but alpha particles.Whathefoundwasthatnotonly tor evidenceofdamagetothegoldleaffrom Today wcwouldcall‘alphaparticles"heliumatoms, passed throughthegoldfoilonlyafewalphaparti Rutherford latersaid,“Itwasalmostasincredible nium (andotherradioactivematerials).Thepurpose and theyareoneoftheby-productsdecayingura¬ particles wouldblasttheirwaythroughthegold. ventional wisdomofthetimestaledthatalpha barded apieceofgoldfoilwithalphaparticles;con¬ 122 123Robotics ExperimentsfortheEvil Genius these experimentswouldbeexplained.Einstein’s results ofRutherford’sexperiment,inwhichhebom¬ model fortheatomandlightinwhichresultsof get. Theresultsofthisexperiment,alongwiththe passed throughadiffractiongrating. slits.The actualresultisshowninFigure8-2.Light attempt toexplainwhatlightwas.Lightwaspassed ble amountofforceseemedtobeappliedthetar¬ experiments.The firstwaswhenlightshoneona discovered (hatforeachelement,thefrequenciesof to thatofawave,suchaswaveinwater,when and darkspotsappeared,theresultsweresimilar made upofsmallparticles,twobrightspotswould and thenobservedonaplatebehindit.Itlightwere through twonarrowslits(calledadiffractiongrating) particle. became moredifficultaftertheresultsofthreeother appear onthepaperbehindmaterialwith Planck’s theories,seemedtosuggestthatlightwasa black targetinadarkenedarea;smallbutmeasura¬ light outputwereevenmultiplesofhXv. In 1905,AlbertEinsteinproposedinapaper Further addingtotheconsternationwere The experimentshowninfigure8-2wasanother Making thedeterminationotwhatlightwas photovoltaic effect. spectrum thathaswavelengthsfrom0.01millimeters to 100nanometers.Thehumaneyecanseelightin output it. ber ofdifferentdevicesbothreacttolightaswell as quantummechanics)presentedhere.Alongwith incoming lightoroutputitusingthetheories(known used tobuildthem. LEDs, whichyouwereintroducedtoearlier,anum¬ at afrequencythatisdependentonthechemicals with forquiteafewexperiments.LEDsoutputlight appropriate quantumofenergy.Thiswascalledthe to alowerexcitationstate,releasingphotonatthe When anatomreleasedenergy,electronwouldfall not beusedtoincreaseanelectron’sexcitationstate. would notbeabsorbed;likewise,ifithadmore defined byPlanck’sformulamentionedearlier.Ifthe When energywasaddedtotheelectron,itwould the operationofLEDsthatyouhavebeenworking photon didnothavethislevelofenergy,thenit higher potential(orexcitation)state.1hisenergywas absorb aphotonandanelectronwouldjumpto quanta ofenergy.Thisenergywasstoredintheatom energy thanwhatPlank'sformuladictated,itwould atom viaaphoton(histerm)thathadPlanck's theory suggestedthatenergyispassedtoorfroman in theorbitofitselectrons(asshownFigure8-3). grating withtheactualresults Figure 8-2Passinglightthroughadiffraction Optoelectronics aredevicesthateitherprocess Light isconsideredthepartofelectromagnetic Fhc photovoltaiceffectcanbeseenveryclearlyin on Screen Grating Diffraction Behind i_tyi itrdLLtif11 Atom Releasing Atom Absorbing Section Eight — Optroeiectronics Energy as a Energy from a Photon Photon

the range of 400 to 720 nanometers. Wavelengths Table 8-1 Colors and their wavelengths greater than 720 nanometers are in the infrared range, and wavelengths less than 400 nanometers are Color UJayelpngth in the ultraviolet range. The seven basic colors of the Infrared 720+ nni rainbow with (heir wavelengths are listed in Red 610-720 nm Table 8-1. When you are asked what the colors of the rain Orange 580- 610 nm bow are. remember the name “ROY G. B1V,” which Yellow 530-580 nm

is the acronym of the first letters of the visible colors. Green 480- 530 nm

Blue 430-480 nm

Indigo 410-430 nm

Violet 400-410 nm

Section Eight Optoelectronics 123 Experiment 43 — Different Color LEDs tivity andtobetotallyaccurate,itstatesthatnothing relative toanobservercantravelfasterthanlight anything cartravel.Thisispartofthetheoryrela¬ with thephotovoltaiceffect,Einsteinalsopostulated ably notawareof,andthatishowalightwavelength that thespeedoflightisfastestatwhich is relatedtoenergy.Asyouareprobablyaware,along the amountofcurrentpassingthroughthem). to environmentalconditions(includingvariancesin slowing down,itswavelength lengthens.Thisisproba¬ you cannotmakeitgofaster? Theansweristhatas that wasusedtomakethemandcannotchangedue because thewavelengthisdependentonmaterial 124 ens. Ifyoutakeenergyaway fromlight,ratherthan you addmoreenergytolight, itswavelengthshort¬ by electionsfallingfromoneenergyleveltoanother. ( oloredLEDsaredifferentfromlightfilamentsas bly hardtounderstand. they emitlightatasinglewavelengthofcaused they donotemitaspectraotlightduetoheating, frequencies otlightrequiremoreenergytoproduce. remembered, butonmyunderstandingthathigher output, withtheshorterwavelength(thehigher across anLEDwasrelatedtothewavelengthoflight made (hehypothesistomyselfthatthevoltagedrop When Iwroteoutthedifferentwavelengthsoflight make thishypothesisbasedonanythingIconsciously Tins makesJ_EDsusefulforcalibratinglightsensors the frequency),greatervoltagedrop.1didnot for thedifferentLEDsatstartofthissection,I There’s onepieceofthepuzzlethatyouareprob¬ Tbe questionis.howdoyouaddenergytolightif 153 Robotics Experiments for the Evil(ienius White LED Blue LED Green LED Yellow LED Orange LED Different ColorLEDs Experiment 43 of thespectrum,whichiswhy astronomersmeasure decreases, theirwavelength lengthens. Aswave¬ lengths lengthen,lightmoves towardtheredportion the photonsdecreases.As energyofphotons true forlight:insteadofslowingdown,theenergy the Earthawayfiomsendinggalaxy.Thisisalso physical object,theenergyithaswhenimpacts same aswhenitleft. galaxy thatistravelingawayfromtheEarth physical objectaswelltheenergyoflight Earth islessenedbecauseoftherelativemotion Ihey passbetweenthegalaxies.Incaseof thinking aboutspeed;thinktheenergyofa tions. ifdoesn'tmakesensethatlightfromafaraway per second(2.99792x10t‘m/s).Comparingthesitua¬ observer. So,whenthelightfromfar-offgalaxy speed oflightcannotbechangedrelativetoits galaxy (wheretheEarthislocated)hasstayedrela¬ reaches theEarth,i!isstilltravelingat186,000miles the ‘objectsentfromothergalaxyislight; tively closetothecenterofuniversebecauseit the expandinguniverse,whereasMilkyWay behind thisisthataftertheRigBang,galaxiesand objects intheuniversebytheirredshift.Thetheory was notgivenasmuchenergyfromtheBigBang. were thrownoutatthefastestspeedarerimot other objectswereflungoutfromthecenterof universe atdifferentratesofspeed.Thegalaxiesthat To solvethisproblem,don'tlimityourselfto The problemcomesaboutwhenyouconsiderthat Astronomers measurethedistancebetween distances between objects by what astronomer's call Experiment 43 — Different Color LEDs the light’s red shifi.

With this background, 1 came up with the hvpoth * esis that (he shorter the wavelength of light produced by an LED, the greater the voltage drop across it because of the greater amount of energy passed from the electricity to the light.To test out this hypothesis, 1 used the simple circuit shown in Figure 8-4 and measured the voltage across a number of different LEDs. The results of the experiment are lifted in Figure 8-5 Different wavelengths of light (measured Table 8-2. in nm) released from or absorbed by tungsten atoms Looking at the results, you can see that there is some correlation between wavelength and voltage drop: An infrared LED. which has the longest wave¬ Hus was confusing to me until I considered the length has the smallest voltage drop: and the blue different materials that are used to make ihe LED, which has one of the shortest wavelengths, has different color LEDs. Each element emits light at dif¬ a large voltage drop. What doesn’t make sense is the ferent frequencies. For example, if you look at tung¬ values for the “middle" colors (red, orange, yellow, sten (Figure 8-5), you will see that it has eight and green). electron orbits (each with their owat energy levels), and a number of wavelengths of light can be pro¬ duced. depending on which electron orbits are changed. From this information, I came to the conclu sion that the voltage diop was more of a function of the doping material of the LED than the wavelength of the light produced. When I tested the different I.FDs,you'll see that I also tested a white LED. When white I.FDs are man¬ ufactured, they start out as blue LEDs, hut phospho rus is added to the LED before it is placed in the epoxy lens. This causes the LED to produce light across the cmire visible spectrum, resulting in white light being output rather than just one frequency of light. I included the results for the white LED for Figure R-M Circuit for tesi reference, but 1 did not consider it as part of the hy¬ pothesis.

Iable 8-2 Results of the i

LED Color Voltage lltlr;uc

Reef 1 96 V

Orange 1.82 V

Yellow 1.86 V

Green 1 95 V

Ulue 2.71 V

While 2.76 V

Section Eight Optoplectronics 125 Experiment 44 — Changing an LED's Brightness control electronics. using thiscircuit,andtheloaddrew2amps,heat amount ofpowerthatIslostinthePNPtransistor providing avariablevoltagetodeviceisduethe for applicationsotherthanthatofapowersupplytor comparator, itisactuallyvervdifficulttogetwork¬ transistor wouldbe10watts. Hiisisasignificant that wouldhavetobedissipatedthroughthePNP 1 orexample,ifyouwantedtodrop10volts5 ing correctly.()neaspectmakesitveryundesirable iar withtheoperationoftransistoraswell probably seemsquitesimpletoyou.asyouarefamil¬ plies. Althoughtheoperationoflinearregulator introduce theconceptandoperationofpowersup¬ regulator, andIwilldiscussitinmoredetailwhen a voltagecomparatorincircuitknownaslinear ply couldbeaccomplishedusingaPNPtransistorand 126 amount ofheatthatwillhave tobepassedthesur¬ device istolowerthevoltagebeingappliedit.This with whentheyareaskedtovarythepowerlevelofa power thatisbeinglosta considerable drainona control arobot'smotorspeeds, thenthe10wattsof rounding air.IIthelinearregulator isbeingusedto doesn’t forsome),itcanbeverydifficulttoimplement. from lightbulbstomotors.Theproblemwiththis makes senseforavarietyofdifferentdevices,ranging robot's batteries. method isthatalthoughitworksformostdevices(it Parts Bxn The reasonthelinearregulatorisundesirablefor Implementing avariablevoltage-levelpowersup¬ Die automaticsolutionthatmostpeoplecomeup 153 Robotics Experiments for the EvilGenius Assembled FOB Two 10kresistors LED, anycolor 555 timerchipin8-pin 0 1|jFcapacitorany 0.01 piFcapacitor,any 100k potentiometer Ik ohmresistor Changing anLED’sBrightness type type DIP package Experiment 44 second). IhereasonforspecifyingPWMspeedsisto or lessthan66ps(15,000PWMcyclesmoreper can makeasound,itsPWMperiodshouldeitherhe should beshorterthan20ms(whichresultsin50 signal, andthefirstisperiodofsignal.The as pulsewidthmodulation(PWM).andifyouwereto with.This switchingonandoffofthepowerisknown power totheloadonandoff.resultinginaverage make surethatthethrottlingetlectotPWMis more than20ms(50PWMcyclesorlesspersecond) range ofhumanvisualperception;thismeansthatit period ofthePWMsignalshouldbeoutside look atitonanoscilloscope,wouldsomething power beingwhatyouwanttocontrolthedevice PWM withadevicethatemitslight.Whenthe PWM cyclespersecondormore)ifyouareusingthe like Figure8-6. Figure 8-6Pulsewavemodulated signal waveform Tool Box A muchbettersolutionistoperiodicallyturn You shouldbeawareoftwofeaturesthePWM i, Pulsej j*- Period-1 i Width i Duty Cycle=100%*Pulse Width Period observed, not the switching on and oft of the PWM i« the duty cycle of the PWM signal when the LED is Experiment 44 — Changing an LED s Brightness itself. low. When the LED is brighter, the time in between The duty cycle of the PWM signal i'' the percent¬ the low periods of the repeating output of the 555 is age of time the signal is active during the PWM reduced and looks something like Figure 8-9. The period, f have hedged a bit on the definition because duty cycle for this signal is around 45 percent. the active portion of the signal can either be high I ooktng at the two oscilloscope pictures in Figure (which is what most people consider it to be) or low 8-8 and Figure 8-9, you should see that something (as I use in this experiment ). hinny is happening. Instead of changing the PW M’s To demonstrate the operation of a device con duty cycle and keeping the PWM signal's period con¬ trolled by a PWM. I came up with the circuit shown stant. 1 am actually decreasing the time the PWM sig¬ in Figuie 8- 7. You should recognize this circuit and nal is inactive (decreasing the PWM signal’s period). with a bit of studying figure it out as an astable 555 If you were to look at the period, you would sec that oscillator in which the lime the output wave is high is it ranges from about)() msecs dow n to 2.2 msecs or variable.The purpose of this experiment is to demon¬ from 100 H/ to around 450 Hr If you have experi¬ strate the operation of a PWM controlling the bright mented with the 555's astable oscillator,you will know ness of an LED. as well as show that a 555 may be that regardless of how much you try to change the poor device to consider as the basis for a PW M signal resistor and capacitor values used in the circuit, you generator*. will never get the PWM's duty cycle above 50 percent. When you build and test the application, you will These are the two problems with using a 555 timer see that by varying the potentiometer, you can vary for a PW M.The first problem is that you could use the brightness of the LED and you will not see any flashing of the I.FD being turned on and off very quickly. The turning on and off of the LED is hap¬ pening so quickly that your eye “averages” out the time the LED is on and off and gives the appearance that it is on continuously, but at a lower brightness level than if it were on 100 percent of the time. If you were to look at the operation of the PWM using an oscilloscope, you would see that when the LED is quite dim, the signal would look like Figure 8-8. The LED is active when the output signal is low. and the proportion of time that the signal is low is quite short, about 17 percent of the PW M period. This 17 percent Figure 8-8 PWM at 17percent duty cycle

9V 9V 9V

Figure 8-7 555 LED PWM circuit Figure 8-9 PWM at 49 percent duty cycle

Section Eight Optoelectronics 127 Experiment 45 — Multisegment LEDs 128 digital watches,butalsoinkitchenappliances,cars, person's inabilitytohandlethelatestintechnology. segment LEDsonaclockorVCRisthesymbolof instruments, and,ofcourse,irtvideocassetterecorders tound virtuallyeverywhere,beingusednotonlyin modern civilization.Seven-segmentLEDscanbe digital watches.Inthe30ormoreyearssincetheir with msomeapplications,but whenyouareworking on themarketmakecomponent easiertowork display isnottrivialtowork with.Anumberofchips (VCRs). Iheflashing“12:00”createdusingseven- introduction, theyhavebecomeaubiquitouspartof first becamepopularinthe1970swithadventof is theseven-segmentLEDdisplay(Figure8-10),It One oldiemostcommoniconsofourmodernsociety change thetwol()kresistorswithofhigher impossible toobserve. become noticeableandthevaryingoutputcouldbe value, theturningonandoffofIJEDcould perceive theoperationofPWM.Ifyouwereto be movingitintotherangewhereapersoncould changing thePWMsignal’speriodyoucouldpossibly for someapplications.Thesecondproblemisthatby percent to55percent,whichmaynotbegoodenough but youwillfindthatthedutycyclerangesfrom85 the outputof555tolightLEDwhenit'shigh, Despite itscommonality,the seven-segmentLED 13 3 Robotics Experiments for the EvilGenius Assembled PCBwith Two breadboard-mountable Two LEDs,anycolor Common anodeseven- 13 10k,1/4-watt 13 ZTX649NPNtransis¬ 13 lk,1/4-watt resistors SPDT switches tors breadboard resisters segment LEDdisplay Multisegment LEDs Experiment 45 duty cycle. power requiredtorunthemotorswitha100percent active onlyhalfthetime.Thishassomeinteresting equation (P=Vxi),bothvoltageandcurrentare wrong—it isactually25percentbecauseinthepower 50 peicent,howmuchpowerisbeingusedbythe running at71percentdutycycleareusinghalfthe implications formotorpower.Forexample,motors load? Ifyouanswered50percent,wouldbe an application.WhenthePWMsignal’sdutycycleis Tool Box A PWMcanresultinsubstantialpowersavings with robots or your own projects, you will find that well as numbers, then you will have to use an LED Experiment 45 — Multisegment LEDs these “canned” functions don’t quite do what you with more segments; these are available as either 16- want them to do. You will find that you will have to segment displays or as matrixes of LEDs that display come up with your own circuitry to decode data the character as a font, just as on y our computer along with some way of handling multiple displays. In screen. this experiment, I would like to introduce you to the Each LED in the display can be wired convention¬ seven-segment LED display and some of the circuitry ally to control whether or not it is turned on or off. needed to decode incoming numeric bit values before Controlling individual LEDs in the displays is quite displaying. easy, it gets quite a bit more difficult when you have In Figure 8-10,1 have shown the appearance of the to control multiple LEDs anil even more difficult seven-segment LED display: it can be put in the same when you want them to display something useful. “footpnnt" as a 0.300-inch-wide 14 pin DIP package, When I first blocked out the book, I wanted to show hut some of the pins (N/C for “no connect”) are not how just a few logic chips could be used to display all present. Fhe DP LLD stands tor the “decimal point.” the characters from “0" to “9” and “A” to “F” to The seven-segment LED display can he wired as demonstrate how the displays can be used tor hexa¬ either a common anode or common cathode. In this decimal displays. As I worked through the logic for experiment wc will be using a common anode, which this, I found the number of logic chips required to do is wired as shown in Figure 8-11. For this part, the two this to be prohibitive. I then worked down to wanting “common” pins are connected to all ( and occasion to display all the characters from ”0” to “8” and also ally some) of the anodes of the eight LLDs built into found that the complexity of the circuit was too much the display.This simplifies the wiring you will have to for the breadboard that is mounted on the PCB I do somewhat and makes woiking with multiple dis¬ finally decided on the numbers “0” to “3” and used plays a bit easier, as I will show in a later experiment. two lines for input As you are probably aware, by turning on each of To decide how to wire the circuit. I created Table the different LF.Ds differently, you can create differ¬ 8-3, which lists which segments are active for the ent digits. Figure 8-12 lists how different LEDs of different lout output digits, and then wrote out the seven segments can be used to display the 10 numeric “sum of products" statements (explained later in the characters. Along with the 10 numbers are a numbei book).The inputs were labeled “A0" and "Al” for the of letters that can he displayed, although only a few least significant and most significant hits used to of them look exactly like the characters they are sup¬ select the numbers to be displayed, respectively. posed to represent. II you want to display letters as These two signals could be considered a two "bit” numhi r.The bit numbering system as well as the AND and ()R logic gates will also be described in Common Common 3 14 more detail later m the book.

Table 8-3 Rctive segments fur the uutput digits

„2„ "O ' "!" "3" Terms Comments

a i i 1 !A0 ■ IA1 ‘ Al Same as d

Figure 8-11 Internal wiring for common anode b l t 1 1 1 Always on seven-segment Lilly display c i 1 1 !AJ + AO ■ Al

d ) l ) JA0 • !At + Al Same as a

aa a a a a a t> b b bfbf f bfbfb e 1 1 !A0 9 0 9 " 0 9 9 9 • C C 9 C C C9C C 8 C * li d 4 4 4 * 4 f l ! A0 • ! Al Uses AND from a d Figure 8-13 Seven-segment LLD display values g l ! Al for the digits 0 through 9

Section Fight Optoelectronics 129 Experiment 45 — Multisegment LEDs as digitsonaseven-segmentLLDdisplayLED Figure 8-13Logicfordecodingtwobitstodisplay8-14Transistordriversseven-segment through thelkresistor.Ibisisprobablynotdoingthis,makesurethatyoubuildeachtransistor the transistorsessentially■mAorsothatcomesdriverfortwoLEDs.Whenyouare stream. ITiebasesotthedownstreamcircuitshavemendstartingwithtwoswitchinputsfollowedby 130 absolutely required,binitisagooddesignruletofofcircuitinassmaManareapossible. a lkresistorispassedtothetransistorcircuitsdown-lenge.Whenyouwirethiscircuit.1wouldrecom- have markedtheoutputsofeachgatesameway.t]ian^ejour^.,^5Qfthisone. ated switchinputs(whichareinverted)andtwothistypeoflogiccanbeeasilyexpandedifyou would makeloramoreinterestingcircuit,first,Iere-gatesrequiredfortheapplicationarewellsuitedto would useRIL(Resistor-Transistor-Logic)becauseitlectortransistorsshowninfigure8-1:4.ThetwoOR 10k resistorstokeeptheactualcurrentflowsthroughdie“iA().;Al”and“AO•termsthen AND gatesthatareshowninFigure8-13.NoteIwantedtocreateacircuitcouldoutputmore done ibiswithTELlogicchips,butIthoughtlhalThejp.Ddriversconsistofthevariousopencol- designed alongwiththeLEDdrivers.IcouldhaveLEDs(makingsuretheyareallequallybright), any situationswhere1couldsimplifythecircuitry.upmtransistors,anditalsoensuresanequal Essentially, sixuniquecircuitswillhavetobeamountofcurrentflowsthrougheachsegmentthe For anyothesefourgates,currentpassedthroughWiringthisexperiment'scircuitisabitofchal- When Icreatedthistable,madesurethatnotedlowtomakeexcessivecurrentsdonotbuild 123 Robotics Experiments for the EvilGenius Experiment 46 — Optoisolator Lock and. Key

Experiment 46 □ptoisolator Lock and Key

Tool Box

Assembled PCB with Wiring kit breadboaid Scissors Foul opto-interiupt.ers

Six Zetcx ZTXb49 NPN transistors

Five red LEDs

Green LED

Seven lk, 1/4-watt resistors

Six 10k, 1/4-watt resistors

Sheet of cardboard

When you have moved up the robotic “food chain” and phototransistor are normally built together in an and are starting to work with much heavier robots opaque black plastic chip package so that external than the ones that are presented here, you will start light does not atfeet the operation of the transistor. to get into the realm of high-voltage/high-current Optoisolator’s are not as fast as other transistor- electronics. For the most part, this is not difficult and based switching circuits (taking 0.5 to 5 ms to change you will find that available parts will let you work state) and can only switch a few milfi-amps at a time. with high-power motors and batteries exactly as if llie signal passed is typically digital (which means they were the small devices that I use in this book, it is either on or off), and when a high signal is passed the problem will come when you want to integrate to the optoisolator, it turns on the LED, which allows the robot’s controller electronics to the motor sys¬ current to pass from the phototransistor’s collector to tems: the difference in voltages and currents could the emitter, connecting the output signal to ground. result in the controller electronics being damaged In the reverse situation, if the signal passed to the (although “fried” would probably be a more accurate LED is a low voltage, the LLD is off and the photo¬ term). An obvious solution to this potential problem transistor does not. conduct. is to use relays that are driven by the control elec¬ A modification of the optoisolator is the opto- tronics to switch the motors on and off. As I have interrupter (Figure 8-16). in which the light path indicated earlier in the book. I do not like to use between the LED and phototransistoi is opened to relays in robots because they are mechanical devices that require substantial current to operate ami do not Fhototransistor opeiate at electronic speeds that allow tot effective LED Anode Collector PWM motor control. Fhe all electronic solution to the problem of iso¬ lating high-voltage/current motor circuits from low- LED Phototransistor voltage/cuirent control circuits is the optoisolator.

Ihis component (in the dotted line of Figure 8-15) LED Cathode Phototransistor Emitter consists of an LED that can shine light on a photo- Light Path transistor. When the LED is on, the light causes the Between LED and production of electrons in the phototransistor, which Phototransistor acts as a base current and allows current to flow from the collector to the emitter. The optoisolator’s LED Figure 8-lE> Optoisolator

Section Eight Ootoe 1 setron i cs 131 Experiment 46 — Optoisolator Lock and. Key “Y" Direction sensed. ation oftheopto-interruptersusedinrobotstomoni¬ angles; thedirectionofIhcwheelturningcanalsobe detect themovementofwheel,butbyoffsetting makes ittheoptimalsolutioninsomeapplications, some external,physicalevent,Theoplointerrupter tor itsmotionandposition.Usingoptointerruptersin the operationofPCmouseisbecauseoper them sothattheyareturnedonandoffatdifferent wheel withholesinitthatallowslighttopassthrough switch, nordoesittequireanyforcetooperate,which does nothavethesame“bounce”asaphysical 132 PC’s mousetodetermineits motion Figure 8-17Twoopticalinterrupters usedina how twoopto-interiuptersareusedtonotonly rupters usedforeachwheel.InFigure8-18.1show shown inFigure8-17 in asimplePCmouse;theballturnsshaftthathas A verytypicalapplicationtortheopto-interrupteris “switch” onandoffthephototransistorbased allow foraphysicalblockofthelight,asmethodto operation it andbesensedbyanopto-interrupterasIhave Figure S16Opto-interruptercircuitryand Opto-lnterrupter 1-► . ^"S.EDCathode L PhototransistorCollector The reasonwhyfamgoingintosuchdetailabout The drawingsinFigure8-17showtheoplo-inter- Part View f^<^tL,Photrans|stor (PT) K Emitter Oplional Pin“1" Indicator “Y" Direction Wheel Sensor 153 Robctics Experiments for' the EvilGenius Direction Cptc-lnterrupiors Wheels with 'n HolePositions Sensing Changes Holed Against Ball Wheel Axle Pressing He eou-ili Vcc Mouse Wheel Sensor 'X” Direction the channel between the LED islitwhile unobstructed. LED andPTis Test Circuit Against Ball Wheel Axle Pressing Holed stand. Theoutputsforeachtumblerconsistofan circuit (Figure8-20),theindividualcircuitstoreach base controlledinatraditionalmanner.Thecollector NPN transistorwithitsemittertiedtogroundand opto-interrupter tumblerseemtobequitesimple,but the combinationofcircuitsisabithardtounder¬ A lienyoulookattheschematicdiagramlorlock used toturnonthe“TumblerBlocked”transistor. flows fromthecollectortoemitter:thiseuirenlis When lightispassedtothephototransistor,current distance betweentheqpto-interrupters. cardboard andshouldbedesignedwhenyouhave shown inFigure8-19.Ihiskeyiscutfromapieceof creating alockcircuitthatrequiresthepaper"key” the operationofoptoisolator/opto-interrupterby movement oftherobotisrecordedinanefforttonav¬ robots ispartofthescienceodometryinwhich igate ittoaspecificlocationinspace. Figure 8-19Keyforopto-interrupter lock built thecircuitshowninFigure8-20andknow wheel todetectrotarymovementanddirection Figure B-18Anopticalinterrupteronaholed For thisexperiment,Twouldliketodemonstrate The opto-interrupterisusedasacurrentswitch. (Spaced foreachOpticalInterrupter) in KeyforOptical-lntemjpters * 10Degrees Opto 2 Opto 1 Wheel with Holes Every Opto IsolatorsDuring 25 Degrees Optoisolator “2at 0 Degrees, Optoisolator “1"at Wheel Turning ted AND gate.The digital AND gate only passes a Experiment 47 — White/Black Surface Sensor high output when all of its inputs are high Hie dotted AND gate shown in Figure 8-20 fulfills this require¬ ment as any of the multiple open collector transistors wired in parallel can pull the circuit to ground for low). In the later sections when I discuss digital logic, the AND function will become clearer, but for now, you should remember the dotted AND used here in which the output is high if and only it all the open collector transistor drivers are turned off. In Figure 8-20,1 have indicated that the opto- Figure 8-20 Opto-interrupter lock circuit. Mole snteriupter open and blocked transistor collector out¬ that lock tumblers are adjustable. puts tor each tumbler can be wired to the locked LED (which is connected to the unlocked LED via an NPN transistor). In the figure. I wired all of the is passed to a circuit with a central resistor tied to the open collector connections except for one (w'hich output voltage This output transistor configuration is used the blocked collector connection) to the locked known as an open collector output and allows for the LED. You can vary this wiring or add additional output ol multiple tiansistor circuits to be tied opto-interrupters and transistor circuits to make the together m a common configuration known as a dot¬ lock more sophisticated and difficult to “pick."

Experiment 47 UL)hite/Black Surface Sensor

Tool Box Assembled PCB with Wiring kit breadboard Wire clippers Opto-interrupter Black Magic Marker LLD, any color White paint pen 10k resistor

Two lk resistors

Paper

The most useful type of light used for mechanical the surface is white, you will find that the IR light sensors occurs in wavelengths that are invisible to the from the LED reflects very efficiently, turning on the human eye. Infrared(IR) light (Figure 8-21) is used for a variety of purposes, including being a part of pass-through interrupters, as shown in the previous 720 nm 2 um 4 uni 10 uni experiment, and a number of different sensor appli¬ Visible Near Raoio cations that l will show in this experiment. In Figure Light InfraRed Frequencies 8-21,1 show some of the different wavelengths of IE Jet Boiling Water Human light that are produced by different objects. Exhaust (1000 C) (7 um) The simplest infrared sensor (and most tradition¬ ' Heat (9 um) ally used in robotics) is the line follower, which con¬ sists of an infrared LED and phototransistor Figure 8-31 JR light and temperatures for different reflecting light from a surface (Figure 8-22). When wavelengths

5ection Eight Optoelectronics 133 IR Light Reflected Much Less Reflectec by White Surface IR Light from the LEU from the LED to to the Photot'ansistor the Phototransistor on a Biack Surface IR LED u y IR Phototransistor u Opaque Barrier ' Preventing Direct \ / o Transmission of \ f IR Light CO White Surface Black Surface c <11 Figure 8-22 Infrared LED andphototransisior

0) phototransistor. A black surface tends to absorb infrared light and very little is reflected, keeping the o Figure 8-2M Photograph of stock opto-interrupt&r phototransistor turned off fO and one that has been separated on prototype M-l The traditional way of building IK Sine detectors is breadboard circuit. When cutting apart the opto- M to drill multiple holes in a wood for metal) block as interrupter remember to keep track of the ELD and P shown in Figure 8-23. These holes are drilled in such a phototransistor, as well as their polarities. 0} way that light from the LLD can only pass to the phototransistor if it reflects off of some object. There cannot be a direct path from the IFF) to the photo- LED1'!cathode and phototransistor's collector) using transistor, which can make part placement and their the white paint pen before you clip apart the two a geometry challenging Rather than going through the parts. Along with this, make sure you keep an unmod- flS hassle of anting up a piece of wood or metal (and ified opto interrupter on hand to help you figure out potentially having to paint it black to minimize the how the part is to be wired. PQ chance for reflections). I want to use an electronic Once you have cut apart the two halves of the device that is basically designed for this application opto-interrupter as shown in Figure 8-24, you can

End View ”_Hole Drilled for IR LED/Phototransistor

Depression in Bottom for IR Light to Reflect and Shield IR Pholotransistor from External Light

* Figure 8-23 Simple holder block for IR LED and Figure 8 25 Opto-interrupter white/black sensor w phototransistm used for line follow-ini’ circuit

134 123 Robotics Experiments for the Evil Genius Experiment 48 — Line-Following Robot

Experiment 48 Line-FollDLuing Robot

Tool Box

Assembled PCB with Wiring kit breadboard Black Magic Marker

DC robot motor vase with Five-minute epoxy four AA battery clip Tin snips and switch Rotary cutting tool with Two opto-interrupters carbide bit (see text)

LM339 quad comparator

Two ZIX649 NPN bipolar transjstors

Two XTX749 PNP bipolar transistors

Two LEDs, any color

Two 100k resistors

Ten 10k resistors

Two lk resistors

Two 470 il resistors

Two 100 11 resistors

Two 10k breadboard- mountable potentiome¬ ters

1/8-inch heat shrink tubing

Aluminum rain gutter end cap (see text)

22-inch by 28-inch sheet ot white Bristol board (see text.)

Now that you have seen a simple JR opto interrupter When 1 lay out my tracks, I keep the line 4 inches being used as a white/black detector, you can add this (10 centimeters) from the edge of the board and capability to your robot projects and give yourself a round each corner with a radius of 3 inches chance to compete against other robot developers. One of the most popular robot contests that you may Bristol Board want to entet is ihe "line follower," in which a robot Start'Stcp Marker is expected to follow a black line on a sheet of paper. 3" Radius Curves With the material listed in lhe Parts Bin and the knowledge and skills you have developed, you can Minimum 4" Between create a simple line-following robot. Line and Edge of Board or Between Lines To start off. you will need a line to follow. 1 am going to suggest that you make this first because it is 1/2 - to 3/4 -W dc useful to test the robot and its sensors as you build Black L ine the circuit that I will present to you. Using a standard piece of Bristol Board and a Magic Marker, you can Figure 8-26 hack for robot to follow made from put down a track like the one shown in Figure 8-26. a 22" by 28" piece ofbristol board

Section Eight Optoelectronics 13% (7.5 centimeters). I try to make my lines 7; inch (1 oE lO centimeter) to '7, inch (1.5 centimeter) wide. If you r-- o 0 V (0.25 cm) 0,r (0.25 cmf put on a “Start/Stop” maik, you might want to keep it d4 1 away from any possible robot sensors, as they may he n r incorrectly identified as turns for the robot. Once you have built your track, you will have v _ to make a mounting plate lor the cut-up opto- _ Round Front mterrupters. In Figure 8-27, you can see that 1 started 3,5" (8.89 cm) Corners with a with a piece of aluminum gutter end cap (which I 1/2” (1 cm) Radius bought at a hardware store for $0.25) and cut it down 4-> so that it could be mounted on the DC Motor robot Figure 8-28 IR sensor mounting plate made from o using the 1-inch (2.54 centimeter) standoffs. mild tduminiim A I chose the aluminum gutter caps because of their 0 low cost and the ease in which they can be formed, Separated Oplo-lnterrupter l ooking around any “big box" haidware store will ■p Halves Pc TO 9-Voll Power yield a number of different products that can be O TD_Q adapted for this purpose. I did not find a plastic prod¬ TO tn

136 1E 3 Robotics E x p e riments for the Evil Genius Experiment 48 — Line-Following Robot

Figure 8-30 Schematic diagram for DC motor-dm en line following robot

phototransistors in the opto-interrupters to a 10k included a potentiometer that can be used to come resistor: as the current increased, the voltage across up with the voltage transition between white and the 10k resistor increased and could he compared black. ()nce the sensors are working reliably, you can using die LM339 comparator chip. The second then wire the circuits to the other two comparators requirement was that this circuit would have to work (which invert the signal from the first comparators) both on its own as well as undei Parallax BASIC and then add the motor drivers. Remember to make Stamp 2 control,This requirement resulted in Ihis cir¬ sure that you have a switch on the four A A battery cuit, which can be powered two different ways with pack this is an application where the robot will start up to three different power supplies (9 volts from the running unpredictably. battery, regulated 5 volts, and 6 volts for the motors), Tire 100 H resistors used as the current-limiting and it necessitated the use of the PNP transistors to resistors for the motor driver transistors were opti¬ pass current to the motor driver NPN transistors. mum for the motors that I chose; the robot should When you build this experiment, I recommend move at about 2 inches (5 centimeters) per second. that you first gel the LEDs to light when the opto- You will have to experiment with different resistors interrupter is over a black line. Because the photo¬ to get the best performance w ith your motors and transistor output voltage level can vary, 1 have robot.

Spctinn Eight Optoelectronics 137 Section Nine Audio Electronics

We take few things for granted more than “simple" The advantages of the crystal speaker over the audio electronics such as radios, stereo amplifiers, and dynamic speaker are its low cost, its responsiveness CD and MP3 players. Ihis lack ol appreciation is to small currents, and its robustness. The dynamic unfortunate because not only do these devices have speaker is better suited lor situations where high- much of Ihe same technology as high performance powered signals are used to drive the speaker. It you computer systems to provide memory functions, but are going to listen to AC/DC on your personal MP3 they also have advanced analog electronics that allow player, you are going to use headphones with crystal them to inexpensively provide high levels of analog speakers built into them, but if vou arc going to the power with very limited distortion. Even discounting digital technology provided for many of these devices, the science of audio electronics is quite advanced. Audio electronics also go back more than 150 years to Samuel Morse’s first telegraph message Although the first experimental telegraphs wrote on paper tape (with dashes and dots printed as varying line lengths as the tape was drawn through the tele¬ graph). it became a practical instrument when a Magnet series of audible clicks were produced by a simple electromagnetic speaker that deforms a steel plate Force Produced by Magnetic Field (or diaphragm) when current passes through the Created by Current in Speaker Coil electromagnet, causing it to click. Ihe telegraph clicker was improved upon to pro¬ duce a speaker in which a specific voltage would Figure 9 1 Dynamic speaker cause a partial movement in the diaphragm.This dynamic speaker consists of a permanent magnet and a diaphragm that has a coil of wire built into it (Fig¬ ure 9-1). By rapidly changing the applied voltage, the position of the diaphragm changes and produces an audible sound The first practical application tor this device w as the telephone. Along with the dynamic speaker, several other device* convert voltages and currents to sound. If you have a set of headphones, then chances are you are listening to sound by use of a piezo-electric crystal- based speaker (Figure 9-2). A piezo-electric crystal produces a small but measurable change in its size when an electric current passes through it. Ihis prop erty is used to drive a speaker diaphragm. Figure 9-9 Piezo-electric crystal speaker

139 Section Nine — Audio Electronics ance orvoltagebasedontheinputsound,value pletely differenttheory:ratherthanchangingresist¬ dirty" publicaddress(PA)systemwhenyouareata type ofmicrophoneisknown asacondense)micro- of acapacitorbuiltintothemicrophoneChanges.This party andyouneedtogetpeople'sattention. when youtalkintothem.Thisisauseful“quickand phone inputofyourstereoandseewhathappens you cantryistoconnectheadphonesintothemicro¬ dynamic microphone,whichworksonthereversed the crystalspeaker.Aninterestingexperimentthat field. Thecrystalmicrophonealsoworksinreverseto an inducedvoltagebymovingacoilinmagnetic applied voltageproducingasound,soundproduces get betteiperformance,anumberofdifferentmicro¬ granules continuallyrubbingagainsteachother.To principle ofthedynamicspeaker;ratherthanan phones havebeeninventedthefirstwas 140 provide alowlevelnoise(orhiss)duetothecarbon expensive (aswellasdirty)tomanufactureandwill according tothenoiseapplieddiaphragm microphone consistedoladiaphragmconnectedto age changebytheuseofatransformer. current changeisamplifiedandconvertedtoavolt¬ rent byapplyingavoltagetothemicrophone.This resistance wasalteredtoachangeinelectricalcur¬ using thecircuitshowninFigure9-3.'Iliechange microphone wasconvertedtoachangeinvoltage found thattheresistanceofthisapparatuschanged plate pressingoncarbonnametalcup.Berlinerhad amount ofpressureplacedonthemchanges.His have thepropertyofchangingresistancewhen on theamountofpressureplacedkey stration fromatelegraphershowingthattheelectro cal currentflowingfromatelegraphkeywasbased its firstappearancein1837)asaresultofdemon Berliner's microphoneusedcarbongranulesthat concert, thenthemusicfromAngusYoung’sguitar will hedrivenoutof(large)dynamicspeakers. 1876 byEmileBerliner(thetelegraphspeakermade Most modernmicrophonesworkwithacom¬ 'Hie firstpracticalmicrophonewasinventedin Ilie carbonmicrophoneworksquitewell,butitis 1 hechangeinelecliicalresistanceofthecarbon 12 3 Robotics Experiments for the EvilGenius phone (condenserbeingtheoriginalnametorcapaci¬ phone iscalledtheelectret(Figure9-4)and amplified andusedlikethevoltagesproducedby- on oneofthecapacitorplates.Now,whencapaci¬ most popularmicrophoneusedtoday. crystal ordynamicmicrophones.Thistypeotmicro tor platesmove,asmallvoltageisinducedthatcanbe charged material(Teflonisgoodforthisapplication) and resistor.Thisisdonebyplacingapermanently ideal wouldbetheeliminationofpowersource some todesignaspartofacompletesystem.The change incapacitancehastobeconvertedintoa tors). isverysimpletomanufacture,andoffersgood change involtage. frequency response.likethecarbonmicrophone, Figure 9-MElectretmicrophone resistance ofthecarbonmicrophonetovoltage Figure 9-3Circuittoconvertthechanging Sound Input This circuitworkswell,butitissomewhatcumber¬ Imo.d_ HJODD” Voltage Signal 0 Out Diaphragm Microphone Element »* Capacitor Negatively ChargedMaterial Signal Voltage Out Experiment 49 — Buzzers

Experiment 49 Buzzers

Parts Bin Tool Box

Assembled. PCB with Wiring kit breadboard

3-20 volt DC buzzer

Breadboard-mountable SPDT switch

One of the few things that has never changed from when I was a kid is the basic electronic kit in which you can build a clanging bell that is driven by a single battery. At the time, the bells were used for almost all alarm applications, even though today they have been largely replaced by electronic alarms fh.it are usually part of a public address system The basic design for the bell is shown in Figure 9-5, and it is built using an electromagnet and a spring, both of which push against each other. When the spring is holding the clapper away from the bell, there is a closed circuit and the electromagnet is active. Tire electromagnet pulls the iron bar (along with the clap¬ per) toward it. When the iron bar starts moving, the circuit is broken drives a speaker or have a buzzer (Figure 9-6). Buzzers generally require 50 mA or more current to The process of the electromagnet pulling the elap- operate and should be driven by a circuit such as the pei toward the bell, followed by the spring pulling it one shown in Figure 9-7. awav, will repeat indefinitely while electrical power is applied to the bell mechanism Practically speaking, When f looked at reference information on the contact points and the copper contact of the bell buzzers, f found the curious line that buzzers work mechanism (identified in Figure 9-5) will have to be exactly the same way as bells This is true to the point changed and adjusted periodically as each time the that a part in a buzzer, just as in a bell, moves when bell rings, the contacts will become oxidized and current passes through it. and then the part returns to worn by repeated action. To he fair, electrical bells the original state when the current stops; however, have been around for more than 150 years, so they everything else about the two devices is completely are well understood, and the maintenance required different. Ihe buzzer does not include any magnet for them is minimal. components as the bell does; instead, it takes advan¬ tage of the characteristics of a piece of piezo electric Although electric bells work well, they are not material, practical for many electronic projects. Ihe reasons why they are not practical are due to the amount of When used in a buzzer, the piezo electric material space they take up. the relatively low frequencies of is held at one end with an electrical connection while sound output the large amounts of current draw, and at the other end, a piece of copper is placed in con¬ the effects they can have on a circuit Ihe electromag¬ tact with the material. When current flows through net switching on and off can cause large voltage the piezo-electric material, it deforms and the con¬ spikes in the circuit’s power supply. For the past 50 nection to the contact is lost; this causes the material years or so, most smaller circuits that require sound to return to its original form, which closes the con¬ output either have an oscillator built into them that nection again and the process rej

Secticn Nine Audio Electronics Experiment 49 — Buzzers ament dnver simple circuitshowninFigure 9-8.Theswitchinthe Figure 9-8Buzzerschematic Figure 97Circuittodrivebuzzerfrontlow- circuit willturnthebuzzeron andoff. Figure 96Buzzerassemblyandappearance 142 place youieardirectlyagainst thebuzzerwhenitis You cantesttheoperationof abuzzerusingthe 1 wouldliketoemphasizethat youshouldnever material Piezo-electric Output’ Dr iver 12 3Robotics Experimoots fotheEvil Genius Switch Internal Assembly Vcc Buzzer BlackWire Wire Point Copper Connection Buzzer f \ Power In Buzzer RedWire Buzzer 2m fromeye 75 decibels(dB).ThedBrangeisameasureofsound sure th.ityoudonotbuyabuzzerthatisratedatover operating. Alongwithtinswarning,youshouldmake could bedefinedusingtheformula: you couldsaythattheapparentsizeofobject appear tobeone-thudthesize.Putmathematically, proportional tothedistanceitisfromyoureye.To a robotgetsfartherawayfromyoureve,itssizeis you arefromtheobjectInFigure9-9fshowthatas statement maybehardtounderstandandconceptu¬ of distanceratherthanlinearlywithdistance.This waves moveawayfromitinasphericalpattern buzzer. pressure, ortheloudnessofsoundcomingout three timesthedistanceofclosest,itwould hall thesizeofcloserone.ft'youputanobject your eyeandanidenticalobjecttwicethedistance prove this,placeanobjectacertaindistancefrom find thatitsapparentsizechangeswithhowfaraway alize. from thesource,theirpowerdecreasesassquare prise foryouisthatasthesoundwavesmoveaway (which shouldnotbeasurprise).Whatmaysur¬ from youreye.Thefurtherobjectwillappeartobe Figure 9-9Perceivedrobot distance When youmoveawayfromanobject,will W hensomethingisproducingsound,thesound External Appearance 1 mfromeye Angle ofrobot 1 mfromeyeistwicerobot RobotSize = RobotSize@lmeter x distance the v directions. Put mathematically, you can state Experiment 50 — Basic Transistor Oscillator that sound pressure is defined as ‘Apparent size in a subjective term, and when it is used, you are only thinking in terms of one dimen¬ SoundPressure = SoundPressure(?lmeter x sion (the object looks like it is halt the size because it (distance3) is halt as tall). You must remember that there are two dimensions and both are halved, which means the When you get closer to the sound source, the actual area of the object being viewed is one quarter sound pressure increases according to the same when it is twice as far away. square law. and this is why I emphatically state that When you are discussing sound or light, the oppo¬ you should not place your ear any closer to the site phenomenon occurs. After traveling twice the buzzer than a few feet. When the buzzer ts close to distance, the sound, is spiead out over four times the your car, the sound pressure applied to your ear will area because the same amount of sound energy is very quickly get to the level where your eai (ami its now spread out over twice the distance in the x and hearing) will be damaged

When I was growing up, all educational and hob- The oscillator circuit that I am going to work with byist circuits were built from individual transistors— is the basic relaxation oscillator ciicuit shown in Fig- .t wasn t until the mid to late 1970s that chips such as lire 9 10, Included in Figure 9-10 arc the formulas for the 555,1 M3.39.1 .M386. and I,M741 started to be when the output is high and low, as well as an impor- commonly used as budding blocks for these circuits. tant formula indicating that the value of R1 and R2 lhese chips are all very configurable, but none offer (the time defining resistors) must be the transistor the range of operation amt low coM of discrete iran It multiplied by the value of the pull up resistors sistors. In this experiment, I could have introduced (Rpu). If R1 or R2 is less than this product, then you you to a simple oscillator driving a speaker designed will find that the oscillator will not start reliably and to be used for learning Morse code with a 555 timer, not run at a constant frequency, but 1 want to go back in time and show you how this I he transistor relaxation circuit that I came up could be done with a few transistors, resistors, and with is shown in Figure 9-11. If you apply the formu- capacitors. las given in Figure 9 10. you will discover that the

Sectinn Nine Audio Electronics ment 50 — Basic Transistor Oscillator short time,not50percentofthewaveformasyou and itonlyactivatesthespeakertransistorforavery expect (itisnotasquareorsmoothlyroundedwave), would expect.Thisisnormal,andifasquarewaveor oscilloscope pictureoftheactualoscillatorsignal frequency oftheoscillatoris154fI/..Lookingatan is probablyquiteabitdifferentfromwhatyouwould fairly closetothis(182Hz),althoughitsappearance (Figure 9-12),youwillseethatthesignal'speriodis Figure 9-12Astableoscillatorcircuitwaveforms tor wouldbeused,orthissignal Wouldbefilteredand a sinewaveisrequired,ihen anothertypeofoscilla¬ modified toproducedthedesired signal. Figure 9-11AstableoscillatorusedasaMorsecodepracticetool Figure 9-10NPNtransistorbasedastabheoscillator Morse’s firstmessage(“What HathGodWrought’). 91 fj.cwiJvMmS ■ —.tj—Ww. Morse codehasnotremained staticsinceSamuel 9-Volt Battery 12 3 Robotics Experiments for the EvilGenius ZTX649 ■ Rpu>R1

Experiment 51 Electronic Stethoscope

Parts Bin Tool Box m » Assembled PCB with Wiring kit

Rubber cement LM386 8-pin audio Scissors

Electret liii'cto phone (see

Plastic straw (see text)

10k breaaboard~mountafcle potentiometer

10k resrstor

10 U resistor

Two 0.01 (j.F capacitors, any type

220 |iF electrolytic capacitor

8/16 a Speaker

The genesis of this experiment was trying to figure problem with a small part, but a soda straw cut down out where a rattle was located in the “wall-following to 3 inches (7,62 cm) in length works quite well. To robot” presented later in the book. When the robot’s avoid the potential embarrassment of having some¬ left wheel was running. I heard a lunny noise that I body walk in on me while having a short piece of couldn't find bv running the robot and trying to tind soda straw stuck in my ear and holding up a running it by car The solution was to go back to an old robot, I decided to come up with an amplifier circuit mechanic's trick for finding the source of a funny- that would pass the sound coming through the straw noise in a car's engine. In case you’ve never seen a to a microphone and then to a speaker. The finished mechanic find the source of a noise under the hood “electronic stethoscope" block diagram is show n in of a car. they do it by using a length of garden hose. Figure 9 13. The hose directs the sound coming in to it along its length and to the ear of the mechanic. It's probably the simplest diagnostic tool used with modern cars, Microphone Speaker but often the most effective for situations such as iso Soria Slraw Rubber Cemented lating a knocking valve. To End _;i.K To find the problem (a motor with a piece of metal rattling around inside it), I used the same principle as Amolifier the garden hose to the car motor trick, but scaled down for the small robot You shouldn’t be surprised that a garden hose would be too large tor finding a F i g u re 9-13 Electronic stethoscope block diagram

Section Nine Audio Electronics Experiment 51 — Electronic Stethoscope signals thatareverysmall;aninputsignalof1volt, even withagainof20times,willbe“clipped”bythe tor valuetochangethegainupwards200(from mula includedinFigure9-17,youcanchoosearesis¬ done byaddinga10p.Fcapacitorandresistortothe can bemodifiedquit®abit.Oneofthemostpopular commonly usedmthe1970s.LM386’sparameters two transistordriver.Thisdriver (knownasa“totem have anamplitude200timesgreaterthantheinput. the nominal20).whichmeanssignaloutputwill two gainpinsasshowninFigure9-17Usingthefor¬ modifications ischangingthegain(howmuch Figure 9-16. driving verysmallmotors—insteadofitwith “small signal”sourceandboostingit.Itcanalsobe current outputdriverwitha21)to200timesgainItis 9-15). Phischipisageneralpurposedifferentialhigh- would gooutsidetheselimits, itisjustclipped.Some¬ to thepowerinputLM386, andifthesignal pole5' driver)canonlydrive theoutputfromground amplifier multipliesthesignal)ofchip.Thisis amplifier wiredasavoltagefollower,shownin used foravarietyofotherapplications,including very oftenusedforapplicationslikethisone.takinga straw. Ididfindafairlynarrowmicrophoneatan PWM. ananalogvoltagecouldbeusedwiththe not getanyglueonthefaceofmicrophone.Once straw. 1gluedthemicrophoneintoit.takingcareto electronics storeandusedalargeshakestrawfrom ing anelectretmicrophonethatfitinsideasoda that wasdone.1builtthecircuitshowninFigure9-14. fast-food restaurant.Aftercuttingdownthesoda Figure 9-14Electronicstethoscopeschematic 146 153 Robotics Experiments for the Evil Genius Like the555andsomeotherchipsthatbecame Tins levelofamplificationshouldonlybeusedfor Ihe basistorthestethoscopeisL.V1386(Figure Ihe mostdifficultaspectofthispiejectwasfind¬ sound butforthemostpart,itisconsideredtobedis¬ discover thatitwailswhenthespeakerisbrought tortion andshouldbeavoidedatallcosts. times clippingisusedinrecordingtogetaunique Figure 9-17 Changing LM386outputgain Figure 9-16UsinganLM386todriveamotor Figure 9-15LM386pinout Analog Input- When youbuildthisexperiment'scircuit,may CD 'CD C 10 mfa “Voltage Follower1’ CO U) if) >> Q. 03 Wiring Speaker 8/16-Ohm > o o Output toMotor Gain = > O =3 150 <1350•

(D

Section Nine Audio Electronics 147 Experiment 52 — Sound-Level Meter experiment, Iwouldliketolookatwhatbasicspeech sure itunderstandsthatthefollowingcommandisfor speech andprefacedbytherobot’sname,tomake scope, youwouldseesomethinglikeFigure9-20.The called anoscilloscope,whichdisplayschangingvolt small electricalsignalsfromthemicrophoneintoa always performedwithmindlessefficiency.Inthis ator. lhesecommandsarespokennormally,although based onthe(usuallyverbal)commandsofitscre¬ electron gunusedbytheCRT wouldbecontinuously age levelsovertimeasIshowinFigure9-19. power signalthatcouldbeusedtodriveaspeaker, required todisplaytheelectricalsignals. nals byamicrophone,aswellthetoolsthatare although somemayheexecutedtooliterally,theyare tt lhesecommandsarerarelymisunderstood,and they mayheabitlouderandsufferthannormal hulking man-tikemachinethatwreaksdestruction the LM586audioamplifier.Thischipconverts becomes afterithasbeenconvertedtoelectricalsig¬ active andmovingacrossthe screen,lefttorightand then snappinghacktotheleft andstarlingover.Ihis movement oftheelectronbeam isperformedbyaset rhe imageofarobotthatusuallycomestomindis 148 lhese signalsaregenerallydisplayedusingatool Parts. Bin Nine lkresistors Three 0.01p.Fcapacitors,anytype Three 10kresistors Electret microphone If youweretolookinsideaveryprimitiveoscillo¬ In thepreviousexperiments,Iintroducedyouto 10 jjFelectrolyticcapacitor 10 SIresistor 100k breadboard-mountablepotentiometer 1E 3 Robotics Experiments for the EvilGenius Assembled PCBand LM386 8-pinaudio Four brightLEDs(see LM339 quadcomparator breadboard text) amp 1ifier Sound-Level Meter Experiment 52 scope willgiveyoutheabilitytoobserveoneortwo sawtooth wavethatispassedtothedeflectionplates sweep generator.Hiegeneratorproducesa of electrostaticdeflectionplatesthataredrivenbya expensive oscilloscopes(costingwellover$100,000) changing signalsatspeedsuptoalewMHz.More shown whenIputinanoscilloscopescreenshot and causesthebeamtomovefromleftright. nals inthe(ill7(microwave)frequencies. will havemorethantwoinputsandcanobservesig¬ ($500 andup).Averybasicinexpensiveoscillo¬ but itshouldhelpyoutounderstandwhatisbeing this hook.Oscilloscopestendtohequiteexpensive input andamplifieroutput Figure 9-IQOscilloscope (racesofmicrophone Tool Box This isaverycursoryintroductiontooscilloscopes, Time (lOms/Gratinulci) Vertical Deflection Cathode Ray Tube make their operation more noticeable, you should

(CRT) Experiment 52 — Sound-Level Meter use the brightest LFDs you can find. If you look around the Internet,you will find some circuits that

Waveform hold the voltage for a few hundred milliseconds in ’Drawn" on CRT order for the LEDs to be active for a few seconds. Second, looking at the circuit, you II see that I had to increase the gain of the L\138b by wiring the 100k Sweet- Generator potentiometer to the LM386 in such a manner that Figure 9-20 Basic oscilloscope internal block the gam would be increased over the 200 times nor diagram mally produced by the capacitor across the gain pins. ITie actual gain of the circuit is about 5,000 times to increase the output to the point '•\here the I I Ds will Rather than requiring you to purchase an oscillo¬ indicate different levels of sound inputs. You may scope, in this experiment I would like to give you a find that you will have to change the resistor and simple circuit that can be used to observe simple elec¬ potentiometer values of the components connected trical signals, such as audio input. This circuit (Figure to the 1 M38b for the circuit to work with the micro¬ 9-21) converts small audio signals to signals that can phone that you use. Finally, a number of chips can be be compared. LEDs can then be lit depending on the purchased that will perform the same function as this output level of the sound I only provide output lor circuit and are very easy to wire into a circuit I four LEDs to fit on the breadboard that is built on the decided to build the circuit out of discrete parts to P( B that comes with the book. give you a better understanding of how audio signals You should be aware of a few issues when you are converted to electrical signals and how compara¬ build tilts circuit. First, when the circuit is operating tors work you will find that the LEDs will turn on for very Ihe LM339 (Figure 9-22) contains tour open short intervals for loud noises and spoken words.To collector output voltage comparators. In this

Figure 9-21 Sound-level-meter circuit diagram

Section Nine Audio Electronics 149 Experiment 52 — Sound-Level Meter The numberotLEDsthatareusedtodisplaythe collector outputs the currentaudiooutputusinganumberofLEDs. ages thatcanheusedtocompareagainstthesound- divider “ladder"thatprovidesasteppedsetofvolt¬ experiment's circuit,Ihavecreatedaresistorvoltage sound levelcanbeincreasedbysimplyadding to thecircuitthatisbuiltintoyouistereodisplay level inputtotheI.M386.Thiscircuitisverysimilar Figure 9-22LM339quadcomparatorwithopen another LM339chipalongwithlourmore10kresis¬ Figure 9-23SounddisplaycircuitLM339amplifier operation 150 123 Robotics Experiments for the Evil Genius 0UT3 0U.T4GndIN4rIN4-IN3+IN3- ?) lStope].CH2;50mV’10m 1) (Scope|.CH*50mVIfim? 4) rScopc).CH45V10mS 5) !ScopcJ.CH35V10mS comparator. age dividerasIhaveshowninFigure9-23.Thesignal small voltagewhenthemicrophoneiswiredinavoll- tors toprovideadditionalvoltagelevel“steps"forthe note thatatthebottomofFigure9-23,voltage signals (andunderstandwhat“smallsignal"means), on myoscilloscope)thatarepassedalong. clipped. Figure9-23showsboththedifferentpartsof sure thattheoutputsignalfromLM386isnot voltage divideractsasavolumecontrolandmakes passed toIheIM339comparator,itiszerobased amplified usingtheLM386.Beforefinalsignalis is passedthroughacapacitorandresistorthen the inputcircuitaswellwaveforms(displayed using the0.01pFcapacitorand10kresistor.Thefinal scope picturesshowninthisbook). is definedasthevoltagerangebetweengraticuleson levels foreachsignalaredisplayed.Thisvoltagelevel the oscilloscopepicture(aswellasanyotheroscillo¬ the oscilloscopescreen,whicharedottedlineson To getanideaofthedifferentmagnitudes When soundhitsthemicrophone,itproducesa Section Ten Digital Logic

I ho mathematics of logic came from the need to mathematical statements in order to better under¬ understand philosophical statements such as the stand them and test their validity. By restating a text following: proposition as a mathematical equation and making the assumption that all propositions were either true Now some of these perceptions are so transparently or false, he came up with a simple set of rules that clear and at the same lime so simple that wc cannot became the basis for digital electronics and computer ever think them without believing them to be true systems, as well as helped people understand the 'Ihe fact that I exist so long as I am thinking, or that ramblings of philosophers like Descartes. what is done cannot be undone, are examples of It I had an old mongrel that had gotten into a fight truth m respect of w hich wc manifestly possess this and lost an ear, he could not he considered to be a kind of certainty. For we cannot doubt them unless dog using the logic statements used to define a dbg wc tliink them: hut we cannot think them without at presented previously: the same lime believing they arc true, as was supposed. Hence we cannot doubt them without at 1. My pet has tur. (true) the same lime believing they are true; that is, we can 2. My pet has one ear. (true) never doubt them. 3. My pet is a dog. (false) -The Philosophical Writings of Descartes. Volumes I and 11 Ihe last statement is false because the original proposition was that all dogs have two ears and l ur. It may be possible to understand what Descartes is Any animal that doesn't meet these criteria could not trying to say in the propositions presented in this truthfully be called a dog. You might be thinking that quote by reading through it, but I am at close to a by using the proposition ‘‘all dogs have two ears and complete loss at what exactly is being said despite fur” as the test, you could claim that a cat or a rabbit having spent many minutes of studying the text and w'as a dog. and you would be right. trying to break it down into some simple statements. What we are interested in is the idea of applying Part of the problem is that Iht^ quote is quite confus mathematical principles to these statements, (t we ing with what seems to be extraneous statements as consider that something can either he true or false, well as seemingly poorly constructed phrases. If you. then we can extend this knowledge, along with other like me, have trouble understanding what Descartes pieces of know ledge, to test to see if something is is trying to put forward here, don’t w orry; we are in true. In the example of the "dog" above. I have made good company because others for many hundreds of the proposition that an animal is a dog il it has two years have been trying to easily and clearly under ears and fur. If you had an animal with no fur. but stand what a philosopher is trying to say. two ears, it could not be considered a dog, just as if One of the people who was instrumental in help¬ you had an animal that had three ears and no fur ing philosophers figure out exactly what other Putting this into table format (known as a truth philosophers were saying was a school teacher by the table), we could write out this proposition in a format name of George Boole. Boole worked to define a that is easy to understand, as show n in Table 10-1. method of converting a written proposition (such as Tn digital electronics, instead of using "true" and “All dogs have two ears and fur”) into a series of “false.” the terms “1” and “0” or “high” and “low” are

151 Section Ten — Digital Logic Table 10-2Logic"END"truthtab'e ered wasthe“NOT"ornegation.Ihisoperationis become morecomplex,theneedforsimplifyingthem time. Idothisbecauseasthelogicaloperations “A" and“B,”noticethatIhavedoneitinsuchaway only ifbothinputsarctrue. "AND.” the"OR”iswrittenoutasshowninTable ues tobecomemuchmoreobvious. value atatimeallowsrelationshipsbetweentheval¬ becomes moreimportant,andonlychangingone high) thentheresultwillbetrue. thinking ofthe“OP"ifbothvaluesaretrue(or1or a situationtobetrue,llusisnotanaccuratewayof “()R" aseitheronevalueoranotherbutnotbothfor true. Usingthetruthtableformat1usedlor sonality”) ifeitherorbothoftheconditionsweie (such as“Acatisananimalwithclawsorabadper¬ that onlyoneofthetwovalueschangesatanyone¬ the “AND”function:resultofwhichistrueifand that twovaluesinan“OR”statementwouldbetrue and 10-3.Tables10-1through10-3areexamplesot could berestatedinthesetermsusingthelabels“A” RE nandB for “Twobars”and“B”tor“Tur.”asinTables10-2 used. The“AND"truthtablewrittenasTable10-1 152 10-4, True o o Two Ears Table 10-1“Truthtable"usedtodefinea"dog False False n i o True t i 1 0 0 When Ihavewiittenoutthedifferentvaluesfor In moderncolloquialEnglish,wetendtothinkof Along withthe“AND”operation,Boolefound The lastbasiclogicaloperationthatBoolediscov¬ 1 ?3 Robotics Experiments for the EvilGenius True 1 also False Fur hue False False- False Dog? True cation oftheserulesinAnInvestigationtheLaws of Thought(1854),theywerediscoveredbycomputer them. metic, alongwiththebasiccircuitsthatimplement duce youtomanyoftheintricaciesBooleanarith arithmetic. Inthefollowingexperiments,Iwillintro¬ within thecomputersandbecameknownasBoolean perform simpleoperationsonthem, electronic computers,whichcouldsensehighand architects anddesignerswhendevelopingthefirst ations toperformverycomplexoperations(liketest¬ ter) totest.The“NOT”truthtableisshowninTable because itonlyhasoneinputvalue(calledaparame¬ wheels”). “NOT"isdifferentfrom“AND”or"OR” true ifitsvalueisfalse(asin“Acardoesnothavesix low-voltage levelscheaplyandefficientlyaswell the startofthissection).Manyyearsafterpubli¬ ing thepropositionsmadeinparagraphquotedat 10-5, Table 10-4 Table 10-3Voltage-level"RND"gate Table 10-5TheNOTtruthfable R input/output truthtable R Not R 0 0 Low o i High High Low 1 I 0 ! Boole’s rulesbecamethebasistotoperations Boole wasabletocombinethesethreebasicoper¬ Logic High low Low B 0 0 l High l B "DR truthtable 0 1 High 1 1 R DPB Low Low Low R andB ' “- Experiment 53 X Basic Gate Operation nc CD riment 53 — Basic Gate Operation

Three LEDs, any color

74C09, CMOS AND gate

74032. CMOS OR gate

74C04 CMOS NOT gate

0.01 pF Capacitor (any type)

I think the best way to understand the operation of will discuss this important difference in more detail digital logic is to actually build some circuits to test later in this section them out.The circuits presented in this experiment If you are familiar with electronics, you might be can be built in just a few seconds, and by using I .EDS, surprised that I did not use the 40xx series of CMOS you will see how the outputs change based on the parts. The 40xx series is the most popular CMOS value of the inputs. Although modern Transistor-to- logic family, but it does not have enough current Tmnsistor Logic (TTL) logic chips are very easy to drive capabilities to light an LED. If you wanted to work with, they require a 5-volt regulated power sup¬ drive an LED from it, you would have to use a bipo¬ ply. To avoid the need for a separate power supply, lar transistor to amplify the output current, as 1 have the circuits presented in this section will use 74Cxx shown in Figure 10-1, which allows current to flow logic, which can be run from 3 volts to 15 volts and is through the LED when current is output from the ideally suited for a 9 Volt alkaline radio battery. CMOS gate to the transistor’s base. TT L is a bipolar transistor-based logic technology To change the voltage at the input of the logic and first invented m the mid-T>htis. remaining popu¬ chips. I used the circuit on the left-hand side of Figure lar ever since. The chips themselves offer fast per¬ formance (an 8-nanosecond transition time or less) and reasonable output current capabilities (approxi¬ Vbat mately 20 mA). The logic functions built into the 74xx chips are called “gates” because they gate out¬ put signals based on theii inputs. The 74Cxx logic chips have the same pinout as standard TTL chips (which are presented at the end of this section), can run over a wide power input, and can source enough current to light an LED.They do not operate at the same speed as TT L and cannot source or sink as much current as FI L. For the most part 74Cxx can be put in any application that uses standard TTL, as long as you remember that Comple¬ mentary Metal Oxide Semiconductor (CMOS) logic is Figure 10-1 Current amplifier for 40xx to drive an voltage based, whereas TTL logic is current based. I LEI)

Section Ten Digital Logic 153 Experiment 53 — Basic Gate Operation gate. UsingtheknowledgethatwhenLLDison. the ANDgate;>oushoulddiscover itisthesameas the introductiontothissection. table likeTable10-6toinvestigate theoperationof the correspondinginputishigh,youcancreatea back andforthtotestoutthefunctionofAND 15 4 the ANDgate, youcanlookattheoperation ofthe ation oftheANDgate,usecircuitshowninFigure AND gateusingtworelays;whenbothinputscause “high.” Figure10-4showsapossiblecircuitforan only passesanelectricalsignalwhenbothinputsare indicating thechip'spowerinputsononeofitsgates. 10-5. Inthisdrawing.Ihaveusedtheconventionof the relaystoclose.Vpowerisoutput.Totestoper¬ (the schematicsymbolisshowninFigure10-3),which instruments. track theoperationoflogiccircuitwithout need otadigitalmultimeter(DMM)orothertest output isSlow.”Thesecircuitswillallowyoutoeasily age outputis"high”andnotlighttheLEDwhen a “0”)willnothavetheLEDlit.Theoutputcircuit to groundthroughthe1kresistorandLEDwill age). Iftheswitchisopen,gatewillbeconnected (the rightsideofFigure10-2)willlightwhenthevolt (or a“1")willlighttheLEDand"low"voltage not belighted.Byusingthiscircuit,a"high"voltage lor thegate'sinputtorecognizeitasa"high"volt across theLEDlwhichwillalwaysbehighenough will beequaltothebatteryvoltageminus passes throughtheLEDdownlkresis¬ and Output tor. Thevoltageattheswitch'lkresistorconnection LFDy^ Figure 10-2LEDcircuitsfortestinglogicinput 10-2. Inthiscircuit,whentheswitchisclosed,power When youarecomfortable with theoperationof When youhavethecircuitbuilt,moveswitches Hie mostobviouslogicfunctionorgateis"AND” Vbat ;SPST Switch 123 Robotics Experiments for the EvilGenius Gate Input Oupul Gate Figure 10-6ORgate Table 10-6TruthtablefortestingANDandOR Pin I3 gates Figure 10-5CircuittolestoperationofANDgate Figure IQ-MTworelayANDgateanalog Voltage fOutputJ High (IEDon)Low(LEDoff) Figure 10-3ANDgate High (LEDon) L.ow (I.FDoff)High(LEDon) 1 ,ow(I,EDoff)Iow(LED A B Vpower Output Output Output OR gate (the schematic symbol shown in Figure 10- Experiment 54 — CMOS Touch Switch A-[>> Output 6), which outputs a high voltage if either input is high. The circuit for testing the OR gate is shown in Figure Figure 10-8 NOT gate 10-7, anti the breadboard wiring is identical to the one used tor the AND gate. The last basic gate is the NOT (the schematic sym bol shown in Figure 10-8) and inverts the logical sig¬ nal from a high to a low. The NOT gate is different from the AND and OR gates as it only has one input

Figure 10-9 Circuit to teat operation of NOT gate

Build the NOT test circuit shown in Figure 10-9 and once you have done this, create a three-row by two-column table, recording the output values for the Figure 10-7 Circuit to test operation of OR gate inputs.

Experiment 5 4 CMOS Touch Switch

Assemble^ hrPaabo

24-gauge

74CC4

1 OM res i si

1.5m resistcr

lk resistor

LED, any color

0.01 (iF Capacitor, any type

It is a very common misconception that digital logic one. digital logic can be keyed by both voltage and always uses voltage as its input. Often it is assumed current with the most popular logic families being that digital inputs are keyed by voltage, but this isn’t controlled by current and not voltage. always the case. Voltage is used to check the logic lev¬ When I was a teenager, it wasn't unusual for prod¬ els, but.as I will show in lhis experiment and the next ucts to be built with touch switches where the user

Section fen Diqital Logic 155 Experiment 54 — CMOS Touch Switch shows theoriginaltouchswitchcircuit;whenauser simply touchedametalpadonanelectronicdevice used tc>simulatethebehaviorofahigh-gainampli- amplifying configurationinwhichtheamplification circuitry. would touchthemetalpad,115-voltACpresent amplifier iswiredinwhatknownasanoninverting voltage andmakesuiethatonlythepositivecompo¬ fied laytheoperationalamplifierandpassedtoother in theroomthatisinducedwithinapersonampli¬ that performedsomekindofaction.Figure10-10 passed totheop-amp ing whentheswitchisn'tbeingtouched,orwillheat oi moretoensurethattheoutputwilleitherbenoth¬ positive input.Thegainofthecircuitshouldbeat2(X) age dividerandamplifiesanysignalpassedtothe to thenegativeinputofop-ampthroughvolt¬ factor (knownasgain)isdefinedbytheformulaon nent ofthesignalispassedtoamplifier.The Figure ID-IDSimpleop-amp-basedtouchswitch 156 touched andrhevoltageoftheperson'sbodyisbeing the positivevoltagelevelwhenswitchisbeing Figure 10-10.Iheoutputoftheamplifieristedback Figure 10-12 CMOS inverteroperation fordifferentinputs CMOS logiciscontrolledbyvoltageandcanbe Hie diodeinthecircuitisusedtoclampinput 123 Robotics Experiments for the EvilGenius A “0” Input OFF ON ,r- MOSFET N Channel MOSFET P-Channel Amplifer Wired asa Op-Amp High-Gain Noninverling Op AmpGam-(1+Rb/Ra) -"I" Output Through Current Output MOSFET P Channel Sourced The CMOSNOT(inverter)logicisshowninFigure Clamping Clamping I diodes thatensurethevoltageinputleveldoesnot Diode Diode A gate, thenchannelMOSFETconnectedtoground current) controlled.MC)SFET-basedlogicischeaper diodes helppreventdamagingvoltagesfrombeing as electrostaticdischargeorESD),andthetwo damage thetransistorswitlunchip).N-channel exceed thepowersupplyranges(andpotentially tier, suchastheoperationalamplifierinFigure10-10. Figure 10-12.Whenahighvoltageisinputtothelogic its logicandrequiresfewermanufacturingsteps. passed tothetransistors. and PchannelMOSFETtransistorsusedinCMOS lo manufactureduetotheeliminationofresistorsin bipolar transistorsisthatMOSFETSarevoltage(not logic areverysensitivetostaticshocks(alsoknown 10-1. Figure 10-11BasicCMOSinvertercircuit Input The CMOSNOTgateconsistsoftwoclamping The operationofthetwotransistorsisshownin Ihe primarydifferencebetweenMOSFETsand A Vdd A “1" Input ON MOSFET OFF N-Channel MOSFET P-Channel Vdd Vss - Buffered Through Current MOSFET N-Cbannel Sunk MOSFET P-Channel MOSFET N-Channel - O'Output Input Inverted turns on and pulls the output to ground (Vss or Experiment 54 — CMOS Touch Switch CMOS logic). When the input is a low voltage, the n- channel MOSFE1 is turned off and the p- Channel MOSI LI is turned on, tying the output to the chip’s power input (Vdd). To demonstrate the operation of the CMOS inverter and how it can be controlled by just voltage. Figure 10-13 Practical touch switch circuit I created the circuit shown in Figure 10-13. Hie input to ihe circuit’s inverter is held low by the 10M resis there is a good chance that it will work without any tor tied to ground, but will change state when the problems. If you are in a room with incandescent input is connected to a voltage source. wiring, which does no! radiate as much energy,you When you wire the circuit, make sure that you may find that touching the switch will not turn of) the place two pieces of stripped wire side by side as LED; this is w by 1 included the connection to Vdd. shown in the wiring diagram (Figure 10-14).These Your skin normally has a resistance of around 1.5k, so two bare wires are your touch switch; when you when you touch both the wire connected to Vdd and touc h both of them, you will complete a very low cur the 1.5M/10M resistors, you are actually creating a rent circuit and the input of the CMOS gate w ill be voltage divider circuit with the voltage at the inverter pulled to a high voltage, which will turn off the LED. input at almost Vdd. If you do the math, you’ll dis¬ Removing your finger will allow the gate to be pulled cover that the v oltage being passed to the CMOS gate down to ground again (via the 10M resistor) and the will be around 90 percent of the Vdd voltage. LED will turn on. You may find that the LED lights tin predictably You might want to try removing the bared wire when you touch the bared input wire or simply wave that is connected to Vdd to see if just the induced volt¬ your hand over the chip. In this circuit, there may be age in your body would cause the inverter to change some induced voltages from your body that are ocea state. If you are in a room with fluorescent lighting. sionallv high enough that the CMOS inputs recognize

annna a- - — 1 1 cuquq u Bared Wires 5 5 Touch Switch

Figure 10-1M Wiring for CMOS touch switch. Note the bared wires for the +5-volt connection and the touch sensor.

Section Ten Digital Logic 15? Experiment 55 — Bipolar Transistor Gate technology thatisaprecursor toTTL. ples canbecombinedtoperformspecificlogicfunc¬ one: thiscircuitdoesworkasaninverterandmulti¬ strated iutheearliersection), butitisnotasrobust tions, butitisnotaTTLgate. Thisgateisactuallya chip. IInlikeCMOSlogic.TTLiscurrentcontrolled, Resistor-to-Transistor Logic (RTI)gate,whichisa tused thiswithaTTLlogicgate,butitactuallyisn't ated anumberofdifferentlogicfunctionsusingthe which givesitsomedifferentoperatingcharacteristics tor Logic"(TILiTTLiscreatedfromNPNbipolar ple stai1workingwithiscalled‘TransistortoTransis¬ either toVddorVssinyourcircuit,youcouldfind 158 resistor/NPN transistorinverter.Youmayhavecon¬ that 1willdemonstrateinthisexperiment. transistors andresistorsthatarebuiltonasilicon unexpected responsesindifferentsituations. reason, everyunusedCM()Sinputmustbetied amplifier circuitshowninFigure10-10)andtorthis to veryhighgainamplifiersHiketheoperational thorn ashighinputs.CMOSgatesworkverysimilarly Fhe mostpopularformofdigitallogicthatpeo¬ KIL canbeusedforlogicfunctions (asIdemon In thesectiondealingwithoptoelectronics,1cre¬ Bipolar Transistor-BasedTTL“NOT”Gate 123 Robotics Experiments for the EvilGenius Assembled PCBwith SPOT switch Two 100kresistors 2.2k resistor Two 1N914/1N4148silicon Four ZTX649transistors 10k PCB'-mountablepoten¬ 150 tiresistor 4 .7kresistor 1.5k resistor Ik resistor tiometer breadboard diodes Experiment 55 signals canbesent,lessening theusefulnessofRIL delayed riseandfallslowsdown thetimeinwhich and signalswilltakesometime toriseandfall.This should recognizethattheresistorwillbepartof current ispassedthroughtheresistortoground, current thatcanpassthroughtheresistorconnected TTL.TTL soughitorectifytwoproblemswiththe RC networkusedtotimetheoperationof555, timer thatIintroducedearlierinthebook,you and thetransistor’scollector.(ToingbacktoIhe555 wasting asignificantamountofpower. be used,butIfthetransistorison.alargeamountof carpet orbytouchinglivewiresinyourhome.Inthe before touchingtheswitchbyshufflingonasynthetic logic. limiting resistorbetweenpower(calledVccforTTI,) ing diodesontheinput. hood thatyouwilldamagethem,despitetheclamp¬ energy tothegates,andthereisaveryhighlikeli¬ to thetransistor’scollector,Asmallvalueresistorcan RTI gate.Thefirstproblemisthelimitedamountof first case,youwillbepassingamassivesurgeof Tool Box The secondproblemistheuseofcurrent- Please donotattemptto“chargeup”yourbody Wire strippers Wiring kit DMM Experiment 55 — Bipolar Translator Gate A ITL inverter (Figure 10-11), although it looks Vcc Vcc Vcc more complex, is actually a very elegant circuit as ] will explain in this experiment. In tact, it has some features that make it easier to use than the CM( >S logic chips I primarily use in this section. The first feature that I would like to bring to your attention is that TT L. is not voltage conttolled the Output "Tied to same way that CMOS logic is. A TTL is active when Ground current is drawn from it. ITie input diode, resistor, and transistor can be modeled as the three diodes anil resistor. You should see that current can be drawn from the input, and it comes from a current limiting resistor connected to the chip’s power Figure 10-lb TIL inverter with a “/” or floating input Current cannot be driven into the input pin of a TTL gate because ol the reverse-biased diode built into the emitter ol the input transistor. I his means Vcc Vcc that while also being current controlled, the current used lot control is provided within the chip, mini- Current mizing any worrying that you might have about Flow Input properly sourcing the correct amount ot current to Pulling the gate. Current from Transistor Output When current is not being drawn from the ITL “tied’' to inverter gate input, current follows the path shown m Vcc Figure 10--16. When you follow the current path, you will see that the current will ultimately turn on the bottom-right transistor, connecting the gate’s output pin to ground (low voltage output). When current is Figure 10-17 TTL inverter with a 0 input drawn from the TTL input pin (Figure 10-1J), the current that ultimately turned on the bottom right transistor is taken away, due to the in a different path effectively tying the output to power and driving out for currents taken within the gate. This change in cur¬ a high voltage. rent flow ultimately turns on the top-iight transistor. To see the operation of the TTL. inverter, you can build it as a circuit as shown in Figure 10-lb. By con¬ necting the SP1 )T switch to ground, you will be allowing current to flow from the ITL inverter to ground, causing the upper right transistor to turn on, passing current to the LLL> to turn it on. If you checked the voltage of the input pin while the switc h was open or connected to 9V, you would find that there is no voltage; this is due to the effectively reversed diodes of the gate that block current flow. Output When there is no current flow, there is no voltage. With this done, you can now look at the analog aspects of the circuit by putting a potentiometer in the circuit, as I have shown in Figure 10-18, and adjust it until the L.EL) Hashes on and Off. Measure the voltage across the potentiometer and then

Sectiun Ten Digital Logic 159 Experiment 55 — Bipolar Transistor Gate operation operation Figure 10-19CircuittotestvoltagecontrolofTTL Figure ID18(ircuittotestamentdrawforTTL —j— Battery SPDT <> Switch 9-Volt 123 Robotics Experiments for the EvilGenius > 4.7k2.2k _L Input B Input A cuit. Insteadofusinganinputtransistorwithasingle built hasathresholdcurrentofaround1mA. ure theresistance(seeFigure10-19).Using()hm's CMOS logicisbuiltfromNORgates. with multipleemitters.Thismodificationchangesthe emitter, thebasicTTLlogicgateusesatransistor the multipleinputgatesbuiltfromTTLlogic.At but youareprobablywonderinghowitisrelevantto law. youwillfindthattheinvertercircuitwas remove thepotentiometerfromcircuitandmeas¬ that allothersarebuiltfrom(seeFigure10-20). inverter intoaNANDgate,whichistheTTLgate just wanttosaythatallTTLlogicisbasedoilthiscir risk ofstealingthethunderfromalaterexperiment,I transistor Figure 10-20TTLNANDgateusingtwo-emitter Die TILinverterisusefulfortheNOToperation, Output Experiment 56 — Sum of Product Circuits Experiment 56 Sum of Product Circuits

Tool Box

Assembled PCB with Wiring kit battery

Three SPOT switches

Four Ik resistors

Four LEDs, any color

7 9C08, CMOS AND gate

74C32, CMOS OR gate

7 4C0<}, CMOS NOT gate

Three 0.01 |iF capaci¬ tors. any type

When l presented the basic logic circuits, one thing input is zero, then zero multiplied by anything is zero; that may not have been clear is that they are building the product of 1 and 1 is 1). OR is represented as blocks and not necessarily complete functions addition because the result is not equal to zero if needed for an application. When these basic func¬ either input is not equal to zero. The exclamation tions are combined, they allow multiple inputs to cre¬ point (!) is used for the not (Junction, ate specific outputs to meet specific requirements. Looking at the equation above, you should see that For example, when you are starting the “program the first thing done is to bring together the inputs that function of your VCR, you can cither press the all have to be true for the output to be true. These Record and Play buttons on the front panel of the ANDed outputs are combined together in an OR unit or press the Record button on the remote con¬ gate to produce the final output. Using the nomencla¬ trol. You could write this out as the statement; ture introduced above, the AND output could be rep¬

Start recording it the Record and Play buttons on the resented as a product and the OR output as a sum. front panel of the VCR are being pressed or if the 1 his is where the term sum of products comes Record button of the remote control is pressed. from.Tliis is a very intuitive way to represent com¬ plex logic functions and will be used throughout this Hits is not quite as profound as the logic state¬ book land most others). In this experiment I will ments put toiward by the great philosophers, but it show how the logic functions are combined as a sum follows the same rules of the logic as discussed at the of products to create a complex function. start of this section. If we were to assume that the buttons were true when they were pressed, and In Figure 10-21.1 have shown a memory map for replaced AND with a dot (■') and OR with an addi¬ a fictional computer that only has eight memory tion sign ( + ) the function could be written as an locations. l our of them are located in a single chip equation such as: They are the shaded regions and are accessed when a pin has a high (1) voltage applied to it.

Start Recording = {"Panel Record" Ihe table in Figure 10-21 could be considered the "Panel Play") + "Remote Record" truth table for the decoder function.The first is that I treat the three address line inputs like a three-bit These two symbols for AN Ding and ORing are binary value (I will explain this in more detail later in based on the two functions’ operations, AND the book) and change each value in an orderly pro¬ behaves like a multiplication operation. I sing binary gression. making sure that each possible value is rep¬ values, the result is 1 only if both inputs are 1 (if one resented m the table.

Section Ten Digital Logic 161 Experiment 56 — Sum of Product Circuits confirm thatitreallydoeswork. create atruthtableandworkthroughthegatesto would looklike.Thecircuitisquitestraightforward, cuit forthedecoderdesignedtorthisexperiment together andANDingtheresultisnotintuitive.Fig¬ with, becausethinkingintermsofORinginputs there is,butitisquiteabitmoredifficulttocomeUp common aboutthemaswell.InTable10-7.1have one ofthe"products*’Iwasdiscussingearlier.The although toreallyseehowitworks,youwillhave ure 10-23showswhataproductofthesumlogiccir¬ a "productofsums’'methodpresentinglogic.Yes. duce thisfunctionisshowninFigure10-22. plished bytheN()Tgate,andlogiccircuittopro before theyareANDcdtogether.Thisisaccom¬ found thattheoutputishighif!A1AND!A0true. moved thefifthentrytobebesidefirstand that resultin"OutputHigh"toseeitthereisanything truth tablecanberearrangedwiththetwoinputsets Figure 10-21Simplethree-address-linememorymap have tobeinverted,sozerosarechangedones 162 Combining A2ANDA1togettheoutputhighis You mightbewonderingifthereissuchathingas For thiscasetobetrue,thevaluesforA1andAO 153 Robotics Experiments fortheEvil Genius Enable' LineisActive Shaded Regionsare Addresses inwhich the 'MemoryChip junctions asthesumofproductsusedinthis Table 10-7Outputresults experiment Figur e1023Productofsumsprovidingthesame Figure 10-99Three-address-linedecodercircuit RP RlROOutputComments 0 10 0 110 0 1 0 1Outputishighit!A1• 110 1OutputishighifA2• 10 toot At istrue ! A0istrue I )—Chip Enabler Memory Experiment t>7 — Common Logic Experiment 57 Common Logic Built from the NOR Gate

Parts Bin Tool Box Assembled PCB with Wiring kit. battery

Two SPOT switches

Two lk resistors

470 .0 resistor

Tnree LEDs, any color

74C02, CMOS NOR gate

Two 0.01 (J.F capacitors, any tyPe

When you purchased the chips for the previous two channel MOSFET transistors are turned on and pro experiments, you probably assumed that they were vide a direct path for current to flow from the chip’s built from something called AND, OR. and NOT power source to the output. When the inputs arc low. gates, last as I showed how a complex circuit could the n-channet MOSFET transistors are turned off be built from these basic gates in the previous experi¬ and there is no ground connection. In Figure 10-26’s ment. these gates are built from even simpler gates: drawing on the right, one of the inputs is high and the CMOS logic technology uses the NOR gate (see p-channel MOSFET transistoi that it is connected to Figure 10-24). is turned olf while the N channel MOSFET is turned The NOR gate outputs high (!) when its two on. This blocks current from the power source and inputs are tow (0),' and it can be built veiy easily in connects the output directly to ground. CMOS technology. Looking at it from the perspec¬ To implement the three basic functions that 1 tive you have heen given so far, the NOR gate con¬ introduced in this section using the NOR gate is quite sists of an OR gate m which the output has been simple, and this will be the point ot this experiment. inverted. The small circle at the end of the OR sy m Before going on, I suggest that you wire the bread¬ bol indicates that the output is inverted.!(A 4 B) is board as 1 have shown in Figure 10-27; from here, you the written format for the gate. will create custom wiring to create each different It is piohably surprising to hear that the NOR gate gate. Note (hat in Figure 10-27 1 have wired an LED can be built very easily in CMOS technology. Figure to act as the circuit output; this output will be used 10-25 shows how a two-input NOR gate is imple¬ for each circuit presented in this experiment. For all mented using four MOSFF.T transistors. When laid out on a silicon chip, this function can he imple¬ mented in a very small amount of area without respiring any aluminum traces that could interfere Input A- with gate interconnections on the chip rhe operation of the NOR gate is show n in Figure 10-26. In the left drawing. I have shown what happens Input B when both inputs are tow. In this case, the two p- Output

Output

Figure 10-2M NOR gate Figure 10-25 CMOS NOR gate

Section Ten Digital Logic Experiment 57 — Common Logic k Figure 10-26CMOSNORgateoperationwithdifferentinputs these circuits.Irecommendthatyoucreateatruth functions huiltfromthetwo-inputNORgate dependent onthevalueofsingleinput.Youmay implemented asshowninFigure10-28.Withone tion asthebasicgates. the resultsandmakesurecombinedgatesfunc¬ Figure 10-27Basicwiringfortestingoutdifferent instead ofonlyusingoneinput andtheothertiedto see somecircuitsthathavebotliinputstiedtogether input tiedtoground,theNC)Rgate'soutputwillbe table, asinthesection'sfirstexperiment,tovalidate ground, 1havetiedoneinput oftheNORgateto ground tominimizetheload thecircuitdriving input willhave.ForthisciicuU, wheretheloadispro- 164 The mostbasiclogicgateistheNOT,andit 123 Robotics Exoeoiments fortheEvil Genius High Low n at HighVoltage 1 Input Voltage Output Low- Lew Low — vided byaswitchconnectedtothePCH’spowersup¬ connected totheoutputmustbeconsideredandide¬ ply, thisisnotanissueatall.Whenyouaredriving quite easytosee;theoutputofNORgateis gates canbeusedtocreateasingleORgateasshown as aruleofthumb. ally minimizedtonomorethantwoinputsperoutput inputs froma(M<)Soutput,thenumherof realization thatitperformsthesamefunctionas and isimplementedasshowninFigure10-30.The inverted inordertogetapositiveORgatefunction. in Figure10-29.Theoperationofthecircuitshouldbe AND gateisprobablymoresurprising.Tocreatean NO Tgate Figure 1028NORgateusedtomanufacturea manufacture anORgate Figure 10-29TwoNORgates usedto The finalofthebasicthreegatesisANDgate Using theabilitytonegateasignal,twoNOR "’put_Or Output Both Inputs at LowVoltage Voltage Output High- Output Identity Functions Experiment 57 — Common Logic A ■ 1 = A Output A + 0 = 0

Output Set/Reset

A ■ 0 = 0 A + 1 = 1

Double Negation I,aw

Figure 10-30 Three NOR gates used to ! ( 1A) = A manufacture an AND gate Complementary Law A ■ !A = 0 AND gate using NOR gates. 1 used the laws listed at A +! A = 1 the end of this experiment. Knowing that I wanted an Idempotent Law AND function and all I had was a negated OR. I A ■ A = A started with a double negated AND statement along A * A = A with De Morgan's theorem. Commutative Law The follow ing basic rules for Boolean arithmetic A ■ B = B ■ A will allow vou to create virtually any function using a A + B = B + A technology’s basic gates or whatever you have on Associative Law hand. 1 admit that I apparently came up with the (A ■ B) ■ C = A ■ (B ■ C) AND gate equivalent from the NOR gates very (A + B) + C = A + (B + C) quickly, but as you become more comfortable with digital logic and the rules below, you will be able to Distributive Law bend the laws to come up very complex circuits using A ■ (B + C) = (A ■ B) + (A • C) basic NOR (for CMOS logic) and NAND (for IT L A + (B K C) = (A + B) K (A + C) logic) gates. De Morgan's Theorem

’ (A + 3) = IA • !E

! (A • B) = ’A + LB Experiment 58 XORs and Rdders

Tool Box Assembled PCB with battery

Two SPOT switches

Four Ik resistors

Four LEDs, any color

7 4C08, CMOS AND gate

74C86, CMOS XOR gate

Two 0.01 jjlF Capacitors, any type CO M So far in this section. I have introduced you to five of XOR is not a basic operation in any type of logic. m the six basic logic gates (AND, ()R, N( )T, NAND. It is normally written out as a compound operation in tS and NOR). These gates can provide you with almost the sum of products form: tJ all of the capabilities that you will require for any digital circuit.The last type of gate is required for XOR (A, B) = (!A ■ B) + (A ■ !B) < providing basic math functions in digital logic, as I will demonstrate in this experiment. It can also be written out in the produst of sums form as The XOR gate outputs a I any time one but not c the other input is equal to 1. In many texts and refer¬ XOR (A, B} = ! ( (A. + IB) ■ (!A + B) ) ences, the symbol you will see is a plus sign ( + ) with a eucle around it. In this book, I will use the symbol A To prove this is true, you can use the Boolean CO to indicate the XOR function (which is the same arithmetic laws presented in the previous experi¬ Pi symbol as used in PBASIC ).The XOR operation is ment. or you can construct a truth table, such as Table O 10-9, in which each intermediate value for the input Output = A * B X values is calculated and used to find the final value. This type of tool is useful for seeing how a logic equa¬ Ihis operation has the truth table (seeTable tion works (or why it doesn’t) and only takes a few I 10-8) and symbol shown in Figure 10-31. moments to create. Tire X< )R gate is useful when you are confronted 00 lahlc IH-8 XGH gate truth table IT) with situations such as adding two binary numbers together. When 1 start discussing programming, I will R B fl A E present the concept of binary numbers in more -P n (l o detail, but for this experiment, when I add together c o i I two binary values, I would like to display the results

166 123 Robotics Experiments for the Evil Genius Table 10-9 Truth table explaining operation of XOR gate Experiment 58 — XORs and Adders

R B R -i- IB !R B Iff -t- ~!BI ■ (

0 10 1 0 1

111 1 1 0

10 1 0 0 1

I LED when only one input is high is a bit more diffi¬ cult. Betore going on with the experiment, take a pencil and paper, and using the Boolean arithmetic rules that I have presented try to figure out how to mst turn on the LED with AND, OR, NOT, NAND. and NOR gates. 'T” LED or "Carry' If you came up with something that did the job, it would be an implementation of the XOR gate that 1 have presented here. Although I have shown two equations for the function, you may also have discov¬ ‘2“ LED or ‘‘Sum’' ered the following:

Figure 10-32 Half adder circuit

XOR (A, B) = } (!'(!A + !B) + ! (A + B) )

This is the formula used to implement the XOR half adder did for two bits. To do this, two halt adders gate in C TvlOS logic (using NOR gates) and it is the are wired together as shown in Figure 10-33. basis for the 74C86, which is used in the circuit shown When several full adders are combined to form an in 1 igure 10 32 to turn on the 1 LED when only one adder for two multibit numbers, the time required for input is active.The circuit in Figure 10-32 is known as the correct answer is the longest amount of time a a half adder and will turn on the 1 LED only w hen signal takes to pass through all the different halt one input is high and the 2 LED only when both adders to get to the most significant bit. Because the inputs are high. result changes as the signal passes through the circuit, When the circuit shown in Figure 10-32 is used as it is known as a ripple adder. For many applications, part of an adder circuit, the 1 LED output is labeled this type of adder and its delay is acceptable, but for “S” for “Sum” and the 2 LED output is labeled “Cn high-performance computing applications (such as foi “Carry. " The sum outputs the bit result tor adding the two input lines, and the carry outputs whether or not the resuh is greater than I. Hus circuit is the basis 1/2 Adder __ for the adder circuits built into computers, but for it to be useful in a computer some more circuitry has to be added to it. Ihe reason tor having to add circuitry to this cir cuit is in the case where there is a lesser bit providing its cairy value to it In this case, the bits actually have three inputs and must somehow add them all together and pass out an “S ' and “C” bit. just as the Experiment 59 — Pull-Ups/Pull-Downs some ofthedigitalinputstohighlogiclevels.The look ahead)thatproducesitscarryoutputbytesting directly toVcc(togetahighlogiclevel)orground obvious solutiontothisdilemmaistietheinputs you willprobablydiscoverthatwillhavetoset When youdesignyourfirst“practical”digitalcircuit, is thatitcanneverbechanged.Insteadoftyinga explain inthisexperiment, direct connectionsshouldneverbeused,asIwill and anothertypeofadderisused(knownasacarry the signalstopassthroughadderisjusttoolong, the microprocessorinyourPC),timerequiredfor (to getalowlogiclevel)asIhaveshowninFigure 10 34.Thiswillwork,buttherearereasonswhythese inputs tologichighsandlows Figure 10BM(Obviousmethods fortyinggate 168 Ihe problemwithtyingtheinputdirectlytopower Chip Power input Tiedto 123 Robotics Experiments fortheEvil Genius Three breadboard-mount¬ 0.01 |xFcapacitor,any 7 4C00CMOSquadNA4JD gate able SPDTswitches tyFe Pull-Ups/Pull-Doujns Experiment 59 erated anddoesnotrequireasignaltoripple This willholdbothCMOSamiTILinputshigh,and through. the inputvalueswhileoutputisbeinggen¬ strange, butitisveryimportantwhenyouaredesign¬ through apulled-upgateprobablyseemstobe flow throughtheresistortoground. the inputdownifithastobechangedfromahigh a switch(orevensimplewire)canbeusedtopull it througha10kresistorasshowninFigure10-35. pull-up (ICT), whichprovidesamultitudeofpins(knownas ing productstobemanufactured.TheIn-circuitTester pull-down isactuallyrequired,thenjust100pAwill input toalowinput.Byusingtheswitchorwire,if logic inputtothepowerinput.Irecommendpassing Figure 10-35Thebestmethod forimplementinga Being worriedabouthowmuchcuirentisflowing Output Logic Tying lo_ Switch / Optional 1 r- > u r 10k Experiment 59 — Pull-Ups/Pull—Downs PCB to Be Tested Output of Inverter Is Low Due tc Pull- \> Up Resistor 1_> TD- L ‘Bed of Nails," Each *Pin" ICT “Pin” Logic_ or "Nail" Has Driver Circuit or “Nail" State Shown to Right p. Sense Output ICT input Pull-Down ! Passed Override to Tester Figure 10-37 lhe method l recommend to pull down a Ionic input Figure 10-36 InCircuit Tester (ICT) bed of nails connection to PCB

a "bed of nails” and shown in Figure 10-36) that con¬ Switch to Simulate <10k ICT Oulput to Change tact the product’s PCR. is a very common manufac NAND Output toM' turing test. In its simplest version, each pin probe (or "nail") has a logic input, and an open collector dii\er —|-> 7 with each pin is connected to one of the connections (or "nets”) in the cireuit.To test the operation of the I gate, the ICT can cither sense the current logic value or drive the pin low to see what the result is at a Figure 10-38 Circuit to demonstrate pull-up "downstream” test pin. control of an AND gate Even if you are thinking that it is not very likely

that your applications will be manufactured, it is still TI L inputs low, the problem is its impedance is lower a good idea to use resistor pull-ups as shown in Fig¬ than many ICTs can overcome and drive to a high ure 10-35.There will be cases where you may want io voltage level, rhis may seem like actually more disable different sections of your circuit, and having a trouble than its worth (and for virtually all hobbyist pull-up resistor in place will allow the addition of a projects I would agree with you), but if you ever hit direct or switched connection to ground. Many times the big time, you should know what changes should over the years Fvc been thankful to have had the be made to your circuitry to make it easy to forethought of putting in a pull-up instead of directly manufacture. connecting a pin to power or ground, which would For this experiment-1 would like to look at the have meant 1 would have had to unsolder the pin and operation of the pull-up as I have discussed so far. add a resistor. The circuit that I would like use is the AND gate Following a logical progression, you are probably built from two NAND gates shown in Figure 10-38. thinking that putting in a resistor to ground should • When the switch on the 10k pull-up is open, the out¬ be used when you want to "pull down” a logic input put will behave like a standard AND gate. When the pin. Actually, tins is something that you will w ant to pull up switch is closed, the output will be high (and avoid; instead use a pulled-up inverter output as T the LED lit), regardless of the state of the other two have shown in Figure 10-37. switches. Although a single resistor pull-down (no more than 470 fl) could be used for tying both CMOS and

Section Ten Digital Logic 169 Experiment 60 — Mickey Mouse Logic circuit showninFigure10-39 Theshadedareaisused (with goodcurrentsinkingcapability). should notresultinlongswitchingtimes,whichwill to indicatethelocationof MMLgate,andwhen1 nections shouldbeused. present differentgatecircuits thisareawithitscon¬ transistor turnsonandtheoutputispulledtoground should notbeasurprise.ThecircuitfortheMMI, affect theoperationofapplication MMI. mustbematchedtodifferentlogicfamiliesand and simpletheyseemtobe.Tobeusedsuccessfully. or notyoushouldaddanotherchiptothecircuit.In short, andyouateleftwiththequestionofwhether low' current).Whencurrentispassedtothegale, when itisnotbeingdrivenbyanycurrent(andvery NPN transistor.Thisinverteroutputsahighvoltage inverter canbebuiltoutoftwoH)kresistorsandan few resistors,diodes,andmaybeatransistor. most cases,agatecanbe"cobbled’'togetherwith you willoftendiscoverthatareagateortwo 1?0 tal electroniccircuitsisthatwhenyoufinishthem, Mouse Logic(MML)becauseothowunorthodox One ofthemostfrustratingaspectsdesigningdigi- To testtheoperationofiheRtLinverter,use The mostbasicMMLgateisthe"inverter"and lhese simplegatesareottenreferredtoasMickey 15.1 Robotics Experiments fortneEvil Genius Assembled PCEwith Three PCB-mountSPDT Three LEDs,anycolor Two ZTX649NPNtransis¬ Two IN9.14or1N4148 Three 10k.resistors Three lkresistors 0.01 (iFcapacitor,any 7 4C08CMOSquadANDgate 470

Gate Inputs B-O

Figure 10-P0 RTL NOR gate Figure I0-M2 OR gate analog drain

When you have assembled the circuit, test it out by changing the switch positions and seeing how the A—W- Output output changes. You should also create a simple truth table for (his circuit as well as the following ones to B-Kh make sure that they behave as you would expect Once you have tested out the operation of the Figure 1C-M3 AND gate analog circuit inverter, you can simply modify the circuit by adding another transistor and resistor as shown in Figure 10- voltage level will he pulled down and current will be 40 to create an RTF NOR gate. The RTL NAND drawn from the input gate to which it is connected. gate is shown in Figure 10-41. Although the MML AND and OR gates pre¬ Implementing an AND or OR gate in MML is a sented here will work in virtually any application, you bit more complex and requires a good understanding may find that you will want to use a 470 fl resistor of the parameters of the logic families. In Figure 10- with TTI and a 10k one in CMOS logic applications. 42.1 have shown a sample design for an ()R using Ihe reason for doing this is to minimize the current two diodes and a resistor, Ihe use of a pull-down drawn bv the application; with a 470 fl resistor, resistor is probably suipnsmg, but it was chosen to roughly 1.0 mA will be drawn when the output of the allow the gate to he used with both CMOS and TTI gate is low. This current draw decreases to 100 p A logic. In this case, it neither input has a high voltage, when a 10k resistor is used instead of the resistors in then the resistor will pull the input to ground. If the these two gates. input is a CMOS gate, then the input will behave as if it were tied to ground. A 470 fi resistor will allow the I I L input current to pass through ground, and it will behave as it the input was at a low logic level In For Consideration either case, when one of the inputs is driven high, the input pin will be held high, and the gate connected to You should be aware of two myths that are com¬ the output of the OR gate will behave as if a high monly believed about TTI. chips and make sure you logic level was applied to it. understand why they are inaccurate.TI L gates are An MML AND gate (Figure 10-43) is the simplest often said to be internally pulled to power (Vcc). This in terms of components. The diode and resistor work is not accurate, although the gate with no connection together to provide a high voltage when both inputs to an input pin does behave identically to an input are high, but w hen one of them is pulled low, then the tied directly to Vcc. The second myth is related and states that you have to tie an unused TI L input to Vcc because electrical noise can affect its operation, TI L is controlled by current that is sourced within the chip, and external voltage variations will not lead to inadvertently incorrect inputs. CMOS logic (even 74Cxx chips), on the other hand, can be affected by noise and is not internally pulled up. Any uncon¬ nected CMOS inputs will behave as if they are tied to a low voltage input and they can be affected by

Section Ten Digital Logic 17-1 Experiment 60 — Mickey Mouse Logic eties ofTTI,C.AC.andHC/HCTlogicfamilies,'the to considerforyourownuse.Forthedifferentvari¬ when youdon't. don’t havetoworryaboutwhenyouand Table 10-10Logicchips part numberstartswith74.Forthe4000seriesof have compiledalistofbasicchipsthatyouwillwant CMOS chips,thechiphasafour-digitpartnumber. If youalwaystit',upyourunusedinputs,then inputs tovoltageorground,againthroughapull-up.) electrical noise.YoushouldalwaystieunusedCMOS 172 tion, andit'snotabadideatoalwaystieunusedTIL ably throughapull-upasdescribedlaterinthissec¬ Chip Type inputs tovoltageorgroundasageneralrule.(Prefer¬ SUL TIL 4l HO HC/HCT AC CMOS C CMOS F TTL ALS TIL ASUL LUL¬ LS TTL To aidyouinlookingatdifferentlogicchips.I 12 3 Robotics Experiments for t,he EvilGenius Vdd Vcc Vcc Vcc = Vcc - Vcc Vcc = Vcc = Vcc = Vcc — Power Supply Vcc - 3to15V 4 5to5.5V 4 75to525V 4 5toV 4.5 to5.5V 4.5 to5.5V 2 to6V 3 to15V 4.5 tr.5.5V 2 to6V 4 5to5.5V 8 9 ns 30 ns 8 ns 50 ns 4 2 2 ns 5 15 in Transition 0 7Vcc 0 5Vdd 0 7Vcc. 0 7Vcc N/A N/A N/A N/A N/A N/A N/A I/P Threshold starting with4.Table10-10liststhedifferentaspects threshold specificationisanappropriateparameter. section,T ILiscurrentdrivenrathervoltagedriven. to use. of thedifferenttypeslogicchipsthatyouwillwant CMOS logicisvoltagedriven,sotheinput as “notapplicable”because,Idemonstratedinthis source andsinkcapabilitiesconsiderably. voltage oftheindicatedCMOSparts(markedwitha voltage of5volts.IIyouincreasethepowersupply The outputsinkcurrentsarespecifiedforapower In thetable.ImarkedTTIinputthresholdvoltage you willalsoincreasetheiroutputcurrent 0.3 V 0 1V 0 1V 0.1 V 0.1 Vcc 0.3 V 0 3V 0.3 V 0.5 V 0.3 V 0.3 V O' O/P 0 9Vcc 3.4 V 3.4 V 3.3 V Vcc -0.1V 3.5 V Vcc -2V Vcc 2V 3.4 V Vdd 0.1V Vcc -0.1V "1" Output 25 mA 50 mA 3.3 mA* 20 mA 8 mA 20 mA 8 mA 5 mA 0.8 mA* 40 mA Output Sink 12 mA Section Eleven Power Supplies

For most of this book, I tJo a pretty good job of speci¬ lhc resistor values can be specified using the formula fying electronics that are very tolerant of differing for the voltage divider: power supplies and work quite well with simple bat¬ tery packs. Ibis was accomplished by only specifying Voue = vin x (Rs/(Hn + Rs)) parts that can run from a variety of different supplies And: (battery packs) that produce power at voltages from 2.4 volts to over 9 volts. Ilns makes the book experi¬ Vout = 5 volts ments easy to build and increases the possibility that Vin =18 Volts they will work for you the first time, but in the real world, you will have to work with components that To find Rn and Rs. I could go back to Ohm's law must have power supplied at a set voltage and that (assuming 1 wanted 100 mA at I 5 Volts): does not vary by more than a few tens of millivolts or it could stop working. In these cases, you will have to R = V/I include a circuit, called a power supply, which regu¬ lates the voltages and supplies enough current for the Where: circuits to work reliably. V = 5 volts I have presented you with the DC power J = 100 mA equation: R = 50 ohms p = v x r This R is actually Rs in the voltage divider for¬ In this equation,“P" is the power consumed (in mula. and it is actually the resistor equivalent load to watts),“V” is the voltage applied to the circuit, and “I" is the current (in amperes or amps) drawn from the power supply. For example, in a +5 volt Vin Transistor-to-Tnmsistor Logic (TI L) circuit, if 0.15 amps are drawn from the power supply, then the cir¬ cuit is dissipating 0.75 watts or 750 milliwatts. Larlier in the book, I presented the concept of the voltage divider (see Figure 11-1). which is used to convert an input voltage to a smaller output voltage. Vout You might be thinking that you could use this circuit to convert a higher voltage into something that is useable by your electronics, but this is quite problem¬ atic. To illustrate the problems with using a simple voltage divider in an electronic circuit, consider the Vout = Vin * Rs / (Rn + Rs) situation where a robot’s 18-volt battery source is used to provide 5 volts at 100 mA to TTL electronics. Figure 11-1 Voltage di vider

173 the electronics running at 5 volts. This value (even tronics will work at, the robot's logic will fail by turn¬ though it is never used) must be calculated, so that ing on one LED. the current limiting resistor (Rn) can be calculated: Rather than trying to come up with work-arounds for these problems, let me just suggest that you look Vout = Vin x (Ks/(Rn + Rs)) at using a voltage regulator, which will convert one 5 volts = 18 volts x (50 ohms/(Rn voltage to another (one that can be used by the elec¬ + 50 ohms)) tronics m your circuit) and, more important, will be Rn = (18/5) x 50 ohms - 50 ohms tolerant of changes in the supply voltage and in the

= 130 ohms current load In this section, I will introduce you to some simple power supply circuits that have the fol¬ Finding or producing a 130-ohm. resistor isn't diffi¬ low ing characteristics: cult: at least it isn’t for a standard power dissipation resistor like the 1/4 watt resistors that have been used • They are safe for their users and designers. for the projects in this book. I Tie problem comes • ITiev are relatively efficient in terms of the w when you start looking for a resistor that will dissi amount of power that is lost converting volt¬ pate the amount of power that this one does. If you age levels. 0) use this formula (recognizing that there is a 13-volt ■H • They provide very accurate voltage levels drop across the 130-ohm resistor), you will be dissi¬ independent of the voltage input or the cur r*HI pating 1.3 watts of power. Although a 1/4 watt resis rent required by the application. CL. tor can be purchased for a penny or less, you’re going • They are inexpensive. 04 to find that a 2-watt resistor will cost you several dot P lars and it will get surprisingly hot in operation (lost • Their design can be optimized for the applica CO power that could have been used by the robot). tion that they are providing power for. Another problem with this circuit is what happens A few important points about what is presented in M if the load changes or the battery output changes. As this book: I will be focusing on creating power sup¬ 1 will discuss in this section, battery output changes p.F or greater) and a medium value (0.001 to 0.1 pF) robot, you will find that turning them on or off will CD capacitor on the controller power input.The large drastically affect the effective load of the electronics H capacitor will be responsible for filtering out low- and, m turn, the voltage being applied to it. Assuming CO frequency power upsets, w hereas the smaller capaci¬ that a resistor requires 5 mA to light, when ail LED is tor will help take care of high-frequency transients added to the circuit, the voltage drop through the (such as caused by motors turning on and off). Along a I 300. resistor increases by 5 percent, or (rom 13 volts with the Capacitors, you might want to consider a o to 13.65 volts, resulting in 4.35 volts lor the electron¬ series inductor to filter out any current transients. •H ics. Since 4.5 volts is the minimum voltage the elec¬ -P O

174 123 Robotics Experiments f o" the Evil Genius Experiment 61 Zener Diodes

Assembled PCB with Tool Box Wiring kit breadboard DMM 220 i 1, 1/4-watt resistor

200 11, 1/4 watt resistor

330 11, 1/4-watt. resistor

5.1 V Zener Diode, any tyFe

LED, any color

At the start of this book, I demonstrated electrical This is exactly how the Zener diode works, except concepts using water analogies, but quickly stopped that extra current does not leak out over the side” doing this as I started looking at semiconductors, but is passed (or shunted) through the diode.The ITicse devices can rarely be modeled effectively using diode itself is expected to be reverse biased when it is water analogs. Some semiconductor-based circuits, wired into the circuit, and it will pass current through like Zener diode power supplies (Figuie 11 -2), do it to maintain a set voltage level at its anode (positive lend themselves to being modeled using water terming). This property is known as breakdown and analogs (Figure 11-3) The Zener diode power supply it is not unique to the Zener diode. All diodes will works as a shunt regulator, applying a specified break down when a high-enough reverse-bias voltage amount of current to a circuit at a rated voltage and is applied to them. A diode will resist passing current shunting the rest as wasted power. as voltage is applied to it until n reaches a point When the term “shunt is used, it is simply saying where the reversed PN junction is overwhelmed and that excess is passed through the Zener, away from the diode starts conducting in the reverse-bias direc¬ the circuit, and this concept is illustrated in the water tion. ITie breakdown voltage for a Zener diode is pressure regulator shown in Figure 11-3. This water usually specified to be in the range of 1.5 to 25 volts, regulator simply consists of a catch basin with a hole whereas the breakdown voltage for a typical diode at the bottom: water coming out of the hole is at a (say. the 1N4148/1N914 that I usually use) is 75 to 1(H) pressure that is determined by the depth of water in volts. the basin, lo maintain this depth (and bottom pres¬ Specifying a Zenei diode for use as a power sup¬ sure), even with water being drawn from the hole at ply in an application isn’t very difficult, but it will the bottom, water is continually poured into the require you to understand what your incoming power basin. More water is pouring in than is expected to specifications are, as well as what the required exit through the hole in the bottom, with the excess leaking out over the side.

High-Pressure Water Source Voltage Input Current- Water Falling Into Limiting ^Bow Height of Water Resistor Overflow Determines Water Regulated Shilling . Pressure Output out of Zerer the "Regulated" Diode Bowl 1—Output Flow

Figure 11-3 Constant water pressure using basic Figure 11-<2 Zener diode voltage regulator shunting

SeLtion Eleven Power Supplies 17? Experiment 61 — Zener Diodes drop throughitwillallowthesameamountofcur¬ current-limiting resistorRmustbedeterminedFora can beassembled,thevaluetorZenerdiode’s cuit ThecircuitisshowninFigure11-4,andbeforeit experiment dram the valueofRcanbecalculated: has a2-voltdrop,sousingthebasicelectricalformu¬ rent asthepoweredcircuitusestopassthioughit.In Zener diode),Rmustbechosensothatthevoltage in termsofcurrent(noisshuntedthroughthe Zener diodepowersupplytobeLOGpercentefficient Zener diodetoactasapowersupplyforanLTDcir¬ enough currenttobepoweredinallcircumstances, Care mustbetakentoensurethatthecircuithas diode’s powerrating,canbesomewhatcomplex. to beusedwiththeZenerdiode,aswell diode ratedat5,1volts.Specifyingtheresistorthatis las, 1candeterminethecurrentthroughL.ED: this application.IamgoingtoassumethattheLED margins mustbedesignedintothecircuit. battery thatisdischarging).Todothis,somekindot including iftheinputpowersags(ifitispoweredbya the Zenerdiode,For5-voltcircuits,1usea circuit’s voltageshouldbethesameasratingof current isforthecircuitbeingpowered.Thepowered 176 Tiguie 11-MZenerdiodevoltage regulator Assuming thatthebatteryproducesaneven9v, I-or thisexperiment.1wouldliketousea5.1-volt R =V/i i =V/R = 415il = (9V-5.1V)/9.3.9wA = 9.39jnA = (5.1V-2V)/330il 153 Robotics Experiments for the EvilGenius used inapplicationsthatare batterypowered;they For thisreason,Zeneidiode regulatorsarerarely Zener diode,resistor,andL ED applicationislost another way.five-sixthsolthe powersuppliedtothe dissipated intheZenerdiodeanditsresistor.This shunt 50percentofthecurrentbeingpassedto Zener diodepowersupplies,Inormallydesignthem erant ofsagsintheinputvoltage.When1design 9.4 mApassingthroughtheLED. carbon battery(with9.12Voutput)andmeasured difference olabout1percentfromthetargetedvalue. can makea420flresistorusing200i>and220il makes thisZenerdioderegulatorapplicationonly parts ofthiscircuit.30mWhasdissipatedinthe parts ratedata1/2wattormore. the situationwherepowerdissipationrequires dissipated by174-wattparts,youcanlindyourselfin dissipated byitsresistorandZenerdiode.Amaxi¬ shunted throughtheZenerdiode,youwillhaveto circuit). Forthisexperiment.Ireplacedtheseries420 so thattwicetheexpectedrequiredcurrentpasses with theZenerdiodepowersupply:itisnotverytol¬ them tolighttheLEDIhisismajorproblem 5.1 volts,butnotenoughcurrentwaspassingthrough across theZenerdiodeand330-ohmresistorwasstill that isnormallyrequiredtolightit)Thevoltage being outputfromthebatteryand2.5mA ning overnightandduringthemorning,thenI in series.Thisw'illresultacurrentof9.29mA(a LED/330-ohm resistordiodecircuit,and160mWhas Although thesepowerlevelsarequitelowandeasily tor. and90mWwillhedissipatedbytheZenerdiode. mum ot70mWwillbedissipatedthroughtheresis¬ make sureyoucalculatetheamountofpowerbeing through theLEDtobe5.1mA. was drivingout6.3volts.Imeasuredthecurrent 11 resistancewithasingle220flresistance,andI through theresistor(andsothatZenerdiodewill passed throughtheLED(whichislessthan5rnA found theLTDwasnolongerlit,1measured6.3volts 15.8 percentefficientintermsofpower,orput found thattheLEDlitagain,eventhoughbattery To checkonthestabilityotthiscircuit.1leftitrun¬ When Ibuiltthiscircuit.usedacheap9-volt No standard415Uresistorsareavailable,butI Looking atthepowerdissipatedindifferent By allowing50percentofthecurrenttobe arc suited for applications that use household wall diode's current-limiting resistor. If a short or unex Experiment 62 — Linear Power Supply power. pcctcdlv high current drain is in the circuit being One of the aspects that makes Zener diode regu¬ powered, this resistor will prevent a damaging lars attractive for use in power supplies is the Zener amount of current being passed to the circuit.

Experiment 62 Linear Power Supply

220 fl 9-resistor SIP

10 pF electrolytic capacitor

0.01 jaF caf acitor any type

LED, any color

Eight-position SPST switch

When I described the Zener diode regulator acting When fuel is drawn from lhe bowl, the fuel level like a basin of water in which the unused current within the bowl drops (along with the float) and the was simply lost. I'm sure that many people grimaced valve opens, allowing more fuel into the bowl. because they knew of devices that are much better Ihe carburetor acts as a regulator, just providing at regulating fluid pressure. If this book was written the volume of fuel (current) as required, and the in the 1.980s (or earlier), just about everybody would shallow bowl will result in lower pressure (pressure know about the commonly used fluid regulator that regulation) than what was available from the high- is used in older cars called a carburetor (Figure pressure source (the fuel pump). An electrical version 11-5). of the carburetor would look like Figure 11 7: current The carburetor is a very clever device that pro¬ from the high-voltage source is switched through a vides fuel on demand In Figure 11-6.1 have drawn PNP bipolar transistor with the control of the transis¬ the situation where no tuel is being drawn from the tor being the output of the comparator. I"he compara¬ carburetor, a float is connected to a simple valve that tor's inputs are the current voltage level of the closes when the howl that the float is lull of fuel, regulator’s output, and the specific “output’' voltage

High-Pressure High-Pressure Fluid Source Valve Fluid Source Valve Open / Closed Fuel Entering Bowl

J—c Low- Low Pressure Pressure St*' Regulated" "Regulated' Output Output Flow Flow

Figure 11-5 Car carburetor as a flow regulator Figure 11-6 Car carburetor allowing in fue

Section Eleven Power Supplies 177 Experiment 62 — Linear Power Supply Source High-Vollage 7805) cannormallysourceupto500mAand1 critical.These twofeatureswillshutdowntheregula¬ would recommendthatyoustayawayfromthese chips thatweredesignedfromthisblockdiagram;1 voltage referenceisusuallyaZenerdiodethathas that comesfromsomekindofvoltagereference.The and 78Lxxseries.The78xxshowninFigure11-8 is acrowbar,anditshouldbeenabledifthecurrent limits Thetermusuallyusedfortheregulatorshutoff tor ifitsoperationgoesoutsideofnormaloperating parts whenyoutirefirststartingworkingwithelec¬ Figure 11-7Simpleregulatorcontrollingvoltage lator lessthan125C.whichisthecrowbartempera¬ the powerandkeeptemperaturewithinregu A withheatsinking.Thesinkisusedtodissipate (“xx" standsforthevoltage,soa5-voltregulatoris tors thatprovidethecrowbarfeaturesare78xx operating range. the temperatureofregulatorexceedsnormal drawn fromtheregulatorexceedsitsratedvalueorif tronics becausetheylacktwofeaturesthatIconsider miniscule amountofcurrentpassingthroughit. package ture. Forlower-currentapplicationsfupto100mA), the 78Xxx(Tip,ure11-9)canbeused.Foreither I78 1E 3Robotics Experiments for the Evil Genius Figure 1-8780xvoltageregulator in10-220 The mostpopularpositivelinearvoltageregula¬ You canbuyanumberofdifferentlinearregulator Input Output v Reference Label 780x Voltage find 0 ^Comparator 780x label ( Transistor (''Valve'’) Voltage Out Regulated 1 device, theinputvoltageshouldbeatleast2volts current ortemperatureparametersareexceeded, of capacitanceontheinputanda0.1pFcapacitor regulator incircuit,youshouldincludeatleast10p.F above theregulatedoutputvoltage.Whenwiring current-limiting resistor,youwillseethatitisout- tor. alongwithitscapabilitytoshutitselfdownifthe the output(Figure11-10). putting 5volts(withsomeslightdeviation).Theregu¬ on. andbymeasuringthevoltageacrossit and connectthe9-voltbattery.'HieLEDshouldturn resistors ina“SIP"Package. resistor alongwitheightswitch-controlled220fl tery's outputbeingregulatedto5voltsusinga78L05. in Figure11-1l.Thiscircuitconsistsofa9-voltbat¬ build thecircuitonPCB'sbreadboardasshown lated outputwillremainquitestable,evenifyouclose be slightlywarm.Next;startclosingtheswitches,one a 9-voltinputandoneswitchclosed,the7905should the temperatureof78L05voltageregulator,With through theregulator.Withtopofafinger,check one theswitches,increasingcurrentbeingdrawn package by one,whilewaitingtwoorthreeminutesforthe Figure 11-10Usinga780x asavoltageregulator Figure 11-978L0xvoltageregulatorin10-92 Ihe 78L05powersanLEDwithacurrentlimiting Voltage In Unregulated Output GridInput To demonstratetheoperationofalinearregula¬ Alter buildingthecircuit,openallofswitches U LI 10 uF 78(L)0x 0.01 |)F Voltage Out Regulated 78L05's temperature to stabilize. If you have a DMM Experiment 53 — Switch Mode Power Supply with a temperature sensor, you will see the case tem¬ perature ot the 78LOS rise each time a switch is closed. At some point, the LLD will go out (it was with seven switches closed for me); this is the point at which the crowbar became active. By opening two or three of the switches and waiting a few minutes, the LED should come back on as the 78L05 starts work ing again The crowbar is usually not latched.To test to see if it is. when the LED is back on, short the out¬ put of the 78L05 directly to ground. When you remove the short and the voltage regulator does not come back on until the 9-volt battery is removed and Figure 11-11 Test circuit w iring to find the point plugged back in, the crowbar circuit is latched. where the 78L05 stops operating

Experiment 63 Switch Mode Power Supply

Tool Box Assembled PCB with breadboar. d

LT1173CN8-5 switch mode power supply

Two 74LS123 dual multi¬ vibrator chips

1N5818 Shottkey diode

LED, any color

Dual C switched battery clip

100 uH coil

Two 100k resistors

10k resistor

470 !! resistor

100 |iF electrolytic capacitor

Three 10 p.F Electrolytic capacitors

Two 0 01 fx-F capacitors, any type

Although the Zener diode and linear power supplies terribly efficient. It isn’t unusual if 80 percent or more presented so far in this chapter are useful and easy to of the power input to the Zener diode power supply work with, they do have two characteristics that can is lost, and 40 percent or more is lost in the linear make them problematic when they arc being used in power supply. What is required is a power supply cir¬ a robot. Tirst, thev require a higher voltage than the cuit that is very efficient and will "step up" voltages. regulated output.This can be an issue when you want Although these two requirements seem impossi¬ to use very simple power such as two A A cells for a ble, they can actually be achieved very easily thiough robot- remember that minimizing weight should the use of the switch mode power supply (SMPS) Ihe always be an important goal. Second, they are not basic SMPS circuit (Figure 11-12) is quite simple and

Section Eleven Power Supplies 179 rH . k__k...k. Regulated Output a. Ground (0 Volts) a. Figure 11-13 Switch mode power supply operation t/) Figure 11-12 Switch mode power supply circuit changes along with the transistor control PW M. bringing the output voltage into line. M relies on the energy-storing characteristic of the coil,

180 L 2 3 Robotics Experiments for the Evil Genius Experiment 63 — Switch Mode Power

Figure 11-1M LT1173CNS-5 five-volt switch mode power supply controller chip

keep a number of 74LS123 dual multivibrator chips rising edge of each multivibrator delay tuggers the on hand in case I have to provide a delay within my other multivibrator, resulting in a 50 percent duty circuit Each 741 -SI 23 consists of two multivibrators, cycle or square wave signal). with tluce inputs (the delay will be triggered when Tire flashing 1 ED may seem like a trivial applica¬ ble \ input is fa iing or when B or _CLR is rising) tion (especially because it could be demonstrated and two outputs.The Q output is normally low with a using a 555 time#a few resistors, and capacitors) positive pulse, the duration of which is specified by instead of the SMPS and multivibrator circuit pre¬ in- exU rnal resistor and capacitor, whereas Q is seated here. I'hc purpose of this circuit is to demon normally high and provides a negative pulse of the strate that one or two alkaline or rechargeable same duration.The two multivibrators in the chip batteries can be used to power the digital electronics cannot be wired together to form an astable oscilla- of y0ur rohot, rather than relying on a larger battery tor. but the delays in two s a prate chips can be used to voltage that ma\ make your lobot larger and heavier produce an oscillator as show n in Figure 11-15 (the qlan reqUired

Vcc Vcc Vcc Vcc

Figure 11-15 Flashing circuit

Section Elevpn Power Supplies 181 Section Twelve Sequential Logic Circuits

When you first start working with digital electronics, purpose is twofold first, to show the path electrical playing around with simple logic and building differ¬ signals take through the circuit, and second, to break ent functions is fun. I \c always enjoyed using the dif¬ down the operation of the circuit into small parts that ferent tools (truth tables, Karnaugh maps, and can be easily designed. Boolean arithmetic equations) to look at the differ¬ The “Time Memory” block of Figure 12 1 is a ent ways of providing a logic function and to see how memory unit that is updated on command from a I much I could simplify it. I Unfortunately, simple logic 11/ oscillator input I he triangular feature on the functions (which are known as combinatorial logic “Time Memory" block connected to the 1 H/ oscilla¬ cirants) are not that useful in the real world because tor is known as a clock input and is a common sym¬ they do not change on their own over time or provide bol used in logic diagrams to indicate the input pin a sequence of operations. used by the memory device to store the logic values Virtually all logic circuits that you will work with at the I/P (input) pins. For the digital clock, this hap¬ are known as sequential logic circuits because they pens once every second, so the incremented seconds are designed to provide a sequence of operations. A (and minutes and hours) are saved while the “Time good example of a sequential logic circuit is a digital Update Circuitry” and “Output Formatting Cir¬ ckx:k; the current time is stored in a memory function cuitry” perform logic functions on the value stored in and is updated at different points in time. Along with the “Time Memory.” using the current time as input data, the combinator¬ The 1 Hz oscillator input in Figure 12-1 is often ial logic circuits responsible for formatting the data called a clock when it is a regular signal, as m this output use button inputs for setting the time. Figure case. You may also see it referred to as a time base or 12-1 shows a possible block diagram for a digital trigger, depending on its function within the circuit. dock. In most sequential cncuits. the clock input is used to The block diagram format is one that I use quite a store the updated values for the memory circuitry as bit when working wirh sequential logic circuits, and it is done in this application. is somewhat related to the computer programming Ihe RST input to the Time Memory block is an flowchart that will be discussed in later sections. Its input that will reset memory values to an initial value so the circuit will start out at a known, valid state. For this circuit (and most sequential circuits that I work with), 1 use an RC network to provide a delayed ris¬ ing signal; using a 10k resistor and l!) pF capacitor, I will get a logic low for 10 to 20 milliseconds. Although this signal is low, most digital logic memory devices will hold the memory units reset regardless of the other input signals. Ihe “Time Update Circuitry” is a conventional combinatorial logic circuit that increments (adds one to) the second counter if the button is released or Figure 12-1 Digital clock diagram increments the minute countei it the second button is

183 Section Twelve — Sequential Logic Circuits the statements: of thetimeupdatecircuitrycouldbemodeledwith values forseconds,minutes,andhours,theoperation saved untilthenexthightolowtransitionof1 of incorrectvaluesbeingsavedexists.Inthestatedia¬ pressed. Assumingthatthe“TimeMemory”contains gram showninFigure12-2,1showthattheTime to beloadedintotheTimeMemoryblock,nodanger billionths ofasecond),sowhentheupdatedtimeis to theprogrammingstatementsthatIwillintroduce Hz oscillator. the TimeMemoryblock’sinputsandwillnotbe the TimeUpdateCircuitThenewvalueisdrivento level. Afterthetransition,outputfromTime Memory blocksareupdatedwhenthesignaltrom Memory blockchanges,andthisvalueflowsthrough Figure 12-2Digitalclocktimingdiagram Select Circuitry 1 Hzoscillatortransitionsfromahightolowvoltage Next State|f 18 4 Time Memory~~1 Output Time Memoryk Input • IfMinutesisequalto59.thensei • IfSecondsisequalto59,thenset • IftheTimeSetbuttonispushed,thenSeconds • IfHoursisequalto11,thenset0. The “limeUpdateCircuit”statementsaresimilar These statementsexecuteveryquickly(oveiafew 1 HzClock onds plus1. to 0andHouisissetHoursplus1. to 0andMinutesissetplus1. is setto59;otherwise,SecondsSec¬ 153 Robotics Experiments for the EvilGenius _Save _Save .Time MemoryTime •decimal (1011binary)andarenotequaltozero,then significant hoursbityouwouldhavetoimplementa function suchas complex. Torexample,toclearorincrementtheleast actual Booleanlogicfunctionsareactuallyquite later inthebook.Ihaveusedthemherebecause make upthecurrentnumberofhoursdonotequal11 should seequiteafewsimilaritiestotheclockdia¬ would bedefinedinexactlythesamewayasTime XORed with1.Ifitandtheotherthreebitsthat state (ortime)updatecircuitry. gram ofFigure12-1.ThedifferenceisthatIhave drive fourseven-segmentLEDdisplays. passed backtotheTimeMemoryblock,isused can becleared,andinputisusedaspartofthenext assumed thatthememoryunitIamgoingtouse has theblockdiagramshowninFigure12-3.You Update Circuit,anditsoutput,insteadofbeing 1 isstoredasitsvalueinthebit. Figure 12-3Basicsequentialcircuitblockdiagram The OutputFormattingCircuitofFigure12-3 In thisfunction,theleastsignificantbitofhoursis Circuit Ihe generalformforasequentialdigitalcircuit Clock/' Input Hours.0.Input =((Hours.0.OutputA1) ■ (Hours.3.OutputA0)) !((Hours.0.Output A0) (Hours.2.Output A1) (Hours.1.Output A0) Output Circuit Experiment 64 — RS Flip Flops Experiment 64 RS Flip Flops

Assembled PCB with breadboard Four lk resistors

Four LtDs, any color

Two SPOT breadboard- mountable switches

74C02

Earlier in the book, f presented the idea of building a It you are looking at this circuit for the first time, memory device using a two-coil relay. This device then it probably seems like an improbable device. could be set to one of two states, depending on which The device may seem like one that will potentially relay coil was last energized, and puli the contact oscillate, because if the output value of one gate is towards it. Once electt icity to the coil is stopped,! hen passed to the other and that gate’s output is passed to the state will stay until the other coil is stabilized.This the original, it seems logical that a changing value will device works very similarly to the most basic elec loop between the two gates. Fortunately, this is not ironic memory device that you will work with, the the case: instead, once a value is placed in this circuit, Reset-Set (RS) Hip flop. it will stay there until it is changed or power to the Whereas the relay device relies on friction to keep circuit is taken away. Figure 12-5 shows how by rais the saved value constant, the electronic memory unit ing one pin at a time, the output values of the two takes advantage of feedback to store the value. W hen NOR gates are changed. I discussed the radio control servo, I presented the W hen the R and S inputs arc low, only one signal concept ot analog feedback (in the servo, the current left will affect the output of the NOR gates, anti that position of the control arm is compared against the is output of the other NOR gate. When Q is low, then specified position of the servo and if they do not a low voltage will be passed to the other NOR gate. match, the arm is moved toward the specified posi¬ The other NOR gate outputs a high voltage because tion). The process of sensing the actual position of the its other input is low. fhis high signal is passed to the control arm and passing it back to be compared original NC)R gate and causes it to output a low volt¬ against the specified position is known as feedback. age level, which is passed to the other NOR gate and rhe current output value is used to determine so on. whether or not the servo arm should move.This is an The outputs of the flip flop are labeled as O and example ot analog feedback. The position of the arm Q. Q is the positive output whereas _Q is the nega¬ that is returned can be a range of values, not a spe¬ tive value of O—exactly the same as if it were passed cific on or off (true or false, 1 or 0). Analog means through an inverter. I he underscore character (_) in there is a range of values, usually expressed as a frac¬ front of the output label (O) indicates that the signal tion from 0 to 1 Digital feedback can only be one of two values, so its use in circuits probably seems like it is much more limited than that of analog feedback.This is true, except when it is used as a method to store a result in a circuit like the NOR flip tlop shown in Figure 12-4. Normally, the two inputs are at low voltage levels, except to change the circuit’s state, in which ease one of the inputs is raised to a high logic level. Figure 12-4 NOR gate-based flip flop

Section Twelve Sequential Lcgic Circuits 185 VD U! •H *P o a 0) x U £ I a, RS Flip Flops considered invalidisbecause ofwhathappenswhen state setbytwoswitchesas1showinFigure126 describe theoperationofflipflops,andtruth ous valuesforthetwobits,andnotationindicates These valuesforQwillbesavedwhenRandSare inputs wouldbeinvalid.The reasonwhytheyare and Sworehigh,whiletheoutputsarebothlow, You canbuildyourownNORRSflipflopthathasit< table fortheNORflipflopisshowninTable12-1. are theconventionalshorthandtoindicateprevi¬ returned tothenormallow-voltagelevels.Q,and_Q when Sishigh,theQoutputwillbedrivenhigh. input isdrivenhigh,theOoutputwillbelow',and as theResetandSetpins,respectively.WhenR signal islow.1willexplainnegativeactiveinputslater in thissection. score beforeorthelineabovepinlabel.This grams, youwillseesomeinputsthathavetheunder¬ the label.Youwillnotseea!characterinfrontof circuit diagrams,theyareeitheridentifiedwiththe than theother,thenflip flow willstoreitsstate.If the previousvalues.Truthtablesareoftenusedto that thecurrentvaluesofQand_Qaresameas through aninverter.Whenyoulookatsomechipdia¬ label becausethisimpliesthatthesignalhaspassed underscore prefixorbyahorizontallineontopof is inverted.Wheninvertedoutputsarepresentedin 1S6 123 Robotics Experiments both RandSaiedrivenlow atexactlythesametime indicates thatthepinsareactivewhenincoming Figure 125DifferentstatesofMORflipflop R andSaredrivenlow.Ifone lineisdrivenslower In thetruthtable,1havemarkedthatifbothR Die RandSinputpinsoftheflipflopareknown Flip FlopReset Table 12-1NORR5flipflopstatetable R 5UQ Figure 12-7NANDflipflop Figure 12-bCircuittotestflipflopoperation 0 110 o o„ lino !()0! for the Evil Genius Flip FlopSavingReset Set flipflop Store currentvalue Invalid inputcondition Reset flipflop Comments (not a trivial teat), then the flip flop will be in a Table 12-2 NRND R5 flip flop statp table metastable state, O being neither high nor low, bui anything that disturbs this balance will cause the flip Comments flop to change to that state.The metaslable state, Metaslable input slate although seemingly useless and undesirable, is actu¬ Reset flip flop

ally very effective as a charge amplifier it can be Set flip flop

used to detect very small charges m capacitors. Save current value Along with building a flip flop out of NOR gates, you can also build one out ot NAND gates (Figure 12-7).This circuit works similarly to the NOR gate inputs are low and the inputs are active at low volt¬ cxcepl that its metastable state occurs when both age levels, as shown in Table 12-2,

Experiment 65 Edge-Triggered Flip Flops

Parts Bin Tool Box » Assembled PCB wit.h Wiring kit

Three LtDs, any color

10k resistor

Three Ik resistors

<17 f*F electrolytic capacitor

Two 0.01 ixF capacitors, any type

Two SPOT breadboara-mcunt.able switches

The RS flip flop is useful for many ad hoc types of flip flop and is (he most common type of flip flop that sequential circuits in which the flip flop state is you will have to work with. changed asynchronously (or whenever the appropri¬ line edge-triggered flip flop is based on the RS flip ate inputs are active). For most advanced sequential flop. For this experiment, I will show you how to circuits (like a microprocessor), the RS flip flop is a build an edge-triggered flip flop using NANI) gates. challenge to work with and is very rarely used. Instead ot always calling this circuit a rising edge-trig¬ Instead, most circuits use an edge-triggered flip flap gered flip flop or clocked latch, this circuit is nor¬ that only stores a bit when it is requued. You will mally known as a D flip flop. The organization of the probably discover the edge-triggered flip flop (which may also be known as a clocked latch) to be very use¬

ful in your own applications and easier to design w ith - Data Bit Out Data Bit to - -D" -Q- - Stored Bit than a simple RS flip flop. Be Stored ■ Data Billn Hie operation of the clocked latch is quite Simple "Edge -Triggered" Flip Flop Data Slored (Figure 12-8). A data line is passed to the flip flop on "Falling Edge"

along with a clock line. While the data line stays con¬ “Clock stant. the contents of the flip flop don’t change. When Line the clock line goes from high to low, the data is stored Figure lc?-8 Clocked latch memory device, a single in the flip flop; this is known as a falling edge docked bit of data stored using a clock line

Section Tuuelve Sequential Logic Circuits 187 Experiment 65 — Edge-Triggered Flip Flops to therightflipflop,keepingitinitscurrentstate. no! changethestateofeitherflipflops'output.When properly intheflipflop. cussed inthenextexperiment).Theoutputof show inFigure12-9. Figure I2-9Dflipflopoperation/waveforms the clocklinegoeslow,itforcesouta1tobepassed become high,andtheunknownbitvalueisstored at whichpointthetwoinputstorightflipflop value iswritteninitIfyoulookatthesignalsbeing edge-triggered flipHopstaysunknownuntilsome line ispulleddownbeforetheclockanditdoes passed totherightflipflop,youwillseethat is settherebysomekindofresetcircuit(whichdis¬ not expectaflipfloptobeatspecificstateunlessit when youaredesigningyourowncircuits.Youcan¬ point andonethatyouwillhavetokeepinmind being unknown.Ibisisactuallyaveryimportant flop statesbeforetheirbitvaluesaieestablishedas pass achangingsignalwhentheclockisfalling,asI flip flopsconditiontheclockanddatalinesonly their operationisactuallyquitesimple;thetwoinput 188 inputs areunknownuntilthedatalinebeeomeslow. flip flop*usedinthiscircuitmayseemcomplex,but C(R) D(S) Q2 Q0 U1 Note thatinFigure129Ihavemarkedtheflip Die firstvaluewrittenintoitisazero;thedata 123 Robotics Experiments for the EvilGenius ij L its OutputLow ’R’ Input)Driving 'Right" FlipFlop Low On[ \i n. r d ■ *S" Input.1 its Output 'Right' FlipFlop l owOn Dnvinq High mize thisphenomena,youmightwanttoaddavery falling andrisingedgesastheclockswitchisturned should becomeveryobviousasyoutesttheopera¬ edge operationoftheDflipflopmoreeasilyseen debounce theswitch'ssignalandmakerising one ortwoseconds)toactivelydebouncethissignal long delay555monostable(withanactiveperiodof bouncing. Althoughthe47jil-capacitorwillmini¬ up ordown.Thisisduetotheswitchonclockline kle. Youmayfindthatthedataislatchedonboth tion ofthiscircuit,althoughtheremightbeonewrin edge-triggered flipflopshowninFigure1210.The47 or low. flop cannotbechangedbythedatalinegoinghigh clock linehasgonehigh,thestateofrightflip then loadedwiththecurrentdatavalue.After p Fcapacitoracrosstheclocklineresistorismeantto When theclocklinegoeshigh,rightflipflopis Figure 12-10Dflipfloptestcircuit In thisexperiment,Iwouldlikeyoutobuildthe the operationofedge-triggeredflipflop Experiment 66 — Full D Flip Flop Experiment 66 Full D Flip Flop Tool Box

Assembles PCB with breadboard Wiring kit 78LGS + “5-volt, regulator

74LS74 dual D flip flop

Five LEDs, any color

Five 4 7 0 11 resistors

10k resistor

4? [juF electrolytic capacitor

10 |iF electrolytic capacitor

Two 0.01 |iF capacitors, any type

Four breadboard-mountable SPDT switches

1 find the D flip flop to he the flip flop that 1 build to point out that things are not as simple as you may into my circuits most olten It is simple to work with have thought. It you wanted to convert a two-input and can interface to microcontrollers and micro¬ AND or OR gate to a three input gate, you could processors very easily It is, however quite awkward simply pass two input signals and its output to the to wire, especially when you want to work with the input of a second gate in which the third input is lull circuit which is shown in Figure 12-11.This cir¬ passed to its second input, I neglected to point out cuit not only has data stored on the rising edge of the that this trick does not work for NAND or NOR clock line, but two other lines, _Cf R and PRF,, will gates. For example, if you wanted to use two input force the flip flop's output to a 0 (low voltage) or a l NAND gates to create a three-input NAND gate, you (high voltage), respectively, when they are pulled low. would have to create the logic function shcwvn in Fig¬ This allows for a number of different options when ure 12-12; after two inputs are NANDed together, using the D flip flop in your circuit that can allow you you would then have to invert the output so that they to pull off some amazing feats of digital logic. are ANDed together and then passed to the NAND Looking at Figure 12-11, you might be thinking gate with the other input A three-input NOR gate that the circuit could be easily upgraded to perform would also be built the same way, the full D flip flop function, but before you do. 1 want I sing three gates to produce one two-input NAND gate 18 NAND gates would be required to implement the full D flip flop function, which would require lour and a half 7400 chips.To demonstrate the operation of the circuit, you could build it out of two 7410 (three three input NAND gates),or be lazy

Output !(A• B *C)

Figure IP IP Three input NAND gate hull! from Figure 13-11 Full D flip flop with set/reset controls two input NAND gates

Section Twelve Sequential Logic Circuits 189 Experiment4 66 - Full D Flip Flo 190 switches, placebothoftheseup(closedwiththe LED connectedtotheQoutputofflipflop.You and _CIRswitches,observetheicsultswith operation oftheflipflopswithdataandclock gates. with theoperationof7474’sDflipflop.Before ulator alongwiththefourswitcheslordifferent of theflipflop.Onceyouhavedonethis,bytoggling the PRorCLRSinesfromaffectingoperation (closed withtheJiDsturnedon)positiontokeep powering up,moveallfourswitchestotheUp inputs showninFigure12-13. the 74L.S74,whichnecessitatesuseofa5-voltreg¬ applications. versatile chipandcanbeusedforawiderangeot of thedataorclockpins)areprovidedforeach UFFR turnedon),open(movetodown)thePRi ner aswhenyoubuilttheflipflopoutofNAND two flipflopsbuiltintothechipThe7474isavery to setorresetthestaleofflipflopwithoutuse as welltwopinsthatprovideyouwiththeability being savedintheflipflopexactlysameman¬ the dataandclockswitches,youshouldsee All tourinputsshowninFigure12-11(dataandclock both theQand_Uoutputspassedtochipspins. the differentfunctionsoffullI)flipflop. like Iamandjustuseone74US74toexperimentwith To experimentwiththe7474.1decidedtogo Once youhavebecomecomfortablewiththe The 7474chipconsistsoftwoDflipflopswith With thecircuitbuilt,youcannowexperiment 123 Robotic Projects for the Lvil Genius one. disassemble thecircuit;youwillneeditfornext switch offboththe_PR1and_CLRswitches(LEDs Figure 12-11.youshouldbeabletofigureoutwhy off) andobservewhathappens.11youlookbackat switch islow.theoutputlowandanyincomingdata the flipflopbehavesinthisway(hint:followPre When youlestthe_CIRswitch,willseeasimi¬ using dataandclockwhilePR1islow.youwillfind should seethatwhenthePR1L.FDisoff,flip line andlookatwhereitisconnected). being clockedinwillbeignored.Asafinalcheck, lar operationastothe_PR1sw'itch;when_CLR that youcannotchangethestateofflipflop. flop's outputishigh.Ityouweretotryandsavedata Figure IZf-13Dflipfloptestcircuit Once youarcfinishedwiththeexperiment,don’t 78L06 Experiment 67 — Flip Flop Reset Experiment 67 Flip Flop Reset

1 Ck resistor

Five 470 il resistors

47 |iF electrolytic capacitor

Two 10 |j.F electrolytic capacitors

Two C.01 |.i,F capacitors, any type

Four breadboard-mountable SPDT switches

If you turned power on and off to the D flip Hop built reset, I am describing the state when the circuit is first in the previous experiment several times, you will powered up or stopped to restart it from ihe begin¬ have noticed that the initial state (or value) can be ning. W hen you read the term reset later in the book eitherO (LED off) or I (LED on), with no way of (as well as in other books), remember that it a single predicting winch value it will be.This is normal bit or pin is being described, the term reset means because when power is applied to the Hip flop, it that it is 0 or at a low level. If a sequential circuit (like there is any kind of imbalance in the circuit (tor a microcontroller) is “held reset" or “powering up example, residual charge or induced voltage) on the from reset,” I mean that it is being allowed to execute inputs oi either NAND gate, the dip flop will respond from a known state. to it and this will be its initial state. Often, this ran¬ The 741 S74 used in the previous experiment can dom initial state is not desired; instead the circuitry always be powered up with its output value being a 0 should power up into a specific known state lot it to by replacing the switch. Ik resistor.and LED on the work properly. _CI .R pin with the resistor, capacitor network shown Specifying the state when the circuit is powered up in Figure 12-14. is known as initialization and is required for more The _CLR pin is known as a negative active coil than just sequential logic circuits. When I discuss pro trol and is active when the input is at a low voltage grammmg, 1 will be discussing how the internal parameters to a program (known as variables) must be initialized to specific values for the program to run correctly. Initialization normally takes place when the application is reset, or waiting to start executing In this experiment. 1 will show how the D flip flop pre¬ sented in the previous experiment can be modified so that every time it powers up it. outputs a 0. To avoid confusion later. I should clarify the two types of resets described in this book when 1 talk about digital circuits. Earlier, when I was talking about simple combinatorial circuits, I also called a low or 0 voltage level as being reset (and high oi 1 as bang set). In this experiment, when 1 use the term Figure 12-IM D flip flop with UC reset circuit

Section Trnelvp Sequential Logic Circuits 191 Experiment 67 — Flip Flop Reset cin nil 192 Figure 12-lb(Operationofpower-upRCdelay controllers inrobots,youwillwanttoimplementa okl voltagecanheapproximatedusingtheequation: clear functionisnolongeractive,thechipcanoper¬ good. Whenthesignalon_CL.Rgoeshigh,and controls anopencollector(ordrain)transistor circuit liketheoneshowninFigure12-16This output pinthatwillpulldownanegativeactivereset be presentingyouwithhasacomparator-basedreset more sophisticatedresetcircuit.IheBS2that1will ate normallywithiibeinginaninitialknownstate. pin delaystheriseof(asshowninFigure To makethispinactiveduringpowerupyetallow Response *-AppliedIsApproximately age asasmalltransistor. trol chipandisputintothesameblackplasticpack¬ pin whenpowerdipsbelowsomethresholdvalue. network ontheTransitor-to-Transistor(TTL)input the chiptofunctionnoimally,resistor/capaeitor RC Network/DelayfromPower level (asdemonstratedmthepreviousexperiment). 12-15) sothatthepinisactivelowwhilepower 11ns circuitisoftenavailableasaprocessorresetcon¬ When youworkwithmicroprocessorsandmicro¬ Flic iinrcfortheRC’networktoreachiliresh- Power Applied Delay Time=2.2xRC 123 Robotics Experiments fortheEvil Genius 22xR*C Output Delay Output |_1 Comparator Vcc sistor, pullingthecircuittoground. 01,1 l_L. RST or thedelaylineiscontinuingtooutputalowvalue, makes surethatthepowerlineisstablebeforeallow¬ (>ut anysubsequentglitchesinthepowerlineand delay lineisactivated.Thisusedtofilter set value;thecomparatorstopsoutputtinga1and control chipwhentheinputvoltagedropsbelow is high,anditturnsontheopencollectoroutputtran¬ the outputofNANDgatetheyareconnectedto executing. Whenthecomparatoroutputsalowvalue ing theprocessortoleturnfromresetandcontinue operation oftheinternalpartsprocessorreset from 2.2voltsandupwards.Figure1217showsthe very widevarietyofdifferentcutoffvoltages,ranging Figure 12-17Possiblemicroprocessorresetcircuit Figure 12-lbPossiblymicroprocessorresetcircuit Processor resetcontrolchipsareavailablefora Operating Voltage Satow Threshold Power Operating Threshold Microprocessor Can ResumeOperation Complete, Microprocessor Reset fromVcc“Dip' Microprocessor Reset Signalto Experiment 68 — Parallel Data Experiment 68 Parallel Data

Assembled PCR with breadboard

78L05 +5-volt, regulator

7 4LSI 7 4 Hex D flip flop

Six LEDs, any color

Eight 10k resistors

Six 470 H resistors

Two 10 fiF electrolytic capacitors

Two 0.01 fiF capacitors, any ty^e

Breadboard-mountable eight-switch DIP module

The fiist microprocessor (the Intel 8008) handled working with complex circuits, it is usually easier four data hits at a time. Ihis grouping of four hits is (and faster if speed is a criteria) to work with multi known as the processor's “word” size, and ll you were pie bits in parallel These reasons are why more to chart the progression of the different personal powerful systems generally handle more bits at a computers over the years, you would see how the time as part of the processor’s word size. word size has grown over the past 25 or so years.The l or the remainder of this book, 1 will be working first popular personal computer, the Apple, had a with multiple bits that are grouped in parallel in processor that had a word size of eight hits. Five years some way. You might be thinking that the circuits will later, the IBM PC used the 8088 processor that could become unmanageable because ol the need for mul¬ process data 16 hits at a time (to avoid getting angry tiple chips to take care ot the multiple bits of data, emails later, I want to point out that while the exter¬ but I w ill be taking advantage of some of the many nal data buses were 8 bits, the processor itself handles available products that can handle multiple bits 16 hit data words). Another five years after the intro¬ simultaneously. A good example of this type of chip is duction of the first IBM PC, the first 32-bit word Intel the six (or “hex”) D flip flop chip, the 74174. 80386 based PC's were on the market. Today, if you The D flip flops used in the 74174 are similar to follow the computer press, you’ll know that the latest the D flip flops contained within the 7474 that I pre¬ computer systems and servers are equipped with sented in the previous experiments, except that the 64-hit Intel Itanium or AMD Opteron microproces¬ clock and reset controls are common to all six D flip sors. As the word size of the processors increases, flops in the chip. Ihe reason for “commonning” these their ability to quickly perform complex mathemati¬ pins is ostensibly to save pins on the chip (a six D flip cal operations improves, as does their ability to han¬ flop chip with all 6 lines for each flip flop made avail dle large amounts of data. This increase in word size able to the user would require 38 or more pins), but it is attributed to what is known as Moore’s law.This actually serves the purpose of allowing you to save observation states that the number of transistors (and data in 6 independent bits or clear them at a one by inference their complexity and ability to process time. data) doubles every 18 months. So far in the book, I have been working with data So far m this book, when presenting you with digi¬ one bit at a time. For this experiment I would like to tal electronic circuits for the experiments. I have been repeat the first D flip flop experiment, but with six focusing on processing data one bit at a time. bits.To test tins application out, I came up with the Extremely complex circuits can be created that work circuit in Figure 12-18. with just single bits, but instead of designing and

Section Tiuelvp Sequential Logic Circuits 193 Experiment 69 — Traffic Lights he usedtoimplementtoytraffic lightsrunningintwo set oflightsisred.theother setwillturngreenfora different directions.Youwill discoverthatwhileone 194 the circuit,youwillhaveasequential circuitthatcan breadboard (itwon’tlitonthetraditionalsmall the circuitshowninFigure12-19wiredonalong In breakingwithtradition,Iwouldlikeyoutobuild breadboard) asinFigure12-20.Onceyouhavebuilt lotlh andseetheLEDoutputschangewithtog¬ Figure 12-18HexD-typeflipfloptestcircuit Three 10pFelectrolyticcapacitors Six 0.0JpiFcapacitors,anytype Six 470i)resistors Two greenLEDsikresistor Two yellowLEDslCkresistors Two redLEDs47kresistors ZTX649 bipolarNPNtransistor 74LS00 quadtwo-inputNAND 74LS139 dualtwo-to-fourdecoder It isquiteabitoffuntofliptheswitchesbackand 78L05 Robotics Experimentsfor theEvilGenius Nine-volt batteryand 555 timerchip Long breadboard 7 4LS174HexDflipflop 78L05 f-5-volt.regulator clip Experiment 69 Traffic Lights schematic, butyouareprobably contusedastohow out anykindofintroduction, youshouldrecognize almost allofthepieceswhile lookingatthe could bethebasisforasetoftrafficlightsusedin second andthenyellowforanotherbefore model trainlayout turning redandstartingtheprocessover.Thiscircuit clock pulses)wherethesameamountofdatacould This isbecauseafterseltingeachofthehitvalues, and oneclockpulse). be storedinjusttwoclockcycles(onetosetthedata Using individualDflipflops,inordertosavesixbits, set atthesametime(inparallel)withotherones. once. Afurthersavingsintimeisthateachbitcanbe euit, youshouldseethatthenumberofswitchmove¬ it wouldtake12switchcycles(sixdatasetsandsix you onlyhavetopulsetheclocksignaldownandup ments requiredperbittosavedatahasbeenreduced. this experimenttothefirst74LS74cir apparent, butifyouweretocomparethecircuitin gling oftheclockswitch.Iheincreaseindata- handling powerwillprobablynotbeimmediately Tool Box I’m surethatbyhavingyou buildthiscircuitwith Experiment 69 — Traffic Lights

LtW 11 0.01 uF£ 0.01 liF 74LS174 1/2 74LSI39 _±_ X. ' x xi TTL- _L inj.iC_ -==^9 Volts o.oi ur T v.cc X VCCa^=" -±r L

6 ™ 4 —2 Trig Out g- j-^VI Gndh-| 1/2 74LS139 iumf— - 470 [o.oi IIF X 2Y3 12 W Vcc“ ~ Vcc 2Y2 11 470 iBp,^ “^_0.01 (|F 2Y1 W © - Vcc 2V0 9 X°M F Xx 14 —

2j 47LSOOj

Figure 12-19 Traffic light combinatorial circuit

LED Traffic Light Display © © o tit *£ i ZCIiLL

11» jt n.THtoTrT il x' S 3-5 sz = Z = Z =1

rrrr.::: >»i □•□□□□□ a □ □ □ □ □□nan c □ 11 □ a u □ □□□ □□□□□ unnan □□□□□ □ =i □!□ □ □□ □

LED Traffic Light Display O O Q

Figure 12-50 Traffic light circuit built on a long breadboard because a is too large for the breadboard that Tits on the books PCB

they all work together. I .ooking at the Mart of this makes sense to the designer. Although I would stress section, I gave you a very simple block diagram that you should design your combinatorial circuits describing how a combinatorial circuit works. Ilie cir¬ using the block diagram presented earlier. 1 wanted cuit in 12-19 doesn’t match it in any particular way. to use this circuit to explain how to look at seemingly Idle reason for giving you this circuit is to show complex circuits and figure out what they are doing. you how easily you can end up with a combinatorial This tiattic light circuit should be a fairly good exam¬ circuit that has been optimized in some way that only ple of this problem because when 1 designed it. I was trying to optimize it to the point where it would fit on

Section Twelve Sequential Logic Circui ts Experiment 69 — Traffic Lights ferent HipHopswiredtotheinputsThefirstinputis tied topositivepower,soitisalwaysgoingload start withthe74LM74andseeifwecanfigureout NAND gateandtheopen-collector driver,itiscon¬ you willseethatitisbeinginverted, antithrougha to passfromflipHop flop. Hieonlyproblemis put isconnectedtoitsinput,youwouldexpectthe1 how itissupposedtowork. 196 look attheoutputoflast flipflopinthechain, what happenswhentheyare allloadedwithIs.Ifyou the firstflipflopwith1.Becauseeachflop’sout¬ parts. IwouldstartwithNumber3.butitseemstobe the circuit,Icanseethatamconfusedaboutthree integrated withtheoperationof74LS174,solet's out theblocks(withcomments)as stand them.I!Iweregiventhiscircuit.wouldbreak tional blocksandnotewhetherornotyouunder¬ wiring solution). occurrence whenyouaremovingcircuitrytoanew around tochangingthecircuit(whichisacommon moved tothelargerformfactor,butInevergot comes withthebook.Unfortunately,Ifailedand the smallbreadboardthalisusedwithPCBthat b. Whatisa74LS139?Lookingatthecircuitry,it 5. Theoperationanduseofthe17LS174isvery 3. LEDoutputs.47012currentlimitingresistor 2. 555clockPluggingRandCintothemono¬ 4. Resetcircuitry.The10kresistorand10|xF 1. Powersupply.9-voltbatteryand781.05,stan¬ So. withthisquickreviewofthemajorblocks To understandthecircuit,trytobreakitintofunc¬ ITtc 741.S174iswiredwiththeoutputsofdif¬ cuit. butitspurposeisn'tobvious. looks likeitissomekindotcombinatorialcir¬ confusing. Italsoseemstobeconnectedthe driver isconfusing. reset circuitry. the reasonforopencollectortransistor a periodofroughlyonesecond. inverted Dflipflopoutputisconfusing.Also, resistor andthecapacitoraswell capacitor arelowwhilethecircuitpowersup. used withLEDs. stable oscillatorlormuias,1canseethatithas dard 5-volt.100mAsupply. Fhe reasonfortheNANDgatefedby 1 e3Robotics Experiments fortheEvil Genius decode memoryaddressestoindividualchips.InFig- individual outputlinesandareprimarilyusedto known asdemultiplexors)convertbinaryvaluesinto bunch ofANDs.ORs,andNOTs.Decoders(also an arbitrarylogicfunctionanddon’twanttowireina (74LS138) areincrediblyusefulchipswhenyouneed or maynotbeahelptoyou). Figure 1221Trafficlight Dflipflopoperation see thatitisadualtwo-to-fourdecoder(whichmay¬ because theyprovidelinkstothepartsdatasheets). tor (IrecommendDigiKey®atwww.digikey.com Looking atthe74LS139'spartdescription,youwill function. YoucaneitherdoaGoogleIM with achipthatyouhaveneverseenbefore,1suggest function isinthecircuit.Whenyouareconfronted four NANDgatesotthe74LS00arealreadyused. a MickeyMouselogic(MML)inverter,becausethe open collectordriver.Sincethedriver get set.Iheonlyquestionremainingistheuseof clear allthe174’sflipflopsonpowerupoiifthey shouLd seethatitcombineswiththeRCnetworkto (www.google.com) searchorlookatapartsdistribu¬ is onlyconnectedtooneinput,Iwouldguessthatit chip arereset,thenthepiocessofloadinga1will that youlookitupandseeifcanfigureoutits being resetalongwithalltheotherbits. ure 12-21istheoutputof60goinghighandthen resume, asIshowinFigure12-21.Ihe“glitch”Fig¬ all theflipflopsinchipIt the 74LS174goeslowwhen60high,resetting reset circuitis(circuitblocknumber3),andyou through theline,youwillseethat_CI.Rpinof nected tothechip'sflipHopresetIfyoufollow 60_ _I_ You nowknowwhatpartofthepurpose Ihe onlypieceleftisthe74LS139andwhatits The 741S139andthethree-to-eightdecoder “Glitch" Fable 12-3 Traffic light operation #Y0 - !(! XG»'#A«!#B;

#yi =!(' #g»#a»i#b; State North/South LEDs East/LUest LEDs #Y2 - '(!#_G»#A»#B) 11

O Red on Red on #Y3 = !(!#_G»M»#/B) P Q„ = i Red on Green on #G —-0> O, 1 Red on Yellow on intent 69 — Traffic Lights Figure 12-5? Two-to-four decoder circuitry U:=l Red on Red on

Q, = l Green on Red on

E/W Red = ! (Q0 ■ !Q2) N/S Red = .'P3

N/S Green - p3 • -'2, I still have to invert one value, but this can be done

N/S Yellow = • 2, easily with a leftover NAND gate or an MMI. inverter as I did with the reset circuit. E/W Red - !Q0 + 2,

E/W Green - Q1 • ’ 2; • !0

E/W Yellow = Q • 22 • IQ

Section Twelve Sequential Logic Circuits 1 91 Experiment 70 — Shift Registers strip outeachbitandsendoneseriallyalonga serial datatransmissionandisusedforvirtuallyallof single lineasIshowinFigure12-2.VIhisisknown four timesthetroubleol4bits). become quitecumbersomewhenyouhavealarge clocking orenablebittoindicatethereceiverthat be transmittedquitequickly,butthereneedstoa each bitisgivenitsownwireorpin.Paralleldatacan which multiplebitsofdataaretransmittedinparallel, ally? Sotarinthebook,Ihaveshowncircuits queslion: shouldthedatabepassedinparallelorseri¬ allel port(ititispresent).A serialdatatransfer,even data interfacesremainingin amodernPCconsistof numher ofbits(16arcalotmoretroublethan the dataisreadytobeprocessedParallelcan back andforth,youshouldbeaskingthecritical being sent.Whenmultipledatabitsarepassed computer systems;oftenitisbetweenchipsorsubsys¬ 198 the processor'sfront-sidebus, PCIbuses,andthepar¬ the interfacesbuiltintoyour PC.Theonlyparallel tiple bits,eachofwhichispartthewholethat tems withinarobot.Thisdatausuallyconsistsofmul¬ and forth,fromonechiporblockofchipstoanother. hook), 1willbelookingatcircuitsthatpassdataback For theremainderof1hissection(andmuch This requirementtopassdataisnotalwaysbetween Four 0ClmFcapacitors,anytype tight 470flresistors Two 2.2kresistors tight LEDs,anycolor 1 (j.Felectrolyticcapacitor 100 |iFelectrolyticcapacitor The alternativetosendingdatainparallelis 10 (iFelectrolyticcapacitor 10k resistor 1E 3Robotics Experiments fortheEvil Genius Assembled PCBwith 555 timerchip 7805 voltageregulator 7 4LS17hexDflipflop 74LS74 dualDflipflop breadboard Experiment 70 Shift Registers send eachofthesixbitsindividually. bit. whereastheserialdatarequiresenoughtimeto allel datacanbesentinthetimerequiredforjustone and receiverarcrequired,butthesendingcircuit required. Idsendsixbitsserially,justasingledriver ting dmersandanequalnumberolreceiversare applications. deserialize thedata,ispreferredforvirtuallyall ing circuitmusthaveashittregisterreceiver.Ihepar¬ must haveashiftregistertransmitterandthereceiv though itrequireshardwaretoserializeandthen ^data Figure 12-23Paralleltoserial dataconversion Tool Box Ctrl Clk _1 To sendsixhitsinparallel,ahalf-dozentransmit¬ Load Shift DataOut Serial LineIdle Register i—i n -y X DOiD-02D3t Wiring kit Sdata It probably looks like transmitting data serially high or low. Manchester encoding is a very popular requires a lot of overhead and it slows down the data encoding format for infrared TV remote controls. For transfer. You should consider a number of factors most simple applications in which data is being X before making this assumption,'Ibe lust is that most passed serially between two chips, you will be using a chips are not made out of individual logic gates as the synchronous serial data stream that will be demon¬ (D simple chips presented here are; they are usually very strated in this experiment. Synchronous serial H dense circuits consisting of thousands of gates, with receiver and transmitted circuits are easy to build and He the impact ot adding serial shift registers being very do not require any of the specialized synching equip¬ 3 minimal. Another issue to consider is that it can be ment of the asynchronous or Manchester encoding CD very difficult to synchronize all the parallel bits to methodologies. Looking at Figure 12-25,you will see 3 arrive at the receiver at the same time in high-speed that if the data line changes to an invalid v alue and C* circuits. Finally, multiple wires can take up a lot of returns to the correct value before the falling edge of space and be quite expensive. If chips or subsystems the clock (when data is latched in ), the invalid value -4 could have shift registers built into them, it often is not recorded If an invalid value like this occurred makes sense (both practical and economic) that data in an asynchronous or Manchester-encoded serial O be transferred serially. line, there would be an error. Data can be transmitted serially three different In Figure 12-2b, 1 have shown a simple synchro¬ ways (Figure 12-24) If you are familiar w ith RS-23'1 nous serial circuit that will shift a 1 through the shift Shift Registers (which will be discussed with the I’araliax Basic register continuously by passing data from the output Stamp 2). then you will be familiar with asynchro¬ of one D flip flop to the input of another. When the nous serial data transmission in which one line is eiicuit powers up. all the connected D flip flops of the used to send the data bits. When data is sent asvn shift register will be cleared, except for one D flip chronously, each bit is exactly the same length and a flop that will be loaded with a l.This value will be star! bit indicates a data is coming. Synchro¬ shifted through the D flip flops at a rate of about five nous or clocked serial data requires two lines, a data per second. line and a clock line that indicates when the data In this experiment, I have tied the output of the value is correct. As 1 will show in this experiment, the shift register back to its input,so the value within it is receiving flip Hops are edge-triggered Hip flops with never lost. In a typical circuit, the transmitting shift the incoming data saved on a transition of the clock iegister's input is tied to Vec or ground (so after the (Figure 12-25).The final method of setial data trans¬ data is sent, the known data continues to be sent), mission is known as Manchester encoding and indi¬ and the receiver shift register’s output bit does not cates a data value based on how long the signal is pass d3ta to another shift register.

Start Bit Stop Bit "Glitch" Ignored by Receiver Asynchronous -- ] I BO | 8- | B: | B3 | B4 | as | 36 | B? | | |" •Idle.’' No Sent Data Data Being Data Bits Optional Sent Error Detection Bit Clock uaruirLTLimj Synchronous Data | 90 | S' | B2 '| B3 | BZ | BS | B8 | B7 [ Received Data Clock - in rum nmu 82 83 84 B5 B6 B7 Data Saved on 'Rising Edge' of Clock Signal

Manchester Encoding 1 'Leader* on si n r>r>n Figure 13 -25 Close up detail showing how ^ Bit Timing Synch Pulse synchronous serial works

Figure 12-29 Asynchronous, synchronous, and Manchester-encoded serial data streams

Section Tiuelvp Sequential Logic Circuits 199 Experiment 7l — Christmas Decoration Figure 1226RotatingLEDusingshiftregister 200 son torincludingthiscircuit isnottospreadholiday build thecircuitasaChristmas tree,withtheflashingThesimp|cLFSRillustrated inFigure12-27feeds random tashionandhavesuggested thatthereaderister(LFSR,Figure12-27) included acircuitthatwillturnonandoffLEDsin logic circuitknownastheLinearFeedbackShift/teg- LEDs beingusedasdecorations forthetreeTherea-backbits5and7cf shiftregisterthroughXOR In virtuallyalllliebooks1havewrilten. cheer somuchastoillustrateaveryusefulbinary Parts Bin Three 10piFelectrolyticcapacitors Eight 4?01)resistors Panel mountSPSTswitch Six 0.01capacitors,anytype Two 47kresistors Eight LEDs,anycolor 74LS86 quadtwo-inputXORgates 74LS74 four-bitadder 7 4LS174hexDflipflop 10k resistor 123 Robotics Experiments fortheEvil Genius ***V Nine-voltbatteryholder Nine-volt batteryclip Christmas Decoration Experiment 7l Tool Box Drill withbits Rotary cuttingtool(seetext.) Programmable calculatorwithbinary arithmetic capability Clippers Solder Soldering iron 28-32 gaugewire wrap/prototyping wire Experiment 7l — Christmas Decoration <3 <3 ,<3 Serial Serial Output Input BO B1 B? B3 B4 B5 Be B7 D Q D Q — D Q D Q 1 D Q • L) Q J D O D Q Figure 12-27 Basic 8-hit linear feedback shift register with serial input

Polynomial Number - LFSR Equation = 1 + x + x5 + x* + x8 gates to the input. This changes the bit values in the Bit Numbering Used for Calculator Simulation" " shtft register according to the formula: Figure 12-2G Practical 8-hit LFSR for generating pseudo-random numbers Ei tQ = Bit.o XOR (Bit5 XOR BilJ

The LFSR is typically used for three purposes: In this experiment. I will have you build the eight- • Create a checksum value known as a Cyclical bit IFSR show n in Figure 12 28. II vou were going to Redundancy Check (CRC), which is a unique express this I FSR to somebody else, you could send value or signature for a string of bits. Both the a graphic something like Figure 12-28 or you could transmitter and receiver will pass the data express it according in the polynomial format such as through LFSRs, and at the end of the process, the following: the CRC produced by the transmitter will be compared to the CRC produced by the = 1 * SC4 + Xs + X6 + X8 receiver. If there is a difference in the CRCs, then the receiver will request that the trans¬ The polynomial format is the traditional way of mitter resend the data. expressing how an I .FSR works and is used bv math¬ • Encrypt a string of bits. LFSRs can be used as ematicians to evaluate LFSR operation. an encryption/decryption tool with part of the You should be aware of a few important facts encryption being the initial value in the LFSR. about I FSRs: The value output from the LFSR is dependent

on the initial value loaded into the LFSR. • The LFSR can never have the value zero in it. Decrypting data is also accomplished by using If it contains zero, then it will never have any an LFSR, but configured as the complementary of the bits set function. • Tire ideal LFSR implementation will be able • Produce pseudorandom numbei s. One of the to produce 2"-1 different values. most challenging computer tasks that you will be given is to come up w ith a series of random • A poorly specified I FSR may have the situa¬ numbeis. Computers are generally thought of tion where it ends out with a value of zero. as being deterministic, which means that what they are doing at any given time can be calcu¬ For this experiment, I used the I FSR specified in lated mathematically. Ihis property is impor¬ Figure 12-28 to create a Christmas tree decoration, tant for most applications (nobody wants a fins experiment consists of a 555 timer driving an computer to boot differently each time or have eight-bil LFSR with an LED on each bit used as a a word-processing program respond randomly light.The circuit diagram is shown in Figure 12-29. to keystrokes), but it is a problem for many You should notice a few points about this circuit. I robot applications in w hich the robot has to enable the clear circuitry for the 74LS174 and one L> start moving. flip flop in the 74LS74. In the other D flip flopof the In all of these applications, the LFSR is an ideal 741 ,S74,1 have enabled the set circuitry to ensure choice as a solution because it can be built very sim¬ that at least one bit is set to 1 on power up and not all ply from just a few gates ^meaning low cost and fast zeros, which will result in a circuit that never changes. operation). The LFSR can also be implemented in Before cutting out a Christmas tree shape in a software, as I will show in this experiment. prototyping PCB and building it.1 decided to test

Section Tuuelvp Sequential Logic Circuits 201 the LFSk in two ways. Ihe first was to use my pro¬ ()nce I verified that the circuit worked using both grammable calculator (which has the ability to the calculator as well as the prototype circuit, I then manipulate binary values and perform Boolean built the Christmas decoration to show off the opera¬ arithmetic operations) to make sure that 1 would tion of the LFSR. lo cut the Christmas tiee shape, 1 have 255 different values. used a carbide cutting wheel on my rotary (Dremel) Another way to test the circuit designis to build it cutting tool. When making the cuts, make sure you are on a breadboard.'Tilis circuit is similar to the traffic wearing eye protection and a protective mask. Once Light experiment built earlier (but with the different the shape was cut, I mounted the battery (and power voltage regulator). After building the circuit. I let it switch), followed by the chips and finally the LEDs run for 10 minutes to make sure that it didn’t stop for around the outside of the “tree” as flashing lights. Fig¬ any reason (a bad LFSR design).This is where I dis¬ ure 12-30 shows how the battery is mounted on the covered that 1 should use a 7805 rather than a 78L05. PC B and used as the tree’s “stand” along with a rear view of the point to-point wiring used for the circuit.

+5VA/CC 74LS74 Vcc Powe' PR1 Switch CLR2 D2 CLK1 Q2 CLK2 D1 „PR2 Q1 53 Volt CLR1 Battery Gnd 74LSI 74 Vcc D1 Q1 Vcc D2 Thrsh Rst Q2 Out CLK D3 Q3 Trig Vclrl D4 Dchrg Gnd Q4 D5 Q5 CLR D6 Gnd Q6

Figure 12-29 LFSR used for Christmas tree decoration

LEDs Put (and Wired! Randomly on PCB

Battery and Clip Positioned Power Back View to Act as Stand Switch

Front View Ground Wire Around PCB Perimeter

Figure 12 3C Christmas tree prototype details Experiment 72 — Random Movement Robot Experiment 72 Random Movement Robot

Parts Bin Tool Box Assembled PCB with Wiring kit breadboard

■k DC motor base with four AA battery clip

lf*7 555 timer chip

7 4LSI 7 4 hex C flip flop

74LS86 quad dual input XOR gate

Two 1N314 or 1N4148 silicon diodes

Three 10k resistors

Two 10C 11 resistors

47 |iF electrolytic capacitor

1 pF capacitor, any type

Three 0.01 pF capacitors, any type

The ability to create an LFSR is one that is actually The six bit LFSR s operation (the position of the quite important when you want to create your own taps) was verified using a programmable calculator robot. Often you will want a robot to move randomly program like the one presented in (he previous about a room after completing a task so that it will be experiment. ready for the next one. or if it has boxed itself in a When 1 discussed shift registers earlier in the corner, a very successtul way of getting it out is to book. I said that I preferred using basic D Hip flop move about randomly and restart the activity that got chips and building them into a circuit as required. it stuck. Later in the book, 1 will show how the RS2 This circuit and the Christmas decoration are good can provide you with a random statement that you examples why this is a good philosophy; the 74LS174 can use to move your robot randomly about the can be built into a shift register, an 8 bit I FSR. or this room, but tor this experiment, 1 would like to use the 6-bit LFSR directly. linear feedback shift register that I presented in the In this experiment, I have created a simple robot previous experiment and use it to drive the DC that will move left, right, and forward randomly under Motor control base randomly about the room. the control of the LFSR shown in Figure 12-32.To In designing the LFSR circuit that I would use in allow the entire circuit to be placed on the small the robot. I wanted to make sure that I came up with breadboard included with the robot, I only turn the one that could be located comfortably on the bread¬ board and robot base that 1 have been using for the experiments presented in this book. As in the previ¬ Second XOR ous experiment, many logic circuits cannot be con¬ Gate Acts as an Inverter fined to the small breadboard, so as simple a circuit as possible would have to be created. The I FSR that <3~ <3 1 came up with is shown in Figure 12-31 and could be implemented just using a six bit D flip flop and a chip BO B1 B2 B3 B4 B5 D Q-D Q D Q Jd Q D Q 1 D O with two XOR gates on them Roth these functions are available on chips that you have already worked Figure 1 <3-31 Six bit LFSR for connoiling robot's with. psmiilfl-random motion

Section Twelve Sequenti al Logic Circuits Experiment 72 — Random Movement Robot 204 Figure 12-32/FSRusedforrandom-movementrobot the 9-voltbatteryandavoltageregulatorforlogicanextraXORgatecanbeusediusamewav. robot's motorswiththeAbatterypackandusingcanbeusedasinverters,but1neglectedtonotethat use ofasinglebatterypackinsteaddrivingtheinverter.Earlier.IdiscussedhowNANDsandNORs motor isoffandtheotheractive.Thissomething(andrequiredresistors),butthiswouldhave motors forward.Turningisaccomplishedwhenone(and555timer).Iprobablycouldhaveputina7805 illustrates therandommotionpossiblefroman1JFSR.robotworksquitewellwithasinglepowersupply. less thanwhatIconsidertobeatruerobot,butitmadethecircuitwiringdenser,andinend I hecircuitthat1cameupisshowninFigure12-32.Anotherunusualaspectofthisuse (>ne unusualaspectottherobot(loime)ismyanXORgate,withoneinputtiedtoVccas 1E3 Robotics Experiments fortheEvil Genius Experiment 73 Xperiment 73 — Counters Counters

Tool Box Assembled PCB with Wiring kit breadboard

7805 + 5-voit regulator

555 timer chip

74LS174 hex D flip flop

74LS283 four-bit adder

Four LLDs, any color

Three 10k resistors

Four 470 11 resistors

Two 47 pF electrolytic capacitors

1 |jF capacitor, any type

Four 0.C1 |,'F capacitors, any type

One of the most useful prepackaged sequential logic are creating low-level computer programs, this carry circuits that you can buy is the counter (Figure function is critical for you to be able to create mathe¬ 12-33). Ihe Counter consists of a multibit latch that matical functions for numbers that require more bits passes its output to an adder. Ibis adder increments than the processor can handle (adds one to) the latch output and passes it back to In this experiment, I will show how a counter is the input of the latch and this incremented value is built, using separate adder and lateh chips. When you saved in the latch each time the clock is cycled. Coun¬ add counter functions to your own applications, you ters provide a variety of different purposes and it is will probably use prepackaged TTL and CMOS func important to remember that the clock can be a con tions such as the 74161 and 74193. Both chips are stant frequency clock (in order to time an event) or it four-bit counters, but the 74161 can only count up, can be an external event, the number of which is and value changes (cleai and load) are latched in recorded using the counter with the clock. Ihe '193 can count up or down, and In Figure 12-33. you should note that I have value changes are processed immediately (asynchro¬ included the carry output of the counter's adder. The nously) and not with the input clock (synchronously). carry bit becomes active when the latch value plus one is greater than the value that can be stored in the Counter latch. This output can be cascaded to another counter Clock (as shown in Figure 12-34) to drive it and provide double the number of bits being counted. When you

Edge-Trigged D Flip Flop

Counter Adder To Bit #2 Clock Clock Carry

Bit #1 Counter Output

Figure 12-34 Cascaded counter carry of one bit Figure 12-33 Basic counter design passed to the next one

Section Tuuelve Sequential Logic Circuits 205 Experiment 73 — Counters 206 can beeasilycascadedintolargernumbercounters. used inawidevarietyofdifferentapplicationsand tions thatyoumaywanttoconsiderforyourdesigns. ferent TTI,andCMOSchipsprovidecountingfunc¬ In mostTTLcounters,thevalueisupdatedonris¬ drivers) for“non-evilgenius"users. seven-segment LEDdisplaysandstandarddisplay I personallyusethesetwochipsbecausetheycanbe for easycreationofdecimalcounterdisplays(using 74161 (the74192onlycountsto9aswell).Ihisallows to abitvalueof9.ratherthan15asinthecase Along withthe74161and74193.anumberoldif¬ ITie 74160isidenticaltothe74161butonlycounts 123 RoDotics Experiments for the EvilGenius circuu builtfroma741.SI74hexDflipfloplatchand circuit willbedemonstratedusinga555outputting cant bi(scounterisincrementedatIherighttime. the appropriateinstanttomakesuremoresignifi¬ make surethatthecarryvaluehasarisingedgeat and thenrolloverbacktozero. will justincrementthevaluedisplayedonLEDs a simpleadder(Figure12-35).Thisverycircuit ing edgeoftheclock;thisisimportanttonote until allarelit(displayingavalueof15or%1111) 1 cyclepersecond(1ilz)clockthatisdiivinga In thisexperiment,theoperationofcounter Experiment 74 — Schmitt Trigger Inputs Experiment 74 Schmitt Trigger Inputs and Button Debounce

Bin Assembled PCB with breadboard

78L05 +5-volt regulator

74LSI 91 four bit Up/down -ount e r

74LS14 hex Schmitt, trig¬ ger input inverters

Two 10k resistors

Four 470 Sf resistors

Two 10 pF electrolytic capacitors

Three 0.01 |rF capacitors any type

Momentary push buttons

Breadboard-mountable SPDT switch

I consider the issue of debouncing switches and but bounces of the switch are usually handled as if the tons to be one of the most important and vexing switch was opened and closed multiple times. problems that you will have to deal with when you One method of debouncing a switch is to create a are developing rc'boi applications. Although you small flip flop that can have its state changed by a might think that electrical connections happen double-throw switch like the one in Figure 12-37 Tire instantaneously, you might be surprised to discover sw itch will tie the input to the right logic inverter to that the contacts within a switch actually bounce a w hatever state it is in and this output value is passed few times before the switch makes a constant contact. to the lett inverter.changing its state and putting the This is shown in Figure 12-36. circuit in equilibrium.The inputs and outputs of the When I introduce you to the Parallax Basic Stamp two inverters hold the value of the flip flop when the 2.1 will show how a switch can be read and the switch bounces and is not in contact with either posi¬ bounces filtered out. Passing switch bounces directly tive voltage or ground. to an application is a problem because the multiple The debounce circuit that t recommend you use is shown in Figure 12-38. This circuit consists of a resis tor-capacitor network that charges over a given amount of time or discharges quickly Ihrough a closed switch or button. Figure 12-3d shows the filter¬ ing of the bouncing; it is not perfect, but it is much better than what we started with 1 lie inverters with the funny symbols in Figure 12-40 are Schmitt trigger input inverters and provide

Figure 12-36 Oscilloscope picture of a switch bounce Figure 12-37 Flip flop-based switch debounce

Section Twelve Sequential Logic Circuits 207 Experiment 74 — Schmitt Trigger Inputs On PushButton The Xaxisistheinputvoltagewithrisingvoltagesto for thestrangesymboloninverters,indicating edge. LookingatFigure12-40,youcanseethattheris an extrameasureoffilteringthebuttoninputSchmitt Figure 1238RCandSchmitiniggerdebounce 208 do nothaveaccesstoanoscilloscope.Todemonstrate same torrisingandfallingedgesignals. gates. Forcomparison,atraditionallogicgatedoes forms thesamesymbolthatIputoninverter you shouldseetheresponseofinputandthatit the right,anilYaxisrepresentsresponseof input versusthegateresponseisonanX-Ychart. Schmitt triggerinputs.Figure12-41showswhatthe threshold, whereasthefallingedgethresholdisless. ing edgethresholdisabovethenormalgatevoltage the risingedgeofsignalisdifferentthanfalling Schmitt triggerinputsinwhichthethresholdpointfor ing orfallingedgeofasignalwithhysteresisasshown trigger inputsaredesignedtochangestateontheris¬ Figure 12-39RCdebouncetilleringaction button bouncingandthefilteringofcircuitshown not usethissymbol;theresponsethresholdis the Schmitttriggerinput.Byfollowingnumbers, in Figure1240.Hysteresisisthepiopertyof does notneed tobedebouncedbecausewe don’t edly. Ihaveaddedaclearbutton. Flicclearbutton dow n,andifthebuttonbounces, thecounterwillbe pressing thebutton,counter inputwillbepulled a counterasshowninFigure12-42.Inthiscircuit,bv in Figure12-38,1wanttopasstheinputofabutton incremented severaltimes.To testthecircuitrepeat¬ These changingthresholdvaluesarethereason For thisexperiment,Iamgoingtoassumethatyou Momentary or Switch Input RC Filtered Signal Input 123 Roootics Experiments for the Evilfieriids Vce * Button Pressed Schmitt Trigger Inverter Switch “Bounces" Filtered Inputfrom RC Network Output Debounceri Signal Input Standard Response press),add inthe74LS14invertersand10pFcapaci¬ care howmanytimesthecounterisclearedeachtime (No Hysteresis, allow themtodebounceuser inputsiftheyare Who makesuretoputsome extrachipswithSchmitt cost otjustafewcents.Iknowquitepeople you willfindthattheseimprovementscomewitha cantly betterthanwhatIhadwithnocircuitry,and age droppedto1.2witharangeof12.Although tor todebouncethebuttoninput the buttonispressed. required later. trigger inputs(suchasthe74LS14) intheirdesignsto this debouncecircuitryw-asn’tperfect,itissignifi¬ 74I S14Schmitttriggerinputs,1foundthatthisaver binary valuesdisplayedontheLEDs.Adding the signaldirectlyto74LS191counter.Ifound tested it(recordedthenumberofbouncesperswitch that after10pushesofthebutton,1gotanaverage Figure 12-MOLogicsignalhysteresis 10.1 bouncesperpresswitharangeofIto14forthe Figure 12-MIPlottinglogicsignaltohysteresis Hysteresis_ Response with Aftcr youhavebuiltthecircuitinFigure12-42and Using aparticularlynoisypushbuttonandpassing Signal Input Hysteresis Voltage Thresholdx 50% ofSignal Low-lo-High Threshold Logic withHysteresis with Standard “ © “X-Y" PlotofInputand Hysleresis Response and HysteresisResponse « High-to-Low Threshold Logic withHysteresis © ®©Q 6 j ®j© / © ©_ b 0 rG> ©©\^ Y-T" PlotsofInput Signal "Glitch' in Response tof Stanard Logic ■Glitch" —] CfJ- Built inIgnores"Glitch’ Logic withHysteresis © Experiment 75 — PWM Generation

Experiment 75 PLUM Generation

Parts Bin

Assembled PCB with

, ~ breadboard

/ 78L05 voltage regulator

555 timer

74LS85 4 bit magnitude comparator

Four-bit DIP Switch

LED, any color

Two 4,7k resistors

470 11 resistor

10 |xF electrolytic capacitor

Five 0.01 |iF capacitors, any type l:i Ihis book, I will show you a number of different continuously Another problem with the Basic Stamp ways of generating PWM signals to control motor 2 PWM statement is that it cannot execute in the speed or LED brightness. Earlier in the book. I background while other program statements are exe¬ showed how a 5S5 timer can be used to provide a cuting. What is needed is a simple PWM generator simple PW M, although it has the problem that a full- that will provide varying duty cycles from zero to 100 on or full-off signal cannot be produced. When 1 dis¬ percent and will run continuously without any inter¬ cuss the Parallax Basic Stamp 2,1 will show how the vention from a controller. built in PWM statement works, but this PWM oper¬ Because it is needed, in this expeiiment let’s look ates at only 1 kHz, which has the potential for pro¬ at a design for building this type of PW M generator ducing an audible whine and dors not run circuit. Tlie PWM generator 1 would like to work

Section fujelve Sequential Logic Circuits 209 with will he based on a binary counter driven by a 555 timer. Ihe counter output will be continuously compared against a bit value, and when the bit value is greater than the counter value, a 1 will be output. Ihe block diagram lot the circuit that 1 envisioned is show n in Figure 12-43 and. amazingly enough, worked quite well when I first built it. When you study Figure 12-43, there will probably be one point that won't make sense to you; I show that the counter ranges from 0 to 14 and not 0 to 15. as you would expect for the typical four-bit counter. I Ftqure 13-43 Block diagram of PWM generator wanted the counter to reset itself at 14 rather than 15 so that when 1 compared the binary values. I could down from 0 to 15, but by tying the R pin to the produce a KM) percent duty cycle as well as a 0 per LD (negative active load) pin of the 74x191, you can cent duty cycle by outputting when the set value was load in a new value when the counter reaches zero greater than the counter value. If the counter ran and is about to roll over. Ibis feature is ideal for this from 0 to 15. then the circuit would not be able to produce a PWM with a 100 percent duty cycle by application as it ensures (he count stays between the range of 0 and 14. simply outputting a I when the input value is greater than the counter value. Converting the block diagram to a schematic is Io produce the bit range from 0 to 14,1 used the very straightforward (see Figure 1.2-44) and wiring it 74LS191 chip counting down and tying the LOAD onto the PCB’s breadboard is tight, but not really a challenge. The PWM output value is specilied by the pin to the. RIPPr F. pin and driving the inputs to 14. four position DIP switch. Ihe _ R t Ripple (hrtput) pin becomes active when the chip is rolling over from one extreme to another, I used TI L chips (with the included 78L05 regula¬ and the _LD pin moves the value at the input pins tor) rather than CMOS chips because I found that it into the counter’s latches when it is active. Normally, is difficult locating 74C85 chips. An advantage of when a toui-bil counter is rolling over as it counts using 'll L instead of CMOS tor this circuit was that I

Figure 12-44 PWM generator circuit

210 1E 3 Robotics Experimen t's for the Evil Genius could simply pull the comparator inputs to ground Experiment 75 — PWM Generation apiEHarH’H r-ry-r-T^ -rrrr-p-rrr without a pull-up icsistoi. If you were to build this fc *L777fuS , 4 Output PWM circuit with ( MOS chips, make sure that you have Waveform pull-up resistors on the 1 )1P switch to ensure a high voltage is passed to the comparator. Bit 0 Once you have built the circuit, you will find that jiaimajy.,.^_ Bit 1 the LED’s brightness will be dependent on the value T~—s lx...: on the DTP switch. It will be confusing as the value on u—t r Bit 2 k) fScoj>*J.CH1 Si.,V. ’wffi the DIP switch will seem to be the opposite to the ?S0 uS Bit 3 Milisr.

Section Twelve Sequential Logic Circuits Section Thirteen Learning to Program Using the Parallax BASIC Stamp 2

Over the years, a number of different tools have polling its sensors again. Even without this explana¬ been developed for teaching both programming and tion. chances are you will have figured out how the programming robots. Right now, many people are program works on your own—it is probably easier to introduced (o programming using LEGO® Mind- understand the diagram than this written description. Storms and Spybotics, which are programmed via a I'm not trying to be cruel when 1 say that this will graphical interface. This method of programming is be the last time full applications will be illustrated reminiscent of developing a flowchart for planning using flowcharts in this book. Unfortunately, graph out a program and is reasonably easy for people to cal programming using flowcharts has a number of understand. People who have never programmed in drawbacks that make it a very inefficient method for their lives have created their own MindStorms pro¬ developing the different kind of robot applications grams with very little effort—LEGO® has done a that are presented in this book. Some of the draw wonderful job of reducing the fear in developing a backs include the following: robot application for their product. • Difficulty illustrating complex applications. In To give you an idea of what a flowchart looks like Figure 13-1.1 have just about reached the and how a robot program can be developed using it limit for readability. (or a graphical interface), I have shown a flow chart (Figure 13-1) for a differential robot that will behave • Difficulty in updating or modifying the appli¬ cation. In Figure 13-1, you can see that I had like a moth and move towards the brightest point in to “fold" the direction of execute upward the room. The ovals are the start and end (or stop) when a collision was detected.Traditionally, points to the program. The diamonds are decision execution flows downward. I could have points for the program Ihe square are where changed the flow in this section of the dia¬ something happens in this program or application. gram. but this would have involved making The flow of the program between the different boxes, significant changes to the entire drawing. ovals, and diamonds is illustrated by the arrowed lines in Figure 13-1. Looking at the flow chart, it should be easy to see that the program first stops for 200 msecs. Next, the robot checks (or polls) its collision sensors, and if something is directly in front of the robot, the motors are turned off and the application stops. It there isn't anything in front of the robot, then the light sensors are checked and the motors arc turned on so that the robot turns toward the side that has the brightest light (if the left side is brighter, the right motor runs forward to move the robot toward the light). Aftei the motors are turned on. the robot returns to 'he start of the program and mns for 200 msecs before Figure 13-1 Flowchart of a robot Moth program

213 Fhc expense of creating software that will using many different devices, including what CO convert the graphical image into a program a you can scrounge around for in the home computer can execute. A good part ot the cost (and, ironically, even using some LEGO of a LEGO' MindStorms kit is the cost ot the pieces). In MindStorms, if,you want to turn on o software that runs on youi PC. and off motors, simple command blocks are Hie inability to encompass different hard used, whereas in youi own robot you will have ware. In the kit. remem¬ to plan out how this is done and develop dif¬ •r*4 ber that it will only work with LEGO-defined ferent controls for the robot’s speed and turn¬ £ hardware devices. For your iobots,you will be ing motions. CL, 6 cd Experiment 76 «P C/3 Loading BR5IC Stamp UJindoujs Editor O Softuuare on Your PC M 03 < CQ

tT> a For the rest of the book, I w ill be working w ith the with more memory to get applications that work. You Parallax BS2 microcontroller for controlling both the may later want to test the different BS2 models, but "d cd different hardware experiments and the complete for now use the basic one. robots. Dre RS2 microcontroller is a self-contained Before you can start working with the RS2, the unit with the power regulation, processor, reprogram¬ development software suite (known as the Stamp mable application memory, variable memory, clock¬ Windows Editor) will have to be downloaded and a ing, and I/O built into a 24-ptn. DIP format printed circuit board (PCBypaekage as I’ve shown in the block/pinout diagram in Figure 13-2. V0 It you haven’t already done so, now is the time to buy yourself a BS2. A number of different models of the BS2 are available, but for the projects in this hook. I recommend that you stick with the entry- jj level BS2. which you can buy at a reduced cost a directly from Parallax using the information printed

2 14 12 3 Robotics Experiments for the Evil Genius connection made to the BS2. In this expeiimeni, I After the software has been downloaded,you will Experiment 76 — Loading BASIC Stamp Windows will go through the process of loading the Stamp be asked to select how the software is to be installed. Windows Editor onto your PC. In the next experi¬ Just continue with the defaults (and the typical instal¬ ment. I will walk you through loading an application lation), but make sure that an icon will appear on the and downloading it: into a BS2 mounted onto the Windows desktop, this will allow you to quickly start PC. B that is included with this book. the BASIC Stamp Windows Editor software, When Along with showing you how to download the the BASIC Stamp Windows Editor is installed, you software, I am going to point you to a manual that will get an icon on your desktop. To start it up. dou¬ you should dow nload and two Yahoo! Groups that ble-click it, to close it down, simply click the “X" in you should join to help support you with the book. the upper right-hand corner (as you would with any Windows dialog box). The first time you start up the The PC that you are using must be running some editor, you w ill be asked to assign files with the version of Microsoft's Win32 operating system with a extension \bs2,” as well as others, to the editor. By minimum of 100MB free disk space (you should also clicking “yes" when you select, a BS2 source file from have at least 32MB of main memory) l would recom¬ an Explorer window, the BASIC Stamp Windows mend Windows 98 Release 2. Windows Me, Win¬ Editoi will start up automatically, ready for the file. dows,'NF 4.0, \\ indow's/2000. or Windows/XP. If you The BASIC Stamp Windows Editor is a Windows are running Windows/NT, Windows/2000, or W in dialog box that looks like Figure 13-4. dows/XP. you will have to have administrator rights. You will also need access to the Internet on your PC ’ When the Stamp Windows Editor first starts up. it for downloading the Stamp Windows Editor software will present you with a new hint regarding program¬ as well as for looking up information on the different ming the microcontrollers. I recommend that you electronics parts that aie used. read through each one to better understand how the BS2 works and is programmed. In Figure 13-3,1 To download the Parallax Stamp Windows Editor, downloaded the Beta version of the software. When open your PCs Internet browser and go to www.par- you download the BASIC Stamp Windows Editor, it allax.com. should be a release version and may look a bit differ When you have loaded the Parallax web page, ent from what is shown in the different screen shots. move your mouse over Downloads and a pull-down The Stamp Windows Editor package includes a menu may appear or another page will come up. tool that will allow you to uninstall the software if When the selections appear, click on BASIC Stamp Software. After clicking on B. VSJC Stamp Software from the File Download k] Downloads pull -down, you should get the download *} Some files can harm your computer. If the file information below web page Left click on Download for the BASIC '-TfS looks suspicious, or you do not fully trust the soutce, do not open or save this file Stamp Windows Editor software I recommend that File name: .. .Editor_v2.0_Beta_l jSMB .exe you download the complete file rather than the one File type: Application that “requires Internet connection during install." From: www.parallaxinc.com

Other Beginner's All-Purpose Symbolic Insinn Iion /j\ This type of file could hatm your computer if it contains Code (BASIC) Stamp applications will catch your malicious code eye. but for right now, you should just download and Would you like to open the file ot save it to your computer? indall the Stamp Windows Editor (see Figure 13-3). Save Cancel Mote Info flpgn I [ You will be prompted with a dialog box asking you to open or run the application or save it I recom¬ mend that you click Open or Run and let it download Click on “Open" and install itself. Follow the instructions and select to Install the the typical install as well have the program appear on RASIC Starr-p your desktop. Editor Software Figure 13-3 Download selection dialog box

Section Thirteen Learning to Program 215 Experiment 77 — Connecting the PCB and 216 continually updatedforseveral yearsnowandithas lax Webpage,moveyourmouseto"Downloads,”and you aregoingtodownloadanewversionofit.Hie operating been thoroughlydebuggedby peoplewithevenless software andhardwareisvery robust;ithasbeen With thesoftwareloadedontoyourPC,itisnow installed. IrecommendthatyougobacktotheParal¬ install theBS2and9-voltbattery to theearlierexperiments,assemblePCB,and installed thebatteninit.Nowistimetogoback assembled (solderedpartsonto)thePCBand have gonethrougheachexperimentandyou load yourfirstapplication.Iwillassumethatyou time tohooktheBS2upit.poweritup,anddown uninstaller isaccessedfromthe"Start"menu. Figure 13MBASICStumpWindowsEditor Once youhavetheStampWindowsEditor Before starting.Ijustwantto saythattheBS2's Connecting thePCBandBS2toYourPC 153 Robotics Experiments for the EvilGenius and RunningYourFirstRpplication Experiment 77 came withthebook(in orientation «hownonthe remove thebatteryandmake surethatthereare charged NiMIIbattery.recommend thatyou depending onyourPCandtheoperatingsystemthat you arcrunning. although youmayhavetoworkthroughsomeissues PCB) andpluginafresh9-volt alkalineorrecently ing ittoyourPCarereasonablystraightforward, very littlechanceofdamagingtheBS2oryourPC mechanical skillsthanyouhave.Sorelax,have port Yahoo!groupthatIhavesetup.aswellParal¬ can buy. ming languageinmuchmoredetailthanwaspossible click on"Documentation."Youshoulddownloadand lax’s BASICStampYahoo!group.TheURLsfor book, youshouldjointheEvilGeniusRobotsSup¬ able inapreprintedandboundformatthatyou cal featuresoftheBS2andPBASICprogram plus-page documentwillexplainthedifferentelectri¬ print outtheBASICStampUser’sManual.This300- these groupsarethefollowing: ing throughtherobotexperimentspresentedinthis in thisbook.Parallaxalsomakesmanualavail * http://groups.yahoo.com/group/evilgeniusro- • http://groups.yahoo.com/group/basicstamps/ As shownlater,plugtheBS2intoPCBthat As thelaststepingettingyourPCreadyforwork¬ File proceduresforinstallingtheBS2andconnect¬ botssuport/ I do not recommend buying an RS-232 port ISA Experiment 77 — Connecting the PCB and. BS2 OB-25 (Male) or PCI card for your PC (unless your PC doe« not have USB capability),as thb will involve you open¬ ing up the PC and possibly manually configuring the serial port. USB adapters are fairly inexpensive (usu¬ ally cheaper than a PCI card) and are easy to install, just requi; ing a CD ROM and a few minutes of your time RS-232 Connector The RS-232 port you are mine should only be used for programming the PCB's BS2. Windows does Figure 13 5 IBM PC PB-25 and P-V pin RS-232 not share resources very well and if you share the connectors port with another device (like a Palm Pilot), you will have problems with the operating system trying to determine w hether or not the Rasie Stamp Editor no connections on the PC IB's breadboard before should be able to access the port. plugging in the BS2. Once you have established where the RS-232 port Next, connect the PCB to one of your PC's RS-232 on your PC is. connect it to one end of your cable and serial ports using t he straight-through 9-pin serial the other to the I’CB as shown in Figure 13-6. With (often called a serial extender) cable. As I write this, this done, start up the Stamp Windows Editor soft¬ most desktop and minitower PCs have built in RS ware (Figure 13-7) and enter the following program 232 serial ports. Phe RS-232 port can be either a 9-pip into the tabbed white text box: or 25-pin male Connector and should be connected to a cable with a 9 pin male output pin like the one 1 The first application shown in Figure 13-5. For most PCs, you will have to • {$STAMP BS2 > * {$PBASIC 2.5) buy a 9-pin I)-Shell male to female straight through cable. debug "Hello World!"

Some PCs have a male 25 pin RS-232 port connec¬ end tor. This is the standard connector tor RS-232: IBM Either click Run or the leftward-pointing triangle came up with ihe 9-pin connector for the PC/AT in and the program should be downloaded and started 1984, when they found there wasn't enough space for up. After a status dialog box that pops up and disap¬ two 25-pin connectors (one for the parallel port and pears, the‘‘Debug Terminal" will appear one for the serial port) in one adapter card slot. If you have a P(' that has a 25 pin RS 232-port connector, then you can cither buy an extender cable that con¬ verts from a 25-pin PC RS-232 port to a 9 pin connec¬ tor or use a 25-pin to 9 pin converter If vim go to an electronic or computer store, they should have a num¬ ber of different options for you to choose from to get the male 9-pin I) Shell connector for the PC 'B. Most modern laptops (and some home PCs I do not have RS-232 ports built into them If your PC ' does not have a 9-pin RS-232 port, 1 recommend that you buy a USB RS 232 interface. I have used the BS2 with both true RS-232 USB interfaces (one with lout RS-232 9-pin connectors) and a simple USB interface that is designed for personal digital assistants (Palm Figure 13-6 PCB with BS2 and battery ready to Pilots) successfully with the BS2. go!

~ Section Thirteen Learning to Program 217 There is a good chance that your “Hello World!” will work without any problems if you have followed the instructions l have laid out here. On the chance that your application doesn’t work, there are a few things that you can look for. The first is to make sure that the RS-232 port is not used for any other appli¬ cations in the P('. The PCB is wired in such a way that the Basic Stamp Editor software should detect the BS2 and 4-> automatically start downloading to it. Another device cd may be wired similarly, and the Basic Stamp Editor Figure 13-7 Screen shot of the BASIC Stamp o software could incorrectly recognize it as the PCB. In Windows Editor with the first program entered in •H this case, click “Properties,” then “Debug Port ” and manually select the port that you are using. Manually 04 The Debug Terminal dialog box is a small display selecting the port has the additional advantage that that the PBASIC “debug" statement of the program the Basic Stamp Editor software does not have to 0- c writes to for passing status information back to the search for the port w ith the BS2 on if (which means user. In this section. 1 will be using it to demonstiate downloading will he faster in PCs with a number of the results ot different programming operations. serial ports).

3 o >* Experiment 78 a 5aving Your Applications on Your PC •H > (d co ! oo You are now able to create and download applica¬ you at all times, and if you have set up your PC with r- tions into a Parallax BASIC Stamp 2. In the previous the proper tile extension assignments, when you experiment, you connected your PC B to your PC double-click on these files, the appropriate software started up the Basic Stamp Editor software, entered will come up to read or process the information If 4J in a simple application, downloaded it into the BS2, you download MP3s from the Internet, chances are a and ran it. In this section, I want to explain a bit your desktop is already full of files.

218 12 3 Robotics Experiments for the Evil Genius This is descriptive and accurate and should make categories. If you look at the “C" drive of your PC’, it Experiment. 78 Saving Your Applications knowing what it does simple. If you modify it. you is arranged something like Figure 13-8. might want to change the name to something such as In Figure 13-8,1 have started from the place when Evil Genius—First BS2 Program Modified 11.19.02— you double dick “My Computer." From there, I have Hello World! gone to the “Local Disk (C:)” and then to the Evil This is not very efficient and can be very confus¬ Genius folder and the Hello World! folder within it. ing. The problem of using this method is that your As you can see in Figure 13-8,1 have already saved desktop gets full of different files very quickly, and the application in the C:\Evil Genius\Hcllo World! when they are displayed on the desktop, much of Ihe folder. information is hidden until you single-click the file The space used in the different folders is dynami- icon. cally allocated: you do not have to worry about how The Stamp Editor Software defaults to saving much space is used in each one. TLiis means that you your files in a folder (it shows my age when I call can store as much information as you need (up to the them “directories” or “subdirectories”) in your PC’s amount of available space on the hard file) in any hard file. I f you click 1 ile and then Open, you will see folder. that you can choose from a number of example BS2 To create a unique folder to store the BS2 applica¬ programs, ’ton could save the ■'Hello World!" applica¬ tions presented in this book, click “My Computer” tion in this folder, but it may be difficult to find it followed by “Local Disk ((’:).”To create the Evil again quickly (especially when you come back a few Genius folder, click New and then Folder in the Local months later and aren't 100 percent sure of the file Disk (C:). A new folder will be created and you will name). be prompted to enter in a name for the folder. Give To make it simpler for you to save all the files that this new folder the name Evil Genius. Double click are provided in this book, 1 would like to take advan the Evil Genius folder and create a folder called tage of the tree directory file structure built into Win¬ “Hello World!" within it using the same procedure as dows (and most other operating systems). Hie tree you used to create the Evil Genius folder in the I .ocal directory file structure provides a way of grouping Disk (C:). You are now ready to save applications. and labeling files (and folders) into simple-to-search

lr> Starting at "My Computer,” double-clicking on the appropriate drive and then double-clicking on different folders to locate the “Hello World!” application in its own folder

Figure 13-8 File and folder organization in a PC

Section Thirteen Learni ng to Program 219 v •h Experiment 79 — The 'Hello World! 220 30 years.Fortherestofsection,Iwillbeexplain¬ used toteachpeoplehowprogramformorethan The languagethatisusedbytheBS2PHASICand is avariationontheBASIClanguagethathasbeen and keepthemseparatefromotherfiles(likeMP3s) easy tocreate,save,and(mostimportantly)findfiles, SIC codeiswrittenfortheRS2. ing toyouthebasicsofprogrammingandhowPHA¬ experiment’s applicationinitsownseparatefolderso that maybeonyourdesktop.Ilikekeepingeach difficult tokeeptrackofthedifferentapplications top isonethatIwouldliketodiscouragebecauseit you startworkingwithit.willfindthatitisquite to thefolderthatitislocatedin. within thecurrentoneormovefromfolder with apull-downthatwillallowyoutoselectfolders As" dialogbox(Figure13-91llustoolbarprovidesyou (C:) fromthe“Savein”toolbarattopof "Hello World!”folderthatislocatedintheEvilGenius shown inFigure13-9,willcomeup. that camewiththebook.Chances arethatbylooking World!” whichwasusedto demonstrate thelink I canmodifythecodeandsaveitinsamefolder. folder, youmayhavetonavigatewithintheLocalDisk between yourPCandtheRS2 mountedonthePCB As tosavethefile.Anewdialogbox.likeone in thepreviousexperiment,clickFileandthenSave entered intotheStampWindowsEditor,asdiscussed llie practiceofsavingallyourfilesonthePC’sdesk¬ To savethe”1lelloWorld!”applicationin After the“HelloWorld!"applicationhasbeen rhe systemoffoldersmayseemcomplex,butonce Hie firstprogramrunonyour BS2was'Hello The “HelloLLIorld!’ApplicationExplained ]i?3 Robotics Experiments for the EvilGenius Experiment 79 own folderintheEvilGeniusfolder,and1recom¬ saved theapplicationcodeforeachexperimentinits making iteasiertofindandkeeptrackofthe at thisapplication,youwillbeabletofigureoutwhat when youcomebacktothemlater. other filesinyourPCsothattheywillbeeasytofind your ownapplicationstokeepthemseparatefrom mend thatyoucontinuethispracticeasdevelop Lines: it isdoing. updates. Foreveryapplicationinthisbook,1have Figure 13-9Savingafileinitsfolder Ihe programconsistedotthefollowingseven '{$PBASIC 2.5) 1{$STAMP BS2} ' Thefirstapplication debug "HelloWorld!" end The program above is what is known as an appli¬ tokens that are specific to this device. The next line Experiment 79 — The "Hello World! cation source code or just code. Source code is a set of specifies that the code will take advantage ot human-readable instructions that are converted by a PBASIC version 2.5 compiler into a format that a computer can process The forth and sixth lines of the program arc not an directly. Ihe seven line program above is converted instruction to the BS2, but blank lines known as into a set of tokens that are downloaded into the BS2 whitespace. I suggest placing blank lines around and executed. Ibe tokens for each statement are usu¬ blocks of code to help space them out visually. By ally one or two bytes (or characters) long. Ibey are adding blank lines before and after a block of code, read and executed very quickly by the BS2. The the reader's eve will be directed to them, and it will source code only has meaning to a programmer; it is be obvious where the block begins and ends. Judi¬ not loaded into the BS2. ciously using whitespace in your application will Ibe single quote at the start of the first three lines make your programs easiei to read and understand. is used to indicate the start of a comment that contm Ibe fifth line (debug “Hello World!”) is the first ues to the end of the line, the comment in this case statement that will be compiled, converted into a being the message:“ Ibe first application.” Comments token, and downloaded into the BS2.This statement are used by programmers to document the source will command the BS2 to send the string of charac¬ code and help explain what the program is doing. ters “Hello World!” back to the P( . where they will They can be located anywhere in the source code be displayed in the “DebugTerminal” dialog box. (including after a program instruction). It is very The operation of the “debug” statement is the pri¬ important for you to come up with comments that mary method that you will use for returning informa¬ are meaningful and should try to explain something tion regarding the execution of an application to a that is useful to both yourself and anybody else who PC. In this section and the ones that follow. I will use is looking at the source code. it to return feedback information from the BS2 Going off on a persona) rant. I hate applications to you. that have comments (hat repeat or paraphrase what a Along w ith the “debug” statement, a number of line of code is doing. I could have written the first other built-in “function” statements are available to application as the following: you as you create your application source code These will be explained in this and the following sections. ' The first application '{$STAMP BS2} The string of characters in the double quotes '{$PBASIC 2.5) ("Hello World!”) can be changed within the Stamp debug "Hello World!" Windows Editor simply by moving the cursor to the 1 Print greeting statement and changing the message. You may want end * Stop the program to try changing the string to “Hello from Myke” and see what happens when you execute it again using Ibis code explains what the program instructions Ctrl R or the Run button on the Stamp Editor (called statements) are doing, but not why the instruc¬ Window. tions are there or xvhy they are needed to carry out When you change this string, you change the pro¬ the required task. As I work through the applications gram’s source code. There should be a “Modified” m lliis book try to notice how T have written Ihe message in the bottom line of the BASIC Stamp Win¬ comments and how I use them to explain what is dows Editor that indicates the application has been happening or why 1 have used the code that 1 have, changed, but the changes haven’t been saved. If you without explaining how each instruction works. are too close the program, you would get the message The next two lines are not comments, but instruc¬ indicating that the source code has changed and tions to the BS2 compiler.The first of the two lines would you like to save it. It you click “Yes,” then the f($STAMP BS2)‘) tells the compiler that the Stamp Editor Window software will save the changed target device is the BASIC Stamp 2 and it produces source code as “Hello World!"

SeLtiun Thirteen Learning to Program 221 Experiment 80 — Variables and Data Types 222 123 Robotics Experiments for the Evil Genius whereas inothersthechangesareduetovariances ronment Insomecircumstances,thechangesare are designedtoworkinachangingorvariableenvi¬ concept offlipflopsandhow theycanbeusedto internal tocontinuethenextstepinprocess, tions, youshouldalwaysputan“end"statementat the environmentrobotisworkingin.Thisehang Robots (andtheircontrollingcomputerprograms) mand fromtheStampWindowsEditor. consume 40uAsolcurrenttowaitforanothercom¬ places itinapowerdownmodewherewillonly programming language values readback.Alongwithexplainingwhatvari¬ cation. Asarule,variablescanbewrittentoandtheir application executes. mg datamustbestoredaswellreadbackwhenthe ment slopstheBS2lromexecutingfurtherand World!” applicationsourcecodeis“end.''thisstate¬ arc availablegenericallvaswell asinthePBASIC ables are.Iwillreviewthedifferentdatatypesthat then SaveAs;youcansaveit(inthe‘“HelloWorld!" used tostoreandretrievedataneededbytheappli that isstoredmmemorythecomputersystem,are Updated,.’' folder) as“‘HellofromMyke''or‘‘HelloWorld- changed sourcecodeas“1fell©World!,"clickFileand for eachofyourapplications.Insteadsavingthe The finalline(andstatement)inthe“‘Hello When youfirststartwritingyourownBS2applica¬ In theprevioussection,Iintroduced youtothe This iswhyIrecommendcreatingseparatefolders Variables, whicharenumericorcharacterdata Variables andDataTypes Experiment 80 (a throughzorAZ). Inthebodyofvari- score character(“_")oran alphabetic character groups ofbitsareasshowninFable13-1. ters upto32characterslong, startingwiththeunder¬ used andisintheformat; vides thisfunctionautomatically. combine bitstogether,thePBASIClanguagepro¬ of requiringyoutodevelopprogramsourcecode some programminginstancessinglebits(with store asingleunitofdatacalledthebit.TheBS2pro¬ should be. ger thatexecutionwillcontinuepastyourcode—but. applications youwillrequirelargernumbers.Instead numeric valuesof0or1)areuseful,formostyour vides 206bitsforuseinyourprograms.Although “end" statementtomakesurethattheBS2stopsif one. Inmostrobotapplications,executiontakesplace tion afterithasexecutedpasttheendofcurrent doesn't havean“end"statement,thentheBS2con your applicationisshorterthanapreviousoneandit ot theBS2withouterasinganypreviousprograms.If its executioncontinuespastwhereyouthinkit lust tobeonthesateside,rememberpulm in acontinuouslyrepeatingloop,andthereisnodan¬ tinues executingthecodefrompreviousapplica¬ is loaded,itsimplystoredintheprogrammemory the endofyourapplication.WhenaBS2application The “VariableName”canbe anysitingofeharac To defineavariable,the“declaration"statementis The waysthatPBASIChandlessinglebitsand VariableName varType ByteVar var byte

Table 13-1 PBBSIL data sues and number Experiment 80 — Variables and Data Ty p e ranges Word Var var word

• Assignment Statements BitVar = 0 1 Bits can be 0 or 1 Number cf ByteVar = 0 1 Bytes can be 0 to Bits Tyne Data Range 255 WordVar = 0 1 Words can be 0 to 1 Hit Oto 1 65,535

4 Nib 0 lo 15 ’ Display Variables using debug statement debug ? BitVar 8 Byle Oto 255 or 128 lo 127 debug ? ByteVar debug ? WordVar 16 Word 0 to 65535 or -32.768 to 32.767 end

When you have finished entering the program, able name, alnng with the underscore character and create a Variable Display folder for it inside the Evil alphabetic characters, numeric characters (0 through Genius folder and save the program as Variable Dis¬ 9) can be used. play. Once you have done this, run it with the 0 "Type” in the variable declaration is one of the loaded into the three variables as well as different four types listed in the table above. "Nib” is an abbre¬ vhlues. You might want to try different values greater viation for the word "nybble,” which is commonly than the si/e of each v ariable type to see what kind of used to describe four bits.The nybble is a very useful message comes back from the compiler (as well as data type, especially when you want to display non what is display ed on the Debug Terminal dialog hox). decimal data efficiently. W hen you set a variable to a value greater than PBASIC variables can be "overlaid” on other vari¬ the value that it can hold (try "BitVar = 3”), you will ables or parts of the variables can be used as separate discover that the part of the number that is less than variables. To access a small part of a variable with an the maximum value that I listed in the table will be overlaid variable, the "modifiers” listed in the BS2 saved in the variable.There will be no erioi message. Quick Reference are used. For example, defining a PBASIC ANDs the value to be stored in the variable single bit in a "Flag” variable would be accomplished with the maximum value the variable can hold. Ihis is with the code: an important point to remember because sometimes you will discover that the value you expect to be in a Flag var byt ’ 8 Bit Variable LED var Flag.bitl • Single Bit of "Flag" variable is much lc«s than what it should be because of this ANDing. Ihis could be repeated for all eight bits in the This application first defines three variables (a bit. Flag” variable. Using the "bit#’ modifier, you can byte, and word), loading different values into them specify the use of each bit m a byte, which is an and them out before ending the program. advantage because in some eases, the PBASIC com¬ The three statements that make the variables equal piler will define each “bit in its own byte. You will to the numeric value are called assignment statements. find that your memory space (which is only 26 bytes Passing a constant value to a variable, as is done in [206 bits divided by 8 bits/bytej to begin with) will be this experiment, is the simplest form of the assign¬ used tip very quickly if you want to have several bit ment statement that can be used for much more com¬ var lables. plex operations. To test out the operation of variables, start up the In the debug statements, the contents of the vari¬ Stamp Windows Editor and key in the following pro¬ ables are displayed, but I used the “?" formatter to gram display the variable name along w ith its value. After

' Variable Display - Write to and Display printing the variable name and its value, a new line Different Variable Types on the display is started I will be explaining format '{$STAMP BS2> '{$PBASIC 2.5} ters and the different wavs data can be displayed using the debug statement in the next few experi¬ ' Variables BitVar var bit ments.

Sec-tion Thirteen Learning to Prognam 223 Experiment 81 — Number Data Formats system. expressing binarynumbers(whichonlyhavetwodif- be ignored. were startedat1,thenthefirstpossiblevaluewould which thesmallestpossiblevalueiszero:ifnumbers is alwayszeroandnot1asyouwouldexpect.Die of thevalueeachdigit decimal numbersarewrittenwithabaseof10.Figure power ofthepositiondigit.Thisisexactlyhow either toyouoranotheruserotcomputer 224 reason torthisisduetotheuseofbinaryvaluesin 13-10 showshowthenumber“123"isreallysum bers. eachoneamultipliertimesthebaseto used.These differentformatsareusedtooutputdata, the robotapplicationprogrameasierforyouto parameters thatwillmakethedatacomingbackfrom position, speed,lightlevels.I/Obitslates,andother this book.Idiscusstheappropriatedataformatsfor into numericformsotheBS2canprocessit.Laterin part oftheworkwillbetoquantizeorconvertdata When Ipresenttoyousomerobotapplications,abig ut PBASICfortheBS2andshowhowtheycanbe introduce youtothedifferentdataformatsavailable understand Beforegettingtothispoint.Iwant sum ofpowers10 Figure 13-10Thenumber 123representedasa 'Die methodshowninFigure13-10canbeusedfor A multidigitnumberismadeupofseveralnum¬ In engineeringandcomputerscience,thefirstdigit 1E 3 Robotics Experiments for the EvilGenius T 2x10'=20 1 x102=100 Assembled PCBwithBS2 Number DataFormats 123 Experiment 81 character placedinfrontofthemtoindicatethat is notbinary.InPBASIC,42decimalrepresented is 1.alongwiththe8digit(hit3)and2 number 42.UsingFigure.13-11,the32digit(bit5) ues andviceversaForexample,considerthedecimal ferent possiblevaluesforeachdigit)asdecimalval¬ ditferent hexadecimalnumbersHexadecimalis sent asinglehexadecimaldigit.InTable13-2.1list as %101.010binary. the number.II%isnotpresent,thennumber (bit 1).Alltheotherdigitsarezero.InPBASIC, they usebase16. mnemonics. Hexadecimalnumbershavea$prefix hexadecimal valuesovernine,thelettersAthrough binary isabbreviatedtobinanddecimaldec.For often abbreviatedtothethreelettershex,justas the binary,decimal,andmnemonicstor16 most peopleusehexadecimal(base16)numbersfor “Grace” inbinaryforseveralhours.Ibavoidthis, Bender inFuturamajoinsarobotchurchandrecites take alongtime;greatexampleofthisiswhen binary numbershavea%prefixcharacterinfrontof F areusedandoftenreferredtobytheirphonetic binary data.Fourdigits(onenybble)repre¬ of powers2 Figure 13-11Thenumber 42 representedasasum Tool Box Writing andsayingmultidigitbinaryvaluescan +0x2°= C + 1x.2= + 0x2= + 1x23=8 + 0x24= %101010 =42 1 x25=32 RS-2S2 cable PC Table 13-2 Decimal, binary, hexadecimal and debug "Decimal ", ? Value Experiment 81 — Number Data Formats debug "Binary ", IBIN ? Value mnemonic cross-reference debug "Hex ", IHEX ? Value

end Dec Bin Hex Dec Bin Hex Mnemonic

0 0000 0 8 I IKK) 8 In Ihc debug statements, I have placed the IBIN and IIIEX formatters before the characters to print 1 0001 1 9 1001 9 the variable name and contents of the Value variable. 2 0010 2 10 1010 A "Able’* The IBIN and IHEX formatters will convert the con '3 (Kill 3 II Kill B “Baker tents of Value to binary and hexadecimal and place

4 0100 4 12 1100 C “Charlie" the % anil $ data format indicators in front of the values. Along with IBIN and II IEX. a number of 5 0101 5 13 1101 D "Dog" other formatters are available in the debug statement 6 0110 6 14 mO E "Easy! and they are listed in the BS2 Reference at the end of

7 0111 7 15 1111 F “Fox" lhe book. I recommend that you use just these two format¬ ters (along with dec for decimal) for numeric data to PBASIC will convert data into the different make sure that you don't get into the situation where numeric bases automatically for you. I recommend die number 10 is printed out and you automatically that you look for a cheap scientific calculator with assume that it is 10 (decimal) and not 2 (binary) or 16 this capability built in.This capability is very rarely (hexadecimal).The other formatter options for deci¬ advertised, so when you arc looking at calculators, mal. binary, and hexadecimal numbers can be confus¬ look for ones that have the functions DEC, BIN. ing if they are used w hen you are first starting to HEX, and OCT on the keypad along with the letters learn about programming and are not sure what the A through F. OCT is the representation lor base 8 displayed data means. numbering and was quite popular 30 years ago. I he different number foimats are selected to Except for some C programming situations, octal is make reading data output and programming hard¬ rarely used because it is quite awkward to use (each ware interfaces easier. When you first start program¬ digit is made up of three bits and docs not tit evenly ming I recommend that you stay with decimal (base into a byte or a word). 10) as much as possible because this is what you are To demonstrate the different formats available to most comfortable with In the next section, I will display numbers in PBASIC, you can key in the num¬ show instances where base 2 and 16 numbers are best ber format application below and save it in its own used when interfacing to hardware devices. folder (Number Format) in the Evil Genius folder. Before going on to the next experiment, I want to As in the previous application, change the value share with you an interesting story that shows how assignment statement and run the application again far we’ve come. As you may or may not know, hex is to see what different decimal values look like in the not the correct prefix for 16 (hex actually means 6). different formats. The correct prefix is sex and a base 16 number should be known as sexadecimal. ITiis was obviously a 1 Number Format - Display a Value in Different Number Formats source of mirth for early programmers. When IBM '($STAMP BS2} introduced their System/360 computers in the early 1{$PBASIC 2.5} 1960s, the documentation referred to base 16 num¬ * Variables bers as hexadecimal because the company w*as Value var byte uncomfortable with the idea that their computers 1 Assignment Statements Value = 123 'Arbitrary Value to were programmed in sex and didn't think ;t was Display appropriate for a machine that would be pro¬

' Display Variables using the debug grammed and used by a variety of different people, statement some of whom could be female.

Section Thirteen Learning to Program 225 Experiment 82 — ASCII Characters NUL DLE into abyteandpassedtothereceiver.Youhave control theDebugTerminalthatcanbereviewedin Table 13-4Othercontrolcharactersareavailableto and computerprogramminginterfacing,bytes 48 the BS2reference. bers, anddifferentcharacters.Table13-3showsthe are usedtorepresentdifferentEnglishletters,num¬ ferent formats.Formostcomputercommunications ues aswellbedisplayednumericvaluesindif¬ bits canbecombinedtocreatereasonablylargeval 226 @ SP use (withtheirPHASICequivalents)arelistedin values ofS(X)toSIF)thatyouwillprobablywant most commonwayofrepresentingdifferentcharac¬ 64 32 Interchange (ASCII)characterset. ters istheAmericanStandardCodeforInformation 80 0 16 In thepreviousexperiment,1showedhowgroupsof P 96 ruble 13-3RSCIIcode ' P 112 0 The 128differentcharactersarenormallyloaded Special characters(locatedinthe32byteswith A Q DC1 SOH a q 81 66 1 49 3 17 1 97 113 i 123 Robotics Experiments for the EvilGenius b R B 2 DC 2 STX 2 r 114 98 82 66 18 5C \\ 34 C c DC 3 ETX s S 3 115 99 83 67 3 # 36 19 51 Assembled PCBwithBS2 d T D DC 4 EOT 4 4 20 t 116 100 84 68 $ 36 52 u U NAK e E ENU 21 117 101 85 % 37 69 6 53 5 R5CII Characters Experiment 82 V V ACK & F 70 SYN 22 118 f 102 86 6 38 6 54 W w a G BEL ETB 7 71 7 23 119 103 87 55 3 9 X h X H CAN BS 40 120 72 8 24 8 104 88 56 ( 7-bit container(andhasamaximumof128different as themessagesanddatapassedtoDebugTermi¬ already usedASCIIcharactersinyourexperiments 256 differentcharactersatatime.Themostpopular values). EnhancementstotheASCIIcharacterset to 255).TheASCIIcharactersetwasdesignedfora and couldcontainupto256differentvalues(from0 nal fromthedebugstatements. ASCII characterset, Greek alpha)thatarcnotbuiltintothestandard areas ottext,andcommoncharacters(suchasthe other thanEnglish,theabilitytographicallyboxin acter setprovidesspecialcharacterslorlanguages of theenhancementswasdevelopedbyIBMlor provide anadditional128characterstothestandard PC morethan20yearsago.TheIBM-enhancedchar¬ for differentsituationstoallowabytesendup Tool Box Earlier inthissection,Inotedthatabvteis8bits y Y HT 41 EM 73 25 121 1 105 89 I 9 57 9 ) J LF Z 74 42 SUB 26 z 122 j 106 1C 90 58 k VT K k 75 43 ESC 27 123 .107 + 11 91 59 r { [ NP L < 76 44 FS 28 124 1 108 92 60 \ 12 / ! m M GS CR 77 = 45 29 125 109 61 ] 3 ] 93 - } N n RS - 78 > 126 /V 46 SO 110 94 62 30 14 DEL o 0 US 111 7 9 47 SI 127 95 •p 63 31 15 / Iablo 13-4 Most commonly used HSCII and PBRSIC contiol characters Experiment 82 — ASCII

Symbol PBRJ5IC Symbol Function

M'l. CLS ASCII Normally it is used to terminate a string. In PBASIC, it is used to clear the Debug Terminal dialog box.

SOU HOME ASCII, Start of data header In PBASIC. it is used to move the cursor to the top left hand corner of the Debug Terminal dialog box.

BEL. BELL Beeps the system (PC for BS2) speaker.

BS BK.SP Backspace,

TAB TAB Horizontal tab.

LI none New line (or NL).

CR CR Carriage return.

For all the experiments in this book, I will only be debug "ASCII ", ASC ? Value using the common ASCII characters listed. Different end PCs, as well as different fonts used within different applications, define the enhanced 128 characters dif¬ L ike the previous experiments, run ASCII display ferently. This means that an application that presents after setting Value to different constant values. You beautifully in one application on a certain PC will might even want to assign a value greater than 127 look very poor (or even been unreadable) on another ($7F or % 1111111) to see the enhanced ASCII char¬ PC or in another application. acters are for your PC (running Stamp Windows Fditor). o Along with displaying standard characters, the ST* ASCII character set has a number of “control charac¬ In this and the previous experiment, notice that I ters” (the ones relevant to PBASIC are listed in Table have Imked a constant string (ASCII) with the out 13-4) These codes can be used to move characters put value. This is done by placing a comma (,) h around the debug terminal’s window or indicate the between the two items to be output, and it runs them end of a line (the “cr” character). together without any spaces or new line characters; o this is called concatenation. I’m pointing this out Save the ASCII display application below its own ft because data can be formatted together on a single folder in the Evil Genius folder; fl> line in many ways using a single debug statement, h ' ASCII Display - Display the ASCII Charac¬ with a bit of creativity, you could come up with some ter for a numeric Value very attractive displays on the Debug Terminal. 03 ' {$ STAMP BS2) 1 {$ PBASIC 2.5} A string is a number of characters that are stored

’ Variables together in a computer system. Constant strings arc Value var byte identified in PBASIC as a set of ASCII characters

' Assignment Statements enclosed in a pair ol double quotes (“”). One of the Value = 123 ' Arbitrary Value to primary functions of constant strings is to provide a Display message for the human operator, as I have done in ’ Display Variables using the debug state¬ the programs presented in this section. ment

Section Thirteen Learning to Program 227 Experiment 83 — Variable Arrays I make themup.Ifyoulookatthepreviousapplication number otcharactersineachsentencethisbook, game thatyourunrequiresalotmorespacethanthe do anythinguseful;eventhesmallestapplicationor and countthenumberofstringcharactersthatare than 26bytestostoretheASCIIcharactersrhat you'll discoverthatvirtuallyallofthemrequiremore 30.000 timeslessthanthesmallestdataareaavailable 228 paltry 26bytesavailableintheRS2.Ifyoucount you’re probablywonderinghowexactlytheBS2can in theoriginalPC. to youdiscoverthattheRS2onlyhasonevariable variable datathatyouhave.I'msureitisashock To acertainextent,youareprobablyfamiliarwith memory areaanilncanonlystore2f>bytes,about PC (showninFigure13-12)canbeusedtostoreany bytes). Thememoryinanyofthesethreeareasthe megabytes). Tospeeduptheexecutionofapplica¬ memory) ismeasuredintermsofbillionsbytes memory specificationsthatyouwillconsiderwhen the specificationsgiventoyouwhenlookata that ismeasuredinthousandsotbytes(calledkilo tions theprocessorhaslocalmemorycalledacache tem ismeasuredinmillionsofbytes(called (called gigabytes),andthemainmemoryofsys¬ you arebuyingasystem.Theharddiskspace(or personal computer.MostmodernPCshavethree Figure 13-1.2Memorysystems inaPC Disk If youthinkaboutwhatI'vejustwrittenhere, 123 Robotics Experiments for the EvilGenius Microprocessor (MPU) Assembled PCBwithBS2 Experiment 83 Variable Rrrays t Hh code arestoreddifferentlyintheBS2thanvourPC require 16bytes,leavingonly7forcodeandthe rITiis spaceisusedtorthequotedstrings,suchas devices. InthePC,disk,memory,andcachecan comparison betweenthecapabilitiesoftwo only onebyteofthe26bytesvariablestorageis at thepreviousapplication,youwoulddiscoverthat ment usingCtrl-M(Figure13-14).Ifyouweretolook ones inIhedebugstatementsthepreviousexperi¬ application codeandconstantstorageintheBS2 different memoryislocated. be usedforeithercodeorvariables,whereasinthe ory comparisonofthePCisnotan“applestoapples” variable memorycomparisonoftheBS2tomem Value variable. used inthedebugstatements,you'llseethatthey used fortheapplication’scodeandquotedstrings. used bytheapplication,whereasalmost30bytesare Figure 13-13BS2withmemory locationsmarked ure 13-13showstheBS2withtwochipswere BS2 the26bytescanonlybeusedforvariables.Fig¬ Tool Box Two kilobytesofHI•PROMareavailablefor Although ihevariablememoryandapplication Before goingontoofar.1shouldpointoutthatthe RS-232 cable PC “Size" is the number of bytes or words used by the Experiment 83 — Variable Arrays array (up to 26 bytes or 13 words).'1 VariableName” and “type" are the same as I presented earlier. So, to define a 10-byte array, the following state¬ ment is used.

ArrayVariable var byte(10)

To print out the third byte (also known as the third element in the array) to the debug, terminal, use this statement:

debug ASC ? ArrayVariable(2)

The tirst byte in the array has an index value of 0, Figure 13-1M Dialog box showing BS2 memory which is why I use an index of 2 to access the third utilization brought up with Ciri-M byte in the statement above. Arrays can be used to save numeric data as well as the variable memory behaves the same way in both character data, which results m data similar to the devices. So far in the experiments, I have been delining quoted strings, in this experiment. I will «how how an array is defined,loaded with data, and then printed and accessing single variable bytes directly.The vari able space allows tor variables to be defined with mul out along with a quoted string.The code should be tiple bytes or words and allows individual bits, bytes, or saved as ASCII Strings in its own folder in the L-’vil 16-bit woids fo be accessed arbitrarily bv use of an Genius folder: index. An index is a numeric value that is specified ' ASCII Strings - Read and write to a byte explicitly or mathematically and allows toi a great deal Array of freedom to access any data w ithin a variable array. ■ {$ STAMP BS2 > ' {$PBASIC 2.5) It is important that all variable memory in a com ' Variables puter system is set tip as an array and can be accessed ASCIIArray var byte(5) indirectly by using an index. The classic way of pre ' Assignment Statements seating an array is as a row of post boxes used for ASCIIArray(0) = "E" ' Load "Evil” sorting mail as in the variable array shown in Figure into ASCIIArray(1) = "v" 1 "ASCIIArray" 13-15.The street name is analogous to the variable ASCIIArray(2) = "i" ASCIIArray(3) = "1" name, and to access the mailbox tor an address, the ASCIIArray(4) = 0 house’s street number ( which is analogous to the ' Display Variables using the debug state¬ variable’s index) has to be known ment Array variables use a slightly different format of debug STR ASCIIArray, " Genius", cr the declaration statement 1 presented in the earlier end experiment: If is probably surprising to you that I have ended

VariableName var type(size) the string of characters stored in ASCIIArray with a zero (or ASCII NUI.) character. Hie zero at the end of the string of characters in the array indicates to the STR formatter that the string has ended and no more bytes are to be printed out. Die Nl'L character- ended string is known as an ASCIIZ string.

Figure 13-15 Variable byte organization for an array

Spction Thirteen Learninq to Program 229 Experiment 84 — Using Mathematical Operators commonly usedsymbolsindefiningprogram¬ acter stringsarerepeatedinthestatement.These expressions arealsousedinotherstatements(and ming statements,functions,andoperations. to indicatethecharacterswithinthemareoptional the valuetobesavedinassignmentstatement, as anexpressionAlongwithbeingusedtospecify assignment statementis: 230 operators putintoparentheses.Ifvalueshaveparen¬ ments, orconstants.Theycanalsobevalueswith with before,butthereisonelittletwistthatyouwill very similartootherlanguagesthatyouhaveworked operations (mostofwhichyouarefamiliarwith)for thesis aroundthem,thentheyareevaluatedfirst.The PHASIC functions).Thebraces(“{“and“}”)areused have tobeawareof. gramming already,thenyouwillfindPHASICtobe processing numericdata.Ifyouarefamiliarwithpro¬ other programminglanguages),Iwantedtotakea Now thatyouknow|ustabouteverythingthereisto “Operator" canbeoneofthe followinginTable13-5. look atwhatcanhedonewiththeminanapplication know aboutvariablesinPHASIC'(aswellasmost perform theiroperationson asinglevariable. PBASIC otfersanumberofdifferentmathematical because thereareanumber of unaryoperatorsthat Ihe “..."isusedtoindicatethatthepreviouschar Everything totherightofequalssignisknown The basicformofthePHASIC'mathematical I havemarkedValueAasan optionalterm Ihe “Values”canbevariables,airayvariableele ValueB {Operator...} DestinationVariable ={ValueA}Operator 123 Robotics Experiments for the EvilGenius Using MathematicalOperators in theAssignmentStatement Experiment 84 ited: Iwouldrecommendthat nomorethantwoare within parenthesistolarger expressionsisnotunlim¬ and isprobablyeasiertoreadthanthefirstmethod. used ineachassignmentstatement. in parenthesis. tion tobeevaluatedbyplacingitanditsparameters variable tosavethetemporaryvalue first calculationoftheexpression(3*4)irratempo¬ result of32.TogetaroundtIrisproblem,youcould the easeforPBASIC;itevaluatesexpression given anorderofoperationsorpriority.Thisisnot Remember thatyourability toaddsmallexpressions rary variableandthenadd5totheproduct: break itupintotwoparts,thehistbeingtosave as 5plus3(8)firstandthenmultipliedby4fora you wouldusethestatement: to multiply3by4andadd5theresult(toget17) most high-levellanguages,thedifferentoperatorsare experiment ishowtheoperatorsareevaluated.In from lefttoright. This formatisoftenusedforhigh-levellanguages This methodworkswelldespiterequiringanextra The twistIwastalkingaboutatthestartof But inPBASIC,thisstatementwouldbeevaluated In atraditionalhigh-levellanguage,ifyouwanted f hesecondmethodisto“force”thefirstopera A =5+3*4 A =Temp+5 A =5+(3*4) Temp =3*4 Experiment 84 — Using Mathematical Operators Table 13-5 PBflSIC mathematical operators Try out the simple Operator Test application (in us own folder in the Evil Genius folder):

Operator Function ► ' Operator Test - Look at how different + Return sum of two values operators behave ' {$ STAMP BS2 > Return difference of two values: return negative * {$PBASIC 2.5) of a value ' Variables * Return product of two values Result var Word

*/ Return middle two bytes of product of two 16- ' Assignment Statement - change to test bit values different operators Result = 25 + 32 ** Return upper two bytes of product of two 16-bit values ’ Display Result debug ? Result / Return quotient of a dividend and divisor end // Return remainder of dividing a dividend by a divisor Jn this experiment, change the addition operator

<< Return first value shifted to left by other value (+) with the operators listed in the table along with bits changing the parameters.The different operators

>> Return first value shifted lo right by other value should be quite easy to understand in most cases, bits except for the trigonometric operators (SIN and

& Return bitwise AND of two values COS).

i Return biiwise OR of two values

A Return bitwise XOR of two values

Return complement of a value (same as XOR- ing with $FF)

MIN Limits Value to specified low

MAX L imits Value to a specified maximum

DIG Return specified decimal digit of a value

REV Reverse specified number of bits of a value

ABS Return absolute value of a positive or negative value

DCD Return value with specified bit set

NCD Return most significant bit of value

SQR Return square root of value

SIN Return sine of Value assuming a 256 point circle with a radius of 127

COS Return cosine of Value assuming a 256 point circle with a radius of ill

I

Section Thirteen Learning to Program 231 Experiment 85 — Creating Simple Program Loops input same commandsgetrepeatedoverandagain.If the bottomofprogrambackuptotopwill you lookattheflowchart,codeflowgoingfrom ably looksomethinglikeFigure13-17.inwhichthe would likeyouiapplicationtoexecute,itprob¬ series ofstatements.Ifyouthinkabouthow operations) performedontheinputisprocessing, statements aretheinput,anychange(mathematical 232 Figure 13-16Basicprogrammingmodel to firstsetuptheinitialconditionsandthenrepeata and theresultsonDebugterminalareoutput this section,youshouldbeabletocreateapplications W henItookmyfirstclassincomputerprogramming, culator, butitwillnotbeveryusefulforprogram¬ that followthisdataHow.lltevariableinitialization (Figure 1316).WithwhatIhaveshownyousofarin I wasshownthediagrambelowofatypicalprogram ming arobot. Figure 13-17 Looping programflowchart model 1 hisabilityallowsyoutousetheKS2asasimplecal¬ For arobottoexecuteindefinitely,youwillhave w Processing Robotics Experiments for the Evil Genius Input/Output Creating SimpleProgramLoops initialization Operations Processing Data Data Data & 1 f Experiment 85 >- Output code exactlyasshownmFigure13-17.Thetwostate¬ same commandsoverandagain. execution willallowtheprocessortoexecute ments takethetollowingform: mally referredtoasjus|“doloop”)allowforlooping look likearingorloop.Tltisloopingottheprogram Genius folder. as LoopingStatementsinitsownfoldertheEvil dows Editorsoftware.Onceyou'vedonethis,saveit ments, enterthefollowingcodeintoStampWin¬ to provideamethodofrepeatingseriesstate¬ To demonstratehowthedoloopstatementswork In PHASIC,the“do”and"loop”statements(nor¬ Counter varWord operation ofthe"do-loop" ' Variables '{$PBASIC 2.5} ' {$STAMPBS2} ' LoopingStatements-Demonstratethe 1 Statementsthatexecuterepeatedly Counter =0 Delay 500msecsbeforerepeating do 'Returnherefornextcountervalue Increment counter do 'StartofCodetorepeat loop 'Looparoundanddo again loop Display theCounterValue Processing Initialization Counter =+1 pause 500 debug ?Counter W hen you i un this application, the counter will This program will loop indefinitely (only stopping Experiment 86 — Conditionally Looping increment itself twice every second; the pause state¬ when power is taken away from the BS2 or if it is ment stops the BS2 from executing for the number of reprogrammed I It is known as an infinite loop for milliseconds specified. By specifying 500, the BS2 will this reason. In traditional programming, you should stop for 500 milliseconds, or a half-second. Pause work at avoiding infinite loops because if execution does not put tlie' BS2 into a low-power mode. gets into one, then it will never return or stop When Looking at the execution path of this program, you we work with the robots, you 11 discover that this is will see that it first initializes the Counter variable to 0 not necessarily a bad thing, and you will see that and then enters the loop. In the loop, the counter is many robot applications will involve an infinite loop incremented (or has 1 added to it). Next, the current that will only end when the robot's batteries wear out value of Counter is output, and execution stops for a (or you execute the "Power Off’ application, which is half-second due to the pause statement and then loops shown in a later experiment). back to the do statement and starts the process over

Experiment 86 Conditionally Looping

Tool Box Assembled PCB PC

RS-232 cable

One of thi important points in the definition of struc¬ can be one of the six tests listed in Table 13-6. The tured programming is the ability to execute iteratively, expression is evaluated and if it is true, then execu¬ using repeated statements that perform a specific tion will continue in the loop code. It it is false, then task. In the previous experiment, I showed you the do execution will jump to the first statement follow ing loop programming statements that allow you to loop the loop statement application code repeatedly, but will not allow you to 11 you wanted to pimt out numbers from I to 10, leave if In this experiment. I want to show you how to executing code in do-while loop code while the cur¬ execute looping code while a set of conditions is valid rent number is less than or equal to 10, you could use and introduce you to how conditions are tested in the code; PBASIC (and most other languages). PBASIC has three ways of exiting a do loop sec¬ Number = 1 do while Number <= 10 tion of code, but I am only going to focus on the do- ' Loop while Number is Less than 11 while loop, which executes the code within the loop debug ? Number, cr Number = Number + 1 while the tested parameters are within a valid range. loop The test for the parameters takes place using the end expression format: To indicate the code inside the do-while loop statements, I indented the “debug ? Number, cr” and ValueA Condition ValueB “Number - Number + T statements by two ValueA and ValueB can be variables, array ele¬ columns.This makes the code inside the loop very ments, or constant values. Condition is the test and easy to recognize and is a code-formatting technique

5pction Thirteen Learning to Program 2.33 Experiment 86 — Conditionally Looping were calculatedusingadditionandsubtraction such asmultiplicationanddivision,thefinalvalues one regardlessofthemethodusedtodisplayit. ganized whendisplayedonawebpageusingInternet mically.This methodwastobeusedbyBabbage’s a value(calleddifference)thatispredictedalgorith manually. Ratherthanrelyoncomplexoperations winks, Iwanttoexpandonthesimpleexampleabove and makesurethatilwillbedisplayedasthesame The indentationcanbewhateveryoufeelcomfort¬ 234 "Difference Engine"toperformcomplexcalculations values (likesquares)wereextremelydifficulttodo ence theory.Hundredsofyearsago.calculations and calculatethefirst16squaresby(heuseofdiffer¬ tion codeanywhere,then1recommendthatyoujust want tousemoreoryoumaytabthesource able with.Personally.Iliketwospaces,butyoumay cos erthattheyarerelatedto theprevioussquare without theneedtormultipliersanddivideis. use spacestomovecodeandcommentslotheright Explorer). Ifyouaregoingtodisplayyourapplica¬ ent applicationsdisplaythesourcecodedifferently over. Ifyoutabthecode,thenrememberthatdiffer¬ that Irecommendyouuseinyourownapplications. value byaDeltathatis twogreaterPhanthe (for example,somethingthatlooksgreatonthe value usedtocalculatethat square. InTable13-7.1 BASIC StampWindowsEditorcanlookverydisor¬ Condition OperationComplement > ReturnTrueilValueAis<— <= ReturnTrueifValueAisless> < ReturnTrueifValueAis>= <> ReturnTrueifValueAdoes= table 134FBflSICconditionalexecutiontests If youlookatdifferentsquare values,youwilldis¬ lo demonstratehowthedo-whileloopconstruct greater thanValueB greater thanorequaltoValueB equal toValueB than orequaltoValueL! less thanValueB Return TrueilValueAis< not equalValueB Return TrueifValueAis<> 123 Robotics Experiments for the EvilGenius saved intheSquaresfolderEvilGeniusfolder: out ofthedo-whileloop.Inthiscase,nextstate¬ greater than16Whennis16,thedo- to eachdifference. appropriate differences.TheDeltaisthevalueadded have outlinedthefirstfivesquaresalongwith while conditionisnolongertrueandexecutionjumps ments torepeatthesquarecalculatingcodeuntilnis 16 squaresintheSquaresprogramthatshouldbe ment istheendstatement,whichstopsapplication. calculated usingdifferences Table 13-7Illustratinghouusquarescanbe 5 252 9 36 4 162 7 25 3 92516 2 439 "n SquareDifferenceDelta+I" ii a14 1 usedihedifferencetheorytocalculatethefirst In thisprogram.Iusedthedo-whileloopstate¬ Delta varword Difference varbyte n varbyte difference Square varword Square, cr 1 {$STAMPBS2> 1 Squares-Calculatesquaresbasedon * CalculateNewSquareandDeltavalue 1 FindSquaresforfirst16numbers ' InitializeVariables ' DeclareVariables '{$PBASIC 2.5) Difference =2 Delta =1 n =1 do whilen<=16 Square =1 loop end n =+1 Delta =+2 debug decn,"squared=", Square =+DeltaDifference Square of tn Experiment 87 x “Pauiier Off” Application CD

H* 3 (D 3 c+

After finishing with the looping application,you may ment as I do in the application that I call “Power Off’ have shut down the Stamp Windows Editor, shown here; 00 unplugged the PUB irom the PC, and assumed that -4 the BS2 had stopped running. Unfortunately, this is 1 Put BS2 to sleep with to save power (and not remove not the case; the BS2 will run the current application ' battery). I as long as it has u in memory. The pause instruction '{$STAMP BS2} *{$PBASIC 2.5) does not place the BS2 into a low-power mode, if will continue to drain the 9-volt battery as long as it is 1 Constant Declaration AllInput con 0 installed in the P( B To make matters worse, the PCB outs = AllInput o that you have built to run the BS2 applications does ' All Pins now I/Ps to avoid not have an off switch; the application w til continue ' current source/sink (D to run as long as the battery is inserted into the debug "Goodbye.., cr socket. h end During normal operation, the BS2 will draw 8 milli-amperes of current With a fresh 9-volt alkaline 71ns application can be run with any of the appli¬ o battery, you can expect something less than one day cations or circuits presented later in the book, and it Ht of life. With this information in hand, you might be will put the BS2 into low power inode by simply con Hi

wondering if a mistake was made when the PCB was necting the PCB to a PC and running (Ctrl- R) this > designed application. Looking at the code, there is probably at least one statement that you will be unsure about. When 1 designed the PCB to bo included with this > book, I wanted to take advantage of the low-power In this application. 1 introduce the concept ot con T? modes available in the BS2 and avoid a power switch slants. These are labels.similar to variable labels in 73 for it altogether. This does not violate my “rules of which a constant value is assigned to. Unlike vari M robotics.” As in all the applications where motors are ables, constant labels cannot be changed by the appli H’ driven, the batteries powering the motors do have cation. For example, if you were to put in the switches to make sure the robot can be positively statement: O turned off and prevented from moving unexpectedly. p Allinput = 42 By executing the end statement, the BS2 is put in a ct low power state, consuming only 40 micro-amperes ITie Stamp Windows Editor would return the mes¬ H- ot current. When the BS2 is in the low-power state, a sage “Expected a Variable. I .abel, or Instruction.” fresh 9-volt alkaline could be expected to run for indicating that the constant label cannot be changed. over a year! With this ability built into the BS2,1 The “outs = Allinput” statement forces all the I/O decided to forego putting in a power switch on the pins in the BS2 to be Inputs.” and they are unable to PCB and take advantage of the low power mode that source current to or sink current from other devices. could he entered by simply executing an “end" state By doing this. I will make sure that there isn’t any

- Section Thirteen Learning to Program 235 Experiment 88 — Conditionally Executing Code statements toallowyouchangeexecutionifspeci¬ code.To avoidthisconfusion,Iprefertocharacterize is true.Theproblemwithjustshowingtheifdecision ent locationinanapplicationifaspecifiedcondition statement thatcausesexecutiontojumpadiffer¬ executing. PBAS1Chasacoupleofdifferentbuilt-in ent situationsandinputswhiletheapplicationcodeis ity, however,willnotallowyoutoresponddiffer¬ and uwillallowyoutocreaterobotapplicationsthat probably cometotheconclusionthatanapplication cation isrunningcorrectlyandthenputtheBS2into conditionally executingcodenotjustasonestate is thatyouwon’tknowhowtoarrangeyourPBASIC fied conditionsaremet.Themostbasiconeistheif repeat thesameoperationsindefinitely.Thiscapabil¬ ment inyourabilitytocreatemeaning!ulprograms, form thesametaskaswhat1havedonehere.The low powermodeusingtheendstatement. 2 36 Being ahletoloopanapplicationisahugeadvance¬ that justconsistedofanendstatementwouldper¬ send a“Goodbye”messagetoindicatethattheappli¬ tion istiue.aswellifitfalse,andthenexecution ment, butthree—showingwhatexecutesifthecondi¬ “off’ bythisapplication. shown inFigure13-18. conditionally executingcode thatstartswiththeif additional currentdrainontheRS2whenitisturned included thePBASICstatements thatmakeupthe from thetwoblocksmergingtogetherasIhave If youreadthroughtheBS?documentation,11 Once alltheI/Opinsareputintoinputmode,I On theleftofflowchart in Figure13-18,1ha\e 1E 3 Robotics Experiments for the EvilGenius Conditionally ExecutingCode Experiment 88 statement isredundant)Butit1presentedyouwith when anewapplicationisdownloaded,theBS2 read theBS2documentation,youwilldiscoverthat your ownapplications. the I/Opinsorshowyouhowtodefineconstantsfor automatically (whichmeansthe“outsAllinput' reset andalltheI/Opinsareputintoinputmode Goodbye messageiscertainlynotrequired.Ifyou cutes untilitencountersanelseorendifstatement. statement. Thefirststatementistheif-then ment, thenIwouldn’thavehadtheopportunityto an applicationthatjustconsistedolendstate¬ endif statementindicatesthattheconditionallyexc- then thecodefollowingifstatementexe¬ introduce youtothevariable-likeregisterinterfaceof false byplacingthiscodeafteranelsestatement.The true, youcanalsoexecutecodeiftheconditionis Along withexecutingthecodeitconditionis block olcodeistoexecute.Iftheconditiontrue, that teststheconditionsneededtodeterminewhich Figure 13-18Ifflowchart 2 cuting code is finished and execution should resume But I would discourage you from doing this Experiment 88 — Conditionally Executing Code whether or not the condition is true or false. because it can be difficult to read when you are first Tire else statement as part of conditionally execut starting to program. Although you will want to use ing code is optional. If you wanted to just execute this form when you become more comfortable with code if the condition is tiue, you could eliminate the programming, and it will make your programs more else statement and the statements that follow and just efficient, when you are just starting keep the state¬ key in the following: ments as simple as possible If you do this, you might want to put parentheses around the arithmetic

if Valuel Condition Value2 expression to make the statement more readable 1 Execute if Valuel Condition Value2 is true Along with the not operator, the if statement also endi f lias the “and" and “or” operators that will allow more ' Execute if regardless of being true or false complex if statements. The “and” and “or” operators work just like the digital logic “and” and “or” I dis¬ In some applications, you will see that the pro¬ cussed earlier in the book. Like the complex arith¬ grammer only wants to execute code if the condition metic statements, the conditions arc read from left to is false. The code he or she will come up with will right and code only executes when they all have been look something like this: executed. Some examples of these operators are as follows; if Valuel Condition Value2 else

Executes if test result is false if A > B and A < C then endi f ' Execute if "A" is between "B" and "C"

I would like to discourage this type of program¬ if A = CR or A = 10 then ' Execute if "A" is a line end character ming because it is confusing to read. In the table list¬ (10) or Carriage Return ing the different conditions earlier in the section. I listed the “complement” conditions to the basic six To test out the operation of the if statement, try conditions available to PBASIC. out “It Test” (that should he stored in the If Test folder In the Evil Genius folder). This application will Instead of using the complement, you can also print out the numbers from 1 to 30 that are evenly place the word “not in tront of the Valuel Condition divisible by 3: Value2 expression, but this can make the code con¬

tusing to read (although in some cases, it will make 1 If Test - Print Numbers evenly the function of the code moie obvious). Examples of divisible by 3 1 {$STAMP BS2 > the two different options are shown next '{$PBASIC 2.5}

' Declarations if A <= B then i var byte j var byte if not A > B then

i = 1 Personally, 1 will always write out my applications do while (i < 31) using the first example’s form because 1 teel that it is the clearest when 1 am reading over the source code. j = i // 3 ' Store the remainder of i/3 You may feel differently and want to use the second if j = 0 then example’s form. debug dec i, "is evenly divisible by 3", cr It is possible to put in expressions for the “values” end if such as i = i + 1

' Try the next variable if A + 4 < 37 then

loop

end

Section Thirteen Learning tc Program 237 c Experiment 89 Advanced Conditional Execution

Tool Box fm* V Assembled PCB with BS2 PC RS-232 cable 0) w

cd W in n I first wrote the experiment dealing with con¬ everything is crammed into a single line. Ideally, you c ditional execution, I was doing it with the version of should be able to explain what is happening in the o PBASIC previous to 2.5, which did not have the line with a single comment. structured features of the current version In this ver¬ • £-4 W hen I key in my programs, 1 indent each level of sion, the it statement was a lot simpler and I could -p conditional statements by two spaces (with the start¬ explain both it and another statement type in just one •H ing code two spaces in). J suggest that you follow this experiment. In this experiment, I would like to convention so you do not find your indented code & expand upon some ot the lealures of the"if-else- squeezed over the right of the program, making it endif ’ statement that w ill make it easier for you to verv difficult to read. You can nest youi if-else endit develop complex applications as well as another statements (or any other conditional or looping state u statement type that will allow you to execute multiple ments): if statements w ithout having to write them repeat¬

T) edly. i f A = " A" then a) if B = "B" then W hen 1 described the if-else-endif statement struc¬ ' Execute if variables have first two u ture in the previous experiment, I presented it in the letters of the alphabet else ' A = "A" and B <> "B" a format: 1 Execute if A has "A" but B is different (d endif else ' a <> "A" . . . > if Valuel Condition Value2 then • Execute if Valuel Condition Value2 is id True Instead of resorting to using multiple if statements else to carry out different operations depending on a sin¬ ' Execute if Value2 Condition Value2 is False gle value, you can use the select-ease statement.This endif statement will compare a single value with a case value, as I have shown in the following example: Along with this statement structure,you can com¬ a\ bine these multiple statement^ into a single line: 00 select RobotCommand case 1 If A > B then C = A else C = B 1 "if RobotCommand = 1 then" 1 Move the robot forward -P case 2 Ihis single-line format will avoid the extra lines of G ' "if RobotCommand = 2 then" the multiline format, but it will not allow you to easily ' Move the robot backwards , >. and so on) before the test value x il vou want to capture a number of values. 1 would U) pening should be easier to understand than if

238 12 3 Robotics Experiments for the Evil Csenius recommend that you do not take advantage of this feature until you are very comfortable with program¬ xperiment 90 — Using the for" Loo ming Adding the condition operators is quite dtfft cult to do because they do not allow for testing a range of values (other than from the lowest possible value to a point or fiom a point to the highest possi¬ ble value). To look at how the different if statements work I wanted to do something kind of interesting and print out a sine wave with a period of 20 and an amplitude of 7 so it can be displayed effectively on the debug terminal (Figure 13-19). ITiis application treats the Figure 13-19 BS2 sinewave debug terminal as a raster display and prints a sine wave value if its column is the same as the currently SineValue = sin SineValue printed row After keying in the application below, if SineValue > 32767 then save it av “Sinewave” in its own folder in the Evil SineValue = SineValue A $FFFF + 1 / 37 Genius folder: SineValue = 4 - SineValue else SineValue = SineValue / 37 + 4 ' Sinewave - Output a sine wave on the endif Debug Terminal select Row *{$STAMP BS2} case 4 *{$PBASIC 2.5} if (SineValue = 4) then debug "*" else debug ' Variables case else Row var byte if (SineValue = 8 - Row) then Col var byte debug "else debug " " SineValue var word endselect Col = Col + 1 ’ Initialization loop Row = 1 Row = Row + 1 debug cr do while (Row < 8) loop Col = 0 do while (Col < 40) end SineValue = Col * 14

Experiment 90 Using the "for” Loop in Your Application

fd

With what I have shown you. you now have the capa¬ able to develop a program like that. Maybe today bility to dev elop programs for just about any require¬ you wouldn't be able to develop these applications, ments that you are given. This is probably a shock to but you are further along the road to understanding you because you probably look at a favorite PC? how to program than you might think. Over lime, as application or game and think that you will never be you get more experience programming different

Section Thirteen Learning to Program 239 Experiment 90 — Using the 'for’ Loo application, andsaveit(asBubbleSort)intheFor Statement folderlocatedintheEvilGeniusfolder: Start uptheStampWindowsEditor,Interinthis sort sixrandomintegersandprintthemoutinorder. 240 123 Robotics Experiments for the Evil Genius comprehensive applications. minal displayinFigure13-20 andsortthesixnum¬ compare eachelementinthe arraywiththeonefol¬ bers in"SortArray”oneelement atatune.Itwill background necessarytodevelopverycomplexand applications, youwillgaintheskills,confidence,and lowing it.Ifthecurrentelement isgreaterthanthe Running thisapplicationwillcreatethedebugter¬ Hie firstversionoftheexperiment’ssoftwarewill debug cr debug cr Temp varbyte ArraySize con6 i =01PerformBubbleSortonNumbers SortArray(4) =65:SortArray(5)4 SortArray(2) =100:SortArray(3)2 SortArray(0) =55:SortArra(l)5 j varbyte SortArray varbyte(ArraySize) then i varbyte 1{$PBASIC 2.5} 1{$STAMP BS2} 1 BubbleSort-alistofnumbers 1 LoadInitialvaluesintotheArray 1 Variables do whileiSortArray(j+1) Temp =SortArray(j+1) SortArray(j) =Temp SortArray(j +1)=SortArray(j) The testsarerepeatedonceforeachelementinthe depends onthestepvalue.This valuedefaultstoIif cicnt methodofloopingasetnumberlimesthe array tomakesurethatevenifthelargestnumberin one thatisafterit.thenitwillswapl.heirpositions. no valueisspecified,oiitcan beanyspecifiedposi When theforstatementends, you'llfindthatthevari best waytodothisisusethefornextstatements while itislessthanthefinalvalue(whileincrement through SortArrayseveraltimes,andtodothis.Iini¬ will takelongerthanvirtuallyanyotheisorting arrays— Iwon’tgointodetailswhybecauseforsmall of sortisknownasa“bubblesort"andprobably rear ofthearrayatendprogram.Thistype the arraywasatstart,itwouldbemovedto able willbegreaterthanthe endvalue.Howmuch along withitsinitialvalueaswellendingvalue. works wellforthisapplication,iti«notthemosteffi tialize avariableandrunitthioughdo-whileloop algorithm it isfine,butifyouhavetosorlalargearraythen lists ofnumbersliketheoneusedinthisapplication, the mostinefficientsortknowntomanforlarge that laketheform. ing itinsidetheloop).Althoughdo-whileloop Figure 13-30Sortoutput In thetorstatement,countvariableisdefined In thebubblesorl.you'llseethatlhavetoread {step StepValue} ' Codetoberepeated next for variable=initialValuetoEndValue tive or negative value. You can change the variable in gram, because you could inadvertently change it. Experiment 90 — Using the for" Loop the loop, but this is not recommended. Changing the resulting in the program behaving unexpectedly. loop variable could cause execution to lease the for To show how the lor next statements can improve loop unexpectedly. For this reason, be very careful an application. Consider the Hubble Sort program about how you use the loop variable in youi pro- rewritten to For Sort. It is quite a bit shorter and. 1 think, much easier to read and follow:

• For Sort - Sort a list of numbers using for" statement *{$STAMP BS2} '{$PBASIC 2.5}

1 Variables ArraySize con 6 SortArray var byte(ArraySize) i var byte j var byte Temp var byte

1 Load initial values into the Array SortArray(0) = 55: SortArray(l) = 5: SortArray(2) = 100 SortArray(3) = 2: SortArray(4) = 65: SortArray(5) = 4

debug "Initial Number Order: " for i = 0 to ArraySize - 1 debug dec SortArray(i) if i < (ArraySize - 1} then debug ", " else debug cr next

for i = 0 to ArraySize - 2 ’ Perform Bubble Sort on Numbers for j = 0 to ArraySize - 2 * Find highest in List if SortArray(j) > SortArray(j + 1) then Temp = SortArray(j +1) ’ Swap the two values SortArray(j + 1) = SortArray(j) SortArray(j) = Temp endif next 1 Repeat through the list next * Re-Start List to find next highest

debug "Sorted Number Order: " for i = 0 to ArraySize - 1 debug dec SortArray(i) if i < (ArraySize - 1) then debug ", " else debug cr next

end

Section Thirteen Learning to Program 241 Experiment 91 — Saving Code Space stration application,Ifirstcountdownfrom5and 242 then from10: same application. features ofWindows),butitwillbeaproblemwhen from previousapplicationsusingthecutandpaste over again,Ihisissomethingthatyouwillhavetoget cover thatyouarewritingthesamethingsoverand w rittentotheDebugTerminalusingrepdebug that usesacountdowntimer.IntheTimerDemon¬ you endupputtinginthesamepiecesofcode used to(a(leastUntilyoulearnhowcopycode As youwritemoreandprograms,willdis¬ Statement formatter.Oncethisisdone,Icountdown, waiting onesecondeachloop (thepauseKMX)state¬ ment) beforesendingabackspace fbksp)character print amessagealongwithtwo carriagereturnsso right oftheline.OnceIhave erasedtheperiods,1 to theDebugTerminalerase theperiodon In thisapplication,asetnumberofperiodsare To showyouwhatImean,consideranapplication bksp\l: next bksp\l: next j varbyte from thespecifiedvalue ' Countdovmfrom5seconds ' Countdownfrom10seconds ' Mainline ' {$PBASIC2.5} 1{$STAMP BS2} 1 TimerDemonstration-Countdovm 1 Variables debug "10SecondDelayFinished",cr,cr debug ”5SecondDelayFinished",cr,cr debug rep"."\5 debug rep"."MO for j=1to10:pause1000:debugrep for j=1to5:pause1000:debugrep end 123 Robotics Experiments for the EvilGenius Saving CodeSpaceUsingSubroutines ■■■ HMMMHIHDMHi■Hi!MH Experiment 9l stand whatthecodeisdoing.Casesoccur,however, stration 2inyourTimerDemonstration folder. following applicationandsave itasTimerDemon¬ routine. once thesubroutinecode(startingat saves theaddressotstatementfollowingitso display theperiodsandthen erasethem,keyinthe take advantageofusingthesubroutinecapability Figure 13-21showshowthegosubandreturnstate¬ will allowittocontinueexecutingwhereleftoff. “label ’)hasfinishedexecuting,areturnstatement interesting towatchandtryunderstand.Whena readability ofthecode. a setnumberoftimes).Groupingseriesstate¬ function (inthiscase,backspaceoncepersecondfor a numberofstatementssothevperformsingle like thisone,whenthecolonisusedtobringtogether because itcanmakemuchmoredifficulttounder¬ to placemultiplestatementsonthesameline,Ido below themessage. the nexttextwrittentodisplaywillbetwolines PBASIC toeliminateoneof thesetsofcodeusedto ments areusedtojumpandcomebackfromasub¬ be reusedinanapplication,Thegosubstatement to defineandcallsubroutinesthatwillallowcode delay hasfinished. then erasethem,andputinamessagesayingthatthe three linesthatareusedtodisplayanumberotdots, problem occurs,Jrepeatalmostexactlythesame ments likethisintoasinglefunctioncanenhancethe not recommendthispracticeformostsituations To showhowtheTimer1)emonstrationcould The colon(:)characterusedinthecodeallowsme PBASIC, likemostlanguages,providestheability I hisapplicationworksverywellandiskindof <1 :

Using Ctrl-M to show the program data that is Section Thirteen — Learning to Program stored in the BS2's EEPROM, I can see that Timer I Demonstration 1 requires 160 bytes of EEPROM storage and Tinier Demonstration 2 requires an even smaller 100 bytes. The use of the subroutine in this application results in a more than 35 percent reduc¬ tion in program memory space required. You will find that this reduction in space is quite reasonable for applications that use subroutines over ones that don’t Along with the very tangible benefit of the amount of program memory saved by use of a sub¬ routine, you will find that the elimination of the need to repeat the same code in vour program repeatedly to be quite an important intangible benefit of using Figure 13-21 Subroutine flowchart subroutines.

' Timer Demonstration 2 - Use a Count down Subroutine '{$STAMP BS2} Far Consideration ' {$PBASIC 2.5 >

1 Variables Jf you have worked with the Parallax BS2 before, i var byte j var byte you'll know that 1 have not said anything about three of the most popular basic statements m PBASIX : 1 Mainline i = 5

' Count down from 5 Seconds goto Label gosub CountDown if Condition then Label branch value, LabelO, Label2, i = 10 Label3{, ...} ' Count down from 10 Seconds gosub CountDown Along with ignoring these statements, I seem to end have minimized the importance of Label in PBASIC

CountDown: programming and only promoted its use as an indica¬ 1 Count down subroutine tor for the start of subroutines. If you take a look debug rep "."\i ' Count down "i" seconds around the Internet (at sites such as for j = 1 to i: pause 1000: debug bksp: next www.hth.com/filelibrary/txtfiles/losa.txt) for sample debug dec i, " Second Delay Finished", RS2 applications, you may be confused at iny reti¬ cr, cr return cence to use them because alter looking at them, it ' Return to caller seems impossible to write PBASIC applications with¬ out these three statements. This program executes exactly the same wav as the previous one,but where 1 hardcoded the delays in the As I have explained programming in this section, I first version. I use the variable i (which can be called have taken advantage of the structured programming a subroutine parameter) to indicate to the subroutine features built into the latest version of the BASIC how many seconds it must delay for.The first time Stamp compiler. the CountDown subroutine label is called (using the Structured code is built from very definite blocks gosub statement), i has a value of 5 and the second of code that execute under specific conditions. This is time, it has the value of 10.This value is used to spec an important aspect of the structured programming ify how many periods are written to the Debug Ter¬ philosophy. Each block of code should perform a spe¬ minal as well as how many times the for loop cific function—ideally after each block of code, you executes to erase the different periods. should leave a line of whitespace before and after it

Section Thirteen Learning to Program 2 4 3 Section Thirteen — Learning to Program greater thanorequaltoB(A>:B).Thisiswhy encountered. Forexample,ityouwantedtoexecute gramming. Toexecuteablockofcodeconditionally sequential statementexecution,asthisisafeatureof stand andchangeistheneedforsomebodyother change. Animportantaspectofbeingeasytounder¬ goals ofstructuredprogrammingarethatitiseasyto stand andspecificfunctionsareeasytofind.Ihe write and.onceitiswritten,easytounderstandand The resultingsnippetofcodeisveryeasytounder programming. Itaddsanextralayerofcomplexityto w henyouseclistofthedifferentifstatementcondi¬ you wouldhavetoconvertthatjumpoveritifAis format: (after atest),youwouldhavetowriteitinthe not allowforwhatIcall“positive’'conditionalpro¬ most traditionalprogramminglanguages,butitdid than theoriginalauthortofixprogramatsome later date. why theyareexecuting,separatedbyablankline. gle blockofcode,includinganifstatementindicating the blockofcodeifAislessthanB(A

Loop: use of the branch statement (the need for differently

1 Code executes within the loop named labels, the unstructured appearance of the code, and so on), but the real reason why 1 don’t rec¬ goto Loop ommend it is that it is simpler to use the select-case instead of the do loop statements presented in this statement. Ihe branch statement is quite simple to section.The difficulty in coming up with different work with and can handle a v ariety of different val¬ labels probably seems lessened, and the readability ues. but this results in complex, difficult-to-read code, between the two methods is insignificant. 1 would whereas the select-case statement handles different recommend sticking with the do loop statements values as a matter of course. because their purpose is immediately clear (the state¬ W'hen I have talked about structured program¬ ments make up a loop), and you can add the condi ming, you may have noticed that I have not used any tional “while” to the “do” statement easily. graphics to explain the different concepts.This was Along with a do-while condition loop. PBASIC done to demonstrate one of the most important also has a “do loop until Condition” that I would rec¬ aspects of structured programming; when a program ommend you stay away from, because it is another is written with structured programming concepts in example of negative programming. You stay in Ihe mind, the result can be expressed quite easily vci- loop while something is not true, rather than the ballv and does not require any kind of diagrams. while condition in which the execution stays in the Nonstructured programs cannot be explained very loop while the condition is true. easily verbally, and flow charts and other visual aids are often required. While in a do loop, you can get out of it by execut¬ ing an exit statement (like “if Condition then exit”): Being able to express your structured programs verbally allows you to very simply document them. In

do fact, if you have taken care in naming your variables

* Code executes in Loop and subroutines and have explained the operation of the I/O pins using the pin declaration (explained in if Condition then exit the next section) and comments, you may not have to ’ Code executes after test document your application at all. Properly document¬

loop ing programs is difficult to do and often gets left to the end of a program (where it doesn't get done at This is similar to a goto statement such as all). Io minimize the documenting hassle, make sure that your programs are well written and follow the do structured programming philosophy that I have set Code executes in Loop out here. It’s much easier to document a well-written

if Condition then Loop_Exit and structured program than one that has gotos all over the place with labels like “loop_end_4.” Code executes after test

Section Thirteen Learning to Program 2 45 Section Fourteen Interfacing Hardware to the BRSIC Stamp 2

In the previous section I introduced you to the basics PH ASIC' provides the pin type that allows you to of programming the BS2 The information provided define a pin using the statement: so far is quite generic and can be applied to just about any programming situation. Ihese skills can be Label pin # applied to other microcontrollers, desktop computers, where “#” is the pin number (0 through 15).To define personal digital assistants, and sophisticated tools. By “ourputpin,” make the BS2's “PU" pin an output, and making this information generic, you should be able drive out a low voltage, you could use the code to read other introductions to programming and be

able to follow along and apply what is being pre outputpin pin 0 sented to the BS2. You now have a reasonably good Output outputpin ’ P0 is put into output mode grouding in programming and are ready to leain how outputpin = 0 to create robot applications using the BS2 because I ’ Set pin to "low” or zero output have not presented the hardware interfaces that A more direct way of making the P0 I/O pin a make it unique to other devices. “low" output is to use the "low" built-in function Hie BS2 that you are using is based on the statement. I find this single statement to be a lot Microchip PIC16C57 PlCnncro® microcontroller. more intuitive than the statements above—to This microcontroller contains program code that perform the same function the simple statement that decodes and executes the tokens provided b\ the follows is used: Stamp Windows Lditor software and interfaces to the

PC that downloads the application into the BS2. low outputpin Along with providing these functions, the PIC. micro ' Make P0 output, drive out "low1’ voltage microcontroller also provides the BS2's input/output Along with “low," you can use a number of other (I/O) pin hardware. built-in statements to set Ihe I/O mode of the pins as Ihe PICmicro microcontroller (MCU) I/O pins are well as the output state of the pins.These functions designed to be in either output or input mode by are listed in Table 14-2. enabling or disabling the TRI-State ( I RIS) enable reg¬ ister controlled tti state driver shown in the diagram of the pin's internal circuitry shown in Figure 14-1. W hen Parallax architected the BASIC Stamp and PBAS1C, they wanted to avoid the complexities of the PICmicro MCU I/O pins, so they specified the I/O pins to be accessible in a manner similar to that of variables. They added three labels (along with a number of sublabels) that allow software to interface directly with the BS2‘s PICmicro MC I I/O pins. These registers (and subregisters, allowing you to access smaller groups of pins) are listed in Table 14-1. Figure TM-1 I/O pm

247 Section Fourteen — Interfacing Hardware statements. IfyouhavemultipleI/Opinsthat want toaccessoryouarecheckingthestateofabit ments showedpreviously.Definingapinallowsyou write toindividualI/Opinswiilitheassignmentstate¬ 2 48 to accessthedataasifitwereavariablewhileallow¬ ing youtousethelabelasaconstantinfunction the I/Opinsquitesimpleandeliminateneedto Statement Table 14-2 Table 14-1LabelsbuiltintoPBHSICtuaccesstheRS2input/nutput(I/O)pins LI lordName toggle # reverse ft output # low # input # high # nms OUTS IKS The functionstatementslistedmakecontrolling PBRSIC I/Opinstatements voltage voltage Make I/C>pin»anoutputandtoggleitsstate Make I/Opin#anoutput Make I/Opin#aninput Make I/Opin#anoutputandsettohigh Reverse I/Opin#fromaninputtooutput Make I/Opinianoutputandsettolow rimctional Description OUTL.OUTH INI ,INH DIRL.DIRH Rytp Names Robot! csLxpe^irrents for the Fvil Genius OLID DIRD DIR VDIRRDIRC, OUTA. OUTB.OUTC, INA. INB.INC,IND Nybble Names These built-infunctionsareoneofthemajor introduce youtoanumberofthesefunctionsand pins ontheBS2canbeusedinanumberofdifferent provided withthisbook). port interfaceisalreadybuiltin(suchasthePCB municate withtheBS2insituationswhereaserial ming interface.Thiscanheaconvenientwaytocom you tocreateverycomplexapplicationseasily. strengths oftheBASICStampfamily,andtheyallow' in exactlythesamewayasvariablenames. bly expecting.Iheseventeenth(numberT6’)I/O are availabletotheBS2,youwilldiscoverthat17 how theyprovidedifferentcapabilitiestotheBS2. PBASIC functionstatements.Inthissection.Iwill register namesthatarelisted.Theseused (or groupofbits),youwillhavetousetheI/Opin that youcanuseforserialoperationsistheprogram¬ I/Os canbeusedandnotthe16thatyouareproba¬ OUIO-OOI IS IN0IN15 DIRO DIR15 Bit Names When youreadabouttheserialI/Ofunctionsthat Along withprovidingsimple,digitalI/O.theI/O pin inode(Iforoutput,0inpu Change I/O Save newoutputstatetoPOpins Read stateofinputpins Function Experiment 92 — Controlling an LED Experiment 92 Controlling an LED

Tool Rox Assembled PCB with PC breaaboard, battery RS-232 cable and B32 installed Wiring kit LED, any color

In the previous section, when I wanted to display device, I would recommend that you do not follow data from the BS2.1 used the “debug” statement. This these examples as they ate wasteful of current and do statement works quite well at this task, but it isn’t not provide any protection for the BS2/PICmicro practical in most robot applications—for example, if you had a wall-following robot and wanted to under¬ stand exactly how the program was executing, chances are you could not reasonably pass an RS-232 cable from the robot to a P(' and have the robot work correctly.The ability to output execution infor¬ mation from the BS2 to the user without using the debug” statement is an important capability for robot applications. In ibis experiment, and the others that follow. 1 will present you with different ways in which data can be output from the BS2 without requiring a direct interface to a computer. The most hasic output device for the RS2 is the light-emitting diode (LED), 1 have discussed the LED at length earlier in the book, and in this experiment it Figure 1M-2 LED output will be connected ter the BS2 and controlled to turn on and off.

ITie circuit that you will be working with consists n n n n n □ □ n □ n □ a □ n o □ □ □ of wiring an LEI> to one of the BS2 I/O pins and its □ □ ^ tlat Side ot LtD □ □ Connected to □ □ "D1C" n o □ regulated power supply output as shown in figure r 13 n □ p □ □ □ a □ o n n 14-2. Figure 14-3 shows how the LED will be wired n □ oonnn nnnnn □ □ □ □ nnonn nnonn n n □ n nnonn nnonn □ n into the P(’B"s breadboard. n o nnooD nnnnn □ n nonoo nnnnn □ n nnnno nnnnn n n I would like to point out that it you look on the o n nnnnn nnnnn n n n o onono nnnnn o o Internet, you will tind BS2 and PIC’micro microcon¬ o o nnnno nnnnn oo a n nnnan nnnnn o n troller application circuits that do not use current- o n nnonn nnnnn on n o nnnan nnnnn n n oo nnnnn nnnnn n n limiting resistors at all (in this circuit T take o □ □ □ □ □ □ □ □ □ □ □ n n n a □ □□on nnnnn n □ advantage of the built in 220 i\ resistors built onto n no o □ □ □□no n n nnnno nnnnn n o □ n □ noon □ noon n n the P( R). In these cases, the designer'' are counting o n ooono □ noon □ n o o □ on oo oonnn □ o on the PICmicro MCI J’s I/O pins only being able to o n nnonn □ □ □ □ □ o n supply a maximum of 20 mA to an external device or Figure 113 Adding a single LED to the PCB to sink a maximum of 25 mA from an external

---- Section Fuurteen Interfacing Hardware 249 microcontroller I/O pins. Eliminating the current-lim¬ LED - 0 LED On pause 250 ■ Delay 1/4 second iting resistor could result in a circuit that could burn LED = 1 ' LED off out the I/O pin, leaving you with a damaged BS2. pause 250 I,cop ' Repeat An aspect of the design that you will find surpris¬ ing is that I connected the I ,FD’s anode (positive Save this as "LED Flash 1“ in the LED Flash connection) to one of the PCB's power supply con¬ folder that you have created in the Evil Genius nections and the cathode (negative connection) to folder. Once you have done this and tested it, you can the BS2's I/O pin. This connection follows a conven¬ create the LED Flash 2 application (saving it in the tion that is commonly used for microcontrollers same folder), which uses the low and high built- m because some early chips (the Intel 8051 is a prime PHASIC function statements: example of this) could not source current: they could only sink it.To allow I.FDs to be connected directly ' LED Flash Demonstration 2 - Flash LED on P0 2x per second to the I/O pin, the anode would have to be connected ' {$ STAMP BS2}

to the power source and the cathode to the I/O pin, LED pin 15 ' Define the I/O Pin just as I have done here. ' Mainline Flashing the LED twice per second by accessing do low LED LED On the I/O pin like a variable, using assignment state¬ pause 250 Delay 1/4 second ments, could be accomplished using the application high LED LED off pause 250 code: Loop 1 Repeat

' LED Flash Demonstration 1 - Flash LED LED Flash 2 works identically to LED Flash 1 » did not need a “dirO = 1" or “output 0" statement in LED pin 15 ' Define the I/O Pin UX LED Flash 2 because the first “low 0" statement 1 Mainline places the I/O pin in output mode before driving dirl5 = 1 * P15 is an output it low. a do o r-4 >1 u Experiment 93 Cylon Eye co Tool Box as Assembled PCB with PC breadboard, battery, RS-232 cable and BS2 installed Wiring kit -p Ten-LED "Bargraph" a display 0) S •H In the previous section, when I presented how vari¬ different interfacing situations, as 1 will show in this M ables were declared, I showed how other variables experiment.

2-SO 123 Robotics Experiments for the Evil Genius Experiment 93 — Cylon Eye vour command"), but they did have a pretty cool eve. _,9-Volt * [Battery Tire robot’s eye consisted of a red light that swung back and forth, scanning the area in front of it. Although the series is largely forgotten, this scanning eye lives on as an indicator in a variety of different computer systems to output that the system is “alive Visible and functioning." 10-LED "Bargraph Die circuit consists of wiring the 10-LED bargraph Display display to the HS2 as I’ve shown in the schematic dia¬ gram (Figure 14-4). I ike the other experiments that Notch" in Corner i* '^Indicating LED Anodes use LEDs, I take advantage of the current-limiting resistors built m to the PC 13. Figure IM M Cylon eye When you are wiring in the 10-LED bargraph dis¬ play. install the LED bargraph with the anode orien¬ Take 1 second to run across 10 LEDs tation notch cut into the corner of the display on the bottom right hand corner (Figure 14-4). loop Save the code used for the experiment following in the Cylon Eye folder, located in the Evil Genius The application should be quite simple to under folder on your PC stand. When you get it running, it really is quite attractive (and could be the basis for a Christmas or

’ Cylon Eye - Scan an LED across the other holiday decoration). display '{$ STAMP BS2 > Instead of declaring the pins ESB and MSB from '{$PBASIC 2.50} the outs directory. I could have simply polled the

' Variables individual bits (that is,out0 and out9 toi LSB and Direction var byte LSB pin 0 MSB, respectively) or used mathematical values to ’ Least Significant LED bit find if the numbers were at either extreme. For exam¬ MSB pin 9 ' Most Significant LED bit ple, 1 could have w ritten Ihe first test (“if (MSB = 0) then") to ' Initialization outs = ^1111111110 ' Make all the LED pins outputs if (out9 = 01 then dirs = %1111111111 • With LED at P0 on Direction = 0 or put in the entire bit string that is expected for the ' Start Running Up bits. Another way the “it (MSB = 0) then”statement

do could be written out is

if (Direction = 0) then if (outs « %0111111111) then outs = outs <<1+1 ’ Shift the Lighted LED up if (MSB = 0) then This method of testing the data has a certain Direction = 1 appeal because the expected state of each bit is dis • Change the direction of the Movement endif played in the source code. In this application, writing else outs = outs >> 1 out each bit as you expect it to be is in character with ' Shift the Lighted LED down tile application because of the way 1 initialized the MSB = 1 ' Make sure the MSB bit is set “dirs" and “outs” registers. If (LSB = 0) then • At the bottom Direction = 0 ' Start going up It might be surprising to see that 1 used two state¬ endif ments for the shift down operation. Ihe first state¬ endif ment shifts the bits to the right (moving the lighted pause 100 LED down), and the second explicitly sets the most

Section Fourteen Interfacing Hardware 251 Experiment 94 — Hitachi 44780 LCD which areverylong,thinmoleculethatreacttoelec- applied tothemintheliquid,thesecrystalsarrange trical fields,aresuspendedinaliquid(usuallywater). is thelowpowertheyconsume. ances tocomputerdisplays.Theirprimaryattraction used invirtuallyeverythingfromwatchestoappli¬ familiar withlu/nidcrystaldisplays(I.CDs);theyare devices, butyoucanconsiderothermethodsofpass¬ So farIhaveconcentratedonusingLEDsforoutput (based ontheGreekwordnemaorstring)crystals, that thereactuallyisaliquidinanLCD.Nematic ing informationtotheuser.Iamsurethatyouaie as easytounderstandtheothertwostatements field andblocklight.Whennoelectricalis themselves sotheyareparallelwiththeelectiieal 252 can passthroughthem.LCDdisplavsoperatewith applied, thecrystalsarealignedrandomlyandlight As showtiinFigure14-5.whenanelectricalfieldis very lowcurrentdrainsbecause nocurrentisflowing timed.To make interfacingeasiertotheLCD. anum¬ ware isquitecomplexandmust beveryaccurately through iheliquid. into oneofthethreebelow: ment). Icouldhavecombinedthetwostatements significant hitofthedisplay(the“MSB=1”state¬ You willprobablybeverysurprisedtodiscover The actualinterfacetotheLCD controllerhard¬ I refrainedbecausethesestatementsdonotseem Hitachi ' ShiftdownandsettheMSB ' ShiftdownandsettheMSB ' ShiftdownandsettheMSB outs =>>2+%1000000000 outs =>>2+$200 outs =>>2+512 123 Rcbotics Expprimpnts for the EvilGenius MH780-Controlled LiquidCrystalDisplay Assembled PCBwith 10k pot 16x2 CharacterLCD breadboard, battery, and BS2installed Experiment 94 character. sor willmovetotherightpreparetornext The LCDmoduleworkslikeateletypeorsingle- lineTV display--asyouwritecharacterstoit.acur¬ and havethe14connectionholeslistedinTable14-3. chip, andcarrierareusuallyreferredtoasmodules chip thatisbondedtotheLCDcarrier.TheLCD. them ThemostpopularoftheseistheHitachi44780 ber ofdifferentinterfaceshavebeendevelopedfor would nolongerbesetafterthedataisshiftedup statements willshiftdownthevalueinoutsregis¬ who isnotfamiliarwithprogramming.Thesethree when theapplicationistobesharedwithsomebody most significantbitexplicitly. the codeisdoingasobvioustoyousetting to theshifted-downvalueisthatIdon'tbelievewhat like Ididwiththeshiftingup.adding1tobitthat ter andthensetthemostsignificantbit.Thisisjust Figure IM-5LCDoperation The problemwithadding,512,$200or%1(X)(XX)(XXX) Organization Is to NematicCrystals. Random. Light No VoltageApplied Passes Through. >V,\NV, -V|\vV1 T'iVt'iVt'iVt'i'/- 1/ \^/^/^\/ Tool Box Voltage No Plates. Metal Glass Potential Glass Wiring kit RS-232 cable PC that AttemptstoPassThrough. Voltage FieldBlockingLight 7 hemselvesParalleltothe Nematic CrystalsAlign Metal Platesandthe Voltage Appliedto Bible 14-3 Module connection pins

Pins Oescription/Funciian

1 Ground

2 Vcc

3 Contrast voltage

4 “RS"- Instruetion/register select

5 “RW — Write/read select

6 “F” clock

7-14 Data I/O pins (Do on Fin 7/D7 on Pin '4)

I typically attach a series of pins to the 14 connec¬ tor pins so that the LCD can he easily mounted on a breadboard. In some LCDs, you may discover that 1 LCD Test - Display a simple message on | an LCD module there are 16 connector holes, with t he extra 2 holes ' {$STAMP BS2} used for backlighting. Some other LCD modules •{$PBASIC 2.50} have two rows of seven or eight pins. For the ease of 1 Variables H- creating the experiments in this book and wiring i var byte Character var byte ’ Character to C+ them to the breadboard, you should just use LCD Display LCDData var outl * Define LCD Pins P modules that have a single row of pins. on BS2 O Finding an LC D module with the Hitachi 44780 LCDE pin 8 LCDRW pin 9 3* chip on it is quite easy, and most electronic stores have LCDRS pin 10 H’ a number of different ones in stock. I recommend that Initialization you buy a 10x2 display because it is very common and dirs = ^11111111111 Make Least Significant 11 Bits Output usually reasonably cheap. Looking around a surplus LCDRW = 0: LCDRS = 0: LCDE = 0 store, you should be able to find one either loose or as Initialize LCD interface 4* pause 20 part of another product tor a dollar or so. Wait for LCD to reset itself LCDData = $0C: pulsout LCDE, 300: pause 5 Wiring the LCD to the BS2 is quite straightfor¬ Initialize LCD Module 00 ward as you will see in Figure 14-6. The only unex pulsout LCDE, 300: pulsout LCDE, 300 o Force reset in LCD peeled aspect of the circuit is the potentiometer used LCDData = $1C: pulsout LCDE, 300: pause 5 to set the contrast voltage used by the LCD. Ihe volt¬ Initialize/Set 8 Bit LCDData = $08: pulsout LCDE, 300 age produced by this voltage divider is used to specify No Shifting LCDData = $80: pulsout LCDE, 300: pause 5 O the darkness of the characters on the LCD. Depend¬ Clear LCD D ing on the type of l .CD that you are using,you will LCDData = $60: pulsout LCDE, 300 Specify Cursor Move find that this voltage will either be high or low. LCDData = $70: pulsout LCDE, 300 To simplify the wiring, I have simply passed the Enable Display & Cursor data signals directly between the BS2 connector and Character = 1: i - 0 LCDRS - 1 1 Print Characters the LCD. By doing this. I have to “rotate" the data do while (Character <> 0) bits (using the “rev" operator) so the ASCII charac¬ lookup i, ["Evil Genius", 0], Character if (Character <> 0) then ters read from the “lookup" statement can be passed LCDData = Character rev 8: pulsout directly to the LCD module. LCDE, 300 i = i + 1 The application code will print out Evil Genius” endif loop on the top line of the I.( D and can be used as a basis for other applications. end

SECtinn FDUitem Interfacing Hardware 253 Experiment 95 Musical Tune Output

Tool Box Assembled PCB with PC breadboard. battery, RS-232 cable and BS2 installed Wiring kit LM38S, 6-volt LM386 audio amplifier m 8- 4-> pin "DIP" package P Two ik resistors & 0.01 uF capacitor, any type 4-5 0.1 UF capacitor, any P type O 330 UF 16-volt, elec¬ trolytic capacitor (D 10k pot Eight-ohm SPKR C O £h So far I have introduced you to three ways in which Chances are you would think that the freqout out¬ the BS2 can be used for feeding back information to put would be a square wave at the frequency speci¬ H you during its operation. I he “debug” function is use¬ fied—tins is not the case. The output consists of a cd ful for returning detailed information to either you or series of pulses that are designed to be “filtered” into o the user, but it requires a PC connection, LEDs can a smooth sine wave a< I’ve shown in Figure 14-7, be seen from a fair distance away, but do not do well which is an oscilloscope picture of the two lines din¬ ■H with providing a lot of information or variances of ing operation. In Figure 14-7, the top wave is the out¬ CO information (changing output intensity), rinally, put from the BS2 I/O pin and the lower line is the p LC Ds can display a lot of data and indicate variances, resulting sine wave. 2 but they are difficult to read from far away (it isn't The filter circuit that is used consists of the resis¬ unusual to see robot scientists crawling right behind tors and capacitors between the BS2 output pin and their robots to read LCD output information). If you the LM386 input in Figure 14-8. have an application that requires different levels of When you have built the circuit, key in the follow¬ information and the BS2 may be some distance away, UO ing application code. ON you might consider adding a speaker that can provide status information from some distance away. PHASIC provides the “freqout” function that will 4-5 drive out a musical tone from a specified pin. The for¬ c mat for the freqout function is given below. The

ft* freqout Pin, Duration, Frequency!. {, Frequency2} w Figure M-7 Freqout w0e

254 1 ? -) Robotics Experiments for the Evil Genius ' Start reading through Experiment 95 — Musical Tone Output do while (Note <> 0) 1 Loop through the tune lookup i,[G,G,hAS,hD,he, G,-1,G,G,F, hAS,G,0],Note if (Note <> 0) then -AAA-rAAA- lookup i,[1,1,1,2,4, 5,2,1,1,1, =r=0.01gF •~XvNr- _0.1|iF 2,7,0],Duration VSAttt Duration = Duration * 208 1 Start with 72 beats per minute • -AaAtt if (Note <> -1) then ~W-*r freqout SoundOut, Duration, Note JAfcr- else \A/—r- pause Duration ' -1 means space. Just Delay A/v'-rraw-*: endif AAA-fr endif i = i + 1 end Figure N-8 Note output This application plays the opening lew bars of the theme of the TV show Hawaii 5-0 and sounds surpris¬ ' Hawaii 5-0 - Play the Theme 1{$STAMP BS2} ingly good considering how simple the circuit is. In ’{$PBASIC 2.50} the Note Definition section of the application, I have ' Variables listed out the basic frequencies for the notes from A i var byte Note var word below middle C to D an octave above When 1 is Duration var word encountered, a space is pul into the tune. Ihe Dura SoundOut pin 15 tion i^ in the units of quarter notes, and 1 have multi¬ 1 Note Definition plied it by the number of msecs that a single quarter A con 880 AS con 932 note should take (playing at 72 beats per minute) to B con 988 get the actual delay tor the tune. As an exercise for C con 1046 Middle "C CS con 1108 you, you may want to trv to program a different tune D con 1174 DS con 1249 into the application To do this, you w ill have to find E con 1318 some sheet music and transpose the notes and delays F con 1396 FS con 1480 into the lookup table that I created. It's not very hard G con 1568 and actually quite fun. GS con 1662 hA con 1760 When you run the application, you will find that hAS con. 1873 hB con 1976 the ink potentiometer must be set quite low or else hC con 2094 the LM386 audio amplifier will be overloaded and hCS! con 2218 hD con 2350 nothing will be output. Even with a low potentiome¬ ter setting, you will find that the sound output is quite Application Note = 1: i = 0 loud.

Section Fourteen Interfacing Hardware 255 Experiment 96 — Electronic Dice ate somedigitaldice"usingtheBS2andLEDs you cantakeadvantageofthe“pause”functionbuilt ment taking250ps(usingParallax’sspecificationthat consider thatyoucancountoneachPBASIC'state¬ a timedloop.Ihisisnotasharditsoundsifyou space variable.Ihefunctiondoesnotprovidetiming pressed andeitherincrementsorclearstheWork explained inthePBASICReference. where thebuttonstatement'sparametersare 2 55 started byapressofbuttonrhecircuitschematicis into PBASIC. the BS2tunsat4,000statementspersecond),and tor you—youwillhavetoplacethestatementinside remember thatitexecuteseachtunethebuttonis you willdiscoverthatthebuttonfunctionisalmost you withaverysimpleframeworkfordebouncing shown inFigure14-9. useful functionsdefinedinthePBASIClanguage. ton functionisprobablyqjjcofthemostuniqueand burton input.Actually,ifyoulookatallthedifferent though itisverywellsuitedforrobotapplications. the BS2,1havediscoveredthatoneofmostuse¬ When Ihavelookedatrobotsthatarecontrolledby never used.Thisisamysterytomebecausethebut¬ plex becauseofthedesireto maketheLEDslook BS2 applicationsthatareavailableontheInternet, ful FBASICbuilt-infunctionsisneverused,even Ibis functionisthe“button”function,anditprovides The tricktothebuttonfunctionisthatyouhave Let’s haveabitoffunandforthisexperimentcre¬ The wiringfortheexperiment isabitmorecom¬ Workspace, TargetState,Address button Pin,DovmState,Delay,Rate, 1E 3Robotics Experiments fortheEvil Genius Assembled PCBwith Push button Seven LEDs,anycolor 10k resistor breadboard, battery, and BS2installed Experiment 96 Electronic Dice in aDigitalDicefoldertheFvilCieniusfolder: like dice.Thecodeshouldbesavedas“DigitalDice.” Figure 14-9Digitaldice Tool Box ButtonDownWait: Dice varbyte ButtonCount varbyte ButtonPin pin15 a pushbutton j varbyte i varbyte ' RandomizetheDiceValue ’{$PBASIC 2.50} ' DigitalDice-Createwith ' Looptakesapproximately5.5ms ' MakeP0throughP6outputs ' MakealltheLEDshigh/off ' Initialization 1 Variables '{$STAMP BS2} 1 WaitforButtontobepressed dirl =%1111111 do outs =s$ffff button ButtonPin,0,10,180, pause 4 Dice =+1 Wiring kit RS-232 cable PC Reset 9-Voft Battery ,► ButtontoStart Dice ‘Roll’ Momentary 'On'' ButtonCount, 1, ButtonDown case 4: outl = 60001000 ' Display "6" Experiment 97 — Keypad Input goto ButtonDownWait case 5: outl = 60101010 ' Display "4" 1 Debounce after 55 msecs# repeat lx sec endselect ButtonDown: next for i = 1 to 5 ' Button Pressed next for j = i to 5 loop ’ Display as running down pause i * 125 1 Increasing Delay for value displays Looking at the code. I’m sure you're thinking that Dice = Dice + 1 it s nice, but how is it useful for robotics? I find the select (Dice // 6) Display a Dice Value using "Select" button function to be very useful for implementing case 0: outl = %1110111 “whiskers" on a robot. Multiple whiskers can be Start with "l" case Is outl = %0100010 1 Display "5" polled with multiple button statements, each one with case 2: outl = %0111110 ' Display "2" its own Workspace variable. case 3: outl = 9&1100011 ' Display "3"

Experiment 97 Keypad Input

Part,; Bin Tool Box

Assembled PCB with PC breadboard, battery, RS 232 cable anc BS2 installed Wiring kit. Nine 4.7k “SIP" resistor

Keypad

In the previous experiment, I showed how individ¬ I put the word “addressed" above in quotations ual buttons are polled and debounced using the PHA¬ because how a matrix of switches (often called a SIC button function. Many applications have more switch matrix keyboard or switch matrix keypad) is than one button, and using something like the button read is different from how memory is addressed.lire function would not be very efficient both in terms of rows are normally pulled up and the columns are tied the number ol lines that have to be polled as well as how the code polls the buttons. In most applications, where multiple buttons are required, a matrix of but¬ Vdd Vdd tons is used rather than individual ones.The matrix of Pull buttons is wired togelhei as in Figure 14 10, with a set Ups of row and column connections that allow individual RowO switches to be “addressed" and polled Although using four wires to access four switches Rowl does not seem bettei than wiring individual switches, when many switches arc involved, the power of the matnx becomes obvious. For example, a 16-button matrix could be addressed using eight wires (four ColumnC) Control row and four column). If you were to find a surplus telephone keypad (don’t take apart one at home), ■ Column 1 Control you would discover that it is wired as a four-by-three matrix, with seven wires coming out. Figure 1M-10 Switch matrix operation

Section Fourteen Interfacing Hardware Experiment 97 — Keypad. Input nections comingfromakeypadanddocumentthem which avoidsthisproblem. wiring theotherside,connectionswillseemtobe the opencollectordriver. tor thisexperiment,Iusethepinsconnectedto columns toground.Intheapplicationcodecreated often arrangedwiththeShift,Ctrl,Alt,andother you areworkingwithswitchmatrixkeypads.Thefirst as amatrixtoallowthecontrollerbewiredeffi¬ pull themtogroundwhilepollingtheotherpins, treat alltheconnectionsaspotentialcolumnsand randomized. IntheexperimentcodethatIwrote. designed touseasingle-sidedPCB.andavoid keypad manufacturer:keypadsaregenerally keypad ineitherinputmodeor0outputtosimulate have showninFigure14-10)driverslorpullingthe from theletterandnumberkeys. tion thatarcwiredtodifferentrowsandcolumns keys thatcanbepressedwithothersduringanopera¬ boards. thisisnotaseriousproblembecausetheyare they havebeenpressed.Inmostkeypadsandkey¬ not pressedalsoreturn0,wronglyindicatingthat find thatalongwiththetwokeys,otherkeysare button pressed of therowandcolumnisidentifiedasclosed being pulledup),thentheswitchatintersection ciently. finsexperimentavoidsthisstepandworks (or keyboard)willnotbelaidoutinalogicalorder. is whathappensiftwokeysarcpressed—youmay ground), andthentheindividualswitchesarepolled. It anyreturna0(insteadotthe1,whichresultsfrom cacli switch.Thismethodisprobablythemosteffi through eachlineasa“columnpollingtheother transistor isturnedon(pullingthecolumntolinePackage(SIP)resistorforpullups.TheSIP cicnt wayofdecodingakeypad:onceyouhaverunit lines as“rows”andreturnsauniquehexvaluefor to groundusings\\itches,asIhaveshowninFigureTheschematicforthisexperimentisverysimple, 258 switches, thecodeandhexvalues canbeusedina and recordedthehexvalues torthedifferent “select” statementinanapplication toperforma 14 1U.Toreadacolumnofswitches,thecolumn’sasshowninFigure14-11,1usedI()-pinSingleIn- Ihe reasonforthisisexpediencyonthepartof unique buttonfunction. You mustuseopen-collector(oropendramas1 In otherbooks.Iexplainhowtodecodethecon¬ Last, youwillfindthatthewiringofkeypad You willprobablyrunintothreedifficultieswhen IE 3 Robotics Experiments for the EvilGenius pad thatIusedwasfromalocalsurplusstore,and by adot). consists ofnineresistorswithacommonpin(marked has 20buttonsand9pinstointerfaceto. unique hexvalueforeachbutton.Theindicatedkey¬ Figure 14-11Switchmatrix keypad Ihe application“SwitchMatrix"willreturna ButtonCount varbyte CurrentButton varword LastButton varword Keypad keysasHex Flag varbyte j varbyte Button PressedYet i varbyte • Mainline ' Variables • {$PBASIC2.50} ' {$STAMPBS2} ' SwitchMatrix-Return ' PreviousButton • RecordAddress ' MakeI/O"i""0"Output ' NewButtonResettheCounter ' NoteifbuttonPressed do ButtonCount =0:LastButton-11No next Flag =0 for i=0to7 next dirs -DCDi:outs=0 for j=i+1to8 endi f if (ins.lowbit(j)=0)then else CurrentButton =(j*8)+i endif ButtonCount =0 Flag =1'ButtonPressed if (LastButton=CurrentButton)then LastButton «CurrentButton: ButtonCount =+1 if (Flag = 0) then else Experiment 98 — Resistance Measurement No Button Pressed? ' Held dovm, no autorepeat ButtonCount = 0; LastButton = -1 ' No if (ButtonCount = 3) then ButtonCount

else ' Else Button Pressed = 2 if (ButtonCount = 2) then endif Button Held Dovm? endif Debug "Button = ", shex LastButton, cr loop

Experiment 98 Resistance Measurement

Parts Bin Tool Box Assembled PCR with breadboard, battery, RS-232 cable and BS2 installed Wiring kit Ten LED bargraph display

10k CDS cell (LDR)

Three 0.01 J.IF capacitor, any tyFe

330 UF, 16-volt, elec¬ trolytic capacitor

10k pot

Eight-ohm speaker

LM386, 5-volt, 8 pin DIP package

Two lk resistor

When l created the simple light-seeking robot project w ill see how the expected returned value is derived. earlier in the book. I took advantage of the variable I'm going to skip over this and go directly to the gen¬ CDS cell resistance to work with a 535 timer. CDS eral case where the count returned is defined by the cell resistances can used in the same way for the equation: “retime" function built into the BS2. Figure 14-12 show's how you can easily wire a resistor with a Count = 600.000 x R x C capacitor to the BS2 to measure its time delay. Die “R ’ is the resistance in ohms and “C” is the capac¬ following circuit can also be used for reading the itance in farads. If you were expecting to use a 10k position of a potentiometer. The recommended format for the retime (unction is the following: retime Pin, 1, Variable 4 Waveform ■ high Pin ' Set Pin State at BS2 Pin before retime iable - 600,000 x R x C retime Pin, 1, Variable

(rhe parameters are explained in the PBAS1C Reference at the end of the book.) If you read through the explanation of the retime function in the PBASIC programming manual, you Figure 1M-12 retime function

Section Fourteen Interfacing Hardware Experiment 98 — Resistance Measvirement circuit tobeusedtorthisexperimentisshowninFig¬ and Sound")islistedhere. capacitoi that1usedwas67,sothisisquiteanaccu¬ 260 application.The firstishowIconvertedthelight ure 14-13, ance (whichisdependentonthelightstrikingit) two) orderotmagnitudedisplayoftheCDSresist¬ rate approximationottheexpectedoutput. the maximumvaluewithCDScelland0.01pF from 0to60.WhenItestedmycircuit1foundthat as lightisappliedtoit.theexpectedrangeofvalues delay valuetoanorderofmagnitudefortheLED using anLTDbargraphdisplayandaspeaker.The display andthespeakeroutput Thespeakerand expected “Count'’wouldbe (dark resistance)witha0.01|iFcapacitor,the Using a10kCDScellthatdecreasesinresistance This experiment'scircuitwilloutputthe(base I wouldlikeyoutonoticetwothingsaboutthis The sourcecodeforthisexperiment(called“Light CDSValue varword Translate varword a CDScell/DisplayData + 440 Count =600,000x10k0.01|iF ' Getthehighorderbit ' ReadtheCDSCell • CDScellValueOrderofMagnitude ' CDScellValueReturned ' Variables *{$PBASIC 2.50} 1 {$STAMPBS2} 1 LightandSound-Measureresistanceof • PI5-CDSCellInput,P12Sound ' Initialize do outs =$ffff dirs =%0001001111111111 loop Translate =NCDCDSValue outs =DCDTranslate-1A$3ff retime 12,1,CDSValue high 12 freqout 15,100,(Translate*(440/7)) 123 Robotics Exce^imerts for1 the EvilGenius = 600,000x10(10')0.01(10e) = 60 This wasagoodwayformetoremembercheck statements—instead Icalculatedthevaluestobeout¬ can see/hearthemacrosstheroomwithouthavingto CDS cell? why donl.youchangeitsothatmoreIT-Dslightand strate thatyouhavefiguredouthowthecodeworks, state ofthepinbeforeoperation.Next,Igotcontused put allinasinglestatement,takingadvantageofthe LED outputsaregoodmethodstousebecauseyou the tonegoeshigherasmorelightisappliedto the “outs=”and"freqout"statements.Todemon¬ for it. to workaccordingthesoftwarethatwaswritten the battery(usingatester)ifitdoesnotseem used foroutputtingvariabledatainformation.Finally. cuit sofarmthebook,butIcansaythatitismost wiring thecircuitthisismostcomplexBS2cir¬ in. retimewillalwaysreturn“1."indicatingtheproper put inthe“high12”statementthatsetsstateof ran intothieeproblems.ThefirstwasthatIdidnot left-to-right orderotoperationintheL1S2. to writetheentireapplicationwithoutusinganyif" hover overyourrobot.Second,noticethatIwasable PCB andtheoperationofcircuitbecameerratic, I wasnotpayingattentiontothed-voltbatteryin rewarding andshowshowlightsoundcanbe the I/Opmusedforretimefunction.Ifthisisnot Figure Id-13Lightliteramin After workingthroughthisexperiment,lookat When Ibuiltthisapplicationforthefirsttime,1 •ftJy-TT -/Notch"inCorner *v ^_- VisibleLight H *IndicatingLEDAnodes 1 *VddI Display 10 LED 'Bargraph" Experiment 99 — PWM Analog Voltage Output

Experiment 99 PUUM Rnalog Voltage Output

Tool Box

PC Assembled PCB with RS-232 cable breadboard, battery, Wiring kit ariG BS2 installer

Two lCk resistors DMM

100 fl resistor

0.47 jiF ca^asitor, any tyPe

Push button

Creating true analog voltages in an all-digital device = 0.01SS seconds = 19 msecs like the HS2 is surprisingly easy. In this and the next experiment. I will show how you can create analog The resulting PWM function statement that would voltages that can be used as reference voltages for be used in the application is power supplies, LCD displays, and other circuits. PWM Pin, Duty, 19 Earlier in the book, 1 presented some discrete circuits that can produce a pulse width modulated analog To demonstrate the operation of the PWM, I have signal, and in this experiment 1 will use the built in created the application circuit (Figure 14-14) that will PBASIC PWM function to produce analog allow you to change the output voltage of the circuit voltages. by a “notch" each time you press the button and measure it using your dt^intl multimeter (DMM) PWM Pin, Duty, Cycles The application code, which 1 would like you to i he typical circuit used with the PWM function in name “PWM lest" and store in the PWM lest folder, the BS2 is the resistor/capacitor filter network pre located in the Evil Genius folder, is the following: sented in Figure 14-18 The voltage across the capaci¬ tor is the duty cycle divided by 2.85 and multiplied by ' PWM Test - Output PWM Value on Button Press the BS2’s power source (nominally 5 volts). • {$ STAMP BS2} •{$PBASIC 2.50} 't he PBASIC PWM command executes over a 1 msec period (1,000 Hz). And when it finishes, it sets ’ Variable/Pin Declarations PWMDuty var byte the pm to “input" mode to allow any resistoi/capaci- PWMOut pin 15 tor networks to stay at a constant value instead of ButtonPin pin 3 draining or being sourced by the BS2.To get a stable ' Initialization PWMDuty = 0 ' Start at 0% Duty and accurate voltage output. Parallax recommends Cycle PWM that you use the formula: do ' Loop forever debug dec PWMDuty, M/255=", DEC1 PWMDuty Charge Time = 4 x R x C / 51, debug DEC2 {{PWMDuty // 51) * 100) / 51, cr For a resistance ot 10k and a capacitance of 0.47 do while {ButtonPin = 0) ' Wait for Button High |iF. this time is as follows: PWM PWMOut, PWMDuty, 19 ' Output the PWM Value loop Charge Time = 4 x 10k x 0.4?vF do while {ButtonPin = 1) 1 Wait for Button Low = 4 x 10(103) x 0.47(10 ) seconds PWM PWMOut, PWMDuty, 19 1 Output the PWM Value

Section Fourteen Interfacing Hardware 26] ux

Veld

Figure 14-16 Three-bit R-2K DAC 5-8 out Figure 1*4-15 Three-bit R 2R DAC

Chances are that if you are like me, you would have labeled the currents through each of the resis burn through a lot of paper coining up with this tors and labeled the voltages at the two nodes that answer if you were to calculate it yourself. It’s a good have three resistors connected to them. Using the exercise to go through all eight possible outputs in electronics rules 1 presented earlier, we can use this circuit to help cement the basic principles in your Ohm’s and Kirchoft's Laws to lind the voltages at VI, mind—it is unreasonable to go through all 256 possi¬ V2. and Von t. ble outputs of the 8-bit DAC circuit in Figure 14-17 Io do this, we start by writing out everything we created for this experiment. know about the circuit. Some of the formulas 1 found * R-R2 DAC Test - Output PWM Value on useful are Button Press * {$ STAMP BS2} * {$ PBASIC 2.50} VI = 2R x i4 = Vdd - (2R x il)

ButtonPin pin 15 i.3 = (VI V2J/R

* Initialization il + i2 = i4 + 15 dirl = 9&11111111 • All 8 Low Bits Outputs outl = $ff * All High +1=0 By substituting different values in the equations, you will discover that you can rewrite the first and do 1 Loop forever outl = outl + 1 ' Increment the last equations as Output Value debug dec outl, "/255=M, DECl outl / 51,

4VI = Vdd + 2V2

6VI = 5Vdd - 5V2

By multiplying the second equation by two and replacing the value of “12V1” with three times the value of “4V1” from the first, you will discover that V2 is equal to 7/16 Vdd. When you work through the circuit, you will find that Vout is equal to (R/3R (Vcc V2)) + V2, which simplifies to 10/16 Vdd or 5/8 Vdd (which is what is listed in Table 14 4 for 8\\2 - 1. SW1 -0 and SWQ = 0). u loop e loop of the PWM DAC in the previous experiment. o When you run this experiment, you will probably u find that the actual value isn't as accurate as the Cn o r-4 a < j o 4-5 r—4

4-5

Q DC 04 I DC

o o H

4-i C 0) £ *H u

When I wrote Programming Robot Controllers, I drives is critical to the success of the robot.This does described robot sensors as having exactly the same not mean that you have to design your robot to purpose as the sensors used on the U.S.S. Enterprise include every possible sensor and make sure that it in the Star Irek TV show. Sensors should be able to can handle absolutely any contingency. As I will look at the environment and report if there is some¬ explain, this means defining what the robot is going thing within the sensor’s detection envelope. It an to do. You must select sensors and drives that will object is detected, even if it could damage the robot, allow it to navigate its environment and perform the the sensor should not do anything about tt: that is the required task under the control of the central control job of the robot's controlling software, just as it is the software. captain of the Enterprise's responsibility to do some¬ Sensors have to be designed for a dizzying array of thing about an oncoming “Bird of Prey.” different situations. In 'Iable 15-1.1 have listed just a Figure 15-1 shows a number of the different few of the different things that a robot may have to objects that a robot should be required to be aware be aware ot and the sensors used to detect them. In of. These different objects could be something that this section, I will introduce you to many of these dif¬ the robot must avoid or a place where it is supposed ferent sensors and comment on their effectiveness as to go. This is the reason why 1 want the robot’s well as situations where they will be used to best “smarts” to be in the central control code, not in the advantage. sensor routines. A sensor may detect and object, only to turn inappropriately because additional sensor data is not being included m the decision making process. Light Source Heat One important point to note in Figure 15-1 is that Source when I drew the robot, 1 included a light gray cone indicating the field of view of the sensors. This cone is trying to indicate that a given sensor cannot sense objects all the w av around the robot and that it can only sense objects a specific distance away. When you R>sc m Sensor “Field Terrain of View” are looking at different sensors, you will have to make sure you understand the field of view and the depth ot view (distance) of each sensor that you are considering. I have not yet talked much about the central con¬ trol software, but its integration with sensors and Figure 15-1 Sensor view Section Fifteen — Sensors characteristics 266 123 Robotics Experiments for the Evil Genius Parameter Sound Surface t fbjects I ight Iulile 15-1Differentrobutsensorsandtheir camera camera Skid sensors wiskers V ire Video CDS cells \ tdeo reflections ranging Sensor Microphone Radar Microphone Ultrasonic IR coming fromrobot. direction isdependentondevice. othet soundsfoundtherobot. ditficult toimplementdue collides withanobject.Canbe distance toobject. sensing. Difficulttodetermine consumption. Verywideangle sensing angleisverynarrow. of objectsinbeampath.Requires areas inenvironmentfairlyeasily. Capture sceneinfrontofrobot. implement. a robot,eachgivenitsown on surface.Skipandskidinforma¬ and quiteeasytoimplementMay with ashoutorclap.Lowcost objects tobeeasilydetected. and provideproperlightinglor around robot,Canbedifficultto relatively lowcostandpower Good detectionofobjectsat Good directionalmeasurement surface tronics ifallowedtorubalonga a potentialsourceofUSDtoelec¬ include beingeasilydamagedand Simple toimplement.Drawbacks Very difficulttoidentifyobjects, Capable ofidentifyinglight-dark Multiple CDScellsplacedabout robot's movementandposition. Allows robottobecontrolled implement hardware/software Allows forplottingofobject Provides accuracyindistanceand latge amountsotpowerandthe from therobot. their orientation,andposition robot’s environment,Rasyto tify brightanddaikpartsofthe unique pointofviewtohelpiden¬ tion issensenedwhentracking Detect ifwheelorlegisslipping have someproblemswithnoise Detects soundmadewhenrobot Comments Location animals) and identifying (including I leal humans (tdometry camera ranging GPS Compass camera L'ltrasonic Video photodiodes Pyrometer Video Infrared Radar Tilt sensors exact positionoftherobot. determined arithmetically.Fairly Stores themovementofrobot going upordownahilland implementation toensureheatis of robotfromobjectsaroundit GPS satellitescanbedifficultfor specific locationorfollowapre¬ direction formovement.Very straight andtosettheinitial determine iftobotisnotgoing very difficultdeterminingthe easy toimplement,butitcanbe so thatitscurrentpositioncanbe Return informationitrobotis quite well. arc designedforopticalinter¬ of view sensitive withaverywidefield of objectsaroundtherobotlike within abuilding. robot) towithinseveralmeters. mine position(andheadingofthe programmed route. useful forhelpingarobotfind robot. Usefulforodometryto requires achangeinpower. visible. ing heat.Infraredphotodiodes very difficulttoimplement objects aroundtherobot.Thisis ultrasonic ranging. Can beusedtoidentifypositions receiver around. ultrasonic transmitterand requires mechanismformoving Used totriangulatetheposition the receivertofindifitislocated Use C5PSconstellationtodeter¬ require achilledlens'camcra Most videocameraswilldetect people. Canbeusedtodetectfire to thefrequenciesgivenoffby rupters andmaynotbesensitive Used todefecthumans.Very Can bedifficulttoimplementand Returns currentdirectionof Difficult tosetupfordetect¬ Used tolocateandplot light inthenearinfraredMay Experiment 101 — bLiza, the Snarky Computer

Experiment 101 bLiza, the Snarky Computer

Tool Box

Assembled PCB with BS2 PC

RS-232 cable

As you start working with robot sensors, you may The formatter used for debugin is the same for¬ want to simulate the data returned from them so that matter command used for “debug” and “serout." So. you can test out the software that handles the data. to input a number from the user console into the This is actually a good idea because when you start variable “i.” the follow ing statement would be put in working with intelligent sensors, including many of the application: the different sensors listed in the introduction to this debugin dec i section, you will find that handling the data is just as difficult as wiring the sensor to the robot. When 1 f Jsing the debugin statement for entering in deci¬ introduced you to programming. I had you explicitly mal data is quite simple, and if you have worked change or hard code the new values into the applica¬ through all the progiamming experiments, I would tion's source code. Changing your source code e\ erv expect that you are able to do this quite easily by time you want to try something new is not very effi¬ yourself. Rather than go through an example that you cient and allows for the possibility that when you could create on your own quite easily, 1 wanted to change the value, you end up changing something stretch a bit and use the debugin statement as the else as well. input method for an experiment into artificial It you are working on a PC application, you might intelligence. create a data file that is read in and the data treated When I use the term , 1 am as it it came from the sensors. Tire advantage of doing mostly interested m trying to come up with a pro¬ this is that you can change the data easily without gramming algorithm that mimics simple animals affecting the application. I he problem with this (such as ants), Thflf Is contrary to what most people method is that you can't apply it to a BS2, which think of and are interested when the term comes up. doesn’t have a file system from which the data could They woold like to see a computer (or robot) behave be read. A potential solution is to use the BS2"s capa¬ exactly as if it were a human being. Otis notion of bility to store data in its program memory EEPROM what artificial intelligence is has been rooted in many using the “data” statements, but technically this people’s minds because of the English computer sci¬ involves changing the source code, which is exactly entist. Alan Turing, who suggested that a computer what we didn’t want to do. What is needed is some would be “intelligent” if a person could communicate way of passing arbitrary data to the BS2. with it as it it were another person and not be able to The PBASIC “debugin’' command tits the bill tell the difference. almost perfectly, nib command is the opposite of the One of the first experiments in developing a pro¬ “debug” command; instead of passing data from the gram that passed the Turing test was called Eliza. BS2 to you, you can pass data to the BS2 using this Eliza was developed b\ Joseph Weizenbaum at the command, which has the following format: Massachusetts Institute of technology in 1965 as a demonstration of how a computer could demonstrate debugin formatter Variable w hat appears to be artificial intelligence by looking for keywords in a statement and responding to them. Eliza was an amazing program for its time. It could

Section Fifteen Sensors 267 Experiment 101 — bLiza, the Snarky Computer implemented injustXkofmemory. What wastiulyamazingthatthisprogram generate remarkableresponsestostatementspassed this workonaBS2(whichhasonly2kofmemory) to it(viaanRS-232console)fromordinarypeople. 268 The challengeItookonwastotryandteplicate Temp varbyte RandomCount varRandomWord.LOWBYTE RandomWord varvrord k varbyte FoundFlag varbit LastCharFlag varbit i varbyte Inputstring varbyte(20)'20CharacterString or (Temp>"Z")))then j varRandomWord.HIGHBYTE ' bLiza-Tryingtoimplement"Eliza"A.I.DemonstratorinaBS2 * VariableDeclarations '{$PBASIC 2.5} 1{$STAMP BS2> ’ MainLoop * Initialization ' RandomCount=0*Randomcontinuallyupdated/noinitial do ’LoopForever debug "Hello.I’mbLiza.”,cr do while(LastCharFlag=0)'WaitforCarriageReturn LastCharFlag =0'Wanttoexecuteatleastonce i *0 Inputstring{i) =0'StartwithNullstring else 'RespondtoComment if (i=0)then'BlankString loop debugin strTemp\l'WaitforaCharactertobeinput debug "Typesomething!",cr else do while(FoundFlag=0) ' LookthroughtheDatatables endif if (Temp=cr)then i =0:k1:FoundFlag 01Searchforinputmatch 123 Robotics Experiments for1 the EvilGenius else if (Temp=bksp)and(i<>0)then LastCharFlag =1'StringEnded endif read i.Temp ' ReadtheCurrentCharacter j =0 1 KeepTrackoftheCharacters if (Temp=0)then ' IfFirstisZero,thennomatch endif else 1CanStoretheCharacter debug "",bksp'Backuponespace if (i>-18)or({Temp<>"”)and((Temp<"a")(Temp>"z")){(Temp"A") Inputstring{i) =0 i =-1'MovetheStringBack FoundFlag =1 debug bksp,strTemp\l debug bksp,11'AtendofLineorNON-Character RandomCount =+Temp if {{Temp>*="a")AND(Temp<="z"))thenTemp= Temp -"a"+"A" i =+1 InputString(i) =Temp InputString(i) =0’PutinnewStringEnd ' valuerequired gram listedhere.Irealizethattheapplicationisabit enough, Iwasquitesuccessfulwithmy“bLiza”pro¬ worthwhile. long, butseeingitworkmakestheprocessquite using thedebuganddebuginstatements.Surprisingly else do while ({Temp = Inputstring(j)) and (Inputstring(j) <> 0)) j = j + 1 i = i + 1 *TJ read i, Temp eriment 101 — bLiza, the Snarky Computer loop if (Temp - 0) then String Match FoundFlag = 1 else No Match do while (Temp <> 0) i = i + 1 read i, Temp loop i = i + 1 Point to Start of Next string k = k + 1 Indicate next string type endif endif loop On Exit, "j" points to mismatch

i = 0 ' Remove everything in Inputstring do while (Inputstring(j) <> 0) ' before "j" Inputstring(i) = Inputstring{j) i = i+ l:j = j+ l After copying byte, point to loop the next one Inputstring(i) - 0 Put in Null at end of new string

RANDOM RandomWord Get Random Response Value i - {RandomWord / 8) & 3 if (i = 0) then i » 3 Result 1, 2 or 3

if (k = 1) then j = 11 Only one response to being hated else j =: ( (k - 2) * 3) + i endif

Produce Response to Input if (j <= 9) then select(j) Responses to "I AM ..." case debug Do you like being str Inputstring, case debug And you're happy?" case debug That explains your friends.’ Responses to "I HAVE A case 4 debug "Do you like it?" case 5 debug "Knowing you, it's cheap." case 6 debug "Bite me ", str Inputstring, -boy." Responses to "I WANT ..." case 7 debug "All the young dudes want a str Inputstring, case 8 debug "Well, if you want it.. case 9 debug "Ask the police." endselect else if (j <= 18 then select(j) Responses to "I HATE case 10 debug "That's too bad." case 11 debug "Should I be scared?" case 12 debug "Are you a psycho?" Responses to "MY case 13 debug " Honest?" case 14 debug "You must be proud." case 15 debug "No way, Jose!" Response to "BECAUSE case 16: debug "Wrong." case 17: debug "Sure...I believe you. case 18: debug "That's dumb." endselect else select(j) Responses to "I Like ..." case 19 debug "You should stay off the Internet." case 20 debug "Good for you!" case 21 debug "Don't tell anybody."

Section Fifteen Sensors 269 Experiment 101 — bLiza, the Snarky Computer code. WhenyourunbLiza,notethatthetextbeing This codecomparesthestatementstokeysand stored intheEEPROMusingdatastatements. easier comparisonsinthesecondshadedblockof space keyispressed.Ascharactersareaddedto in themainwindowofDebugTerminal. input (onthetopbar)isdisplayedasuppercase verted touppercasecharacters.Thisisdoneallow String'’ arrayandtakingthemawaywhentheback¬ come in.addingcharactersandblankstothe“Input- character isreceived.Asitwaitingfortheenter stops ifthereisamatch.WhenIworkwithtext ing theinputstringtoeachof10setskeys key. itparsesalltheotherASCIIcharactersthat backspace, blank,oralphabeticcharacter.Thiscode data, andthenchecktoseeifitisacarriagereturn, data entrycodeinwhichIwaitfortheusertoenter 270 strings. 1alwaysendthemwith aNull("0”)character InputString, youshouldnoticethattheyatecon¬ loops untilacarriagereturn(EnterkeyonvourPC) compares eachcharacterin InputString tothecur¬ to indicatewhentheyend.The stringcomparecode I wouldliketobringyourattention.Thefirstisthe returns thenumberofdata statement rent datavalue,anditthetwo stringsmatch,it In thesecondshadedblockofcode,Iamcompar¬ In thesourcecode,Ihaveshadedthreeareasthat RT03 RT07 RTEnd RT10 RT0 6 RT04 RT02 RTCiy RT0 5 PTC 3 RTC 1 loop Potential Startstoanswers(conversationkeys) Responses toanythingel Responses to"WHY[...]" Responses to"ITIS..." endif 123 Kobotics Experiments for the EvilGenius data data data data data data data data data data debug cr endif data endif endselect "I LIKE", "BECAUSE ", "MY ",0 "WHY ",0 "IT IS",0 "I HATE", "I WANT", "I HAVEA" "I AM",0 "I HATEYOU 0 case 30:debug case 29:debug case 28:debug case 25:debug case 24:debug case 23:debug case 22:debug case 26:debug case 27:debug c 0 Cl , 0 " ,0 0 se "Tell memore." "I'm impressed...NOT!" "Are yougainingweight?" "Nobody knowswhy." "That's life." "Live withit." "You believethat?" "Check yourfacts." "That andfourdollarswillbuyacupofdouble-latte." ever havetochangecharacters toallupperor lowercase. want tokeepinthebackof yourmindincaseyou then subtracttheASCIIvalue for“a”andthenadd characters. Changingcharactersfromlowercaseto the ASCIIvaluefor“A.”This isatrickyoumight character isintherangeof“a”to“z”andifitis.I uppercase isquitesimple.Ifirstchecktoseeitthe• ability ofenteringinnumerics(0through9)orother them asabaseforyourowncode.Forexample,inthe developing yourowntextinputprogramsusingthe object canbeeasilyaccessed. first shadedblockofcode,youmaywanttoaddthe RS2, youshouldremembertheseroutinesanduse normally builtintoprogramminglibraries.Ifyouare because someresponsesusetheobjectofsen¬ is thethirdshadedpartofprogram).Ididthis after thematchingparttofrontofsiring(this stop. Thetraditionaltermforthistypeofstringis tence andbyremovingthenounverb, ferent programminglanguages. ters terminatedbyazero,anditisusedinmanydif¬ ASCIIZ, meaningthatitisastringofASCIIcharac¬ ters isusedbyPBASICasanindicatorforwhento These threeshadedareasconsistofcodethatis The Nullcharacterattheendofastringcharac¬ After comparingthestrings.Imoveeverything experiment 102 — Multiple 7-Segment. Displays Experiment 102 Multiple Seven-segment Displays

Assembled PCB with breadboard and BS2

Two dual seven-segment, common cathode dis¬ plays

Four ZTXS49 NPN transis¬ tors llie previous section devoted to interfacing different device control is properly timing the motors PWM. hardware devices to the RS? probably seems to be This can be performed by specialized hardware or, more appropriate for this experiment, but I wanted with a bit of thought beforehand, by using the robot’s to introduce you to how advanced robot program¬ controller. Using the robot's controller is preferable ming is done. Advanced robot programming consists because it will minimize the cost and complexity of of applications that incorporate motor control, sensor the overall robot. 1 choose to use four seven-segment interfacing, output operation, and task programming. displays to demonstrate how the robot code is archie- Creating applications for each of these interfaces is tected, because if there are problems with it. they will quite easy- putting them together is quite hard. be quite literally visible. Ihe most traditional way of Implementing a multiple seven segment display implementing an application that displays data on requires very similar skills to that of developing a multiple seven-segment displays is to cycle through robot application.Tire code for Creating the data each of the displays very quickly, flashing the data on must be integrated with formatting the data, as well each display faster than the hitman eye can perceive as driving rt to the displays.This corresponds to the (Figure 15-3). tasks in a robot of polling the sensor hardware, inter¬ As a rule of thumb, each display should be active preting the data, coming up with a response to the 50 or more times per second. The slower each display input, and, finally, controlling the motors. Ihese oper¬ is flashed on and off, the more likely the human eye ations can be drawn out as in the flowchart shown in will pick up the flashing. A flashing multicharacter Figure 15-2. display is not attractive and could cause headache* in Quite a bit of care must be taken into account to some people (especially if the displays are very make sure that these functions work together In the bright). Ihe time each display is turned on must be as case of controlling DC motors, part of the output

First Digit Displayed Second D git Displayed

Fourth Digit Displayed Third Digit Displayed

Figure 15-? Robot code flow Figurp IB-3 Multiple LED operation

bectiun Fifteen Sensors 271 Experiment 102 — Multiple 7-Segment Displays create yourapplication,youwillfindthatitisnotas 200 timespersecond,andyouwillhaveatotalappli¬ seven-segment displaysdigits.Iusedtwodualcom- difficult asitmayseemwhenyoufirstthinkaboutit. and outputit.Ifyouplanforthistimingwhen cation executiontimeof5msecsinwhichyouwill 50 timespersecondmultipliedbythenumberofdis¬ meet the50-times-persecond-guideline,youareactu play. Whenworkingwithmultipledisplays,inorderto which cannotbeaseasilyobservedtheI.F.Ddis¬ ally goingtohaveloopthroughyourdisplaycode to theperiodanddutycycleofamotor'sPWM, and durationofadisplaybeingactivearcanalogous period ottimewillappeardimmer.Hiefrequency brighter, andconversely,adisplayactiveforshorter period ottunethantheothers,thenitwillappear 272 have lopollyoursensors,respondtothesensordata, plays. So,forafour-digitdisplay,youwillhavetoloop equal aspossible.Itonedisplayisontoralonger For thisexperiment,youwillhavetowireinfour LEDDir varDIRS.NIBO LEDCtrl varOUTS.NIBO DispDir varDIRS.HIGHBYTE DispOut varOUTS.HXGHBYTE Dlay varword Display varbyte(4) CurLED varbyte Counter varword • {$STAl-IPBS2} ' CounterDisplay-secondsonFour7SegmentLEDDisplays 1 {$PBASIC2.5} do CurLED =0:Counter0 DispDir =%01111111:DispOut0 LEDDir =%11:LEDCtrl0 for Dlay=0to3:Display{Dlay) loop 'Repeatforever Variables andI/OPortPmDeclarations CurLED =(CurLED+1)//4:LEDCtrl0'Roll to NextDisplay endif Dlay =+1 lookup Display(CurLED),[$7F,$06,$5B,$4F,$66, $6D,$7D,$07, lookup CurLED,[%0001,%0010,%0100,%1000],LEDCtrl if (Dlay>=235)then Display(1) =(Counter/10) Display(2) =(Counter/100) Display(3) =(Counter/1000 Dlay =0:Counter 123 Robotics Experiments for the EvilGenius $7F, $6F,$00],DispOut*SetupCharacterOutput ) //10 = 0:next / 10:Display(O)=Counter//10 // 10 ' DisplayPinsO/P ' Finishedupdatingseconds ' OneSecondPassed? 1 DisplaysIncrementing(4.25ms) 1 LooptoDisplayNumberonLED 1 TransistorPinsO/P&Off 1 Initialization 1 FourTransistorControlBits 1 OutputBitsforLEDDisplays 1 DelayCount 1 DisplayVariable ! CurrentlyDisplayedLED ! Secondcounter 1 'ResetDlayandIncTime “Counter Display”application Figure 15-4.Totesttheapplication,1created plays wereconnectedtothePCB'sRS2asshownin (with adecimalpoint)or16-pinpackages.Thesedis mon cathodedisplays,whichareavailablein18- Figure 15-MMultipleLEDcircuit ~A^V^~rrr ; Battery —n- LED Segment segment wiredto Connections (each display the others Rightmost Display Leftmost Du,lay V _~ent^g *SSDlJk ' 5 Vent Segment 'G Segment 'A' > i•;moot"B" ment^ Common Cathode Connections Each do loop iteration will execute between 2.75 out incrementing “Count." By repeating the code in and 4.25 ms, which meets the 5 ms requirement for the else, you will have more constant timing that is X four seven-segment displays and the “Dlay” count ol important for an application such as a motor PWM. 235 was found using the worst case (4.25 ms) do-loop Finally, if you want to display leading blanks, then timing. I found that with a Dlay count of 235. the you would have to change the "Display” variable counter incremented significantly faster than once update code to the following: per second, and sometimes a character would appear N- to flash to counter these problems. You may want to if (Count > 100) then Display(2) = (Count / 100) // 10 else Display(2) = 0 3 repeat the code after the if as an else condition with¬ rc P ct

.fc Experiment 103 o RCtime Light Sensor

Tool Box Assembt ed PCB with BS2 PC

Two 10k CDS cfills RS 232 cable

Two 0.C1 jjlF capacitors, any type O Two dual sever.-segment rt LED displays H* Four ZTX649 NPN transistors 3

Section Fifteen Sensors 273 Experiment 103 — RCtime Light Sensor I 274 circuit usedinthepreviousexperiment(Figure15-6). When thisisdone,enterinthefollowing“RCtime |iF; capacitorstothefoursevensegmentLEDdisplay Figure 15-5RCtimewiring State LEDDir LEDCtrl DispDir DispOut CurLED Dlay Dsplay LLDRVal RLDRVal LeftLDR RightLDR ' VariablesandI/OPortPinDeclarations 1 {$PBASIC2.5} 1 {$STAMPBS2} 1 RCtimeDisplay do DispDir CurLED = LEDDir = for Dlay=0to3:Dsplay(Dlay) State = ilect (state) case 11: case 10: case 4: 123 Roootics Experiments for the EvilGenius case 12: case 3; case 13: case 2: case 1: case 0: State high LeftLDR high RightLDR State retime Dsplay(0) =RLDRVal State State State retime if (RLDRVal<=9)then State retime Pin,0,Variable = *01111111:DispOut0' 0 %11: LEDCtrl=0 0: = 13 = 11 = 10 = 4 = 3 var byte' var OUTS.NIBO var DIRS.HIGHBYTE = 1 var DIRS.NIB0 var OUTS.HIGHBYTE' var byte• var byte(4) var byte var word var word pin 5 pin 4 Lef tLDR,1, RightLDR, 1, State =2 State =12 Display thevaluesfromLDRs Vdd LLDRVal RLDRVal Value =600xR(ink)CF) // ' ' ' ' ' ' ' ' ' Dsplay(1)=10 10 State 13 12 11 10 4 2 3 0 1 10: next Loop toDisplayNumberonLED Display PinsO/P Transistor PinsO/P&Off Output BitsforLEDDisplays Currently DisplayedLED Start fromBeginning Four TransistorControlBits Initialization Read StateVariable Delay Count Display Variable Saved LDRValues Read Read Read Read Major Read Read Read Read Read Left : Left : Left Left Right else Right Right Right Right ment Display"intheEvilGeniusfolder. folder ortheoneyoucreatedfor“Seven-Seg¬ Display"'application andputiteitherintoitsown LDR LDR LDR LDR D&p 1ay(1)=RLDRVal/10 All Blank LDR LDR LDR LDR LDR Format MSChar Cap Charge Read CapCharge Start Read Format LSChar Cap Charge Minor Format MSChar Read CapCharge Start Read retime Pin,1,Variable Experiment 104 — Differential Light Sensors LED Segment Connections (each display segment wired to Common Cathode Connections

16 x 220 Ohm Rightmost Display

Figure 15 6 LDR light sensor circuit

if (LLDRVal <= 9) then Dsplay(3)=10 else Dsplay(3)=LLDRVal/10 State = 14 case 14: '14 Read Left LDR Format LS Char Dsplay(2) = LLDRVal //10 State = 0 ' Start Over again... endselect

CurLED = (CurLED + 1) // 4: LEDCtrl = 0 ' Roll to Next Display lookup Dsplay(CurLED), [$3F, $06, $5B, $4F, $66, $6D, $7D, $07, $7F, $6F, $00], DispOut ' Setup Character Output lookup CurLED, [S&0001, %0010, %0100, %1000], LEDCtrl loop ' Repeat forever

Experiment 104 Differential Light Sensors

Tool Box

Assembled PCB with Wiring kit breadboard and BS2 DMM LM339 quad comparator

Two 10k CDS cells

Three 10k resistors

0.01 |rF capacitor. any tyre

The PBAS'IC RCtime statement allows you to very RC time will not be built into the chip ot the code simply and quantitatively measure the light falling on development tools (the compiler and assembler that a CDS cell. I Jnfortunately, when you are using many you are using). If you are programming your robot in other microcontrollers, a function or statement like assembler, then you could probably develop the code

Section Fifteen Sensors 275 Experiment 104 — Differential Light Sensors your resultswillmatchtheinFigure15-7- cell voltagedivider,youcouldwireupthiscircuit whether ornotoneCDScelltheotherisexposed voltage, acomparatorwilltellyouverysimply age divider,butyoucaneasilycompareitagainsta measure thevoltagecomingfromCDScellvolt¬ “left' and‘right''alongwithhowtheyarewiredso quickly andlookatthevoltageoutputwhenyouput cell, youwillfindthatthevoltageacrossother voltage divider(Iassumed“Vdd’'forthisexample). connection betweenthetwoCDScells,youcantell to morelight. known value.Bysettingupanotherfixedvalueresis¬ tor, oravoltagedivideitoprovidenominalhalf- recommend thatyoufollowtheconventionsfor you aregoingtoperformtinssimpleexpetimenl.I your handoveroneCDScellandthentheotherIf about it.Totestouttheoperationoftwo-CDS- that willnotseemtomakesensewhenyoufirstthink CDS cellwillbegreater,resultinginavoltageoutput on thetwoCDScellsofvoltagedivider,volt¬ Figure 15-7,whenanequalamountotlightisfalling which oneisgettingthemostlight.AsIshowin exposed tothebrightestlightiswirethemtogether simple wayoffindingoutwhichlightsensorisbeing 276 age outputwillbeone-halfthevoltageappliedto as avoltagedivider.Bymeasuringtheat may heoutsideyourabilitytoprogramefficiently.A are newtoassemblerprogrammingforthischip.it Figure 15-7 Differential lightsensoroperation that providesthesamefunctionasRCtime.hutifyou Using theBS2,youdonothaveabilityto In thiscircuit,whenmorelighttailsononeCDS 123 RoDGtics Experiments for the EvilGenius is equal.Voltage Light fallingon two CDScells out is1/2Vdd Equal LightLeftMore Vdd 1/2 Vdd More lightfallingonleft tesistance toavalue that islessthanthe CDS celllowersits right. CDScell Vdd -< Vdd CDS Right CDS haslowered resistance Left ■were usedinarobot,youmightfindthattherobot divider asshowninFigure15-8.Whenihiscircuitis divider, thecircuitwillbehaveasiflightinputis divider outputisequaltothefixedresistorvoltage side thepossibleerrorvoltagecausedbyresistor consideration becauseyouwillfindthatwhenthe can resultinavoltagethatisquitebitofffromthe modified fixedresistorvoltagedivider.Ifyoupro- clear differencebetweenleftandright.Whenthe go forward.The1/1*0Rresistorprovidesagap You couldfixthisproblembyaddingasecondcom¬ turned inonedirectionmorethanyouwouldlike. tolerance. most resistorshavingatoleranceof5percent,which two equalvalueresistors.Thisrationalisbasedon you donotneedtoaddtheextracomparatorand manded toturntowardthelight. in thecaseofalight-seekingrobot,itcanbecom¬ output ofonethecomparatorstochange1,and light levelononeCDScellchanges,itwillcausethe between thevoltageforsituationswherethereisa CDS cellsisapproximatelyequalanditshouldjust from bothcomparators,thenthelightfallingon parator andmodifyingthefixedresistorvoltage brighter ononesidethantheother,llthiscircuit the voltagedivideroutputwillbeconsiderablyout¬ light inputtotheCDScellsisevenslightlvdifferent, ideal one-halfoftheinputvoltage.Thisisnotamajor used inanapplication,ifthemicrocontrollerreads0 The secondpointisthatiftheCDScellvoltage You mightwanttouseapotentiometerinsteadof In practicalrobotapplications,youwillfindthat More lightfallingonright resistance toavalue that islessthanthe CDS celllowersits left CDScell Right MoreLight Vdd CDS resistance CDS haslowered Left Right > Vdd Experiment 104 — Differential Light Sensors gram the robot to move forward while it is turning When light on both CDS cells is equal, then output from Iwo (which, in the case of a two-wheel differentially driven robot, is best accomplished by “pulsing” one wheel forward while the other is stationary), then you will not have any problem with the robot turning away from the light. One problem with comparing light levels using a two CDS cell voltage divider as I have shown here is that this circuit cannot detect the case when it is in a completely dark room, which is a leature you get for “free” with the RCtime light-measuring circuits. Figure 15-8 Fixed differential light sensor To demonstrate the operation ot the two-CDS-cell differential light-sensor circuit, you can wire it to a BS2 according to the circuit show n in Figure 15-9. For powvr to it (including a decoupling capacitor). The this circuit, I use the regulated 5 volts provided by the LM339 has open collector outputs, which is why 1 BS2 for the voltage dividers and the comparator ( the added the 10k pull-up resistor on its output.The LM339 chip). I am only using one of the four com¬ application code will indicate when the light input parators in the LM339, but 1 still have to provide level shifts from one C IDS cell to the other.

• Differential Light Sensors - Indicate which CDS Cell is Getting Most Light *{$STAMP BS2} 1{$PBASIC 2.50}

' Variables CDSCells pin 15 * CDS Input Cells LeftMsgFlag var bit 1 Message Out Indicator Bits RightMsgFlag var bit

1 Initialization/Mainline input CDSCells LeftMsgFlag = 0: RightMsgFlag = 0 do 1 Repeat forever if (CDSCells = 0) then 1 Brightest to Left if (LeftMsgFlag = 0) then

-AAA-r-

-\AA-16 x ??0 Ohm

Figure 15-9 Differential light circuit

Section Fifteen Sensors 2 77 debug "Brighter Light to the Left", cr endif LeftMsgFlag = Is RightMsgFlag = 0 else ' Brightest to Right if (RightMsgFlag = 0) then debug "Brighter Light to the Right", cr endif LeftMsgFlag = 0: RightMsgFlag = 1 endif loop ' Loop forever, end of application

Experiment 105 Sound Control

Tool Box r-j Assembled FC.B with breadboard and BS2

o LM32 4 quad op-amp

u 74LS74 dual D flip flop'

4-3 Electret microphone G Four 2.3M resistors O 10k resistor CJ Two 470 11 resistors Two 220 11 resistors "G Six 0.1 |j.F capacitors, any type G Chances are, when you first saw the title for this the D flip flop’s clock.The clock changes the state of 2 experiment, you thought that it would involve being the flip tlop. and it can be polled at any time by the O able to command the robot using sound (and ideally BS2. m your voice). You may have thought that I was going A* the RS2 cannot continuously pOl the output of to give you the secret to voice recognition and allow the op-amps. I have passed its output to a I) flip youi robot to respond as if it weie a dog. Unfortu¬ Hop’s clock, which will change the output state ot Hie nately, this is not the case, but in this experiment I flip flop from “0” (which is loaded into the 74LS74 by in will show you how to create an application that the BS2) to“l.” By doing this, the BS2 just has to poll o responds to loud sound input quite effectively, which the output of the D flip flop periodically to see if will allow you to at least shout at the robot to stop it there have been any loud sounds passed to the circuit r-f before it rolls into Aunt Martha. that the BS2 must respond to. Alter noting the sound The circuit shown in Figure 15-10 filters out high by the change in the Hip flop, the RS2 can reset the 4-3 frequencies i the ones most likely to be found in a flip flop and wait lot the next sound to be received. G robot), leaung the low-frequency sounds that are Ihe w iring is a bit challenging because of all the

278 12 3 Robotics Experiments for the Evil Genius Experiment 105 — Sound. Control

' Initialization/Mainline high ResetPin input Soundlnput Gain = 1 = R2/R1 do pulsout ResetPin, 10 1 Reset the '74 Here “R2" is the 2.3M resistor and “Rl" is the 220 pause 1000 11 resistor. Using these values, you will get a gain of if (Soundlnput = 1} then • Poll Sound Input Pin about 10,000 times. By changing the value of “R2” debug "Keep it Quiet - that was TOO (the 2.3M resistor), you can change the gain of the LOUD!", cr endif amplifier, making the entire circuit less sensitive to loop surrounding noise.

'Iliis application should be very straightforward As well as using a microphone to pick up loud for you to build and should not present any surprises, sounds, such as you shouting “Stop” when the robot except if a radically different microphone than the one 1 had is used. You may tind ‘.hat you have to experiment with the 10k microphone pull up in the circuit until the input to the circuit is in the 50 to 100 mV range show n in Figure 15-11. Depending on the microphone used, you may find that the circuit is more sensitive than you would like. The first op-amp circuit is a double-pole Butterworth low pass with a gain of approximately 1 and a cutoff point around 340 Hz. Ihis circuit will very effectively filter out all higher-frequency components of sound, just resulting in a square wave of approxi¬ mately a 3 ms period, 1 find that this circuit works quite well, and there is very little reason to modify it. Figure IE-11 Sound operation

Section Fifteen Seoscrs 279 Experiment 106 — Robot 'Whiskers don tliketoimplementwhiskersfortworeasons.The an importantsourceofsensoryinputthroughoutthe where itseyesopened.Actually,acat'swhiskersare simple tobuildintotherobot object. Youmaywanttoaddwhiskersyourrobot stop orturnawayandnotriskcollidingwithlhe Secondly. 1wouldliketodetectobjectsseveralinches animal's life.Thewhiskershelpprotectthecatfrom pletely redundantwhenthecatmaturedtopoint as theyareveryeasytounderstandandrelatively (10 cm)ormoretromtherobottoallow first isthattheyaredifficulttoimplementpractically. physical objectsensorstothedesignofrobot.1 when thereisnolight).Theyalsohelpdirectthecats obstacles whenitisinacompletelydarkenviron¬ you’ll seethat1veryrarelyadd'whiskers’'orother tering thatIuseminimizesthepickupofambient through therobot—Ibelievehighfrequencylil because ofmotor,gear,andwheelnoiseconducted although othershavefoundtheoppositetobetrue to beareliablemethodotdetectingcollisions, 28 0 light conditions,buttheyarejustasblindwe ment (catscanseebetterthanhumansinverylow If youhavelookedatmydesignsfoimobilerobots, to bumpersorthechassisofrobot.I'vefoundthis mouth towardsitsprey.Havingthreelimesthediam¬ the robotcollideswithanotherobjectbymountingit deeper, acat'swhiskersare also verysensitivetosub- eter ofregularhairandsetinto theskinmuch is abouttohitanobject,itcanbeuseddetectwhen audible soundsandvibrations. I usedtothinkthatacat’swhiskerswerecom 1E 3 Robotics Experiments for the EvilGenius Assemble^ PCRwith Two 10kresistors Two microswitcheswith breadboard andBS2 long actuatorarms Experiment 106 Robot "UUhiskers wall sensoi.makesurethatthewhiskerisconnected allowing ittofinditswayoutWhenimplementinga design ofyourrobot. phone tothechassis,simplifyingmechanical perimeter oftherobot,youcouldattachamicro¬ noise. Usingthiscircuitfordetectingobjectcollisions ing upontherobotasyourunit.Finally,whiskers face. Youdonotwantastaticelectricalchargebuild¬ to groundandispassedtheoperatingsur¬ also heusedtodetectawallbesidetherobot,which turn orbackawayfromtheobject.Awhiskercan mary usesinrobots.Whenanobjectfrontofthe is somethingtothinkaboutifyouhavearobotthat running acrossthefloorcanbeusedtodetect allows ittokeepone“hand”onthesideofamaze, robot’s motorstostoporitinitiatesasequence robot isdetected,itresultsinacommandtothe Rather thanputtingobjectsensorsaroundthe may collidewhenturningorrunninginreverse. Figure 15-13Whiskertypes Tool Box Collision-Detection As IshowmFigure15-12,whiskershavethreepri¬ Traditional Object- Whiskers Basic Wall-FollowingSurfaceSensor lo SenseWall WhiskerUsed Beside Robot Wiring kit Twenty-four-gauge solid Solder Soldering iron core wire(red) Robot IsRunningOn lo SenseChanges in theSurface Whiskers Used Experiment 106 — Robot Whiskers' rougher surfaces or changes in the running surface A few practical issues must be considered when (from a smooth floor to a raised carpet). adding whiskers to your robot. Many people use a Whiskers can he implemented in a number of dif¬ fairly small diameter wire, such as a guitar string or ferent ways; you’ll see ones that look like large loops, piano w ire These small diameter wires produce a others like a cockroach’s antennae, and ones that act whisker that is quite sensitive and potentially very like skids to help balance the robot. Whiskers change easily deformed The ease with which the w hisker can an electrical signal when they are m contact with an be deformed can be a major headache and will object (Figure 15-13). A pulled-up circuit that the require you to check them before running the robot. whisker pulls down when it makes contact is the most Instead of a wire, 1 usually use a “microswitch” with basic method of interfacing the whisker with the an actuating arm (Figure 15-14), which cannot be eas¬ robot (the left drawing of Figure 15-L3). This signal ily deformed needs to be dcbounced just as it it were a momentary lo demonstrate the operation of whiskers in a on push button. The amount of force on a whisker BS2-based robot, I want you to wire two micro- can be measured using multiple contacts,each one switches as show n in Figure 15-15. When you have closed with a varying amount of force, or by connect the circuit built, then you can key the following code. ing the whisker to the wiper of a potentiometer. Hi is code uses the “Button" PB ASIC statement to

Simple On/Otf Multiple Step Potentiometer Based

Collision Force Collision Force

MCU MCU Grounded WhisKer Grounded Whisker Whisker is Connected Pulls MCU Pm to Pulls One or More Mechanically to Ground when MCU Pins to Potentiometer Ground Depending Pushed Against Wiper Wired as a Pulled up Pin on Force Applied to Voltage Divider, and During Collision Whisker During Electrically Connected Collision to MCU Analog to Digital Converter

Figure 15-13 W hisker implementation

Momentary ‘On’ Microswitch Used r as Left 'Whisker" t Momentary J*On‘ Microswilch .►Used as Right -Whisker"

-tyyy-rrAyy-

-yyy-r-

Figure 1B-IM A 'mail microswitch with a built in ticiuaior arm is ideal for toe as a robot's whisker. Flgurp 15-15 Whisker circuit

Section Fifteen Sensors 281 v Experiment 106 — Robot 'Whiskers ing afalsecollision.Thecodeappearstobesome¬ homemade whiskerwillperiodicallybounce,return¬ tant becauseyoumayfindthatasyourrobottuns,a debounce thetwowhiskers’signals,whichisimpor¬ 282 RightCount RightWhisker LeftButtonDownSkip: LeftCount RightFlag LeftFlag RightButtonDownSkip: RightButtonDown: LeftButtonDown: Leftwhisker ' {$PBASIC2.50} '{$STAMP BS2} ' WhiskerSensors-MonitortwoWhiskersonfrontofRobot do 'Repeatforever LeftFlag =0:RightFlag01ClearFlags/NoHits loop 'Loopforever,endofapplication Variables Initialization else 'WhenwhiskerReleased,Reset else 'WhenWhiskerReleased,Reset endif endif if (Leftwhisker=0)and{LeftFlagthen'WaitforLeft if (RightWhisker=0)and(RightFlagthen'WaitforRight RightCount =0'ResettheLeftWhiskerCount button RightWhisker,0,10,180,RightCount,1,RightButtonDown LeftFlag =1:debug"Ouch,collisiononLeftSide",cr goto LeftButtonDownSkip button Leftwhisker,0,10,180,LeftCount,1,LeftButtonDown RightFlag =1:debug"Ouch,collisiononRightSide",cr goto RightButtonDownSkip LeftCount =0'ResettheLeftWhiskerCount if (Leftwhisker=1)thenLeftflag0 if (RightWhisker=1)thenRightflag0 12 3 Robotics Experiments for the EvilGenius pin var var var pin var byte byte bit bit 14 15 Touched Flags Debounce CounterVariables Define theWhiskers well asdebouncingwhenthewhiskerhasstopped what cumbersomebecauseoftheneedfordebounc being incontactwiththeobject. ing whenthewhiskerisincontactwithanobject,as Experiment 107 — IR Ob-ject Sensors Experiment 107 IR Object Sensors

Assembled PCB with Wiring kit bieadboard and BS2 Twenty-tour-gauge solid Sharp GD2D12Q (D^gi-Key core wire (red, white, part number 425-1162- and black) ND) Soldering iron LM339 Solder 10k breaeboard-mountable Fxve-minute epoxy potentiometer

10k resistor

Along with using physical whiskers, some commonly I/R LED used noncontact methods of detecting objects around Sending 38 kHz your robot also exist.These methods require a bit Poise more electronic expertise than the simple wire ))) whiskers, but 1 find them generally superior to wire whiskers because they do not have to be bent back Opaque Barrier Between LED into shape, and they can often be calibrated for new and Detector Reflected Obstruction environments very easily. The most commonly used Light Waves method is infrared light pulses, although ultrasonic sound (frequencies above human hearing) is com¬ □> I/R 38 kHz monly used as well. These methods work on the same Detector theory as “S()NA R” in submarines; energy is output, Figure 15-16 IR detectam and then a receiver waits for the pulses to return. Hased on the time required for the return, or even the the Manchester encoding scheme in which, when a presence of an echo, it is determined that an object is signal is received, the receiver pulls its output line by the robot. In this experiment, r am going to work low. The start of the packet is indicated using a lung with commonly available infrared object (oi proxim¬ indicator pulse, and O's and 1 s of the data are pro¬ ity) detection modules that can be purchased for a duced by varying lengths of "lows,” This signal is few dollars.These modules work according to the modulated by a 38 kHz sine wave. When a “low” is to SONAR model: an I/R LED outputs a scries of pulses be output an IR LF.D sends a 38 kl 1/ signal that is that may be reflected by an object back to a receiver turned off tor the output to be “high." (Figure 15-16). Tire speed of light generally precludes 1 have used I/R IV remote controls for providing the ability to measure the “flight time"' (and distance a direct control to a robot, as well as for making a to the object), which is why this type of object detec¬ simple proximity detector using a circuit like the one tor is called a proximity detector; it can iust detect an shown in Figure 15-17. Despite appearing very simple object at a specific distance from the robot. and being quite cheap, an IR TV remote control These I/R proximity detector modules generally receiver is actually a very complex circuit, consisting have a commonly used part that you've never of very high-gain amplifiers and filters to recognize thought about: the infrared T V remote control and output the IR signals from an environment that receiver. This small module, which costs about $0.25, is awash in light signals from a variety of different allows for the reception of simple commands (less sources. This complexity means that if you had a con¬ than IP bits long) to a TV. DVD player, or other elec¬ stant 38 kHz signal being transmitted, the IR IV tronic device.The data bits (orpacket) are sent using remote control would recognize it lor about 50 ms

Section Fifteen Sensors 283 w *H

Section Fifteen Sensors 285 Saction Sixteen Mobile Robots

Before starting to design your own mobile robot, 1 The center of mass issue is probably not one of the want to take a look at one that 1 am sure that anyone first, things that comes to mind when you are looking reading this book is very familiar with, both in terms at deficiencies in a robot, but it should be.Tire center ol its design as well as its capabilities. Ibis robot lias of mass is the position of the robot (or a body) about demonstrated the ability to traverse a wide range of which the robot would hang without tilting if a nail terrain,fix an impressive array of different technolo¬ were driven directly through it. Pilots and aircraft gies, access very sophisticated computer systems, and designers call the center of mass the center of gravity, finally record and replav data messages. 1 >espite hav¬ As I show in Figure 16-2, the best position for a ing these qualities, I feel the robot was designed quite robot's center of mass is as close to the center of the poorly, and quite a few different features should be robot with the robot's weight spread over a wide changed for me to consider the design successful. area. When the center of mass is high up, the robot In case you haven’t guessed, the robot I’m talking can tail over when it starts moving or stops, If the about is R2-D2 from the Star Wan movie saga. center of mass is at one end of the robot or the other, then the robot is in danger ot continuously falling The areas in which I would consider R2-D2 (and over or “popping a w hcelie'' when it starts moving in probably the whole R2 series) deficient consist of the one direction. If you are familiar with racing cars, robot's drivetrain, sensors, robot grippers, input/ you’ll know that the designers want to keep the car's output, and basic programming. Despite these limita center of mass as low as possible and in the middle of tions, the robot design works well in a variety of spe¬ the car to ensure all the wheels are on the ground cialized situations (most notably the maintenance during acceleration, breaking, and turning. and operation ol different spacecraft during combat). Going back to R2-D2’s center of mass (Figure Before you dismiss this introduction as whimsical, 16-1) the robot's designers would have trouble figur 1 would like to point out that there were significant mg out what is the correct point for the center of problems with operating R2 D2 in the tirst Star Wars movie (Chapter IV,"A New Hope"), which threat¬ ened to put the film behind schedule and over cost. Despite the apparent sophistication of C-3P0 and © - Center of Mass Symbol other very spectacular effects, one of the biggest chal¬ R2D2 Walking R2D2 Rolling lenges faced by the filmmakers was getting R2 1)2 to work as required. I su«pect that many of these prob¬ lems were due to the issues that I will bring up here, Fite design of R2 D2’s drivetrain seems to be somewhat schizophrenic; most ol the time it seems to be running around on three wheels, but occasionally, the wheels seem to retract into the robot's legs and body and it walks or wobbles around. Two major problems with this movement are understanding where the robot’s center of mass should be and the Figure 16-1 To ensure the stability of R2-D2, its difficulty the mechanism would have traversing center of mass should he as low to the ground as uneven terrain (see Figure 16-1). possible and in the middle of its wheels/legs.

287 Section Sixteen — Mobile Robots stopping, oroperatingonuneventerrain.Theseprob¬ was R2'sinsistenceonfallingoverwhenstarting, over snow,andclimbupstairs.Lookingattherobot to moveoverdifferentsurfacesisoneofthetoughest run (orwalk)onsmooth,polishedfloors.Theability layout, Iwouldexpectthatitonlybeableto deserts, traverserockyterrain,navigateswamps,run legs forarobotthatseemstohavebeenablecross where thecenterofmassrobotwas. lems shouldhavebeenexpectedbasedonlookingat avis oftherobotthatlegsarconorit.willfall Figure 16-2Centerofmass assignments requiredofarobot—mostwillgetstuck. over. Oneofthebigproblemsinlilmingmovie robot musthaveacenterofmassthatisalongthe wheels formaximumstability,butwalking,the ha\e acenterofmasssomewherebetweenthetwo motion. When(herobotisridingonwheels,itshould 288 mass becauseofthetwodifferentmethodsloco¬ Most Stab'e R2-D2 hasremarkablysmallwheelsandstumpy Unstable - RobotSymbol 13 3 Robotics Experiments for the EvilGenius Weight Spread Over Easily. on SmallArea Weight Focused Area. Center ofMass Robot, Robots in Centerof Center ofMass Evenly overLarge Robot, Robot's in Centerof Robot CouldFall Less Stable © -CenterofMassSymbol Abysmal during accelerationor Balanced. Area andRobotcouldtip at ExtremeofRobot. Will FallOverEasily Smalt Area.Robot Weight Focusedon Center ofRobot,Robot’s Center ofMassoff breaking. Unless RobotActively Unevenly overLarge Robot's WeightSpread Center ofMass can moverelativelyindependently.TheMars terrain arebuiltfromanarticulatedbodysuchasthe fall overon.ordamagethendrivetrains(whichthe a muchmoreconsistentmannerthanR2D2. able tosensewhatishappeninginitsenvironment robot thatmaintainsareasonablyflataltitudewillbe it issetat,aswellwhenthedomeonlop D2’s sensor'spointofviewwillchangewiththeangle one showninFigure16-3.Thisexamplerobothas real R2-D2didrepeatedlywhilefilmingthemovies). (where Ipresumethesensorsarelocated)tuins.A the sensorsatarelativelyconstantpointofview.R2- run overthesurfaceofMars. Pathfinder Sojournerrobotusedthistypeofbodyto three setsofwheelsthatarejoinedtothechassisand that itkeepsthechassisrelativelylevel,which Figure lb-3Roughterrain Top View A bigadvantageofthistypemobilerobotis Most robotsthatareexpectedtorunoveruneven to MoveIndependently Joints toAllowWheels Robot Chassis Experiment 108 — DC Motor Control Base

If you take a look around the Internet at different gramming of the robot motors. To demonstrate how home built mobile robots, you will probably discover the 754410 works, I would like you to go back and that many of them use the LM293 motor driver chip. add the finished plywood chassis with the I >C motors Ibis chip is very popular because it can be used as an and a four- A A battery holder wired to it to make a H Bridge control of two DC motors with up to 1 amp simple programmable robot (your first) Before bolt of current. Officially, the LM293 is obsolete, but many ing the plywood chassis to the book PCB, you should sources still have quite a few in stock, or you can use five-minute epoxy two microswitches with long actu the TI 754410, which is an update to the LM293 with ator arms to the base as the robot’s whiskers (Figure some improvements (including thermal shutdown) 16-5). You may have to solder wires to connect these and is widely available at low cost microswitches to the breadboard before gluing them Wiring a 754410 to a microcontroller to control a to the plywood chassis. robot s motors is quite simple as shown in Figure 16-4. It has two power inputs, one being for the logic control inputs (which are Transistor-to- Transistor l ogic [TTL]) and the other being the power supplied to the motors.The chip does not have kickback diodes on the outputs, so you will have to add these to make sure the voltage transients produced by the motors being sw itched on and off do not damage the 754410 (or other chips in the robot). Along with four inputs that control four H-Bndge halves ami that output signal polarity (two halves have to be put together to create a lull H Bridge), two lines are used to enable the motor drivers,These Optional two lines are typically used to provide PWM control "Snubber" to the robot, and they will allow for simplified pro¬ Figure 16-M 754410motor wiring

Section Sixteen dooile Robots 289

Experiment 108 — DC Motor Control Base ping thingsoutwhenyoufirststartedyourdesign.tion.Don'tdisassemblethisrobotarefin- direction wherethingsaregoing:youwillhavecon-circuitinFigure16-7.Ihecompletedrobotshould be grammable robotFigure16-6istheblockdiagramofyouareusing,mayfindthatmoves too epoxicd tothefinishedplywoodchassis 290 Ihcts thatcouldhavebeenavoidedbysimplymap-readytorollafterloadinginthefollowingapplica- a robotthatwillmoverandomlyaboutroomuntilitquicklyfortheBS2tocontroladequately;555 book PCB,youarenowreadytobuildyourfirstpro-eratorforthemotors.Dependingonmotorsthat board, andthefinishedplywoodbaseboltedtoanadjustablemonostabletimeractasaPWMgen- the directionsthatcontrolsignals/poweraremovingcent). resume movingiandomly.NotethatIhavemarkedrobot(withadutycyclerangingfrom66to91per- hits something,atwhichtimeitwillbackupandtimer(withpotentiometer)isaspeedcontrolforthe in. IfindittobeagoodideaalwaysshowtheItshouldquiteeasyforyouwirerobot Figure 165Whiskermicroswitchesfive-minute16-6/,rrobotblockdiagram Figure 16-7DCrobotcircuit With thewhiskersinplace,wiresforbread-surprisingexceptuseof555timerIadded 1E H Robotics Experiments for the EvilGenius

The circuitshowninFigure16-6shouldn'thevery r isheil with this experiment;it is needed in the follow¬ You may have noticed a few things when you have Experiment 108 — DC Motor Control Base ing experiments. run your robot in this experiment. 1 lengthened one set of motor wires and the four AA battery clip wires ' DC Robot 1 - First Program for the DC and wired them diiectlv to the 754410. This was done Robot/Run Randomly ' {$ STAMP BS2 > to avoid the relatively high (on the order of ohms) * {$ PBASIC 2.5} resistance of the breadboard pins—when you are

• Variables and I/O Port Pin Declarations building your own robots, you may want to create i var word LeftCount var byte low-resistance motor wiring to minimize this parasitic RightCount var byte resistance. RandomValue var word MotorValue var RandomValue.NIBO After the robot has been running for a few' sec¬ RandomActive var RandomValue.NIB1 LeftWhisker pin 14 onds, you may find that the 754410 becomes quite RightWhisker pin 15 warm; this is due to the current draw through the MotorCtrl var OUTS.NIBO MotorDir var DIRS.NIBO motors and the voltage drop through the transistors in the 754410. You will not experience any heating of MotorCtrl = %00 00: MotorDir = %1111 RandomValue = 6 the 754410 if you use low current draw motors. As the i = 1 754410 heats up, you will find that its efficiency will do i = i - 1 drop (the motors will not turn as quickly and they if (i = 0) then may whine).The ultimate solution to these problems MotorCtrl = %0000: pause 100 random RandomValue is to work at matching the motors to the 754410 or ' Get New Random Value using a discrete transistor-based H-Bridge with high- MotorCtrl = MotorValue i ~ ((RandomActive & 3) + 1) * 100 gain transistors, such as the one presented in Section endif if (LeftWhisker - 0) then six. In any case, your wiring should use heavy-gauge Button LeftWhisker, 0, 100, 0, copper and ideally be built on a PCB.The reason tor LeftCount, 0, LeftWhiskerDown Goto LeftWhiskerSkip using the 754410 is convenience. The 754410 provides LeftWhiskerDown: you with a fairly cheap and easy-to-use a package 1 Collision MotorCtrl = %0110: pause 3000 that will allow you to experiment quickly with motors LeftWhiskerSkip: and robots. else LeftCount = 0 Finally, you will discover that although the robot's endif if (RightWhisker = 0) then whiskers w ill detect objects in front of it and back Button RightWhisker, 0, 100, 0, away, it will just as often run into objects going back RightCount, 0, RightWhiskerDown Goto RightWhiskerSkip wards and sit there with the motors stalled. In this RightWhiskerDown: application, 1 really should have provided whiskers ' Collision MotorCtrl = %0110: pause 3000 all the way around the robot. In real applications, I RightWhiskerSkip: else would lend to use just a couple of object detectors at RightCount = 0 the front of the robot and never go backward unless I endif loop was backing away from an object.

Section Sixteen Nobile Robots 291 Experiment 109 0> d State Machine Programming

Assembled PCB with breadboard and BS2 cd Assembled flywood base with DC motors, tour - u AA battery pack and power switch, and o microswitch whiskers 7-54410 motor ariver u 555 timer chip pu Eight. 1N91 4 | IN4148) silicon aiodes

0 Two 10k resistors d Two lk resistors •H 10k potentiometer Three 0.C1 J.IF capacitors

U (d 1 rooking over the code used for the previous experi¬ hardware state register is replaced with a state vari¬ 2 ment, you II probably see that it is quite difficult to able and the ROM becomes a series of it statements understand. I should point (hit that the aide works (or a single select statement as 1 show in Figure 16-8). 0 quite well; it is just very difficult to understand what The advantage of the software state machine over -p is happening when the robot is moving. The re are two traditional programming methodologies is not only (d reasons why I wrote the code the way I did in the how easy it is to see what is happening, but also how previous experiment.The first was that I was trying to 4^ easily it can be changed as the requirements for the C/3 demonstrate the operation of the 754410 motor application change. These advantages are only true if driver in a real robot, and the second was that 1 didn t you follow two simple rules when making up your have much space to do it in. By using the random software state machine: statement and mapping bits from it directly to the motors, I was able to create code that is very small I. When you are numbering your states, make a\ and functional When you start creating your own sure that they are separated by 10 instead of 1. If they are separated by 1. you will have to o robot software,you should be working at making the renumber the entire application it you have to code as simple and as readable as possible. add a new state. I his probably seems like it is very difficult to do, 4-5 hut by using a software state machine you will find it d very easy to develop robot code. This tool is the state Program Code 0 machine and is used to periodically update the state of a number of output bits based on the previous 6 state as w ell as any input bit changes. Hie state •H machine is used in a variety of different applications, U including microprocessors, and is usually very easy to 0 create and program w ith specific values. Program¬ CU ming a software state machine is not very difficult: it w'orks almost exactly the same w'ay as the hardware U3 state machine. ITie differences are quite subtle; the Figure 16-8 Software state machine

292 1 ? 3 Roootics Experiments for the Evil Genius 2. Do not execute any it statements within the Experiment 109 — State Machine Programming State = 0 ROM of the state machine. Instead, use exter¬ MotorCtrl = %>0000: MotorDir = %1111 nal inputs to change the state if an action is RandomValue = 5 i = 1 required. This is an important point and one do that can cause confusion for new program i = i - 1 mers. It you are polling a bit. and a state being if (i - 0) then State = State + 1 if (RightWhisker = 0) and (State <> monitored is true, then increment the state 30) then State = 10: MotorCtrl = %0010 variable before it is checked and the state if (LeftWhisker = 0) and (State <> 30) then State = 10: MotorCtrl = %0100 code is executed. if (WhiskerCount = 20) then State = 20 select (State) case 0: To demonstrate the state machine, t have modified 1 Keep Doing what you're doing the previous application’s code to use a state WhiskerCount ~ 0 case 1: machine, and after the robot has backed up after a • Timeout collision, it will then turn away from the whisker that random RandomValue MotorCtrl = MotorValue had the collision. The code should be saved in the i = ((RandomActive & 3) + 1) * 100 same directory as the previous experiment: WhiskerCount = 0 State = 0 case 10:

' DC Robot State Machine - State Machine 1 Collision Version of CD Robot 1st Pgm WhiskerCount - WhiskerCount + 1 '{$STAMP BS2} i = 40 '{$PBASIC 2.5} State = 0 case 20:

' Variables and I/O Port Pin Declarations 1 Debounced Collision State var byte WhiskerCount = 0 TurnAway var byte MotorCtrl = %0110: i = 100 i var word State = 30 WhiskerCount var byte case 30: RandomValue var word 1 Going Backwards MotorValue var RandomValue. NIB0 case 31: RandomActive var RandomValue. NIBl 1 Finished, Resume Operation Leftwhisker pin 14 i = 1 RightWhisker pin 15 State = 0 MotorCtrl var OUTS.NIB0 endselect MotorDir var DIRS.NIB0 loop

Section Sixteen Habile Robots 2 93 Experiment 110 — Robot Moth Example robot circuitisquitesimple(Figure16-10).Ifyoufol¬ create asimplerobotapplicationthatdemonstrates such asthisone.isoftenknownamoth. randomly for30seconds,andthenresumeitssearch collision (asitdidinthepreviousexperiment),move with thelight(orwoodMocksprotectinglight), brightest spotintheroom.Whenrobotcollides the preprogrammedbehaviorofsearchingput easily usingasoftwarestatemachine,Iwantedto With theabilitytocreateormodifyanapplication earlier experimentonwiringintheCDScells,1bent DC robot,thereshouldbespaceatthefrontleftof lowed thewiringdiagramsprovidedfororiginal robot thatapproacheslightandbacksoffrandomly, for light(Figure16-9outlinesthismovement).A the robotwillthenhackupandturnawayfrom their leadsatrightanglesandpositionedthemsothat the breadboardfortheseadditionalparts.Asin 294 they wouldhavedifferentfieldsofview. ous twoDCrobotapplications). 1haverearranged (and shouldbesavedinthe same (olderastheprevi¬ demonstrates howeasyastate machineistomodify some ofthestaresinsoftware, whichagain The codeforthemothapplicationislistedhere Adding twoCDScellswithcapacitorstotheDC 1E 3Robotics Experiments fortheEvil Genius Assembled plywoodbase Assembled PCBwith Five 0.01liFcapacitors Two lkresistors Two 10kresistors Two 10kCDScells Eight 1N914(1N4148) 555 timerchip 754410 motordriver 10k potentiometer microswrtch whiskers AA batterypackand breadboard andBS2 silicon diodes power switch,and with DC,motors,four- Robot MothExample Experiment 110 After Backing Figurp 16-9Mothpath Tool Box MotorDir MotorCtrl MotorValue WhiskerCount RightWhisker RightLight RandomAc tive RightValue LeftWhisker LeftLight RandomValue LeftValue TAway State J i implement a"Moth" 1 VariablesandI/OPortPinDeclarations '{$PBASIC 2.5} '{$ STAMPBS2} ' DCRobotMoth-StateMachinecodeto Point Initial Starting var var var pin pin pin pin var var var var var var var var var Wiring kit Flashlight Two bricks Screwdriver set OUTS.NIBO word word word word DIRS.NIB0 RandomValue.NIB1 RandomValue.NIB0 byte byte byte byte 14 15 12 13 *TJ eriment 110 — Robot Moth Example

WhiskerCount = WhiskerCount + 1 State = 0 State = 0 MotorCtrl = %0000: MotorDir = %1111 case 20: RandomValue = 5 MotorCtrl = %0110: i = 100 i = Is j = 1 WhiskerCount = 0 do State = 30 i = i - 1 case 30: if

Section bixteen Mobile Robots 2 95 Experiment 111 — Random Movement Explained random synergy (touseaword1hate)inhowthesethree see thatIhethreecodelinesinthesoftwareforeach shown inFigure16-11.Inthisexperiment,1would discover thattheyareverytightlyintegratedas pening betweenthesoftwareandrobotyouwill domly arenotwellexplainedandwhatishappening experiment thatareusedtomovetherobotran¬ 296 in themisprobablyprettycontusing.Therealotof Looking overthepreviousthreeexperiments,Ican lines workanilwhenyoutrytovisualizewhatishap¬ Depending onyourmotorsandthedriversthatyou one wheelbeingturnedonandfollowedbytheother. waddle towarditwithacuriousgait.Thisisresultof Figure 16-11Apparentrandom action When therobotismovingtowardlight,itwill (RandomValue) 13 3Robotics Experiments fortheEvil Genius Five 0.01||Fcapacitors Assembled plywoodbase Assembled PCBwith Two lkresistors Two 10kresistors Iwo lCkCDScells Eight. 1N914(1N414&) 555 timerchip 75a410 motordriver 10k potentiometer Random MovementExplained fi 3)+1) & %1111 microswitch whiskers AA batterypackand silicon diodes power switch,and with DCmotors,four- breadboard andBS2 Experiment 111 100 —*i(Count Motor Left Motor Right Duration) drivers thatareconnectedto amotor,themotor experiments Whentwobits are passedtotwo754410 to themotorcontrolbitsas I havedoneinthese 65,535, anditdoesnotrepeatuntilallthevalueshave returned cannotbeeasilydeterminedfromthevalues reacts inoneofthreewavsas definedbyTable16-1. reset, apparentlyrandomly,andcanbepasseddirectly and 15secondsbeforetherewasarepeatingvalue. you wouldfindthatittake18hours,12minutes, values fromtherandomstatementoncepersecond, been displayed.Ifyouweredisplayingthedifferent passed toit.ItcanbeanywhereintherangeofI and itreturnsapseudorandomvalueout.The like toexplainthethinkingbehindthiscodeandhow value. to “i”alter"MotorCtrl”isloadedwiththeturning use. youmayfindthatthetimerobotisturning Each ofthebitsinreturnedvaluecanbesetor back shiftregisteroperationonthevaluepassedtoit. robot applications. too longandyouwillhavetochangethevaluegiven to seeopportunitiesusecodelikethisinyourown Tool Box The “random”statementisasoftwarelinearfeed¬ Wiring kit Screwdriver set So, by simply passing the least sigmticant bits from Ii is somewhat easier to read and understand what Experiment 111 — Random Movement Explained the random statement, 1 am randomly specifying is happening with this code, but it has a number of whether or not the motor is to work and in which concerns, including that it takes more effort to write direction it will turn. I could have used the PBASIC and requires more space in the HS2. memory. Of select statement to perlorm a similar function: course, looking through the statements,somebody new to programming and robots will probably have a random RandomValue couple id questions, such as why isn't there an explicit MotorValue = RandomValue & %1111 select (MotorValue) “Left Motor Stopped, Right Motor Stopped?" The case 0: ' Left Motor Forward, Right Motor Stopped person may note that in 8 cases (out of 16) the “case MotorCtrl = %\000 else" code will execute and both motors will be case 1: 1 Left Motor Forward, Right Motor Forward stopped. Why is that allowed? In the practical terms MotorCtrl = %1010 case 2: ol readability, this modification of the code isn't any ' Left Motor Forward, Right Motor Reverse better than the original. MotorCtrl = %1001 case 3: You may have noticed that when I have specified ' Left Motor Stopped, Right Motor Forward MotorCtrl = %0010 the motor control bits for this application, I arranged case 4: ’ Left Motor Stopped, Right Motor Reverse them to simplify software development. You might be MotorCtrl - %0001 thinking that in a real-world application, the motor case 5: ' Left Motor Reverse, Right Motor Stopped control bits and their pins would be specified in order MotorCtrl = %0100 case 6: to simplify the wiring of the application;software can ' Left Motor Reverse, Right Motor Forward be changed easily. In this case, you would use some¬ MotorCtrl = %0110 case 7: thing like the previous select statement or the follow ' Left Motor Reverse, Right Motor Reverse MotorCtrl = %0101 ing branch statement code where T red. I blk. Rred. case else and Rblk,defined using the pin statement, are the ' Anything Else, Motors Stopped MotorCtrl = %0000 BS2 I/Os that interface to the motor driver. endselect

Table 16-1 Motor response to different Loire connections

Red Black LUire Bit UJne Bit Motor Response

0 0 Motor stopped (Botlrinputs tied to ground so no current flow)

0 I Motor running backward (Current from negative to positive)

I 0 Motor running forward (Current from positive to negative)

1 1 Motor stopped (Both inputs tied to power so no current flow)

random RandomValue MotorValue = RandomValue St %1111 branch MotorValue, [MO, Ml, Mg, M3, M4, MS, M6, M7, M8] Lred = 0: Lblk = 0: Rred = 0: Rblk = 0: goto Mend ' Stopped M0 : Lred = 1: Lblk = 0: Rred = 0 : Kb lk = 0 : goto Mend Ml: Lred = 1; Lblk = 0: Rred = 1: Rblk = 0 : goto Mend M2 : Lred = 1 : Lblk = 0: Rred = 0 : Rblk = 1; goto Mend M3 : Lred = 0 : Lblk = 0: Rred = Is Rblk = 0 : goto Mend M4 : Lred = 0 ; Lblk = 0: Rred = 0: Rblk = 1: goto Mend M5 : Lred = 0 : Lblk = 1: Rred 0 : Rblk = 0 : goto Mend M6 : Lred = 0: Lblk = 1: Rred = 1: Rblk = 0: goto Mend

M7: Lred - 0 : Lblk = 1: Rred = 0: Rblk = 1: goto Mend Mend:

Ejection Sixtpen Habile Robots 297 w *H -P

Parts Bin Tool Box Assembled PCB with Wiring kit breadboard and CS2 Five-minute epoxy Four-AA battery paok Screwdriver set with power switch connected Soldering iron and sol¬ der Raciio-cont rol (R/C) Kmfe servo

Three-pin R/C servo con Rotary cutting tool (see neetors (see text) text) PU Two-inch to 3-inch (5-cnn 3 to 7 5-cm) model air¬ craft wheel or servo

Although I introduced you to robot bases, I used the 1. Disconnect the position feedback potentiome¬ o basic DC motors driving two wheels in a differential ter and replace it with either two resistors of > drive layout. The advantage of this type of method the same value as a voltage divider or a "trim¬ M toi controlling the robot is the relatively simple pro¬ mer" potentiometer, which is wired identically

300 123 RoDotics Experiments for the Evil Genius The only other thing that you will need is the Experiment 113 — R/C Servo Setup breadboard-to-servo connector adapter that you made tor the earlier servo experiment in the book. This adapter isn't absolutely necessary (you could use fft 1-gauge wires between the breadboard and the L _ servo connector), but it is very reliable and will not damage the servo’s connector or the breadboard. When you make up this connector adapter, I suggest that you make a half dozen or so; they are easy parts to lose isec Figure 16 16). I have not included instructions for modifying any specific servos (even the photographs and instruc¬ tions for the Hitec Model 322 are pretty sketchy). Figure Servo top removed, showing the 16-m After doing a quick look on the Internet, I found gearing inside the servo. The motor drive is on (la- instructions for modifying almost 50 different servos; right side and the potentiometer is on the left. when you select a servo to use, do a quick Google™ search to make sure instructions are available for standard panel or PCB mount potentiome¬ modifying the servo. Although most servos can be ter). A standard potentiometer only lias one modified for continuous rotation, for a number of turn for its full motion, whereas a tiimmer them the effort required to do so is prohibitive 1 potentiometer can have 10 or 20 turns. The should caution you that most instructions for modify¬ increased number of turns will allow you to ing servos warn you about making sure that you more precisely center the potentiometer to the software.

2. Remove any mechanical stops inside the servo that prevent it from turning a lull 360 degrees. Often the position feedback poten¬ Tab on Side of tiometer will only allow 00 degrees of move¬ Output Gear to ment, which will require that it is either Remove with a Knife or Rotary removed or reworked to turn continuously. Cutting Tool Along with this, you will probably find tabs on the inside of the servo that wilt restrict the output shaft's motion that will have to be removed with a knite. Figure 16-15 shows a “tab” built into a Hitec Model 322 servo that will have to be cut away with a sharp knife or Figuie 16-15 Tab to remove a rotary (Dremel) tool.

On some servos, you will have to take apart Model Airplane Wheel the feedback position potentiometer anti

remove the pot wiper, which restricts the Control Arm range the pot can tuin. Epoxied to L,. ^Disconnected ^UMUUI Model „ &C! IM-C-JA pOSjtion Sensor Signal 3. Replace the standard output arms, wheels, SK7 ‘jsrEmffi1 ■ Potentiometer horns, and other actuator parts with a wheel. P^> Pulse Width to Voltage Some wheels available on the market are Comoarator convenerConverter designed for use in robots, but I prefer using a Resistor Voltage Divider model aircraft 2.5-inch diameter wheel that has been 5-minute epoxied onto a cut-down control Motor Driver arm.The wheel's hub may have to be dulled out to access the servo arm holding the screw. Figure 16-16 Modified servo innards

Section Sixteen flobi le Robots 301 cu cntvalues,andthevoltagedividerwillnotbe

Experiment■4 113 — R/C Servo Setu supply andtheservo’switmg.Althoughwumg program. stopped. Youwillneedanapplicationtofindthecen¬ shown inFigurelb-17shouldbecorrectforthe value suchas500or1000.thencheckyourpower 750”statement) andguaranteethattheservowillbe in Figurelb-17andthenenterthefollowingBS2 exactly halfthetotalvoltage.Ibisdifferencemeans verv. veryluekv,thesetworesistorswillbeofdifter- a servototurncontinuously,setupthecircuitshown ter orcalibratethevaluethatwillholdservostill. they areactuallyoffbyafewpercent'.Unlessyou resistors arefairlyclosetoanexactvalueof2.2k. tiometer withtwo2.2kresistors.Althoughthe are goingtoreplacethepositionfeedbackpoten¬ digital cameraisnotabadidea). pictures ofthembeforetheyareremovedusinga ally quitestraightforwardandwilllakeyoulessthan sound quiteominous,butyouwillfindthatitisactu¬ that youcannotpassa1.5msignal(using"pulsout know whatyouaredoingandmaketileoperation it isimportanttokeeptrackoftheparts(taking 15 minutesforeachservo.Whenmodifyingaservo, Io findthiscalibrationvalueonceyouhavemodified 302 1 ?3Robotics Experiments for the Evil Genius For thisexperimentIamgoingtoassumethatyou II theservodoesnotmovewhenyouputina CurrentDelay varword i varbyte Servo pin15 1 Initialization/Mainline 1 Variables {$PBASIC 2.50) { $STAMPBS2} do CurrentDelay =750 low Servo loop Calibrate -FindtheCenter/NotMovingPointforServo debug "EnterinNewDelayValue" next debug "CurrentServoDelay do while(CurrentDelay<500)or> 1000} debugin decCurrentDelay for i=0to50 loop pause 18 pulsout Servo,CurrentDelay debug "InvalidValue,Mustbebetween500and1,000", debugin decCurrentDelay debug "EnterinNewDelayValue" Value =",decCurrentDelay,cr Output servovaluefor1second 20 msecCycleTime Repeat forever Start at1.5ms Set ServoPinLov; Servo CenterPoint •servo you’reusing,youmightfindthatsomeservos 'I heBS2powersupplycannotenoughcurrent capable of300mAcurrentoutputfortheservos. other applicationubngservos,itisagoodideatopro¬ for theservotooperate,andifyoudrivefrom volts toit are wireddifferently.Miswiringtheservoshould ply. \\henyouarerunningthisexperiment,orany not damageitunlessyouarepassingmorethanb vide aseparate4.8-volttobvolibatterypowersupply the BS2,youwillburnoutBS2’sbuilt-inpowersup¬ Rgure 1617Servocalibrationcircuit Do notpoweraservofromtheRS2supply1 17= 9V „RV\A-r- -vv- - -vvy-p- _19-Volt VY—w Battery Hus application w ill wait for you to specify a cen¬ Along with being used for centering the servo, tins Experiment 114 — Controlling Multiple Servos ter value and then pass it to the servo for a second so application code can be used to observe the opera¬ you can see whether or not it causes the servo to tion of the modified servo when different values are turn. In the application. I use the “debugin" state¬ passed to it. Remember that the values passed to the ment to allow you to enter numeric values from your servo via the “pulsout" statement must be in the PC's keyboard to find the “pulsout’' value that holds range of 500 (1 ms) to 1000 (2 ms). the servo motionless. Once you have found the center pulsout statement value. I suggest that you write it on the servo.

Experiment 114 Controlling Multiple Servos

Assembled PCD with breadboard and BS2

Assembled plywood base with servos and four- AAbattery pack and power switch

Setting up and calibrating robot sen os with the BS2 A = (b + c) x o (or any other microcontroller) is not very difficult. What can be confusing is how to set up a useful appli- >ou have u> remember that each operator requires cation for a robot that has more than one servo built about 250 ps.so this statement would take about 500 into it.The RS2 is more than fast enough to effec- ,us lo execute. tively control two (or more) servos .it the same tune. To avoid the variable timing issue of the pulsout but you will have to sit down for a few minutes to fig- statement, the simple solution is to execute two puls- ure out how you can control two servos simultane- out statements with a set maximum tune. \V hen 1 ouslv w hile computing how the robot is to move. work with servos, I assume that the maximum time Fortunately for you, I have done this work and in this experiment, 1 will present it to you. The obvious solution to the problem of controlling (he servos is to send a pulse to each of them once every 20 msecs while in a loop, as I show in Figure 16-18. This probably seems quite easy to do because the HS2 is rated as executing one statement every 250 ps.The problem comes in when you look at the actual execution speed of the various statements, and of the “pulsout'' statement and compound statements in particular. The code read and initiation portion of the pulsout statement takes about 250 ps, but you have to add on the time that it is active to get the actual time it is executing. If you have a compound mathematical statement, such as Figui e 16-18 Multiservo program

Section Sixteen Nobile Robots 303 Experiment 114 — Controlling Multiple Servos at thesametime). the robotrandomlyusingservos(whichcanoperate or moreservostoexecutewithin20msecs. equal. TheDummyServopinshouldbeanI/Oon makes itquiteeasytotimeoutaloopcontrollingtwo I cameupwiththefollowingapplicationthatmoves m thecontrolofarobotwithmorethanoneservo, total delayfortheservopulseoutputis3ms.This is addedtothe2.25psdelayofpulseoutput, ServoValue” coderequiresanextra250ps).Whenit actually bethreeinstructiondelays(the“1125- ment intheBS2is2ps:sotogetatotaldelayof2250 the BS2thatisnotusedforanyotherpurpose. a full2.25mspulseandkeepsthestatementliming to puttheleftoverdelaysothatpulseoutexecutes used. Inthesetwostatements,noticethattherewill us usingthepulsoutstatement,atotaldelayof1125is for theservopulseoutputthatIuseis ond picksupthedifference.Thegeneralcaseform pulseout statementissenttotheservowhilesec¬ for thepulseis2.25ms.whichmeansthatfirst To demonstratetheoperationoftheseinstructions l hegranularityprovidedbythepulseoutstate¬ The “DummyServo"pinisusedtoprovideaplace CurrentStep varword RightForward con900 RightStop con750 RightBackward con600 LeftBackward con900 LeftForward con600 RandomValue varword LeftStop con750 RightServoVal varword LeftServoVal varword DummyServo pin1 RightServo pin0 DummyServo LeftServo pin15 About theRoom pulseout DummyServo,1125-ServoValue pulseout SelectedServo,ServoValue ' Variables 1 Initialization/Mainline '{$PBASIC 2.50} 1 {$STAMPBS2} ' ServoRandomMovement-MoveRandomly RandomValue -1000 lov; LeftServo:lowRightServo: do i =1 if (i=0)then i =-1 123 Robotics Experiments for the EvilGenius select ((RandomValue/4) &3) random RandomValue suspicious, Icanhonestlvsay thatIdidnot“cook" The totallooptimeisalmost exactly20ms.whichis spend abitoftimefiguring how longeachsectionof the resultsshowninFigure 16-19. AlthoughIdid exactly whatisrequiredby the servos.Incaseyouare puts suppliedtothetwoservos,aswell switch offastherobotmaystartmovingimmediately “DummyServo” usinganoscilloscope(Figure16-20). ments forthisapplication,Ilookedattheservoout¬ following downloadoftheapplicationcode. and relianceonthebookPCB.Whendownloading essary forthisapplicationbecauseofitssimplicity servos accoidingtoFigure16-10andthenloadedin the application,remembertokeepservopower the application,Ididn'tfeelthataschematicwasnec¬ pulse width.Inthisapplication,Ihaveassumedthat will besavedinthevariableassignedwithservo's counter (“i”)isdecremented(onetakenawayfrom have tobefoundusingthecalibrateapplication. full-speed rotationwilltakeplacewitha1,200psor it) tozero,atwhichpointrandommovementvalues the samepulsewillbesenttoservosunless 1,800 pspulse.Thevaluethatstopsthepulsewill To testhowwell1understoodthetimingrequire To testoutthisapplication.Ijustwiredthetwo The applicationshouldbequiteeasytofollow; LeftServoVal LeftServoVal ' StatementsAboveTake11msecsintotal loop pause 9 pulsout DummyServo,1125- pulsout RightServo,RightServoVal pulsout DummyServo,1125- pulsout LeftServo,LeftServoVal else end if pause 4 endselect i =((RandomActive&3)+1)*120 endselect select ((RandomValue/16)&3) case 3: case 2: case 1: case 0: case 3: case 2: case 1: case 0; RightServoVal =RightBackward RightServoVal =RightStop RightServoVal =RightForward RightServoVal =RightForward LeftServoVal =LeftBackward LeftServoVal =LeftStop LeftServoVal =LeftForward LeftServoVal -LeftForward = LeftBackward - LeftStop LeftForward Experiment 115 — Robot Artist n njin n.. jcuxtxn n i « □ | hSSmm °H£jLeft Servo* Left Servo Control □ □□□□ a[Q]n t Connector ViiVf □ □ □ 0 3 □ | It- Pulse □ a g‘6 □ a Uc5ctaB * c □ □ □ a □□□□□ D □ □□□□□ □□□□□ Right Servo Control □□□□□ a □ □ □ □ Pulse □□□□□ □□□□□ jf- □□□□□ □□□□□ □□□□□ □ aaa □ □□□□□ ao □ □ □ 4-“DumnyServo" □□□□□ aa a □ □ Pulses Following □□□□o □□□□□ □□□□n □□□ JUi Left and R;ght oaaao QoD R'Qht Servd Pulses □ □□□o □ □ p Connector □ □ □ □ o a On □ o I □ □ ji (Scope lCHt 4 V 4mS □ □ □ d - □ □□□□- □□ f> (ScopcVCH? if imS □ asao □{□}□ o c ' □ n in istyv. srits, 1 . , l U...J GO □□□ □□□□□,□□ □ □ f'AA' Battery □ □ Figure 16-20 Multiservo scope □ 5 (Pack Fte-Lyy!? □ □ G AA" RatTmw^ ' 1^2 A □.Pack Black Wire specified loop time, your application should still run Figure 16 19 Multiservo wiring fine. When vou have finished with this experiment, the loop would take to execute, 1 really lucked out don’t disassemble it.The servo platform will be when I combined them and ended up with the ideal required for the next two experiments. 20 ms loop. Fven if you are within 10 percent of the

Experiment 115 Robot Rrtist

Tool Box Assembled PCS with Wiring kit breadboard and BS2 Carpenter's protractor Assembled plywooa base (see text) with serves and four- AA battery pack and power switch

Elastic band (see text)

Magic Marker

Machines for making art or patterns have been man free gear that you would put a pen tip through.The ufactured over the past two or three hundred years, spirograph worked on exactly the same principle as t his is probably surprising to you because you can’t the etching of the patterns on a bill; the gears of the think of any valuable works of art that have been spirograph would put ihc pattern on a sheet of paper made by machine. Actually, to find an example of in an almost identical (but slightly different) pattern. machine-drawn art that has been in use for centuries, You can replicate this pattern with a piece of you don’t have to look any further than your wallet. graph paper, a pencil, and a ruler, as I have shown in The swirls, loops, and pattern'- were made by a Figure 16-21. To make the curve that you see in this machine built from a collection of gears and cogs that picture. I started w ith two lines 90 degrees apart and scratched the pattein on the printing plate used for drew a line from one extreme to the origin and the bill. As a young child, you may have played with a moved along by a few millimeters. The resulting toy called a “Spirograph.” which was a collection of series of intersecting lines appears to describe a gears that you could pin to a piece of paper with one curve.This figure could be repeated with different

Section Sixteen Mobile Kcbots 305 Experiment 115 — Robot Artist simply woundanelasticbandaroundtherearsup¬ one showninFigurelb-22.Inthispattern,therobot could getarobottodrawrepeatingpatternlikethe competitions,you willhavetheopportunitytowatch ports ontheservorobotbaseandusedtltoholda than theothertwo.Forrobottodrawline,I moves inrepeatingsquareswithtwosideslonger ronment. ituseseithetlightsensors(usuallyinthe as aresponsetotheenvironmenttheyareoperating with. in. Iftherobotisprogrammedtorespondenvi¬ their ownpatternseitherasapreestablishedpatternor these competitions,robotsareprogrammedtocreate (and maybecompetein)therobotartcompetitions.In trying toseewhatkindofpatternswecouldcomeup piece ofwoodandthenrunstringbetweenthenails, popular hobbywastoplaceasetiesofnailsinto Magic Marker. form ofCDScells)oramicrophoneandamplifier length lineswithdifferentangles.WhenIwa«akid, for controllingthetwoservomotorsaswaspresented Figure 16-21l.mecurve ate theprogram.Ihadtocomeupwithsomewayof 306 determining howlongtherobot wouldhavetorunin m thepreviousexperiment.Beforeattemptingtocre¬ doing thisislistedhereand has thestopvaluethatI order tomove12inches,then move10inches,and turn 90degrees,lheprogram Icameupwithfor For thisexperiment.Iwantedtoseehowclose1 In termsoftherobotitself.Iusedsamecircuit If yougetachancetogooneofthelargerobot 12 3 Robotics Experiments for the EvilGenius recorded, andtheoperation wasrepeatedfivetimes seconds ).Iheprogramcanbyrestartedsimply pressing theresetbuttononPCB, moving for20020-millisecondloops(whichtake4 the robotbase.Thisprogramdelays5secondsbefore found JrequiredfortheservosthatIwasusingwith Figure 16-2?Proposedrobotart After therobotstopped, distancetraveledwas LeftServoVal LeftServoVal RightBackward RightForward RightServoVal RightServo DummyServo LeftBackward LeftForward RightStop LeftStop LeftServoVal DummyServo LeftServo Robot Speed/unittime i ' StatementsAboveTake7msecsintotal ' Initialization/Mainline ' Variables 1 {$STAMPBS2} ' ServoDistanceCalibrate-FigureOut '{$PBASIC 2.50} pause 5000 loop do while(i<>0) RightServoVal =RightForward i =200 LeftServoVal =LeftForward low LeftServo:RightServo: end pulsout DummyServo,1125- pause 13 pulsout RightServo,RightServoVal pulsout DummyServo,1125- pulsout LeftServo,LeftServoVal i =-1 b var var pin pin pin con var con con con con con 10 word word word 770 777 600 900 900 0 600 1 15 to get the average and used a set number of 20 ms short line. Looking through the program, you can see Experiment 115 — Robot Artist loops before stopping. I repealed the operation fi\e that 1 went to some lengths to make sure that the times and averaged the resulting value.Table 16-2 loop cycle time was 20 msecs. lists the five values as well as the average. ’ Robot Artist - Try to draw the This average distance was then divided into 2(X) to "Wandering Square" get the number of cycles per inch (7.1 cycles per • {$ STAMP BS2 > '{$PBASIC 2.50) inch).To go 12 inches, I would require 85 cycles, and to go 10 inches, 71 cycles are required. Variables LeftServo pin 15 Measuring the angle required the same program RightServo pin 0 DummyServo pin 1 (but with LeftServoVal” loaded with “LeflReverse” LeftServoVal var word rather than “LeftForward,” and the number of cycles RightServoVal var word LeftStop con 111 it turned was reduced to 25 so that the turn would be RightStop con 770 less than 90 degrees). Before starting the program, l LeftForward con 600 LeftBackward con 900 aligned the robot to a sheet of paper, ran it. and RightForward con 900 measured the difference in direction between the RightBackward con 600 i var word starting angle and the finishing angle. Amazingly D var word StepNum var byte enough, the robot turned 90 degrees consistently with 25 servo cy cles. ' Initialization/Mainline low LeftServoj low RightServo: low So. with the number of cycles lor moving 12 inches DummyServo LeftServoVal = LeftStop and 10 inches, as well as turning 90 degrees. 1 was RightServoVal = RightStop ready to test out the program to see how well it could i = 250 StepNum - 0 draw what 1 was calling a “wandering square.” do i = i - 1 Ihe program 1 came up with to draw the wander¬ if {i = 0} then ing squares follows. Note that after moving, 1 stopped StepNum = {StepNum + 1) // 16 j - StepNum // 2 the robot for a quarter-second.This was because the if (j = 0} then turning angle began and ended with a stopped LeftServoVal = LeftStop RightServoVal = RightStop robot- the acceleration of the robot in the term was i = 25 part of the value. Rather than using a table to deter¬ pulsout DummyServo, 250 else mine what the robot was to do next I calculated the RightServoVal = RightForward responses algorithmically. It actually has 16 positions; j - StepNum // 4 if (j = 1} then each even one is a stop, and each one that is equal to LeftServoVal = LeftForward if (StepNum > 8) then one after the step number modulo 4 is found is a i = 71 straight line. Finally, if it is a straight line movement else i = 85 and the step number is greater than 8. then it is a endif else LeftServoVal = LeftBackward i = 25 I'ahle 16-2 Robot distance travelled in j = 16 five seconds endif endif else Tria! Distance pulsout DummyServo, 875 endif pulsout LeftServo, LeftServoVal 1 28.00'' pulsout DummyServo, 1125 - 2 28.13” (28 '/k") LeftServoVal pulsout RightServo, RightServoVal 3 .28.38" (28 V) pulsout DummyServo, 1125 - Left Se rvoVa1 4 28.13 ' (28 Vs”) ' Statements Above Take 8.5 msecs in total 5 28.25” (28 'U") pause 11 pulsout DummyServo, 125 Average 28.178" loop

Section Sixteen Mobile Robots The result of this program is shown in Figure 16-23, and you should notice two things in the photo* graph. The first is the funny arc that is drawn at each curve.The pen is not located at the center of the turn, so it follows the path of the part of the tobot that it is attached to Based on my previous experience with robots, this was not unexpected, ITte second problem is that although I measured 90 degtees using the “Servo Distance Calibrate" •p program for 35 cycles, it obviously wasn’t correct for o the actual application,The actual turn should have PQ been something less than 25 cycles. I Despite these two issues, 1 believe that the result Figure 16-23 The robot did not produce the M ing figure is actually quite attractive, and if it were expected wandering square" hut came up with its D allowed to continue for more than four circuits, it own unique pattern that could definitely be called could have produced quite an interesting figure. If O art. you are interested in true precision, then you would want to add a compass to the robot (to make sure the CO turns are absolutely sharp) along with some way of work is quite interesting, and I'm sure that when you measuring distance, anil put the pen at the center of repeat this experiment, your robot will come up with X the robot's turn Even without these extras, the pic¬ something just as unique and interesting. cd ture the robot produced after just a few hours of

H (d Experiment 116 u cd Parallax's "GUI-Bot" Programming Interface

Parts Bin Tool Box Assembled. F'CF with Wiring kit breadboard and BS2 Five-minute epoxy Dual servo roDot base Clippers with four-AA-battery pack with power switch Wire st. ripper/knif e connected Soldering tools

Two radio-control (R/C) servos

Three-pin R/C servo con¬ -P nectors (see text)

c Two 10k resistors

<1) 11 you have been looking at different hobbyist robots, ety of different methods for output. The robot is built a, then I’m sure that you will be familiar with the Paral¬ around Parallax's Board of Education PCB, which lax ROE-Bot. which is a dual servo robot controlled includes a BS2socket, power input, a breadboard, w by a BS2, and il has some built-in sensors and a varf- and interfaces to servos and Parallax’s line of App-

308 123 Robotics Experiments foe the Evil Genius Mod BS2 adapters.The PCR included with this hook wasn't based in a large measure on the Board of Edu¬ cation PCB to allow you to take control of the BOE- Bot software and development tools like the GUI Bot Hie servo differentially driven BOF-Bot is an excellent way to get into robotics for people who don't want to do the cutting, dr; I ling, gluing, painting, and parts finding that are required for the robots pre¬ sented in this book. Along with the parts necessary to build the robot, the kit comes with an excellent man¬ ual (written by BASIC Stamp expert Jon Williams), along with a wide variety of parts (hat will allow you Figure I6-2M Servo base with microswitch to learn more about electronics and the BASIC whiskers added as object sensors to make the servo Stamp 2. base compatible with the BOL-Bot One feature of the BOE-Bot that makes it very attractive for beginners is the GlJI-Bot software that is designed for use with the robot. Tills tool will allow (w ww.parallax com) and install it the same way as you to cteate applications tor the BOL-Bot that will you did with the BASIC Stamp Windows Editor have it running around and performing basic opera¬ Software (left-click on the link on the w'eh page and tions in no time. In this experiment, 1 would like to open the application to install it). I suggest that you show you how easy it is to work with the GUI-Bot open and print out the readme file. Ihe first time you software and give you some idea ot how graphical open the application, click on “Beginner Mode” of programming can be implemented for robots. operation, at which point you will be greeted with a Before you can work with GUI-Bot, you must dialog box similar to Figure 16-26. have a BOE Bot equivalent robot Eoi this case, I will The big difference between Figure 16-26 and what show you how to make a lobot that is functionally you will see when you first run the application is the equivalent to the BOE-Bot using the R/C servo base program that I have entered under “Actions to Be that you built earlier in this section. This base can be Performed "Thi seven actions that 1 have written out used almost exactly as built; you will just have to add cause the robot to describe a right-angle, triangle as it two microswitch whiskers, similar to the ones you moves.The robot goes forward for three seconds, added to the DC motor base. The microswitches turns, goes for ward, and so on until it finishes, at should have wires soldeied to them so that when the which point it jumps back to the start to try again. switch actuators are pressed, the connection is closed. ()nce the wires are soldered to them, the C n n n n n n n rt n n J_;oo"l ^ □ □□□n microswitches can be soldered to the servo base as □ □□□□ Servo’ □ □□□□ □]Ho i Connector shown in Figure 16-24. □ □ □ □ Hooc 1551 □ □□CD □{ IICL □ D Li □ □ D□□□□ I D □ Ihe wiring necessary to convert the PC B and p a □ □ □ □ □ □ DC Q.Stl □ □ d(c_ robot into a BOE is quite simple. Figure 16-25 shows □ □ □ □ □ □ □ □ □ □ □ □§Righi Servo the circuit elements that are necessary and how they □ □ □ □ □ Q aoConnector □ □□ □□ □ □□□□ iljlj| are wired together, Ihe wires connecting PO and PS □□□t f— — inn I O O I □ n c : i Mk* . Left Whisker” □ 7 d i : to Vcc are needed to simulate an infrared remote □ lood nnnnn i~a| o S onoo rn n I control receiver, which is used on the BOE Bot as an Right Whisker” □ n Ci i i u u j □ p object detector. For this robot, just the microswitch □ |QIj lT . 1t> ixl.OJTLi.Ej □ or.r-AA" Battery oo whiskers are used for object detection. □ o^Pack Red_Wire °° q “AA Battery^^Joo — Once you have the robot completed, you can UPack Black Wire 1^*- download the “GUI-Bot” from the Parallax web site Figure i6-25 BOE-Bot circuit

Section Sixteen flobila Robots 30 9 Experiment 116 — Parallax's "GUI-Bot stopped,click “CalibrateServos"tosavethisinfor¬ function asthePHASICprogramIpresentedearlier up theTestModedialogbox,whichcanbeusedto for theactualservohardware.Toeliminatethis,click will beturningbecausethe“Stop"valueisntcorrect your computerasyouworkonprogram. about reasonablycorrectly.Ibisisn'tadifficult correct timingsforthetriangle,Ispentaboutahalf- for findingthestoppositionofaservo.Whenyou tion oftheservosthatyouareusing.Thisissame test yourwhiskersaswellcalibratethestopposi¬ the TestbuttononGUI-BotInterface.Ibisbiings for anylengthoftime,youwillfindthattheservos process, butitmeansyouwilliunbackandbirthto empirically (alsoknownastrialanderror).Togetthe hour gettingthevaluessothatrobotwouldmove ware whenyoufirstuseit.Iheislearninghow mation intheapplication. have adjustedtheapplicationsothatservosare long actionsshouldbeperformedfor.Ibisisfound Figure 16-26SimpleGUI-Bot with yourprogram(byclickingGo).youwilldiscover that therobotwillstartmoving.Topreventthisfrom happening. 1stronglyrecommendthatyouturnoff the powerfromfourA batteriestotheservos 310 rate) andsuspendtherobot with thewheelsnot (this iswhyIkeeptheBS2and motorpowersepa touching anything.Doingboth isprobablyoverkill, hut hopefullyyou'llremember tocarryoutatleast The la*tis'-ueisthatonceyouprogramtheBS2 You willhavethreeissueswiththeGUI-Botsoft¬ Ibe secondissueisthatwhenyoustoptherobot Clck theGobuttontojendyou'AdtctwbePeitorfred"kltcbot P/RAL{A. 123 Robotics Experiments for the EvilGenius \s 2 m off atableandsmashonthefloorwhileunderpro¬ cations thatrequirevariablesoiadvanceddecision you willfinditquitelimitedwhenwanttomom so thatthemicroswitchwouldbeclosedwhenitwas “Advanced Mode”andyouwillseesomethinglike whiskers andothersensorsaspartoltheprogram. executing. gram control. one oftheseoperationsandnotwatchyourrobotrun making. audio), anditwillnotallowyoutoimplementappli tor theoperationsofyourrobot(byLEDs.LCDs,or ing AdvancedModeapplicationstobefairlyeasy,but tion ifthesensordetectswall.Youwillfindcreat¬ example, Setlturnstherobotinoppositedirec¬ are responsestodifferentsensoractions.Inthis de anobjectinaclockwisedirection.Todevelop and notonethatisveryusefulbecauseitcanonlyca¬ object, itturnsaway.Thisisaverysimpleapplication touching awall. Figure 16-27.whichisasimplewallfollowerandto Quit theGUI-Botapplication,restartit,andselect, ready fortheAdvancedMode,whichincorporates manding yourrobottomoveaboutthefloor,youare and thencreatesmallerprograms(calledsets)that application,you firstsetdownanominalprogram (into thewall),butifrightsensordetectsan implement it,laddedsomewiretotherightwhisker have acoupleofsecondsbeforetheprogramstarts floor, presstheresetbuttononPCBandthen turn ontheservopower.AfterBS2isreset,you Figure 16-27AdvancedGUI-Bot P/rvn.. -•«mp«>ui>k«« Once youhaverunafewbasicprogramscom¬ In thisprogram,therobotnormallyturnsright If youwouldliketotestouttheroboton Experiment 117 — Stepper Motor Control

Experiment 11? Stepper Motor Control

Tool Box

Assembled PCB with Wiring kit. breadboard and BS2 Scissors Four-AA-battery pack Krazy Glue Five-voIt. bipolar stepper motor

Four-pin stepper motor/breadboard con¬ nector (see text)

Eiqht. IN4148 (1-61914) silicon diodes

Paper

A number of different chips will interface to a step¬ 1 preter working with the bipolar stepper motor per motoi and update its position w hen a clock is because (if the extra torque it provides for small passed to it. These chips usually have three inputs, an robots (two coils are always active in the X and V output enable, direction, and clock (which initiates a direction instead of the single coil of the unipolar change in the position of the stepper motor). Ihesc stepper motor). To drive a stepper motor. 1 use the chips normally do not connect directly to the stepper 754410 motor driver, and to demonstrate its opera¬ motor itself because of the differing voltage and cur¬ tion. 1 would w ire it to a BS2 as shown in Figure lb- rent ratings of different motors, instead their output 30. The control code for turning Ihe bipolar stepper is passed to a driver circuit that has been designed for motor is surprisingly simple and is listed here. After the motor that is being controlled. These ehips are building the circuit glue a paper arrow onto the step¬ quite easy to work with, but they are really not neces¬ per motor (just like in the earlier experiment) so that sary, as I will show in this experiment you can see the motor turning easily. When I introduced stepper motors in the book, T neglected to indicate that two different types are commonly used. Ihe unipolar stepper motor consists ol a motor with four coils, wired as pairs with a com¬ Positive Power mon center connection. The unipolar stepper motor’s drive electronics are very simple, as I show in Figure 16-2S. To energize a coil of the unipolar’s stepper motor, its connection is simply pulled to ground using a transistor. Coil Controls Although Ihe control wiring of the unipolar’s step¬ per motor is quite simple, it does not pros ide as much torque as the bipolar stepper motor (which was demonstrated earlier in the book). Phis motor has four coils, just like the Unipolar stepper motor, but it does not have the center connection and has to be driven using haff-H-Bridges as shown in Figure 16-29. Figure !6-c?B Unipolar stepper motor control

Section Sixteen Nobile Robots 3] n n n n n -JD.ndillX- □ □ □ □ D □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ □ c c Stepper Motor c Connector □ □ u □ o i „ a

id □ a u [] □ □ □ □ o a n □ □ □ □ u □ □ □ □ □ u G la □ cn □ □ V □ □ Figure 16-29 Bipolar stepper motor control n rj g n □ □ □ □ o o When you have the circuit built, enter the applica¬ Figure 16-30 Stepper control circuit tion code listed and save it as “Stepper Motor Con¬ trol in a Stepper Vlotor folder located in the Evil u to-right order of operations results in a statement Genius folder. o that is easily readable. For controlling the motor speed. I have entered the "pause 10” statement, and -p 1 Stepper Motor Control - Turn the o Bipolar Stepper Motor this statement’s value can be changed to alter the 1{$STAMP BS2> speed of the motor. 1 started with a delay of 100 ■ {$PBASIC 2.50) msecs (using the “pause 100” statement), and the ' Variables motor 1 used made a lull revolution in two or three u MotorDIRS var DIRS.NIBO MotorCtrl var OUTS.NIB0 seconds. With a 10 ms pause, the pointer glued to the i var byte

312 153 Robotics Experiments for the Evil Genius Table 16-3 Characteristics of different motors used in robots Experiment 117 — Stepper Motor Control

DC Motor Steaoer Motor R/C 5ervo

Size All ranges All ranges. Generally small robots.

Torque Fair to good depending on gearing. Very good. Also will hold position well Good. High torque servos available.

Battery Good. PWM can be used to lessen Poor. At least one coil energized a? Fair. Servo electronics can require consumption current consumption. any time. relatively high current while motors idle.

Speed Fair to very good depending Fair bin usually good enough for Poor to fair but usually good enough on gearing. robot applications for robot applications. base of Can be difficult.There are Fairly easy Stepper motors often Very easy Servos can be mounted physical some kits (notably by Tamiya) have mounting tlanges to facilitate using cither two-sided tape or lugs installation that can make installation of bolting the motor into the robot. buill into servo case. in robot DC motor and drivetrain easier. base of Easy to difficult depending on Quite easy. Fair Implementation of timed pulses controller requirements and controller. for the servos can be difficult, programming Can be very difficult to implement especially if servos do not maintain PWM m some controllers. current position il no pulse train sent:

Fase of Odomotry sensors must be added Faeh change in coil values results (biometry sensors required. position to robot. in an easily determined robot measurement movement.

Scalability Good, larger motors (with different Very good. Motors and drivers can Very difficult once robot is larger than drivers) can he used for "grow ing" be changed easily with little impact what the standard servos can drive applications. to software. easily.

Hazardous Poor.Chance of arcing/sparks within Very good. No changing connections Good it cases have gas-tight seals, environment motor make DC motor not m motors. usage recommended for this type of application?.

Gist Low although drivetrain and Moderate. Note that stepper motors Low to high. Low-cost servos are gearing may be costly. are normally geared so drivetrain competitive with other motor solutions, gearing normally not required. but do not have ball bearing outputs. metal gears, and other features desired for robot applications.

Spt tion Sixteen Ncbile Robots 313 w ■H

38 kHz Oscillator

Figure 16-31 IR '■erialcommunications Figure 16-33 .Asynchronous circuit

Section Sixteen Mobile Robots 315 Experiment 118 — Infrared Two-Way Communications when dataisbeingreceivedbytheIRR/Creceiver. sent (andexpected)bytheBS2.Secondly,thatIhave copies otthisbooktogettwoPCBs,bygettingasim¬ somewhat unreasonabletoexpectyougettwo “Master Comnis:! from thedebuginstatement.Savethisprogramas at oneendwitha9-voltbatteryandclip.The555 ple. longPCB,youcanrepeatthewiringwithaBS?. for boththemasterandslave).Althoughit's book PC'BsthatIhadonhand(thecircuitisidentical output Thiswasdonetogiveavisualindication put a470IfresistorandvisibleLEDontheIRR/C's chronous dataissentfromIheBS2,thelED'soutput This positivevoltageismodulated,sowhentheasyn¬ infrared pingpacketwithacharacterthatyouenter up withthefollowingprogramtosendoutan 74LS74 arepoweredbythe5-voltregulatoron receiver producesalowvoltageonitsopencollector features inthiscircuit.ThefirstisthattheIRR/C BS2. line whendatacomesinthatisidenticaltothesignal is alsomodulated.Youshouldbeawareoftwoother With thehardwaredesignedandinplace,Icame When Ifirstbuiltthecircuit,usedtwoprototype Flag varbit Retn varbyte(5) Serialln Pin0 SerialOut Pin4 BS2 j varbyte i varbyte j\l] i\l, strj\l,cr] NoResponse: ' Initialization/Mainline ’ {$STAMPBS2> ' Variables ' {$PBASIC2.50} ' MasterComms-Send."Ping"toSlave ' UseFlagtoIndicateResponse ' IndicateDataFound [WAIT("ACK"),str Retn\5] ' Timeout-NoResponse do high SerialOut pause 50 debug "SendingCharacter’stri\l. debugin stri\l Hex $",hexi,cr Flag =0 serout SerialOut,3313,["Ping",str j =iA$f Flag =1 serin Serialln,3313,1000,NoResponse, serout SerialOut,3313,[stri\l,str 1 ?3Robotics Experiments fortheEvil Genius accordingly. of thePBASIC“serin"statement sWAIT"and operations simpler,notethat Ihavetakenadvantage rupted. itprintsoutanerrormessage.Tomakethese no responseisreceivedwithinasecondordatacor¬ XOR operator)asachecksumInMasterComms,if grams. notethatwhenIsendadatabyte,followit responds withan“ACKY”messageandreturnsthe the following“SlaveComms”programandresponds “TIMEOUT 'parameters. by its“Escomplement”(eachbitinvertedusingthe byte passedtoitafterincrementingit.Inbotlipro¬ This applicationwaitsforan"ACK”messagefrom Slave Comms,ifthepingisreceivedproperly, received", cr k\l, stri\l,j\l,cr] Serialln SerialOut then k\l, stri\l,j\l,cr] str j\1,"'",cr str Message\3] ' Variables ' BadMessageReceived ' Initialization/Mainline 1 {$PBASIC2.50} 1 {$STAMPBS2} 1 SlaveComms-Respondeto"Ping" do high SerialOut loop loop else endif endif else pause 75 if (Flag=0)then if (i=j)then i =Message(0):jMessage(1)A$FF serin Serialln,3313,[WAIT("Ping"), j ="N"A$FF debug "NoResponsefromRemote",cr endif else k ="N"A$FF k ="Y"A$FF if (Retn(0)="N")and(j serout SerialOut,3313,["ACKN",str serout SerialOut,3313,["ACKY",str j =iA$FF i =+1 debug "ResponsetoMessagewas' debug "Messagenotproperly j =Retn(2) var byte var byte(3) var byte var byte Pin 0 Pin 4 1 found that with this simple setup, the two BS2’s to have a direct line between the transmitter and Experiment 118 — Infrared. Two-Way Communications could communicate successfully across the length of operating receiver. This shouldn’t be a problem by my basement. I Suspect that in the real world, you putting LEDs and receivers in parallel (the open col- may want to have multiple IR L EDs and 1R R/C Iccloi output of the receivers makes doing this quite receivers pointing in different directions in an effort simple).

Section Sixteen Nobile Robots 317 Section Seventeen Navigation

One ot the most difficult things to implement with a Greenwich in Great Britain, and latitudes increase in mobile robot is giving it the ability ot knowing where number as you travel to the east, each unit of latitude it is Robots do not naturally have our capability of being one decree. Latitudes are concentric circles being able to look around and find out where they starting at the equator (zero longitude) and extend are. Humans naturally develop the ability to sense ing to the poles as either north longitudes or south where they are relative to other objects using sight longitudes to a maximum value of 90, and they are and sound. When you first look at adding this capa¬ given the units of degrees like latitude. bility to a robot, you will probably be stumped with Early navigators found their position on the Earth no idea from what direction to attack the problem. using three tools. The first was to use a very accurate Anytime you are faced with a problem that you don't cloek (called a chronometer) kept at Greenwich know how to solve. I recommend that you look at sit¬ Mean Time or Zulu l ime (“Zulu” being the phonetic uations where people have solved similar problems name for the letter “Z,” the first letter of zero). To historically. find the current latitude, when the sun reached its I am saying “historically” because with the advent highest point in the sky (noon), the current time was of technology, we rely on very technologically com¬ recorded and the latitude was calculated as the differ¬ plex solutions that can be difficult to implement in a ence between when noon took place at Greenwich small robot. An example would be using the Globa! and when it took place for the navigator. Because Position System (GPS) satellites in Earth s orbit: they there are 360 degrees of latitude and 24 hours in a can be used for navigating a robot to within just a few day. then there are 15 degrees tor every hour of dif teet ( less than a meter), but they require an unob ference between Greenwich noon and local noon structed view of the sky and can be costly GPS is an The second tool was the compass. Aside from incredibly useful tool as it will return the current being important for keeping track of the direction of position (in terms of latitude and longitude a* well as travel, it was needed to determine when the sun was altitude) and velocity (with direction). Unfortunately. at its highest point in the sky Noon can be defined as GPS is somewhat impractical for the robots that you the time when the sun is m a direct line with the navi will start out working with Because GPS is a rela¬ gator and North tively new invention and people have been traveling all over the world for centuries, the question that you North Pole should be asking is, how did people do it without N Greenwich becoming lost0 lines of Latitude A situation where people, like robots, did not have E any reference points, vet had to navigate is on the Equator oceans. As you are no doubt aware, locations on Earth are specified by the use of latitudes and longi¬ Lines of Longitude tudes as shown in Figure 1? 1. Longitudes are lines South Pole that run trom the North Pole to the South Pole and are numbered from 180 to 180. Zero latitude is Figure 17 1 Earth mapping

319 Section Seventeen — Navigation the timerequiredtocalculateaircraft’sposition easy targetsduringtheday),andexpense the ofteninclementweatherbomberswouldhave gets inEuropewasamajorproblem.Ibisdueto with agreatdealofprecisionquiteeasily.As1have can beusedbyrobotsinthesituationlikeone1 because bythetimecalculationswerefinished, fiom readingthepositionsofstarswasaproblem that wereneeded.Evenifnavigatorsavailable, time requiredtrainingthethousandsofnavigators to flyin,theneedatnight(becausetheywere the threelightscanbeobservedeasily. actual positions,youcancalculateyourposition ing theanglesbetweenthem,andknowingtheir outside therobot'sexpectedmovementareaorenve¬ angles arerequiredtofindyourlocationinspace,This much simplerthanwhatisrequiredforactualnaviga¬ -- robot canonlynavigatewithinacertainareainwhich laid outthemovementenvelopeinFigure17-3. lope. Bycontinuallysightingthethreepoints,measur¬ have showninFigure17-3.Threelightscanbeplaced away fromactualpointtheEarthturnsabout. magnetic NorthPoleisasurprisinglylargedistance sky isusedwithknowledgeofthetimeatfireenwich which theangleofsunatitshighestpointm degrees withtheangleofIhesunwhenitisatits over (hehorizon.Longitudecouldbecalculatedasvu tilted withrespecttoitsorbitalplanearoundthesun. tion; 1haveignoredthefactthatEarth'saxisis is asimplifiedmodelforcelestialnavigationand and thedirectionofEarth’sNorthPole.Thismethod Along withthis,1havealsoignoredthefactthat highest pointintheskysubtractedfromit. 320 Figure 17-2Shipmapping The useofthreetoolscanbeseeninFigure17-2. In WorldWarII,navigatingbomberstotheirtar¬ From thisexample,youcantaketheideathatthree 13 3RoboticsExperiments fortheEvilGenius similarly inarobotbymovingitfromobjectto or hernavigate.Thismethodcanbeimplemented ous headingasshowninFigure17-4. the transmitterbehindthemwhileflyingatacontinu¬ to identifyobjectsinfrontofthepersonhelphim tion withintheroom.Acaneisusedasatouchsensor black lineonthesurfacetheyrunthatissensedby were setup.andthebombersinstructedtokeep already aboardthebombers,powerfultransmitters inspired. Usingradio-direction-findingequipment made. Thesolutiontothisproblemwasquite away fromthepointwheremeasurementswere tries tofindthemhelpunderstandhisorherloca¬ rather thantryingtoavoidobjects,theblindperson a blindpersonwalksthroughroom.Inthiscase, an infraredLEDandphototransistorcombinationas the bombercouldconceivablybeagooddistance I showedearlierinthebook. Figure 17MBombernavigation Figure 17-3trignavigation Another methodofnavigationistakenfromhow Robots canuseasimilarsystembvmarking Light 3 Light 2 Experiment 119 Lin e-Following Robot as shown in Figure 17-5. Normally, the robot's object Object 2 sensors are used to help it avoid objects, but in this ODject 1 ( ) case objects are actively searched out. a complete reversal of the purpose you would expect for the O object sensors. Many other historical methods of navigation can be used in a robot. In the previous examples. I did not menlion dead reckoning, in which the direction of Robot with Noncontact movement is known, as well as the speed of move¬ Object Detectors ment and the length of time since leaving a known point. To get the current position, the lime is multi¬ Figure 17-5 Blind object detection plied by the speed with the product being the dis¬ tance traveled.

Experiment 119 Line-Following Robot Tool Box

Assembled PCB with Wiring kit breadboard and BS2

DC robot motor base with four-AA-battery clip and switch

Two Opto-Interupt.ers mounted on sheet, metal from experiment 48 with infrared Optoint- errupter halves glued to it

LM339 quad comparator

Two ZTX949 NPN bipolar transistors

Two XTX749 PNP bipolar transistors

Two LEDs, any color

Two 100k resistors

Six 10k resistors

Two 470 il resistors

Two 100 SI resistors Two 10k breadboard-mountable potentiome¬ ters

Twenty-two-inch by 28-inch white Bristol board with path marked on it (see text)

I’ve tried not to repeat experiments in this book but I each wheel would be controlled by a sensor on its would like to revisit one case, and that is the line-fol¬ side. When the sensor detected white underneath it, lowing robot that 1 first presented in the “Optoelec¬ the motor would be turned on. and when the sensor tronics” section of the book. In this experiment. I. detected black, the motor would be turned off. Fly- created a simple methodology for following a line: doing this, it a sensor on one side detected black

Section Seventeen Navigation 321 beneath it. the robot would turn away from the black lalile 17-1 LUall-folloujing robot logic truth section by shutting off that motor until it was back in table the white. \\ ith a bit of work, you probably came up with a set of values that worked for your robot, and it Lett Right Left Right ran over the path quite well except in one case: when Sensor Sensor Motor Motor both sensors arc over a black section of the path. In White (1) White (1) On (1) On(J')

this case, the robot would just stop there.The solution White (1) Black (0) 0*0) Off (0) to this problem is actually quite simple: If both sen [thick (0) White (1) Off (0) Oh (1) sors are over black, then the robot should move for¬ 4-> Black (01 Black (0) On (1) On (1) O ward until one of them is over white, at which point XI the robot could turn to the sensor that was still over black, hopefully center itself, and continue going over 0 This could have been implemented using a single the path The problem with implementing this strategy 74C00 (Quad dual-input NANI) gate), but I decided & back in the “Optoelectronics" section was that l had to use the BS2 to implement this function instead of not yet discussed the concept ol digital logic and deci¬ using digital logic.The reasons for going with the BS2 sion making, so 1 had to go with this simple strategy. were to take advantage of the delay (“pause”) and With digital logic, I could have created a truth pulse width modulation (PWM) functions built into •H table in Tahlc 17-1 to plot out how the robot should the controller, as well as its easy programmability to $ move. allow for smoother and more accurate operation. o In the table, I have assumed that when a “1” is The BS2-based line-following robot takes advan¬ r—4 returned, the sensor is over a white part of the paper, tage ol the two optointerruplers mounted on a piece rH and a “0” indicates a black. Using this table data. 1 of sheet metal that you made back in Experiment o could have determined that the left motor would be #48. along with the sheet of Bristol board that you controlled by the formula: Ua marked up with a simple path tor the robot to follow. I The circuit that I used for this experiment uses the Left Motor = '.('.Lett Right)

Right Motor = l (Left '.Right) tested the function of the optointerruplers (by plac-

I ON

4-5 a 0) 6 •H U a) a* x ui Figure 17-6 Line following circuit

322 123 Robotics Experiments for the Evil Genius ing them over a white and black sheet of paper and high LeftMotor: high RightMotor pause 100 seeing the LEDs light when they are over the black), loop you are ready to lest it out with the following pro¬ Lake the original line-following robot, you are gram: eriment 119 — Line-Following Robot going to have to adjust the “Run” and "Stop” times

' Line Follower - Follow the Line for best performance. One nice feature of using the • {$STAMP BS2} RS2 is that you can take advantage of the PWM com¬ •{$PBASIC 2.50} mand built into the PBASIC language. After spend¬ 1 Variables ing a bit of time experimenting w ith the different on LeftSensor Pin 11 RightSensor Pin 10 and off values, I found that I could run my robot LeftMotor Pin 1 RightMotor Pin 0 around the ring at about twice the speed as the origi¬ nal I M339-based robot with much better accuracy. ' Initialization/Mainline high LeftMotor: high RightMotor When you tun the robot, you might notice that the input LeftSensor: input RightSensor do robot bounces back and forth depending on the if (LeftSensor = 0) and (RightSensor = amount of torque available when the motors stop 1) then high LeftMotor and start. In my own case, I found that 1 had to add else another castoi to the front of my robot to prevent the low LeftMotor endif front from “diving” down when the robot paused and if (RightSensor = 0) and (LeftSensor = incorrectly sensed the lines in front of it. If you don’t 1) then high RightMotor w'ant to do this, you can add to the pause time ’ Stop the Right Motor (decreasing the overall speed of your robot) to allow else low RightMotor the robot to slop bouncing before the next time the ' Else, Right Motor can Run endif infrared sensors are polled. pause 50

Section Seventeen Navigation 323 o CM w *H £ r- o rs CD o 7* right wheel stops and the left wheel turns. When both Experiment 120 — Wall-Following Robot sensors detect an object in front of it. the right wheel reverses and the left wheel turns forward to tightly turn the robot away from the obstruction. I call this motion a “waddle;” the reason why will become obvi¬ ous when you see the robot in operation. Earlier in the book. I introduced you to the Sharp GP2D120 IR object detectors and showed how they could he used with a comparator and a voltage dividing potentiometer to indicate when there was an object at a specific distance from it. By gluing on two of these sensors to the leftover sheet metal mounting Figure 17-8 Front of wall-following robot with plate that you made for the line-following robot (Fig¬ Sharp GP2DI20s glued to a sheet metal mounting ure 17-8), you will have noncontact object Sensors lor plate attached to the from of the robot your robot that can be used foi normal operations, such as solving a maze or following a wall as I show m this application. Because of the weight and awk¬ When writing application code for the servo base, wardness of the wires, you will have to clamp the it is important to iemember that the left wheels turn GP2D120s to the sheet metal while the glue is curing: in the opposite direction of the right wheels when the Tfie actual circuit for implementing the line-fol¬ same pulse train is passed to it. For this reason, in the lowing robot is quite simple (Figure 17-9). I chose to PBASIC “wall follow' application that follows, I have use the servo base for this experiment,but the DC defined pulse values for moving forward and back¬ motor base can be used just as easily. The only sur¬ ward for each servo. prise that you should be aware of is the connection of the GP2DI20's power to the four-A A-battery clip ’ Wall Follower - Follow the Perimeter of a Wall (which also powers the servos) because I found their ■{$ SIAM? BS2} current draw was more than the 5-volt regulator on ' {$PBASTC 2,50}' the BS2could handle. ’ Variables

9-Volt Battery

10k Potentiometer

,► Resot

1/4 LM339

10k tw/ Potentiometer

Four "AA’ Battery I

Figure 17-9 Wall-following circuit r-l CM Wk O X Ultrasonic Distance Meas. silent running”andthecaptain(ClarkGable,Cary want towatchforamistakethatisverycommonly over thesonaroperatoraskingifdestroyerthatis Grant, orsomeoneelseoftheirstature)ishovering made inthem.Whilethesubmarineis“riggedfor distinctive “pinging”soundthatisusedinmoviesto attacking themisleavingthearea,youwillhear If youareafanofoldsubmarinemovies,might embarrassing becausethesubmarinewouldnever send thesesignals—instead they wouldbeproduced indicate thesub'ssonarisworking.Thisactually 326 signals toreturnandthedirection theywerecoming destroyer, itwouldthenuse the timeittookfor Once thereflectedsoundwaves werereceivedbythe by thedestroyerasitscanned theoceanforsub. Two 0.01|iFcapacitor,anytyp.e 2.2k resistor T^I-iS'M DualDflipflop 1 fxFcapacitor,anytype 1,000 jifelectrolyticcapacitor 10k resistor RightBackwards RightForwards LeftBackwards LeftForwards RightServo RightSensor LeftSensor i LeftServo 500 ' Initialization/Mainline do Right Fon'/ards=1000:RightBackwards LeftForwards =500:LeftBackv/ards1000 input LeftSensor:RightSensor low LeftServo:RightServo if {LeftSensor=0)then IE 3 Robotics Experiments for the EvilGenius Ultrasonic DistanceMeasurement var var var var var Assembled PCBwith Pin Pin Pin Pin Polaroid 6500Ultrasonic 7 4LS123DualOneShot Unit Distance-Measuring breadboard andBS2 word word word word byte 0 1 14 15 Experiment 121 detect objectswhenmodulated lightisreflectedoff pick themup.andbymonitoringthewatertempera¬ them. Ultrasonic “sonar"work*-inthesame wayand and phototransistorshow theycanbeusedto be reflectedawayfromthe submarine. destroy it.AsanyTomClanevreaderwouldknow, the submarinetodropdepthchargesinaneffort w herethesubwas.itwasthenaracetomoveover depth itwasrunningat.Oncethedestroyeridentified ture andsalinityfsaltcontent),thesoundwavescan they areattenuatedbelowthemicrophone’sabilityto ple; soundwavesinwater,onlytravelsofarbefore the gameofsearchingforasubmarineisnotthissim¬ from toidentifywherethesubmarinewasandwhat Tool Box Earlier inthehook,Iintroduced youtoIRLEDs loop pause 100 endif endif else if {RightSensor=0)then next next for i=0to5 next for i=0to5 for i=0to5 pulsout RightServo,RightForwards pause 18 pulsout LeftServo,LeftBackwards pause 18 pulsout LeftServo,LeftForwards pause 18 Wiring kit •Six-volt lanternbattery (see text) can be easily added lo your robot.The most popular lahle 17-2 Polaroid b500 poiuer and control Experiment 121 — Ultrasonic Distance Meas. device used for this purpose is the Polaroid 6500 wires Sonar Ranging Module (Figure 17-10).This module has two primary issues that you should be aware of il Pin Labpi Function/Comments you would like to use it in your robot: it takes a bit of 1 Ground (Gild) work to interface to a BS2, has a very narrow field of 7 BLNK When driven high, any reflected view, and requires a lot ot power to operate (1 amp signal is blanked out. while the ultrasonic pulses arc being transmitted). 4 INIT Driven high lo initiate sonar rang¬ The first concern is somewhat alleviated by desol ing. When INIT is driven low, the dering the connector that comes with the 6500 and operation of the 6500 stops, even if an echo has hot vet been adding individual wires as shown in Figure 17 10.This received nine-pin connector has six signals that you will have 7 Ft 'HO Open collector signal held low to be familiar with if you are going to interface to the until reflected signal received module (see Table 17-2). 8 BINH Driven high lo disable 2.58 ms Normally, the 6500 vv ill have power connected to it internal masking with ‘BLNK and “BINH” tied to ground with 9 Vec 4 5 to 6 4 volts, with up to I amp "INIT ’ tied to a output driver and “ECH()" pulled drawn. Should have 1.000 pF capacitor across il and Gnd up and connected to a receiver. Figure 17-11 shows normal operation ol the 6500 with IN 11 driven high and ECHO going high upon the reflected pulse. To find out more information about the Polaroid 6500 Sonat Ranging Module, you can download its datasheet from the Internet by first doing a Google™ search on it.The 6500 was originally designed for use as a camera’s range finder (point the black and gold transducer at the subject to find its range). Tliis was an excellent application for it as ultrasonic sonar modules have ver> narrow fields of view (the 6500 is most sensitive for the four degrees within perpendi¬ cular). but one that can make them somewhat diffi

Figure 1711 Ultra echo

cult lo use in robots. A possible solution is to mount the sensor on a servo driven “turret. ' By swivelling the turret, the sonar distance sensor will give you bearing and distance to the objects around the robot. Using the distance and angle information, the position of the robot can be fairly easily determined; the complexity of the mechanical installation of the sonar range finder and the data that is returned is why I consider it ft' be a navigation too) and not a sensor. For the range finder to be used as a sensor, it would have to scan the area around it continuously, Figure 17-10 Polaroid 6500 Sonar Ranging and to do it effectively, this would significantly slow Module with standard connector removed and breadboard wiring added down the movement of the robot.

Section Seventeen Navigation 327 UA 2 ' Setup Hardware for Pulse Read Experiment 121 — Ultrasonic Distance Meas. high InitPin ' Output to Cause 150 ms Pulse pulsin FlightPin, 0, SoundFlight if (SoundFlight <> 0) then debug "Time of Flight is ", dec SoundFlight *2, "ms”, cr Soundln = SoundFlight / 153 SoundFt = Soundln / 12: Soundln « Soundln // 12 debug "Distance from Sensor to Object ”, dec SoundFt, ., dec Soundln, rep 34\1, cr endif low InitPin Pause 1000 Figure 17-13 Sonar waveform loop

To finish off the discussion on different types of Soundln var word object detectors, I have summarized the three pri SoundFt var word mary methods (whiskers. IR proximity, and ultrasonic ' Initialization/Mainline low InitPin ranging) used by robots in Table 17-3. It is important high InitSetupPin to note that there is not one method that will be opti input FlightPin mal for all applications (unless you lightly control the do environment the robot is operating in). pulsout InitSetupPin, 10

Fable 17-3 Different abject detection methods used by robots

Object Detection Method Rdvantages Disadvantages Comments

Physical whiskers Detects all objects Easily damaged Best for "worst case" collision detection Inexpensive Require constant attention Best designed with robot's Variety of different ways to Require software debounce mechanical design manufacture Limited range may result in damage to robot

Potential for static electricity charge build-up Generally small field of view

Infrared proximity Reliable Difficult to get range of object Good general purpose object detection mechanism Relatively inexpensive May be difficult to set up hard¬ ware/,software for detector Can be built on eteeljronics No debouncing required PCR or put remotely on Wide field of view may pick up Prepackaged modules avail robot objects that are not dangerous or able interesting to robot Wide field of view

Ultrasonic ranging Reliable Requires large amounts of power Often most difficult method to get working Narrow field of view allows Limited field of view requires "plotting” of objects around sonic method of scanning to find Should only be considered robot all nearby objects lor advanced robot applications Most expensive option

Section Seventeen Navigation 329 Experiment 122 — Hall Effect Compass semiconductor isknown,notsurprisingly,astheHall effect andisoftenusedinrobotstoimplement defected andpassedtoanothersensor. operating onit.thecurrentpassesstraightthrough piece ofsilicon,anditnoexternalmagneticfieldis operation, thisdevicepassesacurrentthrough aware ofistheHalleffectswitch(Figure17-14).In If thereisamagneticfield,thenthecurrent numbei ofusefulrobotcomponents. thought ofwhenthetopicrobotsisdiscussed.Iam ments. circuits,andstructuresthataren'tgenerally them inanontiaditionalway,lookingforexperi¬ senting thedifferentparts,Ihavetriedtopresent should beabletocomeupwithauniquerobotdesign bringing thisupbecauselhavenotyetdiscusseda required andspecifytheparts.Secondly,whenpre¬ on yourownandchoosethemajorsubsystems theory andpracticeofverybasicrobotcomponents. used twopiimarycriteria.I'hefirstistolookatthe In choosingtheexperimentsforthisbook.Ihave 330 Figure 171M Hull effectswitch Io alargeextent.Ibelieve1havesucceeded.You Current Sensor Current Sensor Nondeflected This magneticdeflectionofcurrentthrougha One ofthemoreusefuldevicesthatyoushouldbe Deflected Current , Magnetic Path Inside Field 12 3 Robotics Experiments for the EvilGenius Assemble^ PCBwith Two 47kresistors Two 3,3Mresistors LM324 quadop-amp Two HAL300UA-Edifferen¬ Magnet breadboard effect switches tial outputhall - ~-pCurrentSource Current PathIf No MagneticField Silicon Hall EffectCompass Experiment 122 times. Thisop-ampapplication isexcellentforsitua- amplification ofthedifferential signalofabout700 south wasofgreatimportance.1havealwayswanted to tryoutthiscircuitseehowwellitworksinrela¬ experiment usingtwoHalleffectswitchestoindicate tion torobots.Thecircuititselfisverysimple(Figure navigation, knowingwhichdirectionwasnorthand As ldiscussedatthestartofthissection,forearly away inmyfiles,lookingfotanopportunitytouseit sheets. Iphotocopiedthedatasheetandtuckedit which directionissouth.Ioriginallydiscoveredthis switch istheonethatIamgoingtoshowyouinthis 17-15) andwilljusttakeyou atewmomentstowire. application inabookofTexasInstrumentsdata formats (suchasopencollector/drain,totempole,or signal pinprovidesoutputinavarietyofdifferent field. indicate thepresenceofa“SouthPole”magnetic analog output).Generally,Halleffectswitcheswill switches aieveryoftenusedinautomotiveantilock odometry. Ratherthansettingupanoptointerrupter. negative voltagepin(ground),andasignalpin.The package, withapositivevoltage(powerin)pin,a require anycleaning,asanopto-interrupterwould. netically actuated,theyareveryrobustanddonot braking circuitsaswheelturnsensors—beingmag¬ rotations usingaHalleffectswitch. magnet ortwotoawheel,gear,axleandcountits as 1didearlierinthebook,youcansimplygluea Tool Box Using thespecifiedresistor values givesmean An interestingapplicationfortheHalleffect Most Halleffectswitchescomeinathree-pin Wiring kit DMM After wiring the circuit, 1 tested it out to see how Experiment 122 Hall Effect Compass effective it was in determining north and south. In my house, the circuit did not produce any kind of notice¬ able change when 1 turned around. Going outside, 1 found that the circuit would repeatedly show an out¬ put voltage of 1.86 volts when the end with the bat¬ ten was pointing toward north, and this would drop to 1,83 volts when the circuit was turned in any other direction. lbis is a difference of 1.6 percent, which would be very difficult to observe within a simple computerized circuit.

Figure 17 lb Compass circuit I would have pursued the compass circuit (and looked for different or more efficient 1 lall effect sen¬ sors) except that the compass output, once the rota¬ lions like this one where the difference between two tion of the circuit stopped, took 15 seconds oi more signals is to be observed. to settle down into a constant value. Along with this Before coming up with an interface to the BS2.1 long time, I found that the range of north was about wanted to test the operation of this circuit. It consists 15 degrees, much too wide to be accurate for any of two Hall effect sensors turned in opposite direc¬ kind of practical robot. tions and their (differential) output greatly amplified Along with these issues. 1 also wondered how using an op-amp. When the Hall effect switch con¬ effective the compass would be on a robot chassis nected to the positive input of the op-amp was point¬ with magnetic devices, many of which produce fields ing directly south, its output was at a maximum, that are larger than the Eat til’s magnetic field. You whereas the op-amp pointing north was at its mini can test this last supposition by moving a permanent mum output. Hie differences in the output would be magnet close to the two Hall effect switches. very small because of the i datively small \alue of the SO in conclusion, the electronic compass circuit Earth's magnetic field that this circuit is detecting. By that I have come up with here does not provide a sig¬ passing these voltages to the inputs of an op-amp. and nificant enough signal to be easily measured, the amplifying the difference between them, the circuit range in which it would indicate north is larger than should be at its highest voltage when the positive would allow effective navigation, and the output set¬ input 1 lall effect switch is pointing south and the neg¬ tling time is very long. ative input Hall effect switch is pointing north

Section Seventeen Navigation 331 Experiment 123 — NMEA GPS Interface stand howitisdone. computer andtherewasaneedforthemtocommu¬ tronic computerswhentherewasmorethanone you justhavetogothroughitatleastonceunder¬ 232 connectionbetweentwocomputers.It’snothard: of graduateengineersthatIgeltoworkwithwho puter systems,I’malwaysdiscouragedbythenumber did notshowtheRS-232electricalinterfacethatis,bv have neversuccessfullyimplementedtheirownRS- far, themostpopularwayofconnectingtwocom¬ return toZero(NRZ)serialcommunications,andyou ous section,IintroducedyoutotheconceptofNon¬ will haveanopportunitytoworkwith.Intheprevi¬ presenting toyouwhat1considerbethemost important computer-to-computerinterfacethatyou euits) sotheiroperatingparametersweresomewhat not builtfromtransistors(letaloneintegratedeir nicate withoneanother.Theseearlysystemswere have beenusingRS-232toprogramtheBS2,but1 332 would probablywanttouse 5 voltsforcommunica¬ unusual comparedtotoday’scomputers.Today,we ally thepaththat wastakenwiththefirstcomputers, other withjustsomelogicgates tobuffer(protect tions andlettwocomputersystems “talk”toeach and repower)thesignalsbetween them.Thisisactu¬ RS-232 goesbacktotheveryearlydaysofelec¬ Before endingthisbook,1realizedthatImissed 12 3 Robotics Experiments for the EvilGenius Twenty four-gaugesolid Maxim MAX232RS-232 Twenty-four-gauge solid Twenty-four-gauge solid Five 1.0fiFelectrolytic GPS unitwithRS-232 Assembled RGBwith Solderable 9-pin"Male ■core redwire core greenwire D-Shell connector core blackwire cap acitors breadboard andBS2 interface chip interface NMEfl GPSInterface Experiment 123 modem. I’mpointingthisout becausetherehadtobe modem; thiswasdonebyspecifying standardconnec¬ some wayofconnectingthe computersystemstothe municate overthephonelines usingadevicecalled systems tobeincloseproximity, sotheyhadtocom¬ 232 theywerenotinthesameroom;youmust tors withdifferent pinfunctions.Fheseconnectors are power requirements,itwasnotpracticalforthetwo is notanexaggeration.Becauseofthespaceand as muchelectricalpowerasmallsubdivision.This much spaceasahighschoolgymnasiumandrequired value goesbacktothefirstteletypes. current tobepassedbetweenthetwosystems—this -3 voltsto+3volts)wascalledtheswitchingregion, remember thatthesesystemsgenerallytookupas between thetwosystemsshouldneverbeinthis volt regioninbetweenthetwovoltageranges(from range, lhestandardspecifiedamaximumof20mA and thevoltagesofcommunicationspassing different.To facilitatesimplecommunications operating voltageswereconsiderablyhigherand between thetwosystems,voltagelevelof-3to levels. Theyusedvacuumtubesforlogic,andtheir but theydidnotrunwithsimple+5andgroundlogic +3 to+15voltsindicatesa“0”(orspace).Thef>- -15 voltswasusedtoindicatea“1”(ormark)and Tool Box When thefirsttwosystemswereconnectedbyRS- Wiring kit Solder Soldering ron known as D-Shcll connectors and were given a stan¬ For this experiment 1 would like you to create an dard wiring pattern, which exists to this day. Figure RS-232 interface between the book PCB and a X 17-lb shows the original 25-pin standard and the peripheral device. The peripheral device that 1 have newer 9-pin standard, which was created for personal chosen is & global positioning system (GPS) receiver *T5 computers. that can interface to other devices using the NMEA (D The connectors that are built into computers are 0183 communications standard. NMEA comes from h male (which means they have pins, as in the photo¬ the National Marine Electronics Association and is H’ graph of the connector in Figure 1716), and are an RS-232 connection tunning at 4800 bps and trails B known as data terminal equipment (DTE) connectors. ferring navigation data as a scries of "sentences.” You (D are probably familiar with GPS: it is a number of Modems have the mating (female) connectors, which 3 are known as data communications equipment satellites in orbit around the Earth that provide sig¬ Ct (DCE). DTE (namely personal computers) generally nals to help aircraft, boats, and motor vehicles to

uses straight-through connectors to connect them to navigate. 123 — NMEA GPS Interface modems and other peripherals (like the PCB You can buy surprisingly sophisticated GPS included in this book). receivers such as my Garmin eTrex (Figure 17-17) for If you look around on the Internet or read some just a few hundred dollars. When choosing a GPS introductory texts on RS-232. you will see some receiver, you should be looking for its ability to com pretty strange circuits used to allow a standard 5-volt municate with other systems via NMEA 0183 (RS- (or 3.3 volt) circuit to interface with an RS-232 line. 232) and transmit both position (GPS) as well as These circuits will work anywhere from most of the heading (compass) data. Depending on the amount lime to some of the time, with your ability to figure of money you have to spend, along w ith features like out communications problems being very limited. To position (returned as latitude and longitude) and avoid the problems of trying to debug RS-232 fail¬ compass heading, a GPS unit can provide you with a ures in circuits that have taken shortcuts with voltage moving map display, showing you exactly where you levels. I am going to recommend that you avoid these are and where you arc headed. circuits and use something like the Maxim MAX232 The NMEA “sentences” Consist of data in the fol¬ to provide you with an RS-232 interlace that oper¬ lowing format in Table 17-4. ates at the correct voltage levels. The MAX232 is a The NMEA data may look like garbage and is very common and popular chip and is actually quite always coming in at a rate (each sentence is sepa easy to wire into a circuit. When you are buying the rated by a 0.8- to 5-second pause) that you can't han¬ chip, you must decide between the MAX232 (which dle. but it is quite easy for a controller such as the uses 1.0 pFcapacitors) and MAX232A (which uses 0.1 m-F capacitors). Most people go with the original MAX232 because 1.0 |xF electrolytic capacitors can be purchased quite inexpensively.

Pin Name HPin TPm LO Direction TxD 2 3 Output (E) "ExE 3 2 Input (1) OB-25 (Male) n-9 (Male) 7 5 1 7 O TT5 5 8 1 "CTE "25 T "C "ESE 6 8 1 T5i 22 8 i "5 i i

9 Pin Male "D -Shell’ Connector

Figure 17-17 The Garmin eTrex provides position and heading information via an NMEA interface as Figure 17-16 RS-232 connectors well as a moving map display.

SeLtion Seventeen Navigation 333

A Experiment 123 — NMEA GPS Interface compass headingisthefollowing: folder intheEvilGeniusfolder: (which canbeseeninFigure17-17)usingthefollow¬ ing informationfromit.TTiesentenceformatforthe NMLA datastreamandextractsthecompasshead¬ simple BS2applicationthatmonitorstheincoming ing application,whichshouldbestoredintheRS232 mation fromit. Table 17-4NMER0183communications Figure 17IKandextractedfromthestreamotdata BS2 tointerpretthedataandfindsomeusefulinfor¬ "sentence" features Character ending 334 Sentence Data I ormatler I leader Identifier The finalexperimentotthisbookistocreatea It canbereceivedusingthehardwareshownin SerialOutput Pin1 Seriallnput Pin0 $HCHDG,Heading, ,,Deviation,W*0A,cr-lf ' Variables •{$PBASIC 2.50} '{$STAMP BS2> ' GPSReceiver-ReceiveDatafromeTrex L2d Robotics Experiments fortheEvil Genius 2-3 4-6 1. Characters Last two Position \ view/“HDG’-—heading commas. Differenttoreach feed ASCIIcharacters. Carriage returnandline Formatter. with deviation "GSV"—GPS Satellitesin Compass heading. • i =5 serin Seriallnput,188, loop i =-1 16 *220Ohm tVv'—RT "\AA~PT 0.1 O.i Fj4C2+Rlinf r-1 V-T1in^ }* 1R2irtR2out I T2outT2in* 4 C2-Rloutf Cl- TioutF V+ Gnd> C1+ Vccy MAX232

l/i

3 '£ SC < ^ bli SC * 2 C i SC a/

3 3 " ~ “ “ f * s 3 £ 3 — ■§ u eg as § ec in a® csai'csaic.caactD;^; 2 3 5's 5 «

3 = >">*>•>■>•>•>- E > 3 > > >

-2 « ■ sc as ® £ « g < < < ^ < 2 u « - » A v B a a , -j >i 3 a£ Q/2 V3 D r~\ «/ GC -y C = p cS— SO co Q/2 < U ?<<<<<<< ! <<<<<< < < <

• ox i ? o £ © X cs •*—> CO 0> £ X x ■*—i O ’5 ox> .£

o> 4c/3 *35 J3 C 3 O o & C/3 c l— cs o £ C/3 0> c _3 E CO >

■*— .u- o *E <4-4c X r~ C/3 '^3c '5 C/3 o *—» Q c c CO 3 U .3 CO £ = sa o t/3 G C/3 c 0> o 3 Lx

« jo1 u 2 y ~j. c. •= ,>■-. * H o c_ .•*- J2 ■? X-

£ "o u T3 — 5 o S -S. - .? > c. S c ■ 3 — y “ _: 5 £ "3 — 141 _ .£ “ js s! 5 g c w u. ez rt>. ^“ D“ o H X J c — o V) ©0 ^ N- —C T3’J i = X

2 1 c o c J a V S U O '!> s i g- 3 2 a> "3 2 x S C S?-o = .5c/> a>w DU — g s 5 | 3 < 3 3 £ c u u

« £ H 5 * S- S « ^ .2 d ■ii 2 _ 3 o ■£ o ^ •—3 3 ,

00 *0 5 1) U -a S rj 3 |T3 £a £c S r < t* -. T3 o ' G =3 O a.S -a£ p£ £ S S x a ^ ■£ SO *0 ?! > •5 ’-5 « Jo g S Xo.C v> X {-E xi3 >>£ *c JS z. & Jtsa X.>> O. 5 > .§ “f *3 _- ■t! r- X •0 § c S* « 5 o £ £ z 25

■d jg § X * a c. fj D <0 tr. .S3 >, 5 « “ -3 •~ i> —r ’'© -2 c x h x sC “ — c_ - # .22 *0 - 2 1 *5w *-» D3u Cl s* X U W *. X X »T« z | 5 Q nU CO -s. < 00 X SO 5 S £

337

•a O so c « o O O r-- 3 3 «Ti OX) X z aic [2‘ o -3 O X ^ 5/> E .£ o £ £ = e * 5/5 Im > o -o g 5/> c £ •II 52 5 C 3 g G w O X 3 — C ^ X v> Z x o e “O c 2 o 2 * .= “O i? o = r*- d -o 3 3 5 o _ o .2 v> c S •£ £ ftt X O £ sc Q £* e E so o SO i/1 — _, w> 3 ! o ft c. C ** yi 0 o T3 S G a 3 OX) yi ‘C 04 c * E O s d- y 0 Oj u O 3 l;s i s 2 .£ o x 0 ft G _c O O T5 _ •— E G C 3 ft G •“ y> *•’ •£ — ■g O 0 2 c dr ’0 ■>- X V. — E 5 £ 3 T3 g ~ ~ 2 O t « 3 S X wow o > •s sc SO £ G E C 5 5/5 ^ 2 1C- « 6 2 T £ - u. ~ M 2 i « J /. «:!_ .—1 ^ 5/1 o c > ri g j*> -5 v d J2 I— • — a 2 > ft G 3 O o O .— a c 22 ft. C- -12 3 0 3 3 -O c: — 5/1 ~ 2 _ o J= 2 §"3 2" o C Oj & G -51 o 3 X C OS'—' 2 13 X “O T3 6.5 i £ o 'U H.S X .2 a II — g o G E 111 G “O -3 oi ^ > V5 ra c o ‘C O o , 1 , 2 ° i! lj g § QC 2 & -5 5* ft- o —• £ £ £ -5 = a •£ G C

G o c yi 0 X o c O . « C O JD C c 'C G . O C X- G £ .3 c ,>. G — . - o 3 G > o w' cL G “ G C? ” "3 3 X G ^ l Sf* 0 G 2 a w ra > (A G .£ 0 c c ox, -£.— 3 C yi •-> OX) 3 ft i J s Cl 3 O y *c £ 3 _o 3 2 3 0 if Uj O c 8 I oil G G C/5 G G G O

c a. O 0 -O 0 3 E ■Si “O X O Oj o X «_ _. o O O 0 5/1 O O £ 3 y> > « ^ 1 £ Sf O is o c 21 3 ‘C J G W^ c2 O G > C 0 £ £ £ 5 G Q G C

C 3 o o o ■30^ vJ _ o X OX) . 3 G O 3 3 -0 -3 E •£ 5A G E c « o V yi X £ o o O 5 -= s J2 E s c 2 5 11 - s o «- „ 3 c ‘Z •C fe £ - ^ 2 X - o Ss D •§ "3 £ C Cl. S 2 O o ^ c -X O ^ VI u 3X^3 c 2 -3 a* 73 3 C T3 - 2 o a 5 O >3 1 2 8 | O, s ^ £ .25 X o w VI0 Q•” r- 3 ^ — 0 c « v 3 — 00 ■— £ - O X ^ « C c a = C -3 a 52 g >. *~ .£ £ o o X 3 if 3 T3 « g i 5 o ^ I 3 I X X 15-2 S= c S J2 o «. c C « S. £ G O z * A fs y 3 — qj •— Z. V> — 11 o o x '4 3 ts5 £ T-i V) -- —■ ’o X X 3 C *3. 3 o 3 A •a *f - k « — . OX) ^ g -s 3 «C r? O 0 a = 2 11 5/1 _ — U-i ■o “ 51 S’ £ ^ £ • O o o coo o •“; yi n 13 A o 3 o “ c X — o ^ £ -5 o ~ 5I? o G (j r-,1. 1 o •- o o £ a ^OO o c OX) ^ - -s OX) — o oC 3 JS 1- ys ^ 5 - ~D o .E C -T3 g »o 3 g ■3-je 6 2 o -5 O O ^ — r3 .2 s yi •£ G c 2 § “T /s r_ G ft *5 O O O C4 AS '— _3 yj y> ^ & E > 3: V5 2xo O — 11* 5 3O <—•O £ « £ o o 3 3 G y- o 3 * 2 ri « O w . £ £ y c 2 a 3 >.. P;5 £ £ -rj c .2 T3 ; ^ “O O VI x S. 2 22 ^ c c ■§ 'C 13 511 C 0 !_ O fl- c C -O 32 wO 1_£ 0“ > 3 3 — I ^ 01 3 OX) C S - c o G v- O e Qj 3 , O o o ~ *— ^ X S c .2 « ro 3 y ,1- c o __ o 5/5 “ o o E ^ G -O ^ T5 G*2 3 > x H o E G 3 e o £ ' o > 3 d c c > O — o/J 3 £ f“ « 3 5/1 3 u- y dJ 5 G 3 X O 3 O r.o tO Ti^ 57O 5.3 ci .9| G *- E 006 G o E v “E J2 — O o 2 £ c •— o I 8 9’ * O X 00^ 5)^0 H 04 o C3 o >< 5 o 7> o 3 2 O C- ^ i3 G ’“O OOO "O •II u -a £l Q ■£ £ DC F ^ •£ 3 Q O o £ s £ c e £ e G C

a £ ~5h : Hi c a 2' d - .0 c x ^ _ £ o£ G H o rft i; c c s *5 6- > ft Oh^ 2 5 T3 '3- I c c ft’ o 1- 3 3 y y_ u o C C a 'D -S ? JS •- oh “D -- ri/ -J x o o ^ d -O ?r ■= ti if,® tip Egg Uj £ C G ^ < o •— w T5 U W TJ r- —

C Oj & P — c 3 O Si £- 2 T3 I i 3 y ei, c 3 O 3 = I in I I C G X ~ if

339 Oft n 23 QJ 3 ^ = ? « o s | C/5 qj o X oj Lad .3 QJ s z C '» ^t > « .S « s c ”3 o. ■= o U Xi fM n E s 3 r QJ X O O ^ > H j y ^ ^ qj 2 2 y i ^ X U O .3 ' C/5 a 1 x E ^ 3 — 12 c/5 13 3 QJ 3 3 “or X X X cj 5" w •O 3 o P H ai QJ i 3 O — = n ° Oft «j QJ o> .£ 22 .a? a ! ^ l- 3 QJ Q. —* .2 5 .2? qj « Q> <0 X -3 -• I d > < 'So 3 •g E = 11 13 £ p — X 3 w. 3 | .2 *o .g O Oft iis 5 E~ s %_ 3 O E •£ E 73 a c 0) c SI2 a ? fiS cl 3 *r* o o -1 = U « • o £ Qu •H..2P 3 2 -5 ° oft I g 3-2 ■S' c S Oj .52 O O/j 3 111 QJ QJ n £ u_ O c 3* QJ n .QJ X E <5 ^ E - 2 «/> « C r c5 tE -3 c = 2- 3 _>> C3 •o •o-S^ 5 -o E £ 73 ~ *0 ^ •o ~ i? !l a | t w Xr >J s o x ~ E a £ 5 3° Q> S I ,i ® « o 5 ,3 *— C js £ -c X X 15 C- O n — C 3 _. .S OJ _ X c c o I 3 3 o S X ^ O 0 n « U & i QJ u. O n £ g 2 jj - V5 &£! "3 X o 15 O 00 QJ QJ in 3 ■S S t T. c X 5 0 3 X c •- 3 > X > c o 0 c x ^ -6 3 x *= X X 2 i y t. y £ *> K £ *5-. 3 O o X O QJ Oj "• !5 y 3 *5. g E o s :i vj 3 T3 ■/-. x V) x -| N J 3 ”2 I LU X QJ C 4-. 3 n 0 C £ MM cc 3 -* II n <5 Q> 3 0 .a - 2 ^ 3 3 — n cj U 3 QJ £ QJ Qi QJ rC - % > V3 CJ 3 QJ w QJ .O 3 3 X S C ft, *S n y a. QJ « S H § « 1 ‘o QJ X 22 a, .2 S- x o Cm "3 Oft ^ X -2 I _ x £■■£ L S c2 £ £ a o •3 t/5 C 2 E ‘o QJ E oft -o X 5 cL 3 r— c 2 S 5. S >. , u .2? 3 g « 3 n O o . o H 3 C X .a 8 n 1—I n '7, a. n ^ .— 3 c/5 w a s 3

c , n : s a C Qj' ?? Qj O. 3 *73 -X ’&<{ 2 3-0 £ . o 3 _ 2 0 a 1 a Z T E -T O - H= If *•" 2 x ^_ = 5 3 I 3 X TD Qj g ^ 3 .3 - 0] o j £- O 3 OJ B 5 .E E “ u. [1 m w £ .£ £ : - d. •? c x 3 ; Uj Scaith g^ay •s c n_i

c. Cj

6 Oj

rc Ln

QJ X Z — QJ — e Qj X o QJ 3 3 u S I 0 T3 X C 5 Of> 3 E « CJ QJ 3 3 — 3 iM E I O X QJ v) £ « 2 .5 « *u x s 1 X o e E 8 8 Q> 0- >' X X x QJ 3 o "O QJ C/5 Jg. i 73 ^ o > a x QJ C J5 c . i—» 3 'm qj X 3 V> 3 C QJ £ O E ^ £ ^ u •= "O £ H 3 X £ Cm X o n H cl LU 0ft ^ QJ ^ tC o O QJ QJ — Cu ^ LU 3 E ■- x X 3 s c — 3 *5 s 5 — x tr LU oft o.-* n ^ 3 y x 5§ ■£ > o 'M- ** s UrJ 0. a c .5 5 QJ *= <*m ^ QJ E 73 C. 73 — "p Qj QJ 3 ■— SLi.i O 2 ‘55 3 X - QJ 3 ^-v X X C/5 3 3 X QJ 3 3 X 5/3 cj « £ OJ c 3 >1 — Oft 3 0/5 X Oft § > *o Cm "3 LLJ g £ 3 Oft 55 l£ •= * 8 X ^ 2 o c 3 3 QJ C C qj n z a “ C c 3 *-* ^ 'S n “» QJ QJ o C W c 73 > QJ -2 > X _ X co oy « £32 X A X 3 ■“ CU-- 3 x X 5 x E QJ 00 3 E ^ n c 3 £ Oft 3 ■2 ^ 1 s. E o QJ 2 o CL 3 C x oj I 3 x 8 jS 3 QJQ> x C QJ - 15 •b S u QJ X 5 i ■ —• r~ > 1 E X « 5 X 3 Cm Hi -. •£ QJ c Sh <0 o 2 3 « }g S E g n -O ,2 | oc C X QJ 3 73 d r > Qj **- c '5 3 Oft 3 X • X 3 QJ E w. 3 "P_ X ; 1 i 73 2 x O ,n £ £ £■ c E X QJ C £2 QJ 73 w 73QJ 3 £ 3 u. QJ n n« c t— CP 3 3 ' * 'g =» £ V5 QJ '3 73 O U O 3 T3 a y Oft 6 3 X 3 c 3 QJ n « £ 73 flu H s. 3 Qj 3 3* QJ G. X 8 -g ri 1 5 QJ X 3 Lu 53 £! « — c 5 O u h 3 >1 u ^ U4 Oo qj 1 6 C OJ QJ 3 jn 3 3 o U4 5S O o .a i e c X

3

c X '5. X c .3 QJ C 3 c .2 5 '£ 3 1 b QJ 3 u. —T ^ CJ X ci - QJ £ 3 £ 7 f 3 a » n ; o / r* > E | X QJ £ 1 jc o 8 QJ fB •§ .2 E £ 1 a 3 * 5 ■= § C Cl x c ^ ■ ” 3 •c £ UJ E > a yo * 22 11 C- n

C E Qj O

E x O o p C Qj 2 CC

340 Acknowledgments

If anybody suggests that you write a book consisting started off as a robot workshop for Celestica, of a number of small projects or experiments, run and it has been a lot of fun talking about and away 'Ihis book, although very satisfying and fun, was planning robots for people to learn with I an awful lot of work. There is no way 1 could have hope our relationship continues for a long completed it w ithout the help and support of the period of time. following indi\ iduals and groups (and some others I've forgotten): • Ben Witz, who is a great resource for bounc¬ ing ideas off of and for discovering that my • The Tabrobotkit, Basicstamp, and PICList list great ideas are not unique (or often workable) servers. Normally, I am very active on these in any way. Over the years, Ben and I have lists, but as I got closer to (and past) my dead¬ worked together on three hobbyist robots and line, the time spent on these great resources 1 look forward to doing many more with him decreased, but I still spent a lot of time lurk¬ ing and learning.These three groups are prob¬ • Judy Bass is my long-suffering editor and I ably the best resources experts and novices appreciate her work with me on the unique alike can use to learn about robots, program¬ format for the book as well as her patience ming, and electronics. despite how tar past the deadline the manu script ended up being. 1 owe you a big lobster • Ken Gracey and the people at Parallax have dinner for putting up with me. been a great help and inspiration for this book. They have a great product line that they • My w ife Patience, who always lives up to her are constantly adding to and they arc commit name, and daughter Marya. who does her ted to customer support. I consider myself namesake proud. Nobody could ask for any¬ lucky to have received as much of Ken's time more support than I get from the two of you and support that I did. Their product line is so Even when smoke and curses are rising from good that if you watch closely you w ill find a the basement, I know that I can get a smile BASIC Stamp 1 in The X-F iles: Fight the and hug from you. Future movie. • Lastly, to everyone that has been involved in » My regular employer. Celestica. Although not the production of the many, many TV show's being a robotics company per se, it is an out¬ and movies I have watched for entertainment, standing technology company with the best inspiration, anil relaxation for a good fraction people in the industry. I am continually hum¬ of my life. You’re rarely right on how you bled by how much 1 don’t know and w hat have portrayed technology, but 1 feel like I am kind of resources the company has. a richer person for questioning, sneering at, and trying to reproduce what you’ve created. • Blair Clarkson and the people at the ()ntario Science Centre here in Toronto. The Centre

Acknowledgments 341 Index

Note: Boldface numbers indicate illustrations. oscillator code practice tool (transistor), 143 145. 144 piezo-electric crystal speaker in, 139-140. 139 public address (PA) systems and, 140 A sound level meter and. 148-150.149.150 stethoscope, electronic. 145-147.145 146 147 acceptors, semiconductors and, 92 actuators. 16 adder circuits. 166-168.166. 167 adhesives (See glues) B alternating current (AC), diodes and. 93 B52, PBASIC Reference Guide, 335-340 American Standard C'ode for Information bar magnet, 63 Interchange (See ASCII) base, transistor. 98 analog control (See also potentiometers; variable BASIC Stamp 2 (BS2) (See Parallax BASIC Stamp resistors), 50 2) analog voltage output PWM. 261 262,262 batteries. 59 62,84 AND, 133,152.152.154-155.154.164-165,164 169, effects of. in robot, 60-61,60 169,171 life of, by type, 61.61 PBASIC Stamp 2 (BS2), 237 nickel cadmium (NiCad). 59-60 sum of product circuits in, 161-162. 162 nickel metal hydride (NiMH), 59-60 applications, PBASIC Stamp 2 (BS2), running. rechargeable, 59-60 216-218,218 super effect in, 59,60 aim. cardboard, 10-13.10 11 1.2 bearings, 16 armature. 72 bending force, 20-22.20,21 arrays of variables. PBASIC Stamp 2 (BS2), 228-229 Berliner. Emile. 140 artificial intelligence, 267 beta, m transistors, 98 Artist robot. 305-308,306,308 bill of materials, in experiments, 13 ASCII characters,226-227,270 binary control (See also switches), 50 assignment statement. PBASIC Stamp 2 (RS2). binary numbers. 224-225 230-231 bipolar PNP transistor motor control. 102-103.162, associative law. logic, 165 103 astable oscillator, 555 timer chip and, 116 bipolar stepper motors, 311-313,311,312 astahlc oscillators, 143-145, 144 bipolar transistor-based TIL NOT gate in. 158-160, asynchronous data/circuit, 315.315 159.160 audio electronics. 139-150 blind object detection. 320-321.321 buzzers and electric bells in. 141 143 141 142 blinking LEDs, 109-111 110.111 clipping in. 146-147 bLiza the Snarkv ( omputer, 267-270 dynamic speakers in. 139.139 BOE -Bot, 309-310.309 feedback in, 147.147 bomber nav igation, 320.320 microphones in. 140.140 bombs and bomb circuit, 35-36. 35

Index 343 263 logic, 153 (BS2), 236-239.236 in. 314-317,315 1R two-way communication RS 232,332-333,333 330,331 Hall effect, 330-331, (NRZ),332 nonreturn to zero 108.108 t555 timer chip and. 262 R-2R digital to analog converter in. 262-264. Kirchoffs current law in. 53-54. 54,55 magnetic fields to generate. 64-65,64.65 measurement, 46-48 47 shift registers in. 198-199.198.199. 200 electron flow vs. current How in, 93-94. 93 threshold, 160 44 codes, resistors. color 125 124-125 LEDs, colored 123,123 their wavelengths, colors and 183 logic circuits, combinatorial 38 terminal, of switch, common compass, 266,319 (CMOS) complementary metal oxide semiconductor compressed air, 12 compression, 20-22. 20 concatenation. 227 Counter LED display, 272-273 2 (BS2), 221 PBASIC Stamp comments. commutator 72 150 comparators, 149-150. compiler, PBASIC Stamp 2 (BS2), 221 2 (BS2), 237 complement operations* PBASIC Stamp complementary law. logic. 165 Cylon Eye project, 250-252.251 conclusions, in experiments, 13 condenser microphone. 140 Stamp 2 conditional execution of code, PBASIC connectors, 33 conversion 332 communications, 165 commutative law, logic. current amplifier for LEDs, 153-154,153 cyclical redundancy check (C RC). LFSR m. 201 conditional looping, 233-2.34,234 counters. 205 -206.205. 206 crane (See motor driven ctane) crowbar, 178 current, 47.173 current limiting resistors. 112 c Genius 123 Robotics Experiments for the Evil 287-288 RC time constant and, 110-111 digital clock diagram for, 183,183 11,110 resistor-capacitor (RC) network in, 110-1 112-114 112.113 155$ timer chip and, dielectric in, 110 sequential logic. 183 344 coils, motor, 72 collector, transistor, 98 colon delimiter, PBASIC Stamp 2 (BS2), 2.42 code practice tool (transistor), 143-145,144 183 Boolean equations, CMOS touch switch in. 1^5-158,156.157 15 body. 15-16. of human bones 151-152 George, Boole, Stamp 2 (BS2). 243,245 PHASIC Branch statement. board) (See printed circuit breadboard diodes, 175 breakdown, in zener bridges, electrical, 56.56 brushes, 72 brazing, 28 clocked latch, 187-188.187 188 timer chip and, 109 buffer, inverting. 555 207.208.209 button debounce, 207-208, 207, 208,209 button debounce, 207-208, Stamp 2 (BS2), 240-241 bubble sorts. PBASIC dopant, 92 and. boron, semiconductors bells. 141-143.141. 142 buzzers and electric clock capacitors. 32,174.109-111110 clipping, audio electronics, 146-147 Christmas decoration using LFSR, 200-202,201 202 circuits, electrical, 36,37-39,37 cardboard arm, 10 13.10.11.12 carry look ahead, in adders. 168 238-239 Case statement, PBASIC Stamp 2 (BS2), CDS cells. 266.275-278. 276 car robot base. R C. 298-299.298.299 carbon microphone, 141), 140 carburetors, 177 178. 177 cardboard, 18 center of mass calculation, mobile robots and, chronometers, 319 cetrtilage m human joints, 16 cathode ray tube (CRT), 121 L21 xspux 171,196 Index D MOSFE rs, 156-157,156.163 NAND operation in, 160.160, 169. 171 D Hip flop, 187-190,188 1X9 I'M* N( )R gate in, 163-165.163.164,165. 171 parallel data in, 193-194,194 NOT operation in, 152. 152,155 155 reset for,. 191-192.191,1*12 OR operation in, 152,152.154. 155 171 D shell connectors,33 PBASIC Stamp 2 (BS2). 237 data pull-ups/pull-downs in. 168-169,168. 169 parallel (See parallel data) resistor-to-lransistor logic t RTF) in 158 serial (See serial data) sum of product circuits in, 161-162,162 data communications. 332 testing logic circuit design in, 153 154.153.154 data communications equipment (DCF).333 transistor to transistor logic (TTL) in. 153,171-172 data terminal equipment (DTE),333 truth tables and, 151-152. 152 data types, PHASIC Stamp 2 (BS2), 222-223.222 XOR and adders in. 166-168,166,167 DC motor control base with H bridge drivers. digital multimeter (DMM),69,154.261 289-291. 2X9.290 current measurement with. 46 48.47 De Morgan's theorem. 165 resistance measurement using, 51-52 51,52 debounce, 207-208,207 208,2(*‘» voltage measurement using. 42 45,43. 47 t5S5 timer chip and. 112-114.112,113 digital-to- analog converter in. 262-264.262 263 debugging, PHASIC Stamp 2 (BS2), 221.223.267 diodes, 93-94.93.94 decimal numbers. 224-225 alternating current (AC), 93 decoders or demulitplexors in. 196-197.197 electron flow vs. current llow in, 93-94.93 degrees of freedom (DOF). 11,77 light-emitting, diodes (LEDs) in. 95 96 98. % demulitplexors in, 196 197,197 rectification and, 93-94,93 Descartes, 151 zener diodes in, 175-177. 175,176 detonators, 35 direct current (dc) motors. 71 -73 72.73 diaphragm, in telegraph dissipation of power, 58 dice, electronic, 256-25". 256 distance measurement, ultrasonic, 326-329,327,328, dielectric, capacitor, 110 329 difference calculation. PBASIC Stamp 2 (BS2), 234 distributive law. logic, 165 differential drive robot chassis, 82-85,83 84 Do statement. PBASIC Stamp 2

Index 3 45 Index electrical theory,35-62 electric bells.141-143,141142 electret microphone.140 electronic dice.256257.256 electron flowvs.currentflow.93-94.93 electromagnets. 64,65-66.66 edge-triggered flipflopsin,187-188.187.188 electroscopes, 69-70,69 electronic stethoscope.145-147.145,146.147 Einstein, Albert,122 dynamic speakers*139.139 dynamic microphone.140 1 EPROM.228-229 Earth’s magneticfield,69-71.70,1 Eattli mapping,319-320.319 346 Dynalloy Flexinol.88-90.88 emitter, transistor,98 Else statement,PBASICStamp 2(BS2t,244 Eliza computer.267-268 voltage dropsin.44-45,45.49.4960-61 Thevinin’s equivalencyin,55-56,55.56 voltage measurementin.41-43 voltage dividersin,52,52 variable resistorsin.505251 switches in,36,37-39,37.40-41.0 series loadsin.48so48,50 power suppliesand,37.38 power in.57-58 circuits in,36,3741.37,40 parallel loadsin,53-54.54 Ohm’s lawin,46-48,47,55,60-61 negative currentin4b light-emitting diodes(LEDs)in,37-39,38.39 ground, grounding.43 dissipation ofpowerin.58 current measurementin,46-48,47 units ofmeasureusedin,47,bl-62 resistors in.37-39.38..9-44-45.50-52.51 relays in.67-68,67<>8 heat sinkingin.58 flow ofelectricity.42 batteries in.59-62 Kirchoffs voltagelawin.48-50,55 Kirchoffs currentlawin,53-55,54 153 Robotics Experiments for'theEvil Genius E flip flop flashing EEDs,181,181 feedback, 16,147.147 Flexinol, 88-90 finishing wood,22-23 finger joints.15-16.1516 filters, powersupplies.174 fields, magnetic.64.64.70 555 timerchip.107-119.107.108 explosives, 35-36 fasteners, 25-28,26 falling edgeclockedflipflop,187 external combustion(steam)motors,75 experimental designtips,1113 excitation state,optoelectronics,1.22 energy vs.work,41 end statement.PBASICStamp2(BS2),222 end effectors.10 end cap.72 end bearing.72 encryption, 1FSRin.201 clocked latchin,187-188.187.188 reset lor.191-192.191.192 parallel datain.193-194.194 NOR in,185-187.185.186 NAM) in.187.187189-190. 189 edge triggered.187-188,187.188 hex. 193-194.194 falling edgeclocked,187 button debounce,207-208207.208209 sequential logic,185 comparator operationin,108,108 D type.187-188,188189-190,89.190 voltage dividerusing,108.108 R/C servocontrolin,114-116114115116 oscillator circuitusing.111.111 monostable oscillatorand,112 inverting bufferoperationin.109 dual inlinepackage(DIP)chips.107 button debounceusing.112-114.12.113 blinking LEDsusing,109-111.lilt111 astable oscillatorm.116 light-seeking robotusing,117-119,17118,119 flip-flop operationin.108-109.109,3-114 F RS. 185-187 Hello World application. PBASIC Stamp 2 (BS2), Index t555 timer chip and, 108-109,109,113-114 220-222 flowchart, 213,213,213 hertz (Hz), 62 fluorescence, 121 hex flip-flops, 193-194,194 foam board, 18 hexadecimal numbers,224-225 force, 57 hinges, hinge pins, 16 Freqout function. PHASIC Stamp 2 (BS2), 254-255, Hitachi 44780-conlrollcd liquid crystal display 254 (LCD), 252-253.252.253 frequency, 62,62 horsepower, 57 friction, in fasteners, 26-27, 27 human body parts vs. robotic structures, 15.91 friction, vs. resistance, 44 hydraulics, 75 fuel cells. 59 hypothesis. 12. 13 fuses, 35 hysteresis, sequential logic. 208 208 gain, 156

I G 1 beams. 21 (5armin eTrex CPS receiver, 333,333 idempotent law, logic, 165 gates, logic, 153-155 identity fauctions, logic, 165 GD2D120 IR detectors, 284-285.284 325 If statement, PHASIC Stamp 2 (BS2), 236-239.236. gears, 76 244 global positioning system (CPS), 266,3.19,332-334 If-Else-Endif in. PBASIC Stamp 2 (RS2), 238-239. glues, 24-25.25 314-245 Cosub statement, PHASIC Stamp 2 (BS2). 242-243 If-Then statement, PBASIC Stamp 2 (BS2), 243.245 Goto statement. PHASIC' Stamp 2 (BS2), 243.244, in circuit tester (ICT), 168-169.169 245 infrared. 123 graticules, in oscilloscope screen, 150 IR object sensors, 283-285,283. 284 Greenwich Mean Time, 319 line-following robot using. 135-137 135.136.137 Grey, Walter, 117 two-way communication in, 314-317,315 grippers, 10 wall-following robot and, 324-326,324,325 ground, grounding, 43 white,'black surface sensor using. 133-134,133.134 GUI-Hot programming interface. 308-310. 309,310 infrared photodiodes, 266 initialization, 191 input/output (I/O) pin. 31 H PBASIC Stamp 2 (BS2). 247-248 247 248 insect, pipe cleaner, 5-7.6 7 11 bridge insulation, on wires, 29 DC motor control base with II bridge drivers in, intelligence, 91.267 289-291 289. 2*81 intermetallic region, in soldering, 28-29 sw itch do motor. 80 82,81.82 internal combustion motors,75 transistor motor. 104-106,105 international code standard, 144 half adder (See also adder circuits), 167 introduction to robots, 1-13 Hall effect compass, 330-331 330 331 inverting buffer operation, t555 timer chip and. 109 hands (See also end effectors; grippers), 10 Investigation of the Laws of I bought. An. 152 hardware interface, PHASIC Stamp 2 (BS2), 247-264 IR object sensors. 283 285,283 284 heat sensors, 266 IR reflection,266 heat sinking, 58

Index 347 Index tight-emitting diodesfLEDs),37--59.38.39.95-96.95. light-dependent resistor(LDR),117-119,273-275, legs, 16 LEGO mobilerobots,7-9,7,89 348 LEGO parts/kits,78.78 left handrule,magnetics,65 Kirchoffs currentlaw.55-54,54:5 LEGO MindStorm,PBASICStamp2(BS2).215-214 latitude, 519 kii builtrobots.77-78.78 keypad input.PBASICStamp2(BS2),257-259,257, joules, 57 joints. 15-1ft.151ft kickback, motor.101 Kirchoffs voltagelaw.48-50.55 Karnaugh maps.185 K'NEX parts/kits,77-78,78 controller usingPBASIC,249-250249 Cylon Eyeprojectin,250-252,251 current amplifiertor,155-154.153 colored. 124-125.125 flashing. 181,181 Counter lEDdisplay,272-275 light-seeking robotusing,117-119.117.1IS.119 measuring voltageacross.42-43.43 brightness of.changing,120128,127 blinking. 109-111,110.Ill oploisolator lockandkeyusing,131-133.131.132. multisegment, 128-130.128129130,271-273.271. line followingrobotusing,135-137,135,136,137 resistor-transistor-logic (RIL) and,130 pulse widthmodulation(PWNl) and.209-211,210, 96. 122 274,275 258 272 211 133 1?3 Robotics Experiments fortheEvil Genius L K J magnetic devices,63-7.3 LT1173CN8 5switchmodepowersupply,180-181, logic (Seedigitallogic:sequentialcircuits) looping. PBASICStamp2(BS2),232-234,232. longitude. 319 logic gates,133.gates.153-155 lock, oploisolatorlockandkey,131-133.131.132133 location sensors,26ft LM339,149-150,150 linkages.? loads liquid crystaldisplay(LCD).Hitachi44780- L.M293 motordriverchips.289 lines ofmagnetictoree.64-65.65 linear regulators,126 linear powersupplies.177-179177.178179 linear inductionmotors.65 linear feedbackshiftregister(LFSR),200-204,201. light sensors,266.273-275.274275.275-278.276.277 line-following robot,135-137.135.136,137,320, light-seeking robot,117-119,117.118,119 left-hand rulein.65 Hall effectcompassin,330-331. 330.331 fields in,64,64.70 current generationand.64-65.64,65 electroscopes. 69-70,69 electromagnets in.64,65-66.66 direct current(dc)motorsin.71-73,7273 Earths magneticfieldand.69-717071 in series.48-50,48.50 in parallel,53-54.54 random movementrobotusing,203-204,203.204 voltage testingin,99 voltage measurementin,125.125 traffic lightsusing,194-197.195,196,197 theramin using,260,260 single poledoublethrow(SPOT)switchfor.40-41. seven segment,128-130.128.271-273.271.272 rotating display,usingshiftregisters,199.200 239-241.245 controlled, 252-253.252.253 321-323,322 181 202 203.204 40.41 M hneai induction motors and, 65 MOSFET transistors, 107.156-157. )5h. 163 lines of magnetic force in, 64-65,65 Moth program flowchart, 213,213 poles in, 63-64,63 Moth robot, 294-296,294,295 relays in, 67-68,67,68 motor driven crane, 77-78.77 mandroid, toilet paper roll, 2-4.3,4 degrees of freedom (DOF) in. 77

mapping, 319-320,319.320 pulleys added to. 79-80.79 811 xapux martensite, 88 motors materials for robot construction. 15, 17. IX bipolar PNP transistor motor control for. 102-103, glues matched to, 25 192 103 mathematical operators in assignment statement. DC motor control base with H bridge drivers in, PBASIC Stamp 2 (BS2), 230-231 289-291 289,290 Maxim MAX323 R8-232 interface, 333 direct current (dc). 71 -73.72.73 Mechano parts/kits. 78, 78 drive motojr with transistor,99-101 tun 1(11 memory systems, PBASIC Stamp 2 (BS2),228-229. drivetrains and, 75-90 228,229 external combustion, 75 meters, sound level meter, 14-S 150.149 150 gears and, 76 metric unit measurements, 62 internal combustion, 75 Mickey Mouse logic (MML) and, 170-171.170 171. kickback in, 101 196 linear induction 65 microcontroller (MCU ) I/O pins, PBASIC Stamp 2 multiple servo control in,303-305,303 305 (BS2), 247 parts ot. 72 microphones, 140.140.266 polarity ot, 73,73 mobile robots, 287-317 pulse width modulation (PWM) in, 209-211.210 Artist robot, 305-308, .106 308 211 BOE-Bot, 309-310,309 R/C servo control in. 114-116,114. 115,116. center ot mass calculation m, 287-288 300-303.301 302 DC motor control base with H bridge drivers in. rpm of, 75 289-291.289,290 speed control in, 75 76 GUI-Bot programming interface (PBASIC). stepper, 85-87,86.311-313.311 312 308-310,309.310 switch dc motor H bridge and, 80-82,81 82 1R two way communication in, 314-317,315 testing, 73.73 LEGO. 7-9.7 8 9 torque and, 76 Moth robot, 294-296,294 295 transistor motor H bridge in. 104-106,105 multiple servo control in. 303-305,303,305 multisegment LEDs, 128-130 128,129,130,271-273, Pathfinder Sojourner robot, 288 271.272 R2-D2,287-288,287 muscle wire, 75,88-90.88,89 random movement in,296-297,296 muscles of human body, 15 16.15 R( car robot base in. 298-299,298.299 Musical' tone output. 254-255 254,255 RC servo setup in 300-303, .Mil 302 rough terrain handling in, 288.288 state machine programming in. 292-293,292 N stepper motor control in. 311-3.13,311,312 nail 26 modules, 1 CD, 252 NAND operation, 160.160, 169,171,187 187 Mondo-Tronics, 89 189-190,189 monostable oscillator. 112 navigation, 319-334 Morse code, 144 blind object detection in. 320-321.321 code practice tool ( transistor). 143-145.144 bomber navigation in. 320.320 Morse, Samuel, 139,144 compass in. 319

Index 349 Index number dataformats,224-225,224,225 odometry, 266 object sensors,266,283-285.283284 object detection,320-321.321 nuts andbolts,2528.26 N-type semiconductors,92 NPN transistors,97-99,97,98,100,00 NOT operation,152,152,155155 'noninverting opamp,156 Ohms law.46-48.47,55,60-61 ny bblesandnibs.PRASICStamp2(RS2).223 NOR operations.163-165,163.164.165.171 nonreturn tozero(NRZ)communications.315.332 nickel metalhydride(NiMH)battery,59-60 open collectortransistor,133 NMEA GPSInterface.332-334.333,34 350 operational amplifiers,156 nickel cadmium(NiCad)battery,59-60 newton meters.57 nematic liquids(Seealsoliquidcrystaldisplay),252 negative programming,PBASICStamp2(BS2);244 negative current.46 optoelectronics, 121137 negative feedback,147 sequential logic,185-187,185.186 bipolar transistor-basedTTLNOTgatein, SONAR.326-329,327 328,329 colors andtheir wavelengthsin,123,123 changing LEDbrightnessin. 126128.127 cathode raytube(CRT)and, 121,121 wall-following robotand,324-326.324,325 sextant in,320 sensors in,320321 coloied LED*-ami,124-125.1 25 ultrasonic distancemeasurementin.326-329.327. lriangulalion in,320,320 time andchronometersin,319 NMEA GPSInterfacein.332-334.333.334 global positioningsystem(GPS)in,319 longitude andlatitudein,319 RS-232,332-333,333 line-following robotsand,320.321-323,322 I talleffectcompassin,330-331,330..VI 328,329 158-160.159 160 1 ?3 Robotics Experiments for the EvilGenius o painting, 22-23 packets, data.283 overlaying variables.PBASICStamp2(BS2),223 output set/reset,logic.165 optoisolator lockandkey,131-133.131.132.133 Parallax BASICStamp'’(BS3).31.213-245 oscilloscopes, 148-149,148.149 oscillator circuit ordinance disposalexperts(ODEs),3S OR, 152.152.154.135,171 debugging in. 221,223,267 connecting thePCBandRS2 toPCandrunning conditional loopingin,233-234, 234 Cylon Eyeprojectin,250-252, 251 conditional executionofcodein.236-237.236, complement operationsin.237 compiler in,221 comments in,221 colon delimiterin242 bubble sortsin,240-241 Case statementin238-239 arrays ofvariablesin.228-229 AND andOKoperatorsin,237 ASCII charactersin,226-227.270 quanta asunitotlightin,121 Branch statementin,243,245 voltage-controlled oscillator(VCO)in.180 code practicetool(transistor).143-145,144 sum ofproductcircuitsm.161162,162 t.555 timerchipand.111.111 white/black surfacesensorusing,133-134,133,134 photovoltaic effectand,122.123 diffraction gratingin,122,122 ultraviolet lightin.123 optoisolator lockandkeyin.131-133,131,132.133 infrared lightin,123 PBASIC Stamp2(BS2),237 multisegmenl LEDsand,128-130.128129,130 line-following robotusing,135-137,135,136137 light-emitting diodes(LEDs)in.122 fluorescence and,121 excitation statein.122 238-239 applications with,216-218.2 17.218 271-273,271.272 P difference calculation in. 234 structured code in,243-244 Index digital logic and, 237 subroutine programming in. 242-243 243 Do loops in, 232-233,245 iherannn using,260,260 Do While loops in, 245 TRI-State (TRIS) register in. 247 electronic dice using. 256-257,256 variables and data types in. 222-223 Else statement in. 244 whitespace in, 221 E nd statement in, 222 Parallax GUI-Hot programming interface,308-310, flowchart for. 213.213 309,310 For loops m,239-241 parallel data, 193-194.194 Go’sub statement in. 242-243 shift registers in, 198-199.198. 199 200 Goto statement in, 243,244.245 parallel loads, 53-54.54 hardware interface in. 247 264 parameters for subroutines. PHASIC Stamp 2 (BS21, Hello World application using, 220-222 243 Hitachi 44780-controlled liquid crystal display particleboard, 18 (LCD) in. 252-253,252.253 Pathfinder Sojourner robot, 288 If-Else Endif statements in,238-239,244-245 PHASIC’ Reference Guide,335-340 If statement in, 236-239.236,244 period of signal, 62,62 If-Then statement in,243,245 permanent magnets 72 input/output (I/O) pin in. 247-248 247.248 permeability, 70 keypad input in, 257 259. 257.258 phosphorus, semiconductors and, dopant,92 layout for. 214.214 photodiodes, 26ft LED control using, 249-250,249 photovoltaic cells. 59 loading Windows Editor on your PC for, 214-216, photovoltaic effect, 122,123 215 piezo electric crystal speaker. 139-140,139 looping in, 232-234,232,239-241,245 pin through hole (PI 11) components, 31 32 mathematical operators in assignment statement pipe cleaner insect, 5-7.6 7 of, 230-231 Planck. Max, 121-122 memory systems in. 228-229.228.229 plastics. 18 microcontroller (MCU) I/O pins in, 247 plexigall. 18 musical tone output using. 254-255. 254,255 plywood, 17-19,18 19 negative programming in, 244 strengthening structures for. 20-22 number data formats in. 224-225.224.225 PNP transistors, bipolar PNP transistor motor nybbles and nibs in. 223 control, 102-103,102.103 overlaying variables in. 223 polarity of motors, 73 73 parameters for subroutines in, 243 poles, magnetic, 63-64,63 power off application in. 235-236 polystyrene, 18 PWV1 analog voltage output using, 261-262 262 positive feedback, 147. 147 R-2R digital to analog converter in, 262-264,262 potentiometers, 50-52,51,300 263 pound force (lbf), 57 Retime function in. 259-260,259 power. 173 resistance measurement in, 259-260,259 power off application. PHASIC.St imp 2 (HS2). RS-232 port for. 217,217 235-236 saving applications on PC from. 218-220,219.220 power supplies. 31,33.173-182 sinewarc in, 239 239 capacitors in. 174 sort output in. 240-241,240 connections to, 37,38 source code tn.221 crowbar in, 178 statements in 221 current in. 173 string manipulation in, 227 filters in, 174

Index 351 linear. 177-179,177.178 179 power in, 173 Q pulse width modulation (PWM) in, 180 quanta.light unit. 121 switch mode (SMPS), 179 181,180,181 transistor to transistor logic (TTL) and. 173 voltage-controlled oscillator (VCO) in. 180 voltage dividers in. 173-174.173 R voltage in. 173 R2-D2,287-288,287 voltage regulators in, 174. 178-179.178 R-2R digital to analog converter in, 262-264.262.263 zener diodes in, 175-177,175.176 radar. 266 power, 57-58 radio control and remote control (R/C),7 pretension, in fasteners. 26 car robot base in. 298-299,298,299 primer tor wood,23 servo control in. 114-116. IL4.115.116 printed circuit board (PC B). 17-18.31-33.33 servo setup in. 300-303,301.302 assemble of, 31-33,33 random movement, 296-297.296 battery wiring and, 84 random movement robot. 203-204,203,204 capacitors on, 32 R/C servo control, 114-116.114,115 116 l) shell connectors in,33 RC time constant, 110-111 DC motor 11 bridge and, 82.82 Retime function, PBASIC Stamp 2 (RS2). 259-260. DIP switches in.32.32 33 259 parts of, 31 RCtime light sensor. 273-275.274,275 PBASIC Stamp 2 (BS2) connection, 216-218 rechargeable battery, 59-60 pin through hole (PI Ht components in, 31,32 rectification, 93-94,9.3 power supply for, 31,33,37,38 reflexes, 16 prototyping on. 38.39 relays, 67-68.67 68 single pole double throw (SPDT) switch on, 40-41. remote contiol (See radio control and remote 40 control) soldering on. 31-32,32 reset for flip flops. 191-192. 191 192 \ias in.31 reset-set flip flop (See RS flip flop) procedures, in experiments. 13 resistance and resistors, 37-39,38.39,44-45,47,50-52, programming interface,31 51 prototyping systems. 38.39 current limiting. 112 proximity detector, 283 light dependent (I DR), 117-119,273-275.274 275 pseudorandom number generators. I FSR in, 201 measurement of, 51-52. 51.52 P-type semiconductors. 92 measurement of, using PBASIC 259-260,259 public address (PA) systems, 140 parallel/in parallel. 53-54.54 pulleys, 79-80.79,80 power test circuit using, 58,58 pull ups/pull-downs. 168-169. 168 169 RC time constant and, 110-111 pulse width modulation (PWM), 180,322 resistor-capacitor (RC) network in, 110-111.110 analog voltage output using, 261-262,262 resistor transistor-logic (RTL) and; 130 generator for. 209-211,210.211 series/in series, 49 LED brightness and, 96,126-128.127 Thevipin’s equivalency in. 55-56,55.56 push button. 113. 113 variable. 50-52.51 % push rods, 16 variable resistors and, 51 pyrometer, 266 Wheatstone bridge and. 56,56 Ti v# resistor-capacitor (RC) network 11.0-111.110 resistor to-transistor logic (RTL)* 158

352 1E 3 Robotics Experiments for the Evil Genius resistor-ti ansistOr-logid (R1 L). 130 white/black. 133-134.133.134 Index results or observations, in experiments, 13 wire whiskers, 280-282.280.281 ripple adder (See also adder circuits). 167 168 sequential logic circuits, 183-211 184 rivet 26 button debounce in. 207-208,207,208 209 robot defined, 1-2 Christmas decoration using, 200-202.201,202 robot structures, 15 33 clocked latch in. 187-188,187 188 robotics. 1 clocks in. 183 rotating I FI) display, using shift registers, 199,200 combinatorial logic circuits and. 183 rough terrain handling, mobile robots and, 288,288 counters in, 205-206.205 206 RS flip flop, 108-109,109,113-114. 185 187 decoders or demulitplexors in. 196-197 197 RS-232,332-333,333 D flip flop in, 187-190,188.189,190 PHASIC Stamp 2 (BS2),217.217 digital clock diagram showing. 183,183 mles of robotics, vii edge-triggered flip flops in, 187 188.187 188 Rutherford, 122 falling edge clocked flip-flop in. 187 feedback in. 185 flip flop reset for. 191-192 191 192 s hex flip flops. 193-194.194 hysteresis in, 208.208 754410 motor wiring, 289-291.289 linear feedback shift register (LFSR) in. 200-204, 78L05 chip. 178-179,179 201 202,203.204 safety in experiments. 11-13 NAND in. 187. 187.189-190.189 sanding wood. 23 NOR in. 185-187,185.186 saturation,, transistor, 101 parallel data m, 193-194.194 saving applications on PC'. PBASIC Stamp 2 (BS2), pulse width modulation (PWM) generation in. 218-220,219, 220 209-211.210.211 Schmitt triggers. 207-208, 207,208 209 random movement robot using, 203-204,203.204 screw, 26 RS flip flops. 185-187 seconds, as unit of measure. 62 Schmitt triggers in.207-208. 207 208.209 semiconductors, 91 106 shift registers in, 198-199,198. 199.200 acceptors and donors in, 92 timing diagrams tn. 184,184 diodes as, 93-94.93, ‘>4 traffic lights, 194-19". 195.196 197 dopants in. 91-92,92 transistor to transistor logic (TI L) in. 192 light-emitting diodes (LEDs) in. 95-96,95 96 serial data, 315 NPN transistors in. 97-100.97.98 100 shift registers in. 198-199.198.199.200 P type vs. N type. 92 series loads. 48-50.48 50 silicon crystal in. 92,92 servos transistors as. 91 multiple servo control in, 303- 305.303 .015 sensors. 265-285.265 R‘C servo control in, 114-116. 114 115.116 bLi/.a the Snarkv Computer. 267-270 remote control ( RC) setup in, 300-303,301,302 CDS cells, 275-278.276 seven-segment LEDs, 128-130.128. 271 273 271 272 differential light sensors in 275 278.276.277 sextant, 320 IR object sensors, 283-285.283 284 Sharp IR detectors,284-285,284,325 navigation. 320-321 shear forces. 21 proximity detector and, 283 shift registers, 198-199, 198 199 200 RCtime light sensor, 273-275 linear feedback (LFSR) in, 2(X)-204.201,202. 203. SONAR and, 283 204 sound control and. 278-280.279 silicon crystal semiconductors, 92,92 types of. 266

Index 353 Index staple, 26 stethoscope, electronic.145-147.145146.147 stepper motors,85-87.86 statements, PHASICStamp2(BS2).221 state machineprogramming,292-293,292 splicing wires,28-30,30 structural forces,20-22.20 stnngs, PHASICStamp?(BS2).227 strengthening structures,20-22 Stiquito robot.89 Spybotics. PHASICStamp2(BS2).21.3 speed control,75-76 speakers source, transistor,102 source code.PHASICStamp2(BS2),221 structured code.PHASICStamp2(BS2),243-244 sound sensors.266 sound control,278-280.279 sort output.PHASICStamp2(BS2),240-241.240 subroutine programming,PHASICStamp2(BS2), sound-level meter,148-150.149.150 SC )NAK,283,326-329,327,328.329 solenoids, 16 soldering wires.28-30.29,30 soldering iron,gun,29-30,30 sum ofproductcircuits,1.61-162. 162 soldering Sojourner robot,288 skid sensors,26b sinovial fluidinhumanjoints.16 surface sensor,266 super effect,inbatteries,59,60 Snai kyComputer,267-270 sink, transistor,102 single poledoublethrow(SPOT)switch,38,40-4,1J 35 4 swimming poolsystemvs.voltage flow.42 single inlinepackage(SIP).258 sine ware.PHASICStamp2(BS2),239.239 simulation programwithintegratedcircuitemphasis bipolar andunipolar.311-313.31,12 dynamic speakersin.139,139 piezo-electric crystalspeakerin,139-140.139 printed circuitboards(PCBs),31-32.32 DIP switches,32,32.33 white/black, 133-134,133,134 242-243.243 40.41.67 (SPICE), 97 123 Robotics Experiments for the EvilGenius transistors (Seealsosemiconductors),97-99,97.98. transistor-to-transistoi logic(TTL),153.171-173.289 traffic lights.194-197.195196.197 touch switch,CMOS,155-158.156.157 torsion (twistingtorce),2022,20 tracked differentiallydrivenrobots,9 torque, 76 timing diagrams.184.184 Thevinin’s equivalency,55-56,55,56 toilet paperrollmandroid,2-4.3,4 tinning, insoldering,29 timer (See555chip) time andchronometers,319 tilt sensors.266 throw', ofswitch.38 threshold current,160 theories, 12,13 terrain handling,mobilerobotsand,288,288 tension, 20-22.20 telegraph. 139 Systeme International(SI)unitsofmeasure.47.61-62 switching regions.332 theramin, 260.260 switches, 36.37-39.37 switch modepowersupply(SNIPS).179-181.180.181 switch matrix.PBASICStamp2(RS2),257-259.57. sw itchdebounce.207208,207.208,209 switch dcmotor11bridge,80-82,81.82 bipolar transistor-basedTTL NOTgatein. bipolar PNPtransistormotor controlfor,102-103, beta in,98 Sequential logic.192 power supplies,173 bipolar transistor-basedTILNOTgatein. relays in,67-68.67,68 keypad, switchmatrixin,257-259.257.258 CMOS touchswitchin.155-158,156,157 binary controlin.50 Hall effect,.330-331,330 100, ton132-133 258 158-160.159. 160 102 103 158-160.159.160 T drive motor using. 99-101, 100. 101 voltage drops, 44-45.45.49.49,60-61 emitter, collector, base in, 98 voltage measurement, 41 -43 logic gates and, 133 light-emitting diodes (LEDs) and. 99.125. 125 3 MOSFETs, 156-157.156 163 voltage drops in, 45.45 CL motor II bridge in, 104-106,105 voltage regulators, 126.174 CP open collector in. 133 linear, 178-179.178 * oscillator code practice tool (transistor). 143-145, voltmeters, 42 144 resistor-transistor-logic (RTL) and. 130.158 saturation region in. 101 w source and sink in, 102 wall follow ing robot. 324-326,324,325 transistor to-transislor logic (TTL) in. 153.171-172 washers, 26.28. 28 triangulation navigation. 320,320 watts, 57 tricycle wheels, 8 Weizenbaum, Joseph, 267 trimmer potentiometers, 300 welding. 28 TRf-State (7RIS) register, PHASIC Stamp 2 (BS2), Wheatstone bridge, 56.5ft 247 wheel/drivetrain system, 17 truth tables, 151-152,152. 1,83 whiskers, 266,280 281 Turing, Alan, 267 w hite/black surface sensor, 133-134,133 134 Turricbots. 117 whitespace. PBASIC Stamp 2 (BS2), 221 two-way communication. IR, 314-317,315 Windows Editor, PBASIC Stamp 2 (I3S2). 214-216, 215 wire whiskers, 266.280,281 u wiring ultrasonic distance measurement. 326-329,327.328. insulation on, 29 329 muscle wire and, 88-91), 88.89 ultrasonic ranging, 266 soldering and splicing, 28-30.29.30 ultraviolet light, 123 wood, finishing, 22-23 unipolar stepper motors, 311-313,311,312 work. 57 units of measure used in electric woi k, 47.61 -62 work , 11 work vs. energy, 41

V variable resistors in. 50-52,51 X variables, 191 XOR, 166-168.166. 167 PBASIC Stamp 2 (BS2), 222-223 vias. in PCB, 31 video cameras, 266 z voltage, 47,58,173 /ener diodes, 175 177 175,176 analog voltage output using, 261-262.262 Zctex ZTX649 transistor, 98-99 Kirchoffs voltage law in, 48-50,55 Zetex ZTX749 transistor. 103 voltage-controlled oscillator (\ CO). 18b Zulu Time (See also Greenwich Mean Time) voltage divider,,,52,52,173-174.173 t555 timer chip and, 108,108

I n d e x 355 Rbout the Author

Myke Prcdko is a new technologies test engineer at Celcstica in Toronto, Canada. He is the author ot McGraw-Hill’s Programming and Customizing PICM'tcro Microcontrollers, Second tdition, and is the principal designer of the TAB Electronics Sumo-Hot,

-" IE3 R□ BQTIC5 EXPERimENTS fBi EVIL GENIUS

123 STEPS NEEDED TO BRUMG OUT THE GENIUS IN EVERY BASEMENT HOBBYIST!

If you enjoy tinkering in your workshop and have a fascination for robotics, you'll have hours of fun working through the 123 experiments found in this innovative project book.

More than just an enjoyable way to spend time, these exciting experiments also provide a solid grounding in robotics, electronics, and programming. Each experiment builds on the skills acquired in those before it so you develop a hands-on, nuts-and-bolts understanding of robotics - from the ground up.

1 S3 ROBOTICS EXPERIMENTS FOR THE EVIL GENIUS-

• Introduces you to robotics, electronics, • Requires only inexpensive, easily obtained and programming for robotics step-by- parts and tools step—you don’t need to be a science whiz • Provides a PCB (printed circuit board) to get started, but you will be when you that will make it easy to create the have finished circuits used in this book as well as • Shows how you can create simple robots your own experiments and models using inexpensive materials • Gives you directions for building a maze¬ and tools found around the house and solving robot, a mine-sweeper two workroom different designs for a light-seeking robot, • Vividly explains the science behind robots a digital sound recorder an artificial and the technologies needed to build intelligence program that will respond them, including: to you. and much more - Electronics • Explains underlying principles and Mechanical assembly suggests other applications Motors and assembly • Supplies parts lists and program listings Programming and microcontrollers • Shows how you can create simple robots and models using materials found around the house and workroom

IMAGINATIVE EXPERIMENTS THAT TEACH THE BASICS - WHILE PROVIDING HOURS OF FUN!

The McGrow Hill Companies

P/N 14135*1 L PART OF Visit TAB Robotics at: http://books. meg raw- hill, com/robots/

Cover design & illustrations: Todd Radom

[ $24.95 U.S.A. | £14.99 U.K. | $39.95 CAN

Robotics