Lab 7 - Buzzer

Objective:  To make music with the piezo element.


Parts List

  Qty
Piezo element 1
Wire (any color) 1
Wire (black) 2

Parts Set-Up

Instructional Parts Set-Up

Part Connection 1 Connection 2
Piezo Element F7 F10 or F9 if it can reach
Wire (black) I7 -ve column
Wire (any color) J9 Arduino Pin 9
Wire (black) -ve column Arduino GND

Visual Parts Set-Up

Graphic from CIRC-06 of the ARDX guide from oomlout.com


Lab Code

Without Comments

With Comments

Line Code Comment
1 int speakerPin = 9; This is the Arduino pin that will control the sound output
2 int length = 15;  This is the number of notes
3 char notes[] = "ccggaagffeeddc ";  These are the notes that will be played.  The space at the end is a rest
4 int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };  
5 int tempo = 300;  
6 void playTone(int tone, int duration)   
7 {  
8   for (long i = 0; i < duration * 1000L; i += tone * 2)   
9   {  
10     digitalWrite(speakerPin, HIGH);  
11     delayMicroseconds(tone);  
12     digitalWrite(speakerPin, LOW);  
13     delayMicroseconds(tone);  
14   }  
15 }  
16 void playNote(char note, int duration)   
17 {  
18   char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };  
19   int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };  
20   for (int i = 0; i < 8; i++)   
21   {  
22     if (names[i] == note)   
23     {  
24       playTone(tones[i], duration);  
25     }  
26   }  
27 }  
28 void setup()   
29 {  
30   pinMode(speakerPin, OUTPUT);  
31 }  
32 void loop()   
33 {  
34   for (int i = 0; i < length; i++)   
35   {  
36     if (notes[i] == ' ')   
37     {  
38       delay(beats[i] * tempo);  
39     }   
40     else   
41     {  
42       playNote(notes[i], beats[i] * tempo);  
43     }  
44     delay(tempo / 2);   
45   }  
46 }  

Notes from the author D. Cuartielles:


 

Try the Mario theme song from this website: Mario Theme Song