SlideShare a Scribd company logo
1 of 4
EXPERIMENT#7. Audio Output
Front Page
I.Learning Objectives:
After successfully completing this lab, students will be able to:
1. create sound by adding a speaker.
2. play tones and a simple melody.
II. Discussion:
Sound is a very powerful output that is usually taken for granted. We see things such as LEDs,
we feel things such as motors, but we also hear. Arduino has a nice little library called Tone that
aids in generating sounds at specific frequencies. For people passionate about music, we can
actually play monophonic songs for the most geekish sound possible.
Sound is produced by vibrating air. A sound has a distinctive pitch if the vibration repeats
regularly.
The tone() function is very easy to use. It generates a square wave of 50% duty cycle at the
specified frequency. What does that mean? It means that the used pin will be HIGH half the time
and LOW half the time. It will change between these two states at the specified frequency. Every
musical note has a specific frequency; in our case, Do, which is a C3, has the frequency of 131
Hz. This wave will make the speaker vibrate and generate sound. Arduino can only support
monophonic sound using the Tone function. This means it can only generate one note at a time.
Still, it is quite useful and fun.
NOTE: if you want to play different pitches on multiple pins, you need to call noTone() on one
pin before calling tone() on the next pin.
Syntax:
tone(pin,frequency)
tone(pin, frequency, duration)
Parameters
pin: the pin on which to generate the tone
frequency: the frequency of the tone in hertz - unsigned int
duration: the duration of the tone in milliseconds (optional) - unsigned long
III. Materials:
 An Arduino board connected to a computer via USB.
 A small 8-ohm speaker.
 A 120-ohm resistor; larger values also work, but the sound will be less powerful. Don't
use resistors under 100 ohms.
IV.Procedure:
Follow these steps to connect a speaker to the Arduino.
1. Connect one terminal of the speaker directly into the GND of the Arduino.
2. Using a 120-ohm resistor in series, connect the other terminal to an available digital pin.
Schematic
This is one possible implementation on the 13th digital pin. Other digital pins can also be used.
Here is an example of how to wire it in the air. No breadboard needed here:
Code
The following code will play the famous —Do Re Mi Fa Sol La Ti:
// defining the 8 frequencies that make the 7 notes
#define Do 131
#define Re 147
#define Mi 165
#define Fa 175
#define Sol 196
#define La 220
#define Ti 247
#define Do2 262
// defining the pin connected to the speaker
int tonePin = 13;
void setup(){
// Tone pins don't need to be declared
}
void loop(){
// Do
tone(tonePin, Do, 125);
delay(125);
// Re
tone(tonePin, Re, 125);
delay(125);
// Mi
tone(tonePin, Mi, 125);
delay(125);
// Fa
tone(tonePin, Fa, 125);
delay(125);
// Sol
tone(tonePin, Sol, 125);
delay(125);
// La
tone(tonePin, La, 125);
delay(125);
// Ti
tone(tonePin, Ti, 125);
delay(125);
// Higher Do
tone(tonePin, Do2, 125);
delay(125);
}
If the speaker is connected to a different pin, simply change the tonePin value to the value of the
pin that has been used.
Playing Tones
const int speakerPin = 9; // connect speaker to pin 9
const int pitchPin = 0; // pot that will determine the frequency of the tone
void setup()
{
}
void loop()
{
int sensor0Reading = analogRead(pitchPin); // read input to set frequency
// map the analog readings to a meaningful range
int frequency = map(sensor0Reading, 0, 1023, 100,5000); // 100Hz to 5kHz
int duration = 250; // how long the tone lasts
tone(speakerPin, frequency, duration); // play the tone
delay(1000); // pause one second
}
Playing a Simple Melody
const int speakerPin = 9; // connect speaker to pin 9
char noteNames[ ] = {'C','D','E','F','G','a','b'};
unsigned int frequencies[ ] = {262,294,330,349,392,440,494};
const byte noteCount = sizeof(noteNames); // number of notes (7 here)
//notes, a space represents a rest
char score[ ] = "CCGGaaGFFEEDDC GGFFEEDGGFFEED CCGGaaGFFEEDDC ";
const byte scoreLen = sizeof(score); // the number of notes in the score
void setup()
{
}
void loop()
{
for (int i = 0; i < scoreLen; i++)
{
int duration = 333; // each note lasts for a third of a second
playNote(score[i], duration); // play the note
}
delay(4000); // wait four seconds before repeating the song
}
void playNote(char note, int duration)
{
// play the tone corresponding to the note name
for (int i = 0; i < noteCount; i++)
{
// try and find a match for the noteName to get the index to the note
if (noteNames[i] == note) // find a matching note name in the array
tone(speakerPin, frequencies[i], duration); // play the note
}
// if there is no match then the note is a rest, so just do the delay
delay(duration);
}
Exercise:
Make a program that will play your own choice of music.

More Related Content

What's hot

PySynth : A toy pure python software synthesizer.
PySynth : A toy pure python software synthesizer.PySynth : A toy pure python software synthesizer.
PySynth : A toy pure python software synthesizer.Ransui Iso
 
Tips for live streaming a musical performance
Tips for live streaming a musical performanceTips for live streaming a musical performance
Tips for live streaming a musical performancePaul Richards
 
Audioglossary
AudioglossaryAudioglossary
Audioglossarypolsinep
 
Basic principles of audio recording
Basic principles of audio recordingBasic principles of audio recording
Basic principles of audio recordingHermogenes Lomosad
 
Go rock bluetooth speakers handling instructions
Go rock bluetooth speakers handling instructionsGo rock bluetooth speakers handling instructions
Go rock bluetooth speakers handling instructionsSteps Forsuccess
 
MIDI DAW II - Class 6
MIDI DAW II - Class 6MIDI DAW II - Class 6
MIDI DAW II - Class 6Walt Ribeiro
 

What's hot (7)

PySynth : A toy pure python software synthesizer.
PySynth : A toy pure python software synthesizer.PySynth : A toy pure python software synthesizer.
PySynth : A toy pure python software synthesizer.
 
Tips for live streaming a musical performance
Tips for live streaming a musical performanceTips for live streaming a musical performance
Tips for live streaming a musical performance
 
Audioglossary
AudioglossaryAudioglossary
Audioglossary
 
Basic principles of audio recording
Basic principles of audio recordingBasic principles of audio recording
Basic principles of audio recording
 
Go rock bluetooth speakers handling instructions
Go rock bluetooth speakers handling instructionsGo rock bluetooth speakers handling instructions
Go rock bluetooth speakers handling instructions
 
MIDI DAW II - Class 6
MIDI DAW II - Class 6MIDI DAW II - Class 6
MIDI DAW II - Class 6
 
DJ Rama
DJ RamaDJ Rama
DJ Rama
 

Similar to Lab Activity

Similar to Lab Activity (20)

Session3
Session3Session3
Session3
 
Project 7: Musical Notes
Project 7: Musical NotesProject 7: Musical Notes
Project 7: Musical Notes
 
[Best]Chromatic Tuner Project Final Report
[Best]Chromatic Tuner Project Final Report[Best]Chromatic Tuner Project Final Report
[Best]Chromatic Tuner Project Final Report
 
Digital Music Production
Digital Music ProductionDigital Music Production
Digital Music Production
 
Arduino projects &amp; tutorials
Arduino projects &amp; tutorialsArduino projects &amp; tutorials
Arduino projects &amp; tutorials
 
It's so quiet. Let's make music.
It's so quiet. Let's make music.It's so quiet. Let's make music.
It's so quiet. Let's make music.
 
Mike to clavinova
Mike to clavinovaMike to clavinova
Mike to clavinova
 
Digital Tuner
Digital TunerDigital Tuner
Digital Tuner
 
Build cool stuff with arduino for sci camp 16 dec13
Build cool stuff with arduino for sci camp 16 dec13Build cool stuff with arduino for sci camp 16 dec13
Build cool stuff with arduino for sci camp 16 dec13
 
Audio-1
Audio-1Audio-1
Audio-1
 
Audio
AudioAudio
Audio
 
electronic mixer
electronic mixerelectronic mixer
electronic mixer
 
sound to light system
sound to light  systemsound to light  system
sound to light system
 
Electronz_Chapter_6.pptx
Electronz_Chapter_6.pptxElectronz_Chapter_6.pptx
Electronz_Chapter_6.pptx
 
Digital Technology
Digital TechnologyDigital Technology
Digital Technology
 
Sound
SoundSound
Sound
 
ecegwp
ecegwpecegwp
ecegwp
 
How to play audio from a microcontroller
How to play audio from a microcontrollerHow to play audio from a microcontroller
How to play audio from a microcontroller
 
Audio systems
Audio systemsAudio systems
Audio systems
 
Drumwavy VST VST3 Audio Unit: Orchestral and Ethnic Percussion VST, VST3 and ...
Drumwavy VST VST3 Audio Unit: Orchestral and Ethnic Percussion VST, VST3 and ...Drumwavy VST VST3 Audio Unit: Orchestral and Ethnic Percussion VST, VST3 and ...
Drumwavy VST VST3 Audio Unit: Orchestral and Ethnic Percussion VST, VST3 and ...
 

More from Dwight Sabio

Human Rights Observatory Description
Human Rights Observatory DescriptionHuman Rights Observatory Description
Human Rights Observatory DescriptionDwight Sabio
 
RIGHTS-BASED SUSTAINABLE DEVELOPMENT GOALS MONITOR
RIGHTS-BASED SUSTAINABLE DEVELOPMENT GOALS MONITORRIGHTS-BASED SUSTAINABLE DEVELOPMENT GOALS MONITOR
RIGHTS-BASED SUSTAINABLE DEVELOPMENT GOALS MONITORDwight Sabio
 
Report on Girl Children: A Rapid Assessment of their Situation
Report on Girl Children: A Rapid Assessment of their SituationReport on Girl Children: A Rapid Assessment of their Situation
Report on Girl Children: A Rapid Assessment of their SituationDwight Sabio
 
Gender ombud report 2016 final
Gender ombud report 2016 finalGender ombud report 2016 final
Gender ombud report 2016 finalDwight Sabio
 
Strengthening legal referral mechanisms on cases of gender
Strengthening legal referral mechanisms on cases of genderStrengthening legal referral mechanisms on cases of gender
Strengthening legal referral mechanisms on cases of genderDwight Sabio
 
CPU scheduling ppt file
CPU scheduling ppt fileCPU scheduling ppt file
CPU scheduling ppt fileDwight Sabio
 
OperatingSystemChp3
OperatingSystemChp3OperatingSystemChp3
OperatingSystemChp3Dwight Sabio
 
Programming Problem 3
Programming Problem 3Programming Problem 3
Programming Problem 3Dwight Sabio
 
Programming Problem 2
Programming Problem 2Programming Problem 2
Programming Problem 2Dwight Sabio
 
Midterm Project Specification
Midterm Project Specification Midterm Project Specification
Midterm Project Specification Dwight Sabio
 
Game Design Document
Game Design DocumentGame Design Document
Game Design DocumentDwight Sabio
 
ProgrammingProblem
ProgrammingProblemProgrammingProblem
ProgrammingProblemDwight Sabio
 

More from Dwight Sabio (20)

Human Rights Observatory Description
Human Rights Observatory DescriptionHuman Rights Observatory Description
Human Rights Observatory Description
 
RIGHTS-BASED SUSTAINABLE DEVELOPMENT GOALS MONITOR
RIGHTS-BASED SUSTAINABLE DEVELOPMENT GOALS MONITORRIGHTS-BASED SUSTAINABLE DEVELOPMENT GOALS MONITOR
RIGHTS-BASED SUSTAINABLE DEVELOPMENT GOALS MONITOR
 
Report on Girl Children: A Rapid Assessment of their Situation
Report on Girl Children: A Rapid Assessment of their SituationReport on Girl Children: A Rapid Assessment of their Situation
Report on Girl Children: A Rapid Assessment of their Situation
 
Gender ombud report 2016 final
Gender ombud report 2016 finalGender ombud report 2016 final
Gender ombud report 2016 final
 
Strengthening legal referral mechanisms on cases of gender
Strengthening legal referral mechanisms on cases of genderStrengthening legal referral mechanisms on cases of gender
Strengthening legal referral mechanisms on cases of gender
 
IP Report
IP ReportIP Report
IP Report
 
CPU scheduling ppt file
CPU scheduling ppt fileCPU scheduling ppt file
CPU scheduling ppt file
 
Ch3OperSys
Ch3OperSysCh3OperSys
Ch3OperSys
 
OperatingSystemChp3
OperatingSystemChp3OperatingSystemChp3
OperatingSystemChp3
 
ABC Supermarket
ABC SupermarketABC Supermarket
ABC Supermarket
 
Programming Problem 3
Programming Problem 3Programming Problem 3
Programming Problem 3
 
Bluetooth
Bluetooth Bluetooth
Bluetooth
 
Programming Problem 2
Programming Problem 2Programming Problem 2
Programming Problem 2
 
Arduino e-book
Arduino e-bookArduino e-book
Arduino e-book
 
Midterm Project Specification
Midterm Project Specification Midterm Project Specification
Midterm Project Specification
 
Game Design Document
Game Design DocumentGame Design Document
Game Design Document
 
Class diagram
Class diagramClass diagram
Class diagram
 
Midterm Project
Midterm Project Midterm Project
Midterm Project
 
ProgrammingProblem
ProgrammingProblemProgrammingProblem
ProgrammingProblem
 
Class Diagram
Class DiagramClass Diagram
Class Diagram
 

Recently uploaded

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 

Recently uploaded (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 

Lab Activity

  • 1. EXPERIMENT#7. Audio Output Front Page I.Learning Objectives: After successfully completing this lab, students will be able to: 1. create sound by adding a speaker. 2. play tones and a simple melody. II. Discussion: Sound is a very powerful output that is usually taken for granted. We see things such as LEDs, we feel things such as motors, but we also hear. Arduino has a nice little library called Tone that aids in generating sounds at specific frequencies. For people passionate about music, we can actually play monophonic songs for the most geekish sound possible. Sound is produced by vibrating air. A sound has a distinctive pitch if the vibration repeats regularly. The tone() function is very easy to use. It generates a square wave of 50% duty cycle at the specified frequency. What does that mean? It means that the used pin will be HIGH half the time and LOW half the time. It will change between these two states at the specified frequency. Every musical note has a specific frequency; in our case, Do, which is a C3, has the frequency of 131 Hz. This wave will make the speaker vibrate and generate sound. Arduino can only support monophonic sound using the Tone function. This means it can only generate one note at a time. Still, it is quite useful and fun. NOTE: if you want to play different pitches on multiple pins, you need to call noTone() on one pin before calling tone() on the next pin. Syntax: tone(pin,frequency) tone(pin, frequency, duration) Parameters pin: the pin on which to generate the tone frequency: the frequency of the tone in hertz - unsigned int duration: the duration of the tone in milliseconds (optional) - unsigned long III. Materials:  An Arduino board connected to a computer via USB.  A small 8-ohm speaker.  A 120-ohm resistor; larger values also work, but the sound will be less powerful. Don't use resistors under 100 ohms. IV.Procedure: Follow these steps to connect a speaker to the Arduino. 1. Connect one terminal of the speaker directly into the GND of the Arduino.
  • 2. 2. Using a 120-ohm resistor in series, connect the other terminal to an available digital pin. Schematic This is one possible implementation on the 13th digital pin. Other digital pins can also be used. Here is an example of how to wire it in the air. No breadboard needed here: Code The following code will play the famous —Do Re Mi Fa Sol La Ti: // defining the 8 frequencies that make the 7 notes #define Do 131 #define Re 147 #define Mi 165 #define Fa 175 #define Sol 196 #define La 220 #define Ti 247
  • 3. #define Do2 262 // defining the pin connected to the speaker int tonePin = 13; void setup(){ // Tone pins don't need to be declared } void loop(){ // Do tone(tonePin, Do, 125); delay(125); // Re tone(tonePin, Re, 125); delay(125); // Mi tone(tonePin, Mi, 125); delay(125); // Fa tone(tonePin, Fa, 125); delay(125); // Sol tone(tonePin, Sol, 125); delay(125); // La tone(tonePin, La, 125); delay(125); // Ti tone(tonePin, Ti, 125); delay(125); // Higher Do tone(tonePin, Do2, 125); delay(125); } If the speaker is connected to a different pin, simply change the tonePin value to the value of the pin that has been used. Playing Tones const int speakerPin = 9; // connect speaker to pin 9 const int pitchPin = 0; // pot that will determine the frequency of the tone void setup() { } void loop() { int sensor0Reading = analogRead(pitchPin); // read input to set frequency // map the analog readings to a meaningful range
  • 4. int frequency = map(sensor0Reading, 0, 1023, 100,5000); // 100Hz to 5kHz int duration = 250; // how long the tone lasts tone(speakerPin, frequency, duration); // play the tone delay(1000); // pause one second } Playing a Simple Melody const int speakerPin = 9; // connect speaker to pin 9 char noteNames[ ] = {'C','D','E','F','G','a','b'}; unsigned int frequencies[ ] = {262,294,330,349,392,440,494}; const byte noteCount = sizeof(noteNames); // number of notes (7 here) //notes, a space represents a rest char score[ ] = "CCGGaaGFFEEDDC GGFFEEDGGFFEED CCGGaaGFFEEDDC "; const byte scoreLen = sizeof(score); // the number of notes in the score void setup() { } void loop() { for (int i = 0; i < scoreLen; i++) { int duration = 333; // each note lasts for a third of a second playNote(score[i], duration); // play the note } delay(4000); // wait four seconds before repeating the song } void playNote(char note, int duration) { // play the tone corresponding to the note name for (int i = 0; i < noteCount; i++) { // try and find a match for the noteName to get the index to the note if (noteNames[i] == note) // find a matching note name in the array tone(speakerPin, frequencies[i], duration); // play the note } // if there is no match then the note is a rest, so just do the delay delay(duration); } Exercise: Make a program that will play your own choice of music.