11

(Marcin) #1

Arduino programming: Sound, envelopes, and interrupts


SCHOOL OF MAKING


if (trigger) {
playSound(261);
} else {
stopSound();
}}
If you now run all the code we’ve just written, you
should find that your Arduino generates a tone at
pitch equivalent to a middle ‘C’ on a piano keyboard.
But this is only part of the project, because a simple
tone isn’t all that exciting. To solve this, we’re going
to change the sound during playback using something
called an ‘envelope’ to modulate the playback pitch.
An audio envelope describes how much a sound
changes over time, from the moment it’s triggered
to when it’s released. Envelopes are typically used to
change the amplitude and pitch of a sound over the
duration of a note, and the most common envelope
type consists of four stages: attack, decay, sustain,
and release, also written as ADSR. Attack, decay, and
release are time durations that indicate how fast or
slowly the audio changes, whereas sustain is a level
that is held while the note is being triggered.

ENVELOPE GENERATOR
Before we start creating our own envelope, we need
to add a few global variables:
const int pitchEnv[] = {500, 250, 200};
const int pitchMax = 255;

The array is going to hold the attack, decay, and sustain
values, with the first two being durations and the final
element being level value. As we’re going to use this

envelope to vary the pitch of our sound, we’ve called
it pitchEnv, along with pitchMax to hold the maximum
value (amplitude) we want the envelope to reach on
the initial attack. Apart from its name, though, there’s
no reason why the envelope can’t be used to control
any other audio-related value to modulate the sound.
Before we write the envelope generator code itself,
we need to patch the envelope effect into our current
code. This is as simple as adding the following to the
beginning of the playSound function:

current to the pin connected to the speaker. It can all
be done with a single line, which we’ll place within its
own function:
void playSound(int pitch) {
tone (piezoPin, pitch);
}

We’ll pair the above function with another to turn the
sound off:
void stopSound(){
noTone(piezoPin);
}

All we now need to do is write the simple loop()
function to trigger either the playSound function or
the stopSound function depending on the state of the
trigger Boolean:
void loop()
{

Below
A piezo buzzer is a
handy component.
It works reasonably
well as a speaker and
can also be used as a
crude microphone

Envelopes are typically
used to change
the amplitude and
pitch of a sound over the
duration of a note


Free download pdf