11

(Marcin) #1

Arduino programming: Sound, envelopes, and interrupts


SCHOOL OF MAKING


something has changed, and the response will be
fast. Or something changed just after the previous
check and won’t now be serviced for a longer
duration. This induces jitter, which is variations in the
delay between when something happens and when
your code can respond to it. Of course, we’re talking
about differences in milliseconds, but it can make
a difference in time-critical situations, or when jitter
can be easily detected such as with strobing lights
or audio playback.
Let’s get started by writing the code for
the interrupt:
const int interruptPin = 2;
const int piezoPin = 3;
unsigned long note_time;
bool trigger = false;
void setup() {
attachInterrupt
(digitalPinToInterrupt(interruptPin),
triggerSound,
CHANGE);
}

All we’re doing in the above chunk is first declaring
a global constant variable to hold the value of the
pin connected to our button, and then using this
value within setup(). We also create an ‘unsigned
long’ variable to hold up to 4 bytes of data with

no negative numbers, which we’ll use to hold a
timestamp, and a bool to hold the press state of the
button. attachInterrupt is the important part, as
this is the Arduino magic that tells your hardware
to automatically launch a function, triggerSound,
when it receives a signal corresponding to the final
argument in the attachInterrupt function call. We’ve
gone for CHANGE, as this triggers the interrupt when
the button is being pressed and released. We could
also have used RISING to trigger the interrupt when
the button is pressed and FALLING when the button is
released, but we can handle both of those states with
CHANGE without using our one remaining interrupt, as
we’ll show. There’s also LOW (and HIGH on selected

‘attachInterrupt’ is the
important part, as this is the
Arduino magic that tells your
hardware to automatically
launch a function



Below
We salvaged our
speaker from an old
PC, but they’re easy
to find by taking
apart almost anything
that used to make
a sound

Below
Momentary switches
only stay connected
as long as the user
presses the button
Free download pdf