Docsity

Electrical and electronic engineering, Lecture notes of Electrical and Electronics Engineering

Partial preview of the text

Download Electrical and electronic engineering and more Lecture notes Electrical and Electronics Engineering in PDF only on Docsity!

Sounds in Arduino

Properties of Sound

  • Sound is transmitted through the air as a pressure wave.
  • As an object such as a speaker, a drum, or a bell vibrates,

that object also vibrates the air around it.

  • As the air particles vibrate, they transfer energy to the

particles around them, vibrating these particles as well.

  • In this fashion, a pressure wave is transferred from the

source to your eardrum, by creating a chain reaction of

vibrating particles.

Three piano notes: low, middle, and soprano C.

Middle C has a frequency of 261.63 Hertz (Hz).

Speaker Produces Sound

cross section of a common speaker

The permanent magnet is mounted behind the voice coil and pole piece shown in the image.

To make sound and sound sequences with an Arduino and

speaker, you use the built-in tone() and noTone() functions.

These functions generate a square wave on a specified pin,

which causes a speaker or passive buzzer to vibrate and

produce sound.

Wiring the Speaker

  • If the duration is not specified, the tone will continue

indefinitely until the noTone() function is called

void setup()

tone(8, 500);

// Play a 500 Hz tone continuously

void loop()

// Program logic can run while the tone plays

Making Sound Sequences (Melodies)

  • To create a sequence of sounds or a melody, you use the tone() and noTone() functions in conjunction with delay() calls within your code.
  • The tone() function uses one of the Arduino's internal timers, so you can only play one tone at a time.

Using Arrays

An array is a sequence of values that are related in some way.

Make an array that will contain four integer values, you could create it like this

  • Optionally initialize the values when you declare the array.
  • If you initialize the values, specifying the length in the brackets is optional.
  • If unspecified, the length is assumed to equal the number of elements that you initialized:

Can access the elements in an array at any given index by putting the index of the relevant value in a square bracket after the variable name.

If you want to set the brightness of an LED connected to pin 9 to the third entry in an array, for example, you can do so like this:

Can change one of the values of the array, you can do so in a similar fashion:

Use these arrays (as shown in these examples) to create a structure that can hold the sequence of notes that you want to play on your speaker.

Play a Song on a Speaker