


It plays six notes, each one twice the frequency of (an octave higher than) the previous one. This sketch generates notes without a timer. Unlike the Arduino tone function, the playTone function described here will block, it will not return until the note has finished. This code does not use a timer, but it will not do anything else while the note is played. The tone function in earlier recipes is easier to use, but it requires a hardware timer, which may be needed for other tasks such as analogWrite.

We want to produce sounds through a speaker or other audio transducer, and you need to generate the tone in software instead of with a timer for example, if we need to use analogWrite on pin 9 or 10. The playNote function does a lookup in the noteNames array to find a match and uses the corresponding entry in the frequencies array to get the frequency to sound. The sketch calls playNote with each character in the score and duration for the notes of one-third of a second. The space character is used as a rest, but any character not defined in noteNames will also produce a rest (no note playing). The score is an array of notes representing the note names you want to play:Ĭhar score = “CCGGaaGFFEEDDC GGFFEEDGGFFEED CCGGaaGFFEEDDC “ Įach character in the score that matches a character in the noteNames array will make the note play. For example, note C (the first entry in the noteNames array) has a frequency of 262Hz (the first entry in the notes array). Each entry in the array is associated with a frequency defined in the notes array. NoteNames is an array of characters to identify notes in a score. We can add a shield that extends Arduino’s capabilities.Ĭode for Simple Melody Buzzer with Arduino It is difficult for Arduino to produce more musically complex sounds without external hardware. The output is a square wave, which sounds harsh and like an antique computer game than a musical instrument. The sound that can be produced by pulsing a speaker is limited and does not sound very musical. On a standard Arduino board, we can produce only one tone at a time. We are going to see how to use this function to make sound and tunes. The Arduino software includes a tune function for producing sound. The range of human hearing is from around 20 hertz up to 20,000 hertz (although it varies by person and changes with age). The unit of frequency is measured in hertz, and it refers to the number of times the signal goes through a repeating cycle in one second. The frequency of the sound is determined by the time it takes to pulse the speaker in and out the shorter the amount of time, the higher the frequency. The Arduino can create sound by driving a loudspeaker or piezo device, converting electronic vibrations into speaker pulses which vibrate the air. A sound has a distinctive pitch (frequency) if the vibration repeats regularly.
