11

(Marcin) #1
FORGE

audio hardware, like the Uno we’re using for our
projects, can generate sound, because sound is
generated by moving a speaker coil using nothing
more than fluctuations in current.
The trigger to start the sound could be almost
anything. An in-game event, for example. But for
our purposes, and to make this project standalone,
we’re going to use an equally simple momentary
switch or button. When the button is depressed,
we’ll generate the sound. When it’s released, we’ll
stop the sound. Two things are going to make this
different to how you might expect. The first is that
we’re going to use an interrupt to automatically wait
for the button state to change, and the second is
that we’re going to modify the sound as it’s being
played. This is called ‘modulation’, and it’s essential
if you want your sound to be more interesting than
a simple beep.


INTERRUPTS
Up until now, we’ve used the ever-running loop()
function to look for changes in the state of things
we wanted to monitor. If a button is pressed, or a
joystick pushed, a variable would change and we
could safely assume an event had taken place.
This approach is typically called ‘polling’, because
we’re constantly waiting and watching, looking for


a value to change. Polling is a great solution on an
Arduino because the device is always on, always
running at full speed, and always iterating through
loop(). Adding extra checks, or polls, shouldn’t add
to the overall processing burden. And if it does, it’s
something the programmer can manage by carefully
prioritising those checks, or reducing the frequency
of less important checks.
But there are strong use cases for not continually
checking for changes in state, and instead waiting
to be informed that something has changed. This
is what an interrupt does. An interrupt allows the
programmer to define a function to run when there’s
a change in state without manually waiting for
it. Just like tapping someone on the shoulder, an
interrupt is often triggered faster than the equivalent
polling code, and the amount of time it takes to
respond to an interrupt is more predictable. Polling
response times can be unpredictable. It could
be that you check for changes in state just as

An interrupt allows the programmer to define a
function to run when there’s a change in state
without manually waiting for it



Left
Speakers are
remarkably resilient,
and can sound good
even when in a poor
state of repair

As you might
imagine, one
thing you can’t do
within the function
triggered by the
interrupt is wait.
delay() won’t
work because the
function is being
executed outside of
the main loop, and
millis() won’t be
incremented either.

QUICK TIP

Free download pdf