11

(Marcin) #1
FORGE

boards) to trigger the interrupt when the input
changes to that particular state.
The triggerSound function that’s called by the
interrupt is actually very simple:


void triggerSound() {
if (trigger = !trigger) {
note_time = millis();
}}

As we’re detecting a change in the button state,
and not whether it’s being turned on or off, we use
a Boolean called trigger to flip between true when
the button is pressed and false when the button
is released. This isn’t obvious in the above code,
and we’re perhaps guilty of needless obfuscation
here, but the if (trigger = !trigger) line is both
the assignment and the comparison. This isn’t a
comparison, using == or !=, as you’d usually expect to
see with an if statement, it’s actually an assignment.
We’re assigning the not value of trigger to trigger
because the exclamation is the not operator. This
makes not true = false and not false = true. If
trigger is true after the assignment, the if statement
will see the expression resolve as true and note_time
= millis(); will be executed. This line adds another
new command, millis(), which assigns the number
of milliseconds the Arduino has been powered
on to note_time, the unsigned long variable we
created earlier.


PLAYING A SOUND
Playing a sound on an Arduino is remarkably easy,
partly because there’s a built-in function, tone(),
so you don’t need to worry about pitch and partly
because all the Arduino has to do is send pulses of


HARDWARE


The great thing about this project is
that you likely already have everything
you need. You can use almost any old
speaker, for example, although the better
the speaker, the better the quality of
sound – we took one from an old PC.
You could also use a small piezo buzzer,
often found in component kits. The sound
output isn’t so good, but the Arduino isn’t
exactly capable of high quality anyway.
It’s connected to pin 3 of the Arduino and
ground, but if you find the output is too

loud, place a resistor between the positive
connection and the Arduino. The higher
the resistance, the lower the volume.
Similarly, we plundered an old
component box to find a momentary
switch to use. One side of this switch
is connected to both digital pin 2 on the
Arduino and a 10 kΩ resistor, which is
itself connected to ground. The other side
of the switch is connected to the 5 V pin or
rail from the Arduino. And that’s all there
is to this circuit.

Below
All the components for
this project should be
easy to find
Free download pdf