Posted on Leave a comment

Adding Piezzo speaker to Analog Output

In my previous post, I was using my LED matrix circuit to display the Fibonacci clock. So I am a bit stretched on the I/O port. And my son asked me, whether I can add a buzzer to beep every 10 seconds so that he can do “plank” exercise. So I found my old Piezzo speaker.

Piezzo Speaker

Because I am running out of port, I am trying to use the Digital Pin 1. Pin one is labelled as TX, so the speaker beeps every second the clock updates. It also makes noise when you loaded the code to Arduino. What I had done is just combining the code from Mario speaker song to play when the button is being pressed on the Fibonacci clock.

It doesn’t work well when I am connecting the piezzo speaker to Digital pin 1. So I go on researching whether I can connect the speaker to Analog pin. Apparently you can program the Analog pin to behave like a digital pin.

Here are the initialisation code:

const int speakerPinMelody =  A0;   // using Analog pin A0 as output

void setup() {
...
pinMode(speakerPinMelody, OUTPUT); // to initialise the analog output
...
}

Once the initialisation is done, I can use the same code to play the melody as used in the Super Mario speaker song circuit.

void playSong(int theSong[], int theTempo[], int arraySize) {
// iterate over the notes of the melody:
int totalNotes = arraySize;
Serial.println("Total note:" + String(totalNotes));
for (int thisNote = 0; thisNote < totalNotes; thisNote++) {

// to calculate the note duration, take one second divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000 / theTempo[thisNote];
tone(speakerPinMelody, theSong[thisNote], noteDuration);
// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
Serial.println("Delay:" + String(pauseBetweenNotes));
delay(pauseBetweenNotes);
Serial.println("Stop");
// stop the tone playing:
noTone(speakerPinMelody);
}

delay(10);
Serial.println("Final Delay");
}

I am using a 1K resistor to connect one end of the piezzo speaker (red wire) to pin A0 and the other end of the speaker (black wire) is connected to the GND.

I omitted the rest of the LED Matrix circuit for simplicity. When the button is pressed the circuit will display a random dice face (1-6) on the LED matrix and then it will play the Super Mario song.

The result can be seen in the following youtube video. I hope you enjoy this post. Please leave a comment if you like this post or subscribe for frequent update on more simple circuits with Arduino. You can also send me an email if you would like the full source code.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.