[Tutorial] LEDs Moving to The Beat of a Piezo Buzzer with Arduino

Today we're going to see how we can use assorted LEDs, a piezo buzzer, and an Arduino board to easily create a program that allows us to visualize music. This is a fairly easy tutorial and you should be able to do it in roughly 15 minutes if not less. 

Without further ado, let's get to work!

💾 Piezo Buzzer
💾 6 assorted LEDs
💾 6 220 ohm resistors
💾 9 wires
💾 Breadboard

The setup is fairly simple. However, you can increase the complexity by adding more LEDs and tweaking the program a bit to account for that. Here's the diagram of how you need to set it up. 

For this program, we used the library pitches.h which essentially translates the musical notes into tones that the piezo buzzer can reproduce. As for the code of the song we used (we've used several but our favorite is the Harry Potter theme song), we got it from here. [Link in the description].

As you can see, we connect each cathode leg of each LED to a different digital pin, while we connect the anode leg to the ground through a 220-ohm resistor. 

For the piezo, we connect one of the legs to the ground and the other to digital pin 8.

Now we're going to do a quick run-through of the code. Firstly we include the library pitches.h we mentioned previously.

After including both the tones of the melody, as well as the duration of each tone, we move onto the setup function. Within said function, we will set up both the buzzer and the LEDs as output devices and we're going to set the LEDs to LOW.

After that, we go ahead and create the function that's going to activate the LEDs depending on the tone registered by the piezo

This code could be significantly more complicated and you can add as many layers to it as you want. However, the basic idea is that when the buzzer produces a tone and said tone is between two ranges or is above or below a particular range then we turn on the LEDs. If that's not the case we go ahead and turn them off.

Finally, we go ahead and write the loop function. Essentially here what we do is we create a for loop that runs through the full array created at the beginning with the melody. 

During each iteration, it creates a variable called duration which takes the durations array and assigns a specific duration to each note in time by dividing the size of the duration by 1 second.

Then it calls upon the tone function which takes to reproduce the note and subsequently calls the playLEDs function which will take the note and duration as parameters.

To differentiate tones there's a pause between tones and a call to the noTone function.  

And that's it. You have used the Arduino, a buzzer, and a few LEDs to create a device that visualizes the music through LEDs. Congratulations!

How would you make this project more interesting? Would you add a microphone or a sound sensor instead? Would you add more LEDs? Let us know in the comment section!