Hardware Reference
In-Depth Information
When you call Timer1.initialize , you are setting the period of the timer in
microseconds. In this case, it has been set to trigger every 1 second. (There are a
million microseconds in 1 second.) When you run Timer1.attachInterrupt() ,
you can choose a function that will be executed every time the specified period
elapses. Obviously, the function you call should take less time to execute than
the time between executions.
Now that you can implement both timer and hardware interrupts, you can
develop hardware that takes advantage of both of them. You will do this in the
next section.
BuildinganInterrupt-DrivenSoundMachine
To finalize and confirm your understanding of hardware and timer interrupts,
you build a “sound machine” that enables you to step through and listen to
multiple octaves of each note on a musical major scale. The system uses a hard-
ware-debounced pushbutton interrupt to select the note played (C, A, B, and so
forth). A timer interrupt steps through all the octaves of the note in order until
the next note is selected with the push button. In loop() , you can run a simple
serial debugging interface that prints the current key and pitch to the screen
of your computer. The notes start at octave 2 (it doesn't sound very good below
that) and go up toward octave 6.
Computing the frequency of each octave is easy once you know the initial
frequency. Consider C, for example. C2, where we will be starting, has a fre-
quency of about 65Hz. To get to C3 (130Hz), multiply the frequency of C2 by
2. To get C4, multiply by 2 again, for 260Hz. The frequency of each step can be
computed as a power of 2 related to the initial frequency. Knowing this, you can
construct a timer interrupt that increases by the power of 2 with each time step.
You can switch between notes in the same way you switched between LED
colors in the earlier example with the pushbutton. Assign base frequencies to
each note, and switch which base frequency is used for tone() every time the
button is pressed.
SoundMachineHardware
The hardware setup here is very simple. Keep the debounced button wired as
you had it in the RGB LED example, and add a speaker to pin 12 through a 150Ω
resistor. I used a piezo speaker, but you can use a larger speaker as well. The
circuit should look the one shown in Figure 12-9.
 
Search WWH ::




Custom Search