A Beginner’s Guide to Circuits: Nine Simple Projects with Lights, Sounds, and More!

Post on 11-Sep-2021

5 views 0 download

Transcript of A Beginner’s Guide to Circuits: Nine Simple Projects with Lights, Sounds, and More!

ABEGINNER’SGUIDETOCIRCUITS

NINESIMPLEPROJECTSWITHLIGHTS,SOUNDS,ANDMORE!

BYØYVINDNYDALDAHL

SANFRANCISCO

ABEGINNER’SGUIDETOCIRCUITS.Copyright©2019byØyvindNydalDahl.

Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageorretrievalsystem,withoutthepriorwrittenpermissionofthecopyrightownerandthepublisher.

2221201918123456789

ISBN-10:1-59327-904-3ISBN-13:978-1-59327904-2

Publisher:WilliamPollockProductionEditor:RileyHoffmanCoverDesign:MimiHeftCoverIllustration:JoshEllingsonInteriorDesign:BethMiddleworthDevelopmentalEditor:ZachLebowskiTechnicalReviewer:JohnHewesCopyeditor:RachelMonaghanCompositor:HappenstanceType-O-RamaProofreader:PaulaL.Fleming

CircuitdiagramsmadeusingFritzing(http://fritzing.org/).

Forinformationondistribution,translations,orbulksales,pleasecontactNoStarchPress,Inc.directly:

NoStarchPress,Inc.2458thStreet,SanFrancisco,CA94103phone:1.415.863.9900;info@nostarch.comwww.nostarch.com

LibraryofCongressCataloging-in-PublicationDataNames:NydalDahl,Øyvind,author.Title:Abeginner’sguidetocircuits:ninesimpleprojectswithlights,sounds,andmore!/ØyvindNydalDahl.Description:SanFrancisco:NoStarchPress,Inc.,[2018].Identifiers:LCCN2018032664(print)|LCCN2018033886(ebook)|ISBN9781593279059(epub)|ISBN1593279051(epub)|ISBN9781593279042(print)|ISBN1593279043(print)|ISBN9781593279059(ebook)|ISBN1593279051(ebook)Subjects:LCSH:Electroniccircuits--Juvenileliterature.Classification:LCCTK7820(ebook)|LCCTK7820.N9272018(print)|DDC621.3815--dc23LCrecordavailableathttps://lccn.loc.gov/2018032664

NoStarchPressandtheNoStarchPresslogoareregisteredtrademarksofNoStarchPress,Inc.Otherproductandcompanynamesmentionedhereinmaybethetrademarksoftheirrespectiveowners.Ratherthanuseatrademarksymbolwitheveryoccurrenceofatrademarkedname,weare

owners.Ratherthanuseatrademarksymbolwitheveryoccurrenceofatrademarkedname,weareusingthenamesonlyinaneditorialfashionandtothebenefitofthetrademarkowner,withnointentionofinfringementofthetrademark.

Theinformationinthisbookisdistributedonan“AsIs”basis,withoutwarranty.Whileeveryprecautionhasbeentakeninthepreparationofthiswork,neithertheauthornorNoStarchPress,Inc.shallhaveanyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedtobecauseddirectlyorindirectlybytheinformationcontainedinit.

THISBOOKISDEDICATEDTOMYBEAUTIFULWIFE,PILI.

ABOUTTHEAUTHORØyvind Nydal Dahl is a maker, programmer, writer, speaker, blogger,author,techenthusiast,guitarplayer,andmore.Hehasamaster’sdegreeinelectronics from the University of Oslo, helps companies develop newproducts,andtravelstheworldwhileteachingelectronicsworkshops.Heisthe founder of the beginner-friendly blog https://www.build-electronic-circuits.com/andthemembershipsitehttps://ohmify.com/.

ABOUTTHETECHNICALREVIEWERJohnHewesbeganconnectingelectricalcircuitsatanearlyage,movingonto electronics projects as a teenager.He later earned aphysics degree andcontinuedtodevelophisinterestinelectronics.JohnhastaughtelectronicsandphysicsuptoanadvancedlevelintheUnitedKingdomandranaschoolelectronics club, setting up the website http://www.electronicsclub.info/ tosupport the club.Hebelieves that everyone can enjoybuilding electronicsprojects,regardlessoftheirageorability.

BRIEFCONTENTS

ACKNOWLEDGMENTSINTRODUCTIONBUILDYOURFIRSTBREADBOARDCIRCUIT

PROJECT1:THESTEADY-HANDGAMEPROJECT2:THETOUCH-ENABLEDLIGHTPROJECT3:THECOOKIEJARALARMPROJECT4:THENIGHT-LIGHTPROJECT5:THEBLINKINGLEDPROJECT6:THERAILROADCROSSINGLIGHTPROJECT7:THEPARTYLIGHTSPROJECT8:THEDIGITALPIANOPROJECT9:THELEDMARQUEE

WHERETOGOFROMHERERESISTORCOLORCODES

CONTENTSINDETAIL

ACKNOWLEDGMENTS

INTRODUCTIONTHECIRCUITSTHEMATERIALSHOWTOBUILDTHECIRCUITSINTHISBOOK

WHATTHECOMPONENTSLOOKLIKEBUILDINGCIRCUITSONABREADBOARD

BUILDYOURFIRSTBREADBOARDCIRCUITTHECIRCUITDIAGRAMTHEPARTSLISTBUILDINGTHECIRCUIT

CONNECTINGTHERESISTORCONNECTINGTHELEDCONNECTINGTOTHEPOWERSUPPLYCOLUMNSCONNECTINGTHEBATTERY

WHATIFTHELEDDOESNOTLIGHTUP?YOU’REREADYTOBUILDTHENINECIRCUITS!

PROJECT1:THESTEADY-HANDGAMETHECIRCUITDIAGRAMTHEPARTSLISTABOUTTHECIRCUIT

CONNECTINGTHEBATTERYTOTHEBUZZERCREATINGTHEGAMETRACKCONNECTINGTHEMETALRINGTOTHE

BREADBOARDCOMMONMISTAKESAQUIETALTERNATIVE

PROJECT2:THETOUCH-ENABLEDLIGHTTHECIRCUITDIAGRAMTHEPARTSLISTINTRODUCINGTHETRANSISTORABOUTTHECIRCUITCOMMONMISTAKESHOWTHECIRCUITWORKS

PROJECT3:THECOOKIEJARALARMTHECIRCUITDIAGRAMTHEPARTSLISTABOUTTHECIRCUITCOMMONMISTAKESHOWTHECIRCUITWORKS

PROJECT4:THENIGHT-LIGHTTHECIRCUITDIAGRAMTHEPARTSLISTABOUTTHECIRCUITCOMMONMISTAKESHOWTHECIRCUITWORKS

PROJECT5:THEBLINKINGLEDTHECIRCUITDIAGRAMTHEPARTSLISTABOUTTHECIRCUITCOMMONMISTAKESHOWTHECIRCUITWORKS

PROJECT6:THERAILROADCROSSINGLIGHTTHECIRCUITDIAGRAMTHEPARTSLISTABOUTTHECIRCUITCOMMONMISTAKES

HOWTHECIRCUITWORKS

PROJECT7:THEPARTYLIGHTSTHECIRCUITDIAGRAMTHEPARTSLISTABOUTTHECIRCUITCOMMONMISTAKESHOWTHECIRCUITWORKS

PROJECT8:THEDIGITALPIANOTHECIRCUITDIAGRAMTHEPARTSLISTABOUTTHECIRCUITCOMMONMISTAKESHOWTHECIRCUITWORKS

PROJECT9:THELEDMARQUEETHECIRCUITDIAGRAMTHEPARTSLISTABOUTTHECIRCUITCOMMONMISTAKESHOWTHISCIRCUITWORKS

WHERETOGOFROMHERE

RESISTORCOLORCODES

ACKNOWLEDGMENTS

ThankstothewholeteamatNoStarchPress,especiallyRileyHoffmanandZach Lebowski, for helping me create yet another book I’m proud of.ThankstoJohnHewes for findingmyerrorsandgivinggreat feedbackonhow to improve things throughout thebook.And a special thanks to JoshEllingsonandMimiHeftforanawesomebookcover!

INTRODUCTION

Thisbookwillhelpyouimproveyourelectronicsskills.I’llteachyouhowtointerpretcircuitdiagramsandusebreadboards.ThenI’llshowyou,step-by-step, how to build a simple circuit on a breadboard. After that, you’re onyourown:you’llrelyonpartslistsandcircuitdiagramstobuildyourcircuits.Buildingcircuitsfromdiagramsisanessentialskillforanyoneinterestedinelectronics,frombeginnerstoexperts.

THECIRCUITSThe circuits become more and more difficult to build as you progressthroughthebook.Here’sabriefdescriptionofeachcircuitproject:

Project 1:The Steady-HandGameWith this super-simple circuit,you’llcreateanOperation-stylegamewhereyouneedasteadyhandtowin.Project2:TheTouch-EnabledLightUsingatouchpad,you’llbuildatouch-enabledlightswitchtoturnonalightwithyourfinger.Project 3:TheCookie Jar Alarm Keep your cookies safe with thiscookie jar alarm, which will scare any cookie thieves away with abuzzingnoise.Project4:TheNight-LightHereyou’llbuildalightthatturnsoninthedarktohelpyouseethingsatnight.Project5:TheBlinkingLEDInthisproject,you’lllearnsomeofthebasics of digital electronics and use an integrated circuit to blink anLED.Project6:TheRailroadCrossingLightAddtoyourmodeltrainsetwith the railroad crossing light, a classic circuit that everyone shouldbuildatsomepoint.Project7:ThePartyLightsThisstringofblinkinglightsisaperfectprojecttoprepareforanupcomingparty.

Project8:TheDigitalPianoBuildyourownmusicalinstrumentfromscratchandentertainyourfriendsandfamily!Project9:TheLEDMarqueeInthisfinalcircuit,you’lluseyournewskillstocreateanawesomeLEDlightshow.

You can find resources for the circuits through the book’s website athttps://nostarch.com/circuits/.

THEMATERIALSAll of the materials you’ll need to build the circuits in this book areinexpensiveandeasy to find.Here’s a listof all theelectroniccomponentsyou’llneed.

NOTE

The part numbers shown here are for Jameco Electronics(https://www.jameco.com/).These components shouldbeavailable fromanyelectronicssupplystore.

# JAMECOPART

NUMBER

VALUE DESCRIPTION

1 #198731 9Vbattery Standard9Vbattery

1 #109154 Batteryclip Componentthatconnectsthebatterytothebreadboard

1 #20601 Breadboard Breadboardwitharound400holes

20 #2237044 Jumperwires Packofatleast20breadboardjumperwires

1 Includedin#2217511

100Ω Standardresistor

4 Includedin#2217511

1kΩ Standardresistors

2 Includedin 10kΩ Standardresistors

2 Includedin#2217511

10kΩ Standardresistors

1 Includedin

#2217511

100kΩ Standardresistor

2 Includedin#2217511

470Ω Standardresistors

2 Includedin#2217511

47kΩ Standardresistors

1 #151116 0.1μF Nonpolarizedcapacitor

1 #31000 4.7μF Polarizedcapacitor

2 #94212 10μF Polarizedcapacitors

1 #158394 100μF Polarizedcapacitor

2 #254801 BC547 Anygeneral-purposeNPNtransistorwillwork

10 #333973 LED Standardlight-emittingdiodes;allmusthaveaboutthesameforward

voltage(Vf)

1 #904085 NE555 555timerIC

1 #12749 CD4017B 4017decadecounterIC

1 #44257 74C14 HexSchmitttriggerinverter

4 #119011 MomentaryON Tactilemini-pushbuttons

1 #202454 LDR/photoresistor Light-dependentresistor(photoresistor)witharound5to10kΩresistanceinlightand200kΩormore

indark

1 #2239146 8Ωspeaker Mini-speaker

1 #2120452 Buzzer Activebuzzerthatworkswitha9Vbattery

Withyourmaterialsinhand,let’sgetstarted!

HOWTOBUILDTHECIRCUITSINTHISBOOKFor each circuit in this book, I provide a circuit diagram and a parts list.Circuitdiagramsaredrawingsthatshowyouhowtoconnectcomponentstobuildanelectroniccircuit(seeFigure1).

FIGURE1Thiscircuitdiagramshowsyouhowtoconnectabattery,aresistor,andanLED.

The parts list tells you which component values you should use—forexample,aresistorwithavalueof470Ωoracapacitorwithavalueof10μF.Eachcomponenthasasymbol,andthesesymbolsareconnectedwith linesthat showyouhow toconnect thecomponents.Witha littlepracticewithcircuit diagrams, you’ll quickly learn how to distinguish the differentsymbols.

WhattheComponentsLookLikeInthissection,I’velistedeachcomponentnexttothesymbolusedforitinthisbook.Youmightseedifferentsymbolsforthesamecomponentinotherelectronicsbooksorresources,butinthisbook,theywillbeconsistent.

Battery

Resistor

Capacitor,nonpolarized

Capacitor,polarized

Light-emittingdiode(LED)

Light-dependentresistor(LDR)

Transistor

Pushbutton(switch)

Speaker

Buzzer

Integratedcircuit

Notethatsomeintegratedcircuits,suchasthefollowingSchmitttriggerinverter, use a symbol that represents their function instead of the boxsymbol.

BuildingCircuitsonaBreadboardAbreadboardisareallysimpletoolforbuildingacircuit.Becauseyoudon’thave to solder—you just plug in the components—you can easily reusecomponentsifyouwanttobuildsomethingelselater.

Most breadboards have two areas for components and two areas forpower supplies. I’ve labeled these fourareas inFigure2.The fiveholesofeachrow inacomponentarea—labeledwithanumeral—areconnectedbymetal strips inside theboard.Therows in the leftcomponentareaarenotconnectedtotherowsintherightcomponentarea.

FIGURE2AtypicalbreadboardwithlabeledareasThewiresofacomponentarecalleditspins,legs,orleads.Tomakeaconnectionbetweentwocomponents,youplugtheirpinsintothesamerowinoneofthecomponentareas.Ifyoucan’tconnectthemonthesamerow,youcanuseajumperwireinordertomaketheconnectionfromonerowtoanother.

InFigure3,thelowerpinoftheresistorandtheupperpinoftheLEDareconnectedtoeachotheronrow7.TheupperpinoftheresistorandthelowerpinoftheLEDdon’tsharearowwithanycomponent,sotheyaren’tconnectedtoanything.

FIGURE3ConnectingaresistorandanLED

Theholes in the supply areas are connected column-wise instead.So ifyou connect the positive (or plus) terminal of your battery to the top-leftholeoftheleft-handsupplyarea,alltheholesfromthetopofthatcolumntothebottomwillbeconnectedtothepositiveterminalofyourbattery.

NOTE

Onbiggerbreadboards,thesupplyareasaresometimesdividedintofourareas:topright,topleft,bottomright,andbottomleft.

BUILDYOURFIRSTBREADBOARDCIRCUIT

THISSIMPLECIRCUITTURNSONALIGHT-EMITTINGDIODE(LED).

THECIRCUITDIAGRAM

THEPARTSLIST

PART VALUE DESCRIPTION

Battery 9V Standard9Vbattery

Batteryclip Componentthatconnectsthebatterytothebreadboard

Breadboard Plasticboardwitharound400holes

Resistor 470Ω ComponentthatreducesthecurrentthroughtheLED

LED Red Standard-outputlight-emittingdiode

Jumperwires

Twobreadboardjumperwiresindifferentcolors

BUILDINGTHECIRCUITTobuildthiscircuit,allyouneedisabattery,aresistor,andanLED.Theresistorreduces theamountofcurrent that flowsthroughtheLED.You’llalwayswantaresistorinserieswithanLED,butitdoesn’tmatterwhetheryouplaceitbeforeoraftertheLED.Whenyouaddaresistorinserieswithacircuit,yougetlesscurrentinthewholecircuit.Ifyoudon’tusearesistor,youriskbreakingtheLED.

ConnectingtheResistorForthiscircuit,you’llneedaresistorof470Ω,orohms.Ifyoulookcloselyataresistor,you’llnoticeithasseveralcoloredbands.Thesecolorstellyouthevalueoftheresistor.Tofinda470Ωresistor,lookforaresistorthathascolored bands in this order: yellow, purple, brown, and gold or silver (seeFigure1).

FIGURE1A470Ωresistor

Connectonepinof the470Ωresistor to the top rowof columnFandattachtheotherpintorow7inthesamecolumn,asshowninFigure2.Itdoesn’t matter which pin you place where; the resistor can be connectedeitherwayaround.

NOTE

In“ResistorColorCodes”onpage64,you’llfindatablethatexplainsthecolorcodingofaresistor.

FIGURE2Connectingtheresistortothebreadboard

ConnectingtheLEDNowyou’ll connect yourLED to thebreadboard.AnLEDhas two sides,called anode and cathode. For the LED to work, you need to connect theanodetothepositiveside(+)ofthebatteryandthecathodetothenegativeside(–).Forsimplicity’ssake,let’scallthemthepositivepinandthenegativepinoftheLED.I’vemarkedtheminFigure3.

FIGURE3AnLEDwithitspositiveandnegativepinsTherearetwowaystotellwhichpiniswhich.LookcloselyatyourLED.Ifonepinislongerthantheother,that’sthepositiveside.Ifbothpinsarethesamelength,lookmorecloselyattheroundedgeatthebottomoftheplastichousing.Onesideofthehousingshouldbeflat,asinFigure3;that’sthenegativepin.Ifyou’restillhavingahardtimedistinguishingbetweenthetwopins,placetheLEDonaflatsurfaceandrollitsoyoucanfindtheflatside.

ConnectyourLED’spositivepintocolumnH,row7,andthenconnectthe negative pin to column H, row 10. Check your connections againstFigure4.

FIGURE4ConnectinganLEDinserieswitharesistorNowthepositivepinoftheLEDisconnectedtotheresistor—asshowninthecircuitdiagram—butthenegativepin,liketheupperpinoftheresistor,isn’tconnectedtoanything.

ConnectingtothePowerSupplyColumnsNextyouneedtoconnectwiresfromthepowersupplyareaontherightsideofthebreadboardtotheappropriaterowsintheright-handcomponentarea.

If you look at the circuit diagram again, you can see that you need toconnect the positive terminal of the battery to the top-most lead of theresistor—the lead in row1.Souse a jumperwire to connect row1 to thepositive column in the supply area. It’s common touse the columnwith ared linenext to itas thepositiveone(tomatchtheredwireof thebatteryclip). Then connect the LED’s negative pin—in row 10—to the negativecolumninthesupplyarea.UseFigure5asareference.

FIGURE5Connectingthecomponentareatothesupplyareaofabreadboard

ConnectingtheBatteryYou have your components in place, and you’ve properly connected thecomponentstothesupplyarea.Nowyouonlyneedtoconnectthebattery.

First,connectyourbatterycliptoyourbattery,makingsuretheexposedmetaloftheredandblackwiresdoesnottouch.Next,connecttheredwirefromyourbatterycliptothepositivecolumnoftheright-handsupplyarea.Finally, connect the black wire from your battery clip to the negativecolumn.CheckyourcircuitagainstFigure6.

FIGURE6Connectingabatterytoabreadboard’ssupplyareaTheLEDshouldnowbelitup!

WHATIFTHELEDDOESNOTLIGHTUP?If your LED isn’t lighting up, go through each connection on thebreadboard tomake sure everything is exactly asdescribed in theprevioussteps.

If you’ve connected everything correctly and it’s still not working, youmighthaveconnectedtheLEDthewrongway.Flipitaroundandtryagain.

If it’s stillnotworking, check the resistancevalueofyour resistorusingthetablein“ResistorColorCodes”onpage64.Yourresistorshouldbe470Ω.

Still not working?Well, then your LED is likely dead, unfortunately.This can happen easily if you connect it directly to the battery—that is,withoutputtingitinserieswitharesistor.ReplaceyourLEDandtryagain.

YOU’REREADYTOBUILDTHENINECIRCUITS!

Nowthatyou’vebuiltyour firstbreadboardcircuit,you’realmostreadytomoveontothisbook’sninecircuitprojects.First,though,Irecommendthatyou play around a little with the circuit you built in this chapter. Try toreally understand why those connections make the circuit work.Understandingthisiscrucialtobuildingtherestofthecircuitsinthisbook.A good test is to see if you can build the circuit again in the left-handcomponentandpowersupplyareas,justbylookingatthecircuitdiagram.

For all the circuits in this book, you’ll need a breadboard, a bunch ofbreadboard jumperwires, a battery, and abattery clip.But for simplicity’ssake,youwon’tseethesecomponentsinthepartslist.

The circuits are sorted by difficulty, starting from the easiest. Thechallenge is to figure out how to connect each of the circuits on thebreadboard.Someofthelatercircuitsmightbechallengingifyoudon’thaveanypreviousexperiencewithcircuits,butthetrickistonotgiveup.

Youcanfindresources forall thecircuits throughthebook’swebsiteathttps://nostarch.com/circuits/.

1THESTEADY-HANDGAME

THISCIRCUITWILLSOUNDABUZZERIFYOULETTHERINGTOUCHTHEWIRE.

THECIRCUITDIAGRAM

THEPARTSLIST

PART DESCRIPTION

Buzzer Buzzerthatworkswith9Vbattery

Steelwire Bareandstiffwire,likeaclotheshanger

Metalring Baremetalring,likeasodacanring

Anoldpen Oldpenformountingthemetalring

Tape Electricaltapeisbest,butanytapeshouldwork

ABOUTTHECIRCUITYoumighthavegrownupplayingagamecalledOperation,inwhichyouplayasurgeonwhousestweezerstoremovesillyailments(likebrainfreezeand

charlie horse) from a patient. If you aren’t careful and touch the wrongplace,aterrifyingbuzzersoundsandthepatient’snoselightsup.

In this chapter, you’ll build a steady-hand game that works a lot likeOperation,butthegoalistomovearingalongatrackofsteelwirewithoutlettingthemtouch.Ifyougettheringallthewaytotheothersidewithouttouchingthewire,youwin.Iftheringtouchesthewire,thebuzzersoundsandyoulose.

Thecircuitworkson thebasicprinciple that for anything tohappen inelectronics,theremustbeaclosedloop—acontinuouspathfromthepositiveto the negative side of the batterywhere the current can flow.When themetal ring doesn’t touch the steel wire, you don’t have a closed loop, sonothing happens.When the ring touches the steel wire, you get a closedloopandthebuzzersounds.

ConnectingtheBatterytotheBuzzerThecircuit itself isprettysimple.Youjustneedtoconnectthebuzzerandthebattery,intheblackpartofthecircuitdiagram,tothebreadboard.Makesureyouplacetheplussign(+)onthebuzzertowardthepositiveterminalofthe battery. Remember, the red lead of the battery clip connects to thepositiveterminalonthebattery.

Addtwoloosejumperwires—onefromthenegative(–)sideofthebuzzerandonefromthenegativebatteryterminal(thetwoyellowwiresinFigure1-1).

FIGURE1-1ConnectingthebatterytothebuzzerNowyoujustneedtocreateagametrackandintegrateitintothecircuit.

CreatingtheGameTrackTocreatethegametrack,useasteelwirefromaclotheshangerandbenditintotheshapeyouwant.Connectthesteelwiretothebreadboardusingtheloose jumper wire from the negative connection of the battery and sometape,asinFigure1-2.Makesurethemetalattheendofthejumperwireistouchingthesteelwiresothere’sagoodelectricalconnectionbetweenthem.

FIGURE1-2TapingajumperwiretothegametrackAnykindoftapeshouldwork,butIrecommendelectricaltapeasitstickswelltometal.

ConnectingtheMetalRingtotheBreadboardFor themetal ring,youcanuse the tab fromacan, like theone shown inFigure1-3.

FIGURE1-3Usethemetalringfromacantolooparoundthetrack.

Tapetheringandthelooseendofthejumperwirefromthenegativesideof thebuzzer to theendofanoldpen,makingsure the jumperwirehasagood connection with the metal (see Figure 1-4). The pen offers playerssomethingtoeasilygraspastheynavigatetheturnsinthetrack.

FIGURE1-4Tapingthemetalringtoapen

That’s it!Thecircuit iscomplete, sonowyoucantesthowsteadyyourhandsare!

COMMONMISTAKESIf thecircuit isnotworkingproperly,double-check thatyouhaven’tmadeanyofthesecommonmistakes:

NotcreatingagoodconnectionbetweenthejumperwireandthetrackNotcreatingagoodconnectionbetweenthejumperwireandtheringConnectingthebuzzerwrongway(rememberthatithasapositiveandanegativeside)

If youare still strugglingwith this circuit, findmore resources throughthebook’swebsiteathttps://nostarch.com/circuits/.

AQUIETALTERNATIVEIf you prefer a noiseless game—so you can play without disturbing otherpeople—youcanmodifythegamesoitusesanLEDinsteadofabuzzer.Just

replacethebuzzerinthecircuitwithanLED.Don’tforgettoputtheLEDin serieswith a resistor (just like your first breadboard circuit); otherwise,youriskbreakingtheLED.

2THETOUCH-ENABLEDLIGHT

LIGHTUPANLEDWHENYOUTOUCHATOUCHPADMADEFROMTWOUNINSULATEDWIRES.

THECIRCUITDIAGRAM

THEPARTSLIST

PART VALUE DESCRIPTION

R1 470Ω Standardresistor

LED Red/yellow/green Standard-outputlight-emittingdiode

Q1 BC547 General-purposeNPNtransistor

INTRODUCINGTHETRANSISTORInthiscircuit,you’lluseatransistor—specifically,anNPNtransistor.Ithasthreepins:

Toppin:CollectorMiddlepin:BaseBottompin:Emitter

Don’tworryaboutthemeaningofthepinnames—justthinkofthemaslabels.

Turn the transistor so its label is facing you and compare the pins to

Figure 2-1. Note, however, that different manufacturers arrange the pinsdifferently.Thesafestbetwhenyou’reusinganewtransistoristocheckthepinoutinthetransistor’sdocumentation,ordatasheet.

FIGURE2-1AnNPNtransistoranditspinout

ABOUTTHECIRCUITInthisproject,you’llbuildatouchsensorbycreatingatouchpadfromtwouninsulatedwires.Usingatransistor,youcandetectwhensomeonetouchesthetouchpadandturnalighton.Whensomeonetouchesthetouchpad,thehigh resistance in their finger connects the base of the transistor to thepositiveterminalofthebattery.Thiscompletesthepathfromthebattery’spositive terminal to its negative terminal and allows a tiny current to flowfromthebasetotheemitter.

The current is tiny because human skin is a poor conductor and has ahigh resistance; the current is tooweak to light anLEDdirectly,which iswhyweneed the transistor.The tinycurrent flowing fromthebase to theemitterwill turn the transistor“on”so thata largercurrentcan flow fromthe collector to the emitter. Current will flow through the LED and theresistor—makingtheLEDlightup—onlyifthetransistoristurnedon.

Whennobodyistouchingthetouchpad,thebaseisleftunconnected,sonocurrentwillflowthroughthatpinandtheLEDwillnotlightup.

To create the touchpad, clip off a bit of yourLED’s pins, as shown in

Figure2-2.Thenplacethesehorizontallyontworows.Leaveoneholeopenforconnectingthetouchpadtotherestofthecircuit.

CAUTION

Do not allow the two metal pads of the touchpad to make contact when thebatteryisconnected.Iftheytouch,alotofcurrentwillflowfromthebasetotheemitterandyoumightdamageyourtransistor,makingitunusable.

FIGURE2-2CuttingthepinsoffyourLEDtouseasatouchpadPlacethecut-offpinshorizontallyontworows.Makesureyouleaveoneholeineachofthoserowsopensoyoucanconnectthetouchpadtotherestofthecircuit.

COMMONMISTAKESIfyoucan’tgetthecircuittowork,makesureyouhaven’tmadeanyofthesecommonmistakes:

MixingupthepinsofthetransistorDestroyingthetransistorbylettingthetwometalpadsofthetouchpadmakedirectcontactConnectingtheLEDbackwardDry fingertip; try wetting your finger a bit (damp skin has a lowerresistance,allowingabitmorecurrenttoflow)

If you’re still struggling with this circuit, you can findmore resourcesthroughthebook’swebsiteathttps://nostarch.com/circuits/.

HOWTHECIRCUITWORKSTo get current to flow in a circuit, you need a path from the battery’spositiveterminaltoitsnegativeterminal.Ifyoudon’thavethispath,currentcan’t flowandtheLEDwon’t lightup.Turningthetransistor“on”allowscurrenttoflowthroughitfromitscollectortoitsemitter.

Toturnthetransistoron,youneedtohavecurrentflowingfromitsbasetoitsemitter,whichinturnletscurrentflowfromitscollectortoitsemitter.Theamountof current flowing from thebase to theemitter controlshowmuchcurrentcanflowfromthecollectortotheemitter.

You can find the relationship between the base-to-emitter and thecollector-to-emitter currents from the current gain of the transistor. ThegainisoftencalledhFEorβ(beta).Forageneral-purposetransistorliketheone you’re using here, the current gain is about 100. This means thecollector-to-emittercurrentcanbeupto100timeslargerthanthebase-to-emittercurrent.

Inthiscircuit,whennooneistouchingthetouchpad,thereisnocurrentflowingfromthebasetotheemitter.Thismeansthetransistoris“off”andthere’snocurrentflowingthroughtheresistorandtheLED.

When you touch the touchpad, your finger acts as a resistor from thepositiveterminalofthebatterytothebaseofthetransistor.Atinycurrentrunsthroughthebasetotheemitter,whichproducesalargercurrentfromthe collector to the emitter. Current will also run through your LED,lightingitup.

3THECOOKIEJARALARM

THISALARMBUZZESWHENITSENSESLIGHT.

THECIRCUITDIAGRAM

THEPARTSLIST

PARTVALUE DESCRIPTION

LDR 200kΩ Light-dependentresistor(photoresistor)witharound5to10kΩresistanceinlightand200kΩormoreindark

Q1 BC547 Anygeneral-purposeNPNtransistor

R2 1kΩ Standardresistor

Buzzer Activebuzzerthatworkswitha9Vbattery

ABOUTTHECIRCUITDoyouwanttokeeppeoplefromstealingcookiesfromyourcookiejar?Orkeepspiesfromsnoopinginyourtreasurechest?Thenthiscircuitisforyou.

Thiscircuit staysquietwhen it’s inadarkplace, suchas inacookie jarwiththe lidon.Butoncethe lidcomesoffandlets light inside, thecircuitsoundsanalarmthatshouldscareoffanycookiethieves.

The circuit uses a light-dependent resistor (LDR) to detect light. Its

resistance changes when it detectsmore or less light. Themore light theLDRdetects,thelowertheresistance.

TheLDRandR2makeupavoltagedivider,whichcontrolstheamountofinputvoltageatthebaseofthetransistor,switchingthetransistorofforondependingonhowmuchlightisdetected.

Once your circuit is complete, you can put it in your cookie jar ortreasurechesttoprotectyourpreciousbelongings.

COMMONMISTAKESIfyoucan’tgetthecircuittowork,checkforthefollowing:

The resistance value ofR2 is too high or too low.Refer to “ResistorColorCodes”onpage64forhelpreadingtheresistor’scolorcoding.Youconnectedthetransistorthewrongway.IfyouneedarefresheronconnectinganNPNtransistor,refertoProject2.

Ifyouwanttomakethecircuitmoreorlesssensitivetolight,replaceR2withahigher(moresensitive)orlower(lesssensitive)resistancevalue.

If you have questions about this circuit, you can find more resourcesthroughthebook’swebsiteathttps://nostarch.com/circuits/.

HOWTHECIRCUITWORKSThe buzzer will sound only if current is flowing through it, which canhappen only if there is a path from the battery’s positive terminal to itsnegativeterminal.Thismeansthealarmwillsoundonly if thetransistor isturned “on” so that current can flow from the battery’s positive terminalthrough thebuzzer, then from the transistor’s collector to its emitter, andfinallybackintothebattery’snegativeterminal.

AsyousawinProject2,foratransistortobeturned“on,”currentneedsto flow from its base to its emitter. This happens only when the voltagebetweenthebaseandemitterisabout0.7V.Whenthevoltageismuchlessthan0.7V,nocurrentflowsthroughthebase,andemitterandthetransistorisoff.

InthecircuitdiagraminFigure3-1,youcanseethatthevoltagefromthebasetotheemitterisequivalenttothevoltageacrossR2.

FIGURE3-1Creatingavoltagedivider

TheLDRandR2areconnectedtoformavoltagedivider.TheLDRisR1 in thisdiagram.The formula for calculating theoutput voltage fromavoltagedivideris:

If it’s dark, theLDRhas around 200 kΩ resistance ormore, andR2 isalways 1 kΩ. You’re using a 9V battery, soVin is 9V. If you plug thesevaluesintotheformula,youget:

ThisgivesyouaVoutofabout0.04V,whichistoolowforthetransistortoturnon.

If it’s light,theLDRhasaround10kΩresistanceor less.Plugthis intothevoltagedividerformula,andyou’llget:

Inthiscase,Voutequalsabout0.8V.Thisismorethanthe0.7Vrequiredforcurrenttoflowfromthebasetotheemitter,sothetransistorturns“on,”allowing current to flow through the buzzer, collector, and emitter andsoundingthealarm.

4THENIGHT-LIGHT

THISCIRCUITISANIGHT-LIGHTTHATTURNSONINTHEDARK.

THECIRCUITDIAGRAM

THEPARTSLIST

PARTVALUE DESCRIPTION

LDR 10kto200kΩ

Light-dependentresistor(photoresistor)witharound5to10kΩresistanceinlightand200kΩormoreindark

Q1 BC547 Anygeneral-purposeNPNtransistor

R1 100kΩ Standardresistor

R3 470Ω Standardresistor

LED Standard-outputlight-emittingdiode

ABOUTTHECIRCUITThiscircuit turnsonanLEDwhen itgetsdark.During theday, the lightstays off, but at night, it can help you see things like the keyhole in yourfrontdoororaglassofwateronyournightstand.

This circuit is similar to the one in Project 3, but here the transistorcontrols an LED instead of a buzzer. Remember, the LED has a resistorconnectedinseriestolimititscurrent.

Also,theresistorandLDR,whichformthevoltagedividerthatsetsthevoltagetothebaseofthetransistor,haveswitchedplaces.

InProject3, theLDRwastheupperresistoronthevoltagedivider.SowhentheresistanceoftheLDRwaslow—thatis,whenitsensedlightfromtheopenedcookiejar—thetransistorturnedon.Inthiscircuit,theLDRisthelowerresistorofthevoltagedivider.ThatmeansthetransistorturnsonwhentheresistanceoftheLDRishigh,whichhappenswhenit’sdark.

COMMONMISTAKESIfyourcircuitisn’tworkingcorrectly,checkforthefollowing:

TheR1resistancevalueistoohigh,sotheLEDneverturnson.Ifyouchange R1, its resistance must not be less than 1 kΩ (see “How theCircuitWorks”next).TheR1resistancevalueistoolow,sotheLEDisalwayson.You used the wrong value for R3—either too much or too littleresistance.Youconnectedthetransistorthewrongway.YouconnectedtheLEDthewrongway.

Youcanchangethecircuit’ssensitivitytolightbychangingtheresistanceofR1,butasmentionedpreviously,itmustnotbelessthan1kΩ(otherwiseyoumaydestroythetransistor).

If you’re still struggling with this circuit, you can findmore resourcesthroughthebook’swebsiteathttps://nostarch.com/circuits/.

HOWTHECIRCUITWORKSJustas in theCookie JarAlarm, theLDRand theresistor (R1)makeupavoltagedividerinthiscircuit.ButsincetheLDRisnowplacedatthebottomof the voltage divider (between the transistor base and negative battery

terminal), it works opposite to how the Cookie Jar Alarm works. In thiscircuit, when it’s dark and theLDR resistance is high, the voltage on thetransistor’sbasewillbehighenoughtoturntheLEDon(showninFigure4-1).ThismeansthetransistorswitchesontheLEDwhenit’sdark.

FIGURE4-1Theamountofcurrentflowingfromthebasetotheemitterdetermineshowmuchcurrentcanflowfromthecollectortotheemitter.

TheLDR that I used for this projecthas around5 to10kΩ resistancewhenit’sinlight.Withthe100kΩresistor(R1),theLEDwillturnonwhenthevalueoftheLDRgoesaboveabout10kΩ.

Acuriousthingaboutthiscircuit isthattheR1resistorwillalsosetthemaximumbrightnessoftheLED.ThisisbecauseR1determinestheamountof current that flows into thebaseof the transistor,which in turndecideshowmuchcurrentcanflowintothecollector.

Forageneral-purposetransistorliketheoneyou’reusinginthisproject,theamountofcurrentflowingfromthecollectortotheemittercanbeupto100timesgreaterthanthecurrentflowingfromthebasetotheemitter.

Thatmeansthatifyouhave0.1mAofcurrentflowingfromthebasetothe emitter, you can have up to 10mA flowing from the collector to theemitter.If10mAistheupperlimitfromthecollectortotheemitter,that’sthemaximumthatcanflowthroughtheLEDtoo.

The current that flows into the base of the transistor has to first flowthroughR1.NotallthecurrentthatflowsthroughR1willgointothebase—some will go through the LDR too—but when it’s dark, the LDRresistanceissohighthatyoucansimplifyforthesakeofthecalculationandsaythatallthecurrentgoesintothebase.

Findingthecurrent(I)throughR1isactuallyquitesimple.Justfindthevoltage(V)acrosstheresistoranddivideitbytheresistorvalue(R):

Thiscalculation isbasedonOhm’s law,whichdescribes therelationshipamongvoltage,resistance,andcurrent.YoucanlearnmoreaboutOhm’slawathttps://www.build-electronic-circuits.com/ohms-law/.

Thevoltageontheuppersideoftheresistoriseasy.It’s9Vbecauseitisconnectedtothepositiveterminalofthebattery,butwhataboutthelowerside?Sinceyou’re looking for themaximumcurrent thatcan flowthroughthetransistor,itonlymakessensetolookatthecurrentwhenthetransistoris turned on. When the transistor is on, the voltage on the base of thetransistorisaround0.7V.

Soyouhave9Vononesideand0.7Vontheother.Thismeansyouhave8.3V across the resistor (R1).UsingOhm’s law, you can divide 8.3V by100,000 Ω (= 100 kΩ) to get 0.000083 A (= 0.083mA), so the maximumcurrent that can flow through the LED and into the collector of thetransistoris100timeslarger,or8.3mA.

SinceR1islimitingthecurrenttoavaluethatissafefortheLED,inthiscircuityoucouldactuallyskiptheR3resistor,whosejobisalsotolimitthecurrenttotheLED.

5THEBLINKINGLED

THISCIRCUITMAKESANLEDBLINKONANDOFF.

THECIRCUITDIAGRAM

THEPARTSLIST

PARTVALUE DESCRIPTION

U1 74C14 HexSchmitttriggerinverter

C1 100μF Polarizedcapacitor

R1 10kΩ Standardresistor

R2 470Ω Standardresistor

LED Standard-outputlight-emittingdiode

ABOUTTHECIRCUITOneofthefirstthingsIwantedtolearninelectronicsasakidwashowtoblink a light. You can do this in one of several ways, but this circuit isprobably the easiest way to do it, especially because it requires so fewcomponents.Infact,youneedonlyfivecomponents, includingtheresistorandtheLED.

The circuit works around an inverter, a component that outputs theoppositevoltageofwhatittakesin.Ifitgetsahighvoltagein,itgivesalowvoltageout,andviceversa.Ahighvoltageisavoltageclosetothepositive

supplyvoltage(9Vinthiscase),andalowvoltageisavoltagecloseto0V.The output of the inverter (U1) is connected back to the inputwith a

resistor,whichcausesoscillation,orjumpingbackandforthbetweenhighandlow voltage. If the inverter input is high, then its outputwill be low.Youconnectthatlow-voltageoutputbacktotheinverter’sinput,andbecausetheinput is low, theoutputwill behigh.Thathigh-voltageoutput is directedbacktotheinverter’sinput,andsoon.

To slow down the oscillation enough to see theLEDblink, you use acapacitor on the input of the inverter. A capacitor stores and dischargesenergy;thecharginganddischargingofthecapacitorinthiscircuit(C1)willincreasethetimeittakesfortheinputtogofromlowtohighandfromhightolow.Theresistor(R1)controlshowmuchcurrentgoesbackandforthtochargeanddischargethecapacitor,sothesizeofR1andC1determinesthespeedoftheoscillation.

You should use a 74C14 IC Schmitt trigger inverter; its threshold forswitching from high to low voltage is different from the threshold forswitchingfromlowtohigh.Thisensuresthattheinverterdoesn’tgetstuckinastateinbetweenhighandlow.

TheSchmitt trigger inverter comes as a 14-pin integrated circuit (IC), asinglechipwithitsowninternalcircuitry.Thenumbernexttoeachpininthe circuit diagram represents the pin number on the integrated circuit.Figure 5-1 shows how the pins are arranged on the 74C14 IC Schmitttriggerinverter.

FIGURE5-1Pinoutofthe74C14Schmitttriggerinverter

ToconnectanICtoabreadboard,youneedtoconnectitacrossthetwo

componentareas,asinFigure5-2.

FIGURE5-2ConnectingtheinverterICacrossthetwocomponentareas

Thiswillgiveyouconnectionsforpins1to7ontheleftcomponentareaandconnectionsforpins8to14ontherightcomponentarea.Notethatpin1 is indicated by a circular indentation in one corner of the inverter or anotchatitspin1end.

COMMONMISTAKESIf your circuit isn’t working correctly, youmight havemade one of thesecommonmistakes:

Forgetting to connect VDD (pin 14) to the positive terminal of thebatteryForgetting to connect GND (pin 7) to the negative terminal of the

batteryMisreadingthepinoutoftheICMistakingthepositiveLEDpinforthenegativepin

Todecreasetheblinkingspeed,increaseeitherthecapacitorvalueortheresistance value of R1 (or both).To increase the blinking speed, decreasethosevalues.

If you are still strugglingwith this circuit, you can findmore resourcesthroughthebook’swebsiteathttps://nostarch.com/circuits/.

HOWTHECIRCUITWORKSAninverterisadevicethatinvertsitsinput.Soalowinputbecomesahighoutput,andviceversa.Youcanbuildasimpleinverterusingatransistorandacoupleofresistors,asshowninFigure5-3.

FIGURE5-3Aninverterbuiltusingatransistor

When you have a low voltage (0 Volts) on the input, the transistor isturned off, andwhen you have a high voltage (9Volts) on the input, thetransistoristurnedon.

SIMPLIFYINGWITHTHEVDDANDGNDSYMBOLS

The symbols at the top and bottom of Figure 5-3 arecommonincircuitdiagrams.Forthebattery-drivencircuitsinthisbook,VDDiswhereyouconnectthepositiveterminalofyour battery, and GND is where you connect its negativeterminal.

You can use these two symbols to simplify your circuitdiagramsabit,becausetheyletyouomitthebatterysymbolandthelinesconnectingittothecircuit.

Whenthetransistorisoff,youcanthinkofitasaresistorwithveryhighresistancebetweenthecollectorandemitter(Rtinthediagram),andwhenthetransistorison,youcanlookatitasaresistorwithzeroresistance.Youmightfindthiseasiertounderstandifyouignoretheinputforasecondandjust lookattheoutputcircuit,as inFigure5-4.Youmayhavenoticedthatyougetavoltagedivider.

FIGURE5-4Thesimpleresistorwiththetransistorturnedoff

In Project 3, you learned how to calculate the voltage from a voltagedivider.ForR1andRtinFigure5-4,theformulaforcalculatingtheoutputvoltagebecomes:

Whenyouhaveahighinput,youcanlookatthetransistorasaresistor(Rt)withzeroresistance(orawire).IfyoureplaceRtwith0inthisformula,it doesn’t matter what the other values are: you’ll get 0 V as the outputvoltage,sothat’salowoutput.

Whenyouhavea low input,youcan lookat the transistoras a resistorwithreallyhighresistance—say,billionsofohms.AnormalvalueforR1is1,000Ω,soifyouhave9VasVinandyoutrytoput1billionohmsintotheformulaasRt,theresultis9V—ahighoutput.

The Schmitt trigger inverter works in a similar way, but with someadditionalcomponentsbuiltintotheICtomakethecircuitswitchfromhightolowandfromlowtohighatdifferentinputvoltages.

The74C14chipyouuseinthisprojectisanintegratedcircuitcontainingsix inverters, which is why it has so many pins. You can see the circuit’spinoutandinternalinvertersinFigure5-5.

FIGURE5-5The74C14chipcontainssixinverters

Becauseofitssmallsize,usinganintegratedcircuitlikethe74C14savesyoualotofspacecomparedtobuildingtheinverterfromscratch.

6THERAILROADCROSSINGLIGHT

THISCIRCUITFLASHESTWOLEDSINANALTERNATINGPATTERN.

THECIRCUITDIAGRAM

THEPARTSLIST

PART VALUE DESCRIPTION

R1,R4 470Ω Standardresistor

R2,R3 47kΩ Standardresistor

Q1,Q2 BC547 Anygeneral-purposeNPNtransistor

C1,C2 10μF Polarizedcapacitor

L1,L2 Standard-outputlight-emittingdiode

ABOUTTHECIRCUITThiscircuitmakestwoLEDsflashinanalternatingpattern.Youcanuseitforamodelrailroadcrossing,forexample,orforeyesonatoyrobot.

This is a classic circuit called an astablemultivibrator. In Project 5, youmade an LED blink using an inverter that turned itself on and offcontinuously. The astable multivibrator is a circuit that instead uses two

transistorsthatturneachotheronandoff.Toreallygraspwhat’sgoingonin this circuit, you need to have a strong understanding of the basics ofelectronics, especially around how voltages behave in circuits withcapacitors.

COMMONMISTAKESThiscircuithasalotofconnections,soit’sveryeasytooverlooksomething.IoftenmakemistakeswhenIbuildthisone,eventhoughI’vedoneitplentyoftimes.Ifyourcircuitisn’tworkingcorrectly,checkforthefollowing:

Using470Ωresistorswhereyouneed47kΩandviceversaConnectingtheLEDsthewrongwayMixingupthetransistorpinsHavingpinsaccidentallytouch,especiallyaroundthetransistorsConnectingthecapacitorsthewrongwayaround

Ifyouwanttochangetheflashingspeed,tryreplacingthetwocapacitors(C1andC2)andtheresistors(R2andR3)withothervalues.

If you’re still struggling with this circuit, you can findmore resourcesthroughthebook’swebsiteathttps://nostarch.com/circuits/.

HOWTHECIRCUITWORKSHaving a good handle on the basics of electronics, especially on howvoltagesbehave incircuitswithcapacitors,willhelpyouunderstandwhat’shappeninghere. Inthiscircuit, showninFigure6-1, theLEDonthe left-handsideislitwhenthetransistorontheleft-handside(Q1)ison,andtheLEDontheright-handsideislitwhenthetransistorontheright-handside(Q2) is on. Transistor Q1 is controlled by the voltage at the junctionbetweenR3andC2,whiletransistorQ2iscontrolledbythevoltageatthejunctionbetweenR2andC1.

FIGURE6-1Thevoltageontheleftnodecontrolstherighttransistor(Q2)andviceversa.

Next,youhavetolookindetailatthevoltagesacrossthetwocapacitors.Ifyouaren’tcomfortablewithhowvoltagesandcurrentsbehaveinacircuit,I recommend reading this article before you move on: https://www.build-electronic-circuits.com/kirchhoffs-law/.

Herearetwothingstokeepinmindbeforedivingintotheexplanation:

Voltage is alwaysmeasured between two points.Whenwe talk aboutthevoltageataspecificpoint,wemeanthevoltagemeasuredfromthatpoint to the battery’s negative terminal—that’s why the negativeterminalis0V.Throughout thisbook,we’reusing the transistor as a switch. Itneeds0.7Vonthemiddlepin(base)toturnon.Whenthetransistorison,itstop pin (collector) is connected to its bottom pin (emitter) so thatcurrent can flow through it.This alsomeans that the toppinhas thesame voltage as the bottom pin when the transistor is on.When thetransistor is off, there’s no connection between the top pin and thebottompin,sonocurrentcanflow.

Let’s start by looking at the circuit whenLEDL1 is lit and the otherLEDisoff.L1islitonlywhentransistorQ1isturnedon.Rememberthat

Q1isturnedononlyifithas0.7Vonitsbase.Sincethenegative(–)sideofcapacitorC2isconnectedtothebaseofQ1,thismustalsobe0.7V.

ThepositivesideofC2isconnectedtothe9VthroughR4andL2,anditalmostinstantlychargestoabout8V(somevoltageisusedupacrossLEDL2).Youmaybethinking,“Hey,ifthereiscurrentflowingthroughR4andL2,whyisn’tL2lit?”Thereasonisthatassoonasthevoltageontherightsideofthecapacitorrisesto8V,nomorecurrentflowsthroughtheLED,andthusitdoesn’tlightup.

Figure6-2showsthevoltageswehavefoundsofar.

FIGURE6-2ThevoltageonthepositivesideofcapacitorC2quicklyreachesabout8VwhentheLEDontheleftislit.

Nowlet’slookatthevoltagesfortheothertransistor,Q2.Sincethetransistorisoff,itsbasemustbelowerthan0.7V.Thenegative

sideofC1isconnectedtothebase,sothatmeansitisalsolowerthan0.7V.But the negative side ofC1 is also connected to 9V through resistorR2,whichmeans it is being charged and the voltage is slowly increasing frombelow0.7V,asshowninFigure6-3.

FIGURE6-3ThevoltageontherightofC1issomewherebelow0.7V,butincreasing,whentheleftLEDislit.

Sothevoltageon thenegative sideofC1 is rising,andwhen it reaches0.7 V, the action starts. When the negative side of C1 reaches 0.7 V,transistorQ2gets0.7Vonitsbaseandturnson;thismeanstheLEDontherightalsoturnson.

WhenQ2turnson,somethinginterestinghappenswiththevoltagesoncapacitorC2: fromFigure6-2,weknowthatC2had0.7Vonitsnegativesideand8Vonitspositiveside.Or,putanotherway,thenegativesidewas7.3Vlowerthanthepositiveside.ButnowthatQ2turnson,thevoltageonthe positive side of C2 is suddenly pulled down to 0 V through thetransistor. The internal charge of the capacitor doesn’t change instantly,though,sothevoltagedifferenceacrossC2initiallystaysthesame,withthenegative side7.3V lower than thepositive side.Butnow that thepositivesideis0V,thenegativesidebecomes7.3Vbelow0,or–7.3V!With–7.3VonthenegativesideofC2,thebaseoftransistorQ1alsogets–7.3V,whichturnsitoff(seeFigure6-4).

FIGURE6-4WhentransistorQ2turnson,thetransistorandLEDontheleftturnoff.

Sonow,theleftLEDandtransistorhaveturnedoff.AndtherightLEDandtransistorhaveturnedon,asshowninFigure6-4.ThenegativesideofC2 starts at –7.3 V and is being charged through resistor R3—and isthereforerising.SincethisisconnectedtothebaseoftransistorQ1,whenitreaches0.7V,Q1turnsonagain,andthecyclerepeats.Thetwotransistorskeepalternatingbetweenonandoff,whichmakes the twoLEDsalternatebetweenonandoffaswell.

7THEPARTYLIGHTS

THISCIRCUITCONNECTSMULTIPLEBLINKINGLEDSTOMAKESTRINGLIGHTS.

THECIRCUITDIAGRAM

THEPARTSLIST

PART VALUE DESCRIPTION

R1 10kΩ Standardresistor

R2 100kΩ Standardresistor

R3 100Ω Standardresistor

C1 4.7μF Polarizedcapacitor

L1toL6

Red,yellow,orgreen

StandardLEDs;allmusthaveaboutthesameforwardvoltage(Vf)

U1 NE555 555timerIC

ABOUTTHECIRCUITIfyouwanttomakesomethingcoolforaparty,thisisthecircuitforyou.It’sasimplewaytomakeseveralLEDsblinkatthesametime.Byropingallthelightstogetheronasinglelongwire,youcanhangtheminawindoworusethemtodecorateatree.

The circuit uses a 555 timer, which is a classic integrated circuit thatmakes things turnonandoff repeatedly;youcan see the timer’spinout inFigure7-1.

FIGURE7-1555timerpinoutTworesistors(R1andR2)andapolarizedcapacitor(C1)settheblinkingspeed,whileathirdresistor(R3)determinesthecurrentthatgoesouttotheLEDs.

COMMONMISTAKESIf your circuit isn’t working correctly, youmight havemade one of thesecommonmistakes:

ConnectingoneormoreoftheLEDsthewrongwayConnectingthe555timerthewrongwayConnectingthecapacitorthewrongwayaroundMixing up the pin numbers of the IC and connecting components tothewrongpin

YoucanaddorremoveLEDsbychangingthevalueoftheresistor(R3).IfeachLEDneeds10mAandyouwanttousefiveLEDs,youneed5×10mA,or50mA,throughtheresistor.YoucanuseOhm’slawtofigureoutthe

correctresistorvalue:Ohm’s law states that the resistance is equal to the voltage across the

resistor divided by the current flowing through it. In your five-LEDexample, that translates to the following equation:

In this case, you areworkingwith a 9Vbattery and there’s about 2VacrosstheLEDs,soyouget7Vasthenumerator.Youdividethatbythe50mAcalculatedearliertoget140Ωofresistance.Notethatyourcircuitwill

require less resistance as you addmoreLEDs andmore resistance as youremoveLEDs.

If you’re struggling with this circuit, you can ask questions and makecommentsthroughthebook’swebsiteathttps://nostarch.com/circuits/.

NOTE

A 555 timer can give out only 100 to 200 mA in total. Check your chip’sdatasheetfortheexactvalue.

HOWTHECIRCUITWORKSFigure7-2showstheinsideofthe555timer.Thegreenboxmarked“flip-flop” is a simple memory device with two states: output high (flip) andoutputlow(flop).Ithastwoinputs,set(S)andreset(R),whicheithersettheoutput(Q)tohighorresetittolow.Qisalwaystheoppositeof .

The two triangles you see are comparators. If the comparator inputmarkedwith+hasahighervoltagethantheonemarkedwith–,theoutputishigh;otherwise,theoutputislow.

FIGURE7-2Theinsideofa555timerThethree5kΩresistorsbetweenVCCandGndarethereasonforthename“555.”TheydividetheVCCvoltagebythreeandsetfixedvoltagesforeachofthecomparators:one-thirdoftheVCCvoltagegoestothepositive(+)inputofcomparator1,andtwo-thirdsoftheVCCvoltagegoestothenegative(–)inputofcomparator2.

If you look at the output (pin 3) in Figure 7-2, you’ll see that it’sconnected to theoutputof the flip-flop.Thismeans that if the flip-flop is“set,”theoutputishigh;otherwise,itislow.Ifyoulookattheinputtotheflip-flop,you’llseethatthetwocomparatorshandlesettingandresettingtheflip-flop.Thismeansthatthepinsresponsibleformakingtheoutputturnonandoffarepins2and6.

Pin 2 is labeledTrigger and is responsible for setting the output high.Whenthevoltageonpin2goeslowerthanone-thirdofVCC,comparator1outputshighandsetstheflip-flop,whichinturnsetstheoutputhigh.Pin6is labeledThreshold; when its voltage exceeds two-thirds of the VCC, it isresponsibleforresettingtheoutputtolow.

Referbacktothecircuitdiagramatthebeginningofthisproject.Forthisproject’s circuit, pins 2 and 6 are connected to each other, so when thevoltageonthesepinsgoeshigh,theoutputgoeslow.Whenthevoltageon

thesepinsgoes low, theoutputgoeshigh.Thatmeansyouneed to switchthevoltageonthesepinsbetweenhighandlowinordertoswitchtheoutputbetweenlowandhigh.

Pin 7 is very important formaking this happen. It is labeledDischarge.Inside the chip, pin 7 is connected to a transistor, as shown in the figure.The transistor is controlled by , the opposite value of the output. Thismeansthatwhentheoutputislow,thetransistorgetsahighvalueandturnson, connectingpin7 toground.Otherwise, the transistor isoff and leavespin7unconnected.

Themomentweapplypower toourcircuit, capacitorC1 iscompletelydischarged. That means pin 2 (Trigger) is low, which means pin 3 (theoutput) ishigh.Thisalsomeansthatpin7(Discharge) isnotconnectedtoanythinginternally.

SinceC1isconnectedto9VthroughR1andR2,C1willstarttocharge,andthevoltageonitspositivepinwillbegintorise.Thismeansthevoltageon pin 6 (Threshold) is increasing, too.When the voltage becomes highenough on Threshold, the output changes from high to low, and pin 7(Discharge)isconnectedinternallytoground.

In this situation,whenpin 7 is connected to ground, the capacitorwillstart to discharge (hence the pin name Discharge) through R2, down togroundatpin7.Sothevoltageacrossthecapacitordecreasesandcontinuesto do so until the voltage on pin 2 is so low that it “triggers.”When ittriggers, the output switches from low to high, and pin 7 is disconnectedfromgroundagain.

Nowwe’reinthesamesituationaswhenwestarted,wherethecapacitoris charging so that the voltage over the capacitor increases. This processrepeatsindefinitely.

Thefollowingisabriefoverviewofeachpinonthe555timer:

Pin1GroundThispinisconnectedtothenegativesideofthebattery.Pin2TriggerWhenthispingoeslow(lessthanone-thirdofVCC),theoutputgoeshigh.Pin3OutputTheoutputvoltagefromthechipisaround1.5VlowerthanVCCwhenhighandaround0Vwhenlow.Pin 4ResetThis pin resets thewhole circuit. It’s an “inverted” pin,

whichmeansitresetswhenthepingoeslow.Thismeansthepinmustbehighnormallysothatthechipisn’tina“reset”state.Pin 5 Control Voltage This pin is used to control the thresholdvoltage of the Threshold pin. This can be useful when you want toadjust the frequencyof the circuitwithout changing thevaluesofR1,R2,andC1.Forthiscircuit,youcanleaveitunconnected.Sometimesyou’llseethispinconnectedwithacapacitortoground;thisisawaytokeepanynoiseonitfrominfluencingthefrequency.Pin6ThresholdThispinsetstheoutputbacktolowwhenthevoltagegoeshigh(abovetwo-thirdsofVCC).Pin7DischargeThispinisunconnectedwhenoutputishigh,andit’sconnectedtogroundwhenoutputislow.Pin8VCCSupplyThisisthepositivepowersupplypinandcantakeavoltagebetween5and15V.

8THEDIGITALPIANO

THISPROJECT’SFOURBUTTONSPLAYFOURUNIQUETONES.

THECIRCUITDIAGRAM

THEPARTSLIST

PART VALUE DESCRIPTION

R1 1kΩ Standardresistor

R2 10kΩ Standardresistor

R3–5 1kΩ Threestandardresistors

R6 100Ω Standardresistor

C1 0.1μF Nonpolarizedcapacitor

U1 NE555 555timerIC

S1–S4 MomentaryONFourtactilemini-pushbuttons

SPK1 8Ω Mini-speaker

ABOUTTHECIRCUITInthiscircuit,you’llbuildamusicalinstrumentwithfourbuttonsthatplayfourdifferenttones.

Tocreatesound,youneedtosendanoscillatingvoltagetothespeaker.So,you’llusea555timertocreateavoltagethatgoesonandoffrapidly—meaningafewhundredtimespersecond!

The value of capacitorC1, the value of resistor R5, and the resistancebetweenpins 6 and 7will set the toneof the sound.You’ll place resistorsbetweeneachpushbutton,sopressingabuttonaffectsthecircuit’sresistance.Thatmeans the resistance between pins 6 and 7 will differ depending onwhichbuttonyoupush,resultinginadifferenttoneforeach.

Apushbuttonhasfourpins.Whenyoulookatitfromthepointofviewshown in Figure 8-1, the two pins in front are always connected to eachother.The same is true for the twopins in theback.Whenyoupush thebutton,thefrontpairgetsconnectedtothebackpair.

FIGURE8-1Apushbuttonhasfourpins.

Mypreferredwaytoconnectthepushbuttonsforthisprojectisacrossthegap in the middle of the board, as shown in Figure 8-2. This gives youplenty of room to connect the resistors and necessary wires.Don’t worryabouttherotation,asthepushbuttonswillonlyfitoneway.

FIGURE8-2Connectthepushbuttonssotheyspanthegap.

It’s a good idea to build the circuitwith just one button first. Start byconnectingbuttonS1.Thenaddthethreeotherbuttonsonceyou’vegottenthefirstoneworking.

WARNING

Makesure theresistorR6 is in serieswith the speaker for tworeasons: (1) tolimitthecurrenttothespeakersothatevenverysmallspeakersdon’tbreakand(2)tomakesureyoudon’tdestroytheICbysqueezingoutmorecurrentthanitcanhandle.

COMMONMISTAKESIfyou’rehavingtroublegettingthecircuittoworkcorrectly,checkthatyou

haven’tmadeoneofthesecommonmistakes:

Connectingthe555timerthewrongwayMixing up the pin numbers of the IC and connecting components tothewrongpinForgetting to connect awire (With somany connections, it’s easy tolosetrack!)

Ifyouwantmorethanfourbuttonsonyourkeyboard,youcanaddmorepushbuttonsandresistors.

If you’re struggling with this circuit, you can ask questions and makecommentsthroughthebook’swebsiteathttps://nostarch.com/circuits/.

HOWTHECIRCUITWORKSInthepreviouschapter,youlearnedhowthe555timerworks.Thiscircuitworksinthesameway,exceptthatinProject7theoutputturnedonandoffslowly,maybeone timeper second. In this circuit, theoutput switchesonandoffseveralhundredtimespersecond!

ThecapacitorC1and the resistorsR1 toR5determinehow frequentlytheoutput (pin3)switchesbetweenahighanda lowvoltage.Tocalculatethe exact frequency of the sound you hear, you’ll use the formula for the

switchingfrequencyofa555timer:TheRXvalueistheresistancebetweenpins6and7,soitwilldependon

whichbuttonyoupush.Let’sseewhatfrequencyyougetwhenyoupushS1:

Ifyouenterthesevaluesintoacalculator,you’llget686.Thatmeansthefrequencyforthefirstbuttonis686Hz.

Fortheotherbuttons,hereisthevalueforRXthatyouneedtoenterinto

thefrequencyformula:Ifyoucrunchthesenumbersonacalculator,youshouldget:S2:626Hz

S3:576HzS4:533Hz

Ifyouwanttochangethefrequency(ortone)ofeachbutton,youneedtochangethevalueofresistorsR2toR5.Trychanginginincrementsof100Ωfirst, and then in smaller and smaller increments to fine-tune the tone.Connectingtworesistorsinseriesgivesyouatotalresistanceequalingtheirsum.

9THELEDMARQUEE

THISCIRCUITCREATESARUNNINGLIGHT,LIKEANOLDTHEATERMARQUEE.

THECIRCUITDIAGRAM

THEPARTSLIST

PART VALUE DESCRIPTION

R1,R2 10kΩ Twostandardresistors

R3 470Ω Standardresistor

C1 4.7μF Polarizedcapacitor

L1toL10 LED Standardlight-emittingdiodes

U1 NE555 555timerIC

U2 CD4017B 4017decadecounterIC

ABOUTTHECIRCUITThis circuit uses a 555 timer and a 4017 decade counter, both integratedcircuits.Thevoltageofthe555timer’spin3switchesbetweenhighandlowrepeatedly,asyousawinProject8.Youconnectthissignaltopin14ofthe4017 IC, and the 4017 counts the number of times the voltage on pin 14goesfromlowtohigh.The4017has10outputs—markedQ0toQ9—thatrepresent this count. For example, after three counts, output Q3 is high,while the others are low.On the 10th count, the counter starts fromQ0again.Figure9-1showsthepinoutforthe4017IC.

FIGURE9-1Thepinoutforthe4017IC

TherunningspeedissetbyR1,R2,andC1.Changeoneofthevalues,and the lights’ runningspeedwill change.Largervalues slow itdown,andsmallervaluesspeeditup.

Thisisalargecircuit,soit’sprettyeasytoconnectawireoracomponentinthewrongplace.Isuggestyouconnectonlythe555timerpartfirst.Afterthat,adda470ΩresistorinserieswithanLEDbetweenthe555outputonpin3andthenegativeterminalofthebattery.YoushouldseetheLEDblinkreally fast. When you do, you can disconnect the LED and resistor andcontinueconnectingtherestofthecircuit.

Thiscircuitincludesalotofconnectionsinasmallarea,soyou’llneedtobecreativewiththewayyouuseyourspace.Irecommendyouuseoneofthecolumnsof the left supply area to connect thenegative side of theLEDs.Thiswillsaveyousomespace.

COMMONMISTAKESIf your circuit isn’tworking correctly, check that youhaven’tmade anyofthesecommonmistakes:

ConnectingoneorbothoftheICsthewrongwayMixingup thepinnumbersof theICsandconnectingcomponents tothewrongpinConnectingoneormoreoftheLEDsinthewrongwayConnectingthecapacitorthewrongwayaroundConnecting a wire or component one row above or below where itshouldbeconnected

Ifyou’restrugglingwiththiscircuit,youcanfindmoreresourcesthroughthebook’swebsiteathttps://nostarch.com/circuits/.

HOWTHISCIRCUITWORKSThiscircuitusesa555timertogenerateacontinuousseriesofpulses(calledclock pulses) and a 4017 decade counter to count the number of pulses itreceives.LEDsonoutputsQ0toQ9indicatethecount.Whenthecounterreaches10,itautomaticallystartsfrom0again.Thisway,itappearsasiftheLEDsarerunningfromonesidetotheother,withoutstopping.

The4017 IC is easy touse.Toget itupand running, just connect theVDD andGNDpins toavoltage source.Avoltagebetween5Vand15Vwillusuallywork.Withthevoltageconnected,thechipisrunningandwillcountanytransitionfromlowtohighvoltageonitsCLK(clock)inputpin.

Note thateachoutputcanprovideonlyabout10mAofcurrent. Ifyoutrytogetmorecurrentoutofeachoutput—forexample,byusingasmallerresistorvalueforR3—youriskstrangebehaviororevenchipdamage.

Thefollowingtableprovidesanoverviewofeachpin’sfunction.

PIN#

NAME DESCRIPTION

1 Q5 Goeshighwhenthecountis5

2 Q1 Goeshighwhenthecountis1

3 Q0 Goeshighwhenthecountis0

4 Q2 Goeshighwhenthecountis2

5 Q6 Goeshighwhenthecountis6

6 Q7 Goeshighwhenthecountis7

7 Q3 Goeshighwhenthecountis3

8 GND Ground(0V)connection

9 Q8 Goeshighwhenthecountis8

10 Q4 Goeshighwhenthecountis4

11 Q9 Goeshighwhenthecountis9

12 CarryOut Highoutputforcounts0to4

13 ClockInhibit

Counterdoesnotcountanyclockpulseswhenthisinputishigh

14 CLK Inputforpulsestobecounted

15 Reset Resetsthethecountto0whenhigh;mustbelowtocount

16 VDD Positivevoltagesupply

WHERETOGOFROMHERE

Congratulations,you’vemadeitallthewaytotheend!If you’ve built all nine circuits, you should have a solid practical

foundation for creating great things with electronics. If you’re new toelectronics,youmightnothaveunderstoodallthedetailsofeachcircuitinthis book, but that’s okay. This book was all about building circuits andimprovingyourpracticalelectronicsskills.

Ifyouwanttounderstandmoreabouthowthesecircuitsworkandhowyoucanbuildyourown,checkoutmybookElectronics forKids (NoStarchPress, 2016),whichwill teach you electronics from scratch, even if you’renotnecessarilya“kid”anymore.

Ifyouwanttostepupyourgameandlearntobuildprojectsthatcandomuchmoreadvancedthings,likeusegraphicaldisplays,createmelodies,andconnect to the internet, I recommend exploring a popular device calledArduino(https://www.arduino.cc/).

Whetheryouwanttobuildanautomaticcatdoorforyourhomeorthenextmust-have gadget for theworld, you’ll need to develop the skills andknowledge necessary to build those projects. That’s why I’m constantlycreatingnew learningmaterial tohelppeoplebring theirown ideas to lifewith electronics. To help people from all backgrounds develop theseabilities, I’ve created a learning portal for electronics calledOhmify. It’s aplacewhereyoucansignupforcoursestolearnavarietyofskills,including:

ArduinoprogrammingBasicelectronicsSolderingPrintedcircuitboard(PCB)designAndmuchmore!

YoucanlearnmoreaboutOhmifyathttps://ohmify.com/.

RESISTORCOLORCODES

www.build-electronic-circuits.com

ABeginner’sGuidetoCircuitsissetinHelveticaNeue,Montserrat,andTrueNorth.

RESOURCESVisit https://nostarch.com/circuits/ for updates, errata, and otherinformation.

Moreno-nonsensebooksfrom NOSTARCHPRESS

ELECTRONICSFORKIDSPlaywithSimpleCircuitsandExperimentwithElectricity!byØYVINDNYDALDAHL

JULY2016,328PP.,$24.95ISBN978-1-59327-725-3fullcolor

LEARNROBOTICSWITHRASPBERRYPIBuildandCodeYourOwnMoving,Sensing,ThinkingRobotsbyMATTTIMMONS-BROWNFALL2018,200PP.,$24.95ISBN978-1-59327-920-2fullcolor

20EASYRASPBERRYPIPROJECTSToys,Tools,Gadgets,andMore!byRUISANTOSandSARASANTOS

APRIL2018,288PP.,$24.95ISBN978-1-59327-843-4fullcolor

ARDUINOPROJECTHANDBOOK,VOL.2

25SimpleElectronicsProjectsforBeginners

byMARKGEDDES

AUGUST2017,272PP.,$24.95ISBN978-1-59327-818-2fullcolor

THEARDUINOINVENTOR’SGUIDELearn Electronics byMaking 10 Awesome Projects by BRIAN HUANG

andDEREKRUNBERG

JUNE2017,336PP.,$29.95ISBN978-1-59327-652-2fullcolor

THEMANGAGUIDETOELECTRICITYbyKAZUHIROFUJITAKI,MATSUDA,andTREND-PROCO,LTD.MARCH2009,224PP.,$19.95ISBN978-1-59327-197-8

1.800.420.7240 or 1.415.863.9900 | sales@nostarch.com |www.nostarch.com

AGES10+

YOUCANDOIT!

ABeginner’sGuidetoCircuitsistheperfectfirststepforanyonereadytojumpintotheworldofelectronicsandcircuitdesign.

First, you’ll learn to read circuit diagrams and use a breadboard, whichallowsyou to connect electrical componentswithoutusing ahot solderingiron!Next,you’llbuildnine simpleprojectsusing just ahandfulof readilyavailablecomponents, likeresistors, transistors,capacitors,andotherparts.Asyoubuild,you’lllearnwhateachcomponentdoes,howitworks,andhowtocombinecomponentstoachievenewandinterestingeffects.

Bytheendofthebook,you’llbeabletobuildyourownelectroniccreations.With easy-to-follow directions, anyone can become an inventor with thehelpofABeginner’sGuidetoCircuits!

BUILDTHESE9SIMPLECIRCUITS!Steady-HandGame:TestyournervesusingawireandabuzzertocreateanOperation-stylegame!

Touch-EnabledLight:Turnonalightwithyourfinger!

CookieJarAlarm:Catchcookiethievesred-handedwiththiscontraption.

Night-Light:Automaticallyturnonalightwhenitgetsdark.

BlinkingLED:ThisclassiccircuitblinksanLED.

RailroadCrossingLight:Danger!Don’tcrossthetracksifthiscircuit’spairoflightsisflashing.

PartyLights:Throwapartywiththesecharmingstringlights.

DigitalPiano:Playatunewiththissimplesynthesizerandlearnhowspeakerswork.

LEDMarquee:Putonalightshowandimpressyourfriendswiththisflashyfinale.

ØyvindNydalDahlbuilthis first circuit at age14, andhaskeptbuildingever since then. Øyvind has a master’s degree in Electronics from theUniversityofOslo,helpscompaniesdevelopnewproducts, and travels theworld while teaching electronics workshops. He is also the author ofElectronics for Kids (No Starch Press, 2016). Read more about Øyvind athttp://www.build-electronic-circuits.com/.

THEFINESTINGEEKENTERTAINMENT™www.nostarch.com