Chapter 9. Audio Output

9.0. Introduction

The Arduino isn’t built to be a synthesizer, but it can certainly produce sound through an output device such as a speaker.

Sound is produced by vibrating air. A sound has a distinctive pitch if the vibration repeats regularly. The Arduino can create sound by driving a loudspeaker or Piezo device (a small ceramic transducer that produces sound when pulsed), converting electronic vibrations into speaker pulses which vibrate the air. The pitch (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 unit of frequency is measured in hertz, and it refers to the number of times the signal goes through its repeating cycle in one second. The range of human hearing is from around 20 hertz (Hz) up to 20,000 hertz (although it varies by person and changes with age).

The Arduino software includes a tone function for producing sound. Recipes 9.1 and 9.2 show how to use this function to make sounds and tunes. The tone function uses hardware timers. On a standard Arduino board, only one tone can be produced at a time. Sketches where the timer (timer2) is needed for other functions, such as analogWrite on pin 9 or 10, cannot use the tone function. To overcome this limitation, Recipe 9.3 shows how to use an enhanced tone library for multiple tones, and Recipe 9.4 shows how sound can be produced without using the tone function or hardware timers.

The sound that can ...

Get Arduino Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.