Académique Documents
Professionnel Documents
Culture Documents
SparkFunInventor'sKit
Examplesketch11
BUZZER
Usethebuzzertoplayasong!
ThebuzzerinyourInventor'sKitisanelectromechanical
componentyoucanusetomakenoise.Insidethebuzzerisa
coilofwireandasmallmagnet.Whencurrentflowsthrough
thecoil,itbecomesmagnetizedandpullstowardsthemagnet,
creatingatiny"click".Whenyoudothisthousandsoftimes
persecond,youcreatetones.
TheArduinohasabuiltincommandcalledtone()whichclicks
thebuzzeratacertainfrequency.Thissketchknowsthe
frequenciesofthecommonnotes,allowingyoutocreatesongs.
We'renevergoingtoletyoudown!
Hardwareconnections:
Thebuzzerhastwopins.Oneispositiveandoneisnegative.
Thepostitivepinismarkedbya"+"symbolonboththetop
andbottomofthebuzzer.
ConnectthepositivepintoArduinodigitalpin9.
(NotethatthismustbeaPWMpin.)
ConnectthenegativepintoGND.
Tip:ifthebuzzerdoesn'tfitintothebreadboardeasily,
tryrotatingitslightlytofitintodiagonalholes.
ThissketchwaswrittenbySparkFunElectronics,
withlotsofhelpfromtheArduinocommunity.
(ThissketchwasoriginallydevelopedbyD.CuartiellesforK3)
Thiscodeiscompletelyfreeforanyuse.
Visit
http://learn.sparkfun.com/products/2
forSIKinformation.
Visit
http://www.arduino.cc
tolearnabouttheArduino.
Version2.06/2012MDG
*/
/*
Thissketchusesthebuzzertoplaysongs.
TheArduino'stone()commandwillplaynotesofagivenfrequency.
We'llprovideafunctionthattakesinnotecharacters(ag),
andreturnsthecorrespondingfrequencyfromthistable:
note frequency
c262Hz
d294Hz
e330Hz
f349Hz
g392Hz
a440Hz
b494Hz
C523Hz
Formoreinformation,see
http://arduino.cc/en/Tutorial/Tone
*/
constintbuzzerPin=9
//We'llsetupanarraywiththenoteswewanttoplay
//changethesevaluestomakedifferentsongs!
//Lengthmustequalthetotalnumberofnotesandspaces
constintsongLength=94
//Notesisanarrayoftextcharacterscorrespondingtothenotes
//inyoursong.Aspacerepresentsarest(notone)
charnotes[]="FAABBdCdcdAABBFAABB
dCdcdAABBQBddeeRddddABBSBddeeTddddddBBUFAABBVdCdcdAABB"//aspace
representsarest.TheseareallofournotestotheIronmansong.
//Beatsisanarrayofvaluesforeachnoteandrest.
//A"1"representsasixteenthnote,"2"aeigthnote,"3"aquarternote,"4"ahalfnote
etc.
//Don'tforgetthattherests(spaces)needalengthaswell.
intbeats[]=
{3,3,2,2,3,1,1,1,1,1,2,2,2,2,3,1,3,3,2,2,3,1,1,1,1,1,2,2,2,2,3,1,3,3,2,2,3,1,1,1,1,1,2,2,3,1,
3,3,2,2,3,1,2,1,1,2,2,2,2,1,3,3,2,2,3,1,1,1,1,1,2,2,2,2,3,1}
//Thetempoishowfasttoplaythesong.
//Tomakethesongplayfaster,decreasethisvalue.
inttempo=200
//LoadtheLiquidCrystallibrary,whichwillgiveus
//commandstointerfacetotheLCD:
#include<LiquidCrystal.h>
//Initializethelibrarywiththepinswe'reusing.
//(Notethatyoucanusedifferentpinsifneeded.)
//See
http://arduino.cc/en/Reference/LiquidCrystal
//formoreinformation:
LiquidCrystallcd(12,11,5,4,3,2)
voidsetup()
{
pinMode(buzzerPin,OUTPUT)
//TheLiquidCrystallibrarycanbeusedwithmanydifferent
//LCDsizes.We'reusingonethat's2linesof16characters,
//sowe'llinformthelibraryofthat:
lcd.begin(16,2)
//Datasenttothedisplaywillstaythereuntilit's
//overwrittenorpowerisremoved.Thiscanbeaproblem
//whenyouuploadanewsketchtotheArduinobutolddata
//remainsonthedisplay.Let'scleartheLCDusingthe
//clear()commandfromtheLiquidCrystallibrary:
lcd.clear()
//Nowwe'lldisplayamessageontheLCD!
//JustaswiththeArduinoIDE,there'sacursorthat
//determineswherethedatayoutypewillappear.Bydefault,
//thiscursorisinvisible,thoughyoucanmakeitvisible
//withotherlibrarycommandsifyouwish.
//Whenthedisplaypowersup,theinvisiblecursorstarts
//onthetoprowandfirstcolumn.
lcd.print("IronMan")
delay(2000)
}
//ThissaysIronManfortwosecondsasoursongstarts.Thisisthetitletooursong.
voidloop()
{
//Youcanmovetheinvisiblecursortoanylocationonthe
//LCDbeforesendingdata.Countingstartsfrom0,sothetop
//lineisline0andthebottomlineisline1.Columnsrange
//from0ontheleftside,to15ontheright.
//Inadditontothe"hello,world!"printedabove,let's
//displayarunningcountofthesecondssincetheArduino
//waslastreset.Notethatthedatayousendtothedisplay
//willstaythereunlessyoueraseitbyoverwritingitor
//sendingalcd.clear()command.
//TIP:Sincethenumericdatawe'resendingisalwaysgrowing
//inlength,newvalueswillalwaysoverwritethepreviousones.
//However,ifyouwanttodisplayvaryingordecreasingnumbers
//likeacountdown,you'llfindthatthedisplaywillleave
//"orphan"characterswhenthenewvalueisshorterthanthe
//oldone.
//Topreventthis,you'llneedtoerasetheoldnumberbefore
//writingthenewone.Youcandothisbyoverwritingthe
//lastnumberwithspaces.Ifyouerasetheoldnumberand
//immediatelywritethenewone,themomentaryerasewon't
//benoticeable.Here'satypicalsequenceofcode:
//lcd.setCursor(0,1)//Setthecursortotheposition
//lcd.print("")//Erasethelargestpossiblenumber
//lcd.setCursor(0,1)//Resetthecursortotheoriginalposition
//lcd.print(millis()/1000)//Printourvalue
inti,duration
for(i=0i<songLengthi++)//stepthroughthesongarrays
{
duration=beats[i]*tempo//lengthofnote/restinms
if(notes[i]=='')//isthisarest?
{
delay(duration)//thenpauseforamoment
}
elseif(notes[i]=='Q')//isthisarest?
{
lcd.setCursor(0,0)
lcd.print("Hashelosthis")
lcd.setCursor(0,1)
lcd.print("mind?")
delay(duration)
}
//ThismakestheLCDsayHashelosthismind?whentheQinournotescomesup.
TheQisarestbut,ittellstheLCDtoshowit.
elseif(notes[i]=='R')//isthisarest?
{
lcd.setCursor(0,0)
lcd.print("Canhesee")
lcd.setCursor(0,1)
lcd.print("orisheblind?")
delay(duration)
}
//ThismakestheLCDsayCanheseeoorisheblind?whentheRinournotes
comesup.TheRisarestbut,ittellstheLCDtoshowit.
elseif(notes[i]=='S')//isthisarest?
{
lcd.setCursor(0,0)
lcd.print("Canhewalk")
lcd.setCursor(0,1)
lcd.print("atall?")
delay(duration)
}
//ThismakestheLCDsayCanhewalkatall?whentheSinournotescomesup.
TheSisarestbut,ittellstheLCDtoshowit.
elseif(notes[i]=='T')//isthisarest?
{
lcd.setCursor(0,0)
lcd.print("Orifhemoves,")
lcd.setCursor(0,1)
lcd.print("willhefall?")
delay(duration)
}
//ThismakestheLCDsayOrifhemocves,willhefall?whentheTinournotes
comesup.TheTisarestbut,ittellstheLCDtoshowit.
elseif(notes[i]=='V')//isthisarest?
{
lcd.setCursor(0,0)
lcd.print("TEAMIRONMAN")
lcd.setCursor(0,1)
lcd.print("ByBeauAL&Connor")
delay(duration)
}
//ThismakestheLCDsayTEAMIRONMANByBeauAl&ConnorwhentheVinour
notescomesup.TheVisarestbut,ittellstheLCDtoshowit.
else//otherwise,playthenote
{
tone(buzzerPin,frequency(notes[i]),duration)
delay(duration)//waitfortonetofinish
}
delay(tempo/10)//briefpausebetweennotes
}
//Weonlywanttoplaythesongonce,sowe'llpauseforever:
//while(true){}
//Ifyou'dlikeyoursongtoplayoverandover,
//removetheabovestatement
}
intfrequency(charnote)
{
//Thisfunctiontakesanotecharacter(ag),andreturnsthe
//correspondingfrequencyinHzforthetone()function.
inti
constintnumNotes=8//numberofnoteswe'restoring
//Thefollowingarraysholdthenotecharactersandtheir
//correspondingfrequencies.Thelast"C"noteisuppercase
//toseparateitfromthefirstlowercase"c".Ifyouwantto
//addmorenotes,you'llneedtouseuniquecharacters.
//Forthe"char"(character)type,weputsinglecharacters
//insinglequotes.
charnames[]={'F','A','B','c','d','e','f','g','a','b','C'}
intfrequencies[]={174.61,220,262,246.94,294,330,349,392,440,494,277.18}
//Nowwe'llsearchthroughthelettersinthearray,andif
//wefindit,we'llreturnthefrequencyforthatnote.
for(i=0i<numNotesi++)//Stepthroughthenotes
{
if(names[i]==note)//Isthistheone?
{
return(frequencies[i])//Yes!Returnthefrequency
}
}
return(0)//Welookedthrougheverythinganddidn'tfindit,
//butwestillneedtoreturnavalue,soreturn0.
}