You can use the piezo speaker to play some basic sound with Arduino. Here you use the EducationShield library’s Melody class to play a melody from a list of notes and durations.
Materials
- 1 Arduino Uno board
- 1 Education shield
- 1 piezo speaker
- 2 jumper wires
Instructions
- Attach the shield onto the top of the Arduino board.
- Connect the piezo across the breadboard gap.
- Connect one leg to digital pin 8 (it does not matter which one) and the other one to GND, using jumper wires.
- Connect the board to the computer and upload example ‘Melody’.
Code
Find the code in Example>EducationShield>Help>Melody.
What you now should hear from the piezo speaker is a short melody, silence for three seconds, a short beep, then silence for another three seconds. This should then repeat.
Commands
-
#include “pitches.h”
– includes the file pitches.h where the tone frequencies are declared as constants. Melody( digitalPin )
– creates a Melody object.- Parameters
-
(
int
)digitalPin
– the digital pin to which the piezo or speaker is connected.
-
- Parameters
play( length, notes[ ], duration[ ], tempo)
– plays a melody.- Parameters
- (
int
)length
– number of notes in the melody. - (
int[]
)notes
– an array holding the melody notes. - (
int[]
)duration
– an array holding the duration of each note. -
(
int
)tempo
– tempo of the melody. Default is 1.3.
- (
- Parameters
-
beep()
– plays a beep.
Troubleshooting
- Make sure that the piezo speaker is properly connected to a digital pin and to GND.
- Make sure you have connected the piezo to the same pin as stated in your code.