NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Playing multiple notes with piezo element

March 27, 2011
by iceman1979
iceman1979's Avatar

Hi, I've been playing around with my nerdkit and the piezo speaker. I was able to program it to play the right hand part of "Music Box Dancer" but when I started looking at the left hand part towards the end of the song there are places where two and three notes are being played at a time.

I was wondering if anyone has figured out how to code it to play multiple notes together. Calling the function something like this... play_tone(D5, C5, DUR);


March 28, 2011
by Hexorg
Hexorg's Avatar

iceman1979, it can be implemented, but it will be much harder then a single note. Let me try to explain.

When you play one note with uC, speaker outputs a square wave of certain frequecy, like this


when you play a note of a different frequency, speaker plays a different wave


when you play 2 notes on a piano, they form a harmonics (or a disharmony, if you are a bad player), btu essantially what your ear hears is the SUM of two waves:


as you can see it'll be much harder to make uC generate a wave like that. My idea would be to use PWM. Also, you might want to look up some wikipedia articles about addition of waveforms.

March 29, 2011
by iceman1979
iceman1979's Avatar

So here is where I show my ignorance... Wouldn't the low point of the wave be included as well when mixing two frequencies? something like this?

March 30, 2011
by bretm
bretm's Avatar

For two notes, you can just connect two pins to the piezo and the speaker will mix them together.

For more than two notes, you can calculate the wave form (adding sine waves of different frequencies together) and then there are various methods for converting the waveform into sound. You can use table lookups to make the sine calculations fast.

In order of increasing sound quality: A) output 1 or 0 bit depending on whether the waveform is positive or negative. B) use BTc encoding to generate the bits, C) use PWM with 4 to 8 bits of precision, D) use an external DAC.

Post a Reply

Please log in to post a reply.

Did you know that talking to the microcontroller over the USB/Serial link is easy under Windows, Linux, and OS X? Learn more...