Upload
mihai-bogdan
View
235
Download
1
Embed Size (px)
DESCRIPTION
Traductoare Interfete Si Achizitii de Date
Citation preview
CHAPTER 7
Sound ProjectsAN ARDUINO BOARD CAN BE used to both generate sounds as an output
and receive sounds as an input using a microphone. In this chapter we
have various “musical instrumenttype” projects as well as projects that
process sound inputs.
Although not strictly a “sound” project, our first project is to create a
simple oscilloscope so that we can view the waveform at an analog input.
Project 18OscilloscopeAn oscilloscope is a device that allows you to see an electronic signal so
that it appears as a waveform. A traditional oscilloscope works by
amplifying a signal to control the position of a dot on the Y axis (vertical
axis) of a cathoderay tube while a timebase mechanism sweeps left to
right on the X axis and then flips back when it reaches the end. The result
will look something like Figure 71.
Figure 71 A 230 Hz sine wave on an oscilloscope.
These days, cathoderay tubes have largely been replaced by digital
oscilloscopes that use LCD displays, but the principles remain the same.
This project reads values from the analog input and sends them over a
USB cable to your computer. Rather than be received by the Serial
Monitor, they are received by a little program that displays them in an
PREV6 Light Projects
NEXT8 Power Projects
ὐ
30 Arduino Projects for the Evil Genius: Second Edition Recent
Topics
Tutorials
Highlights
Settings
Feedback(http://community.safaribooksonline.com)
Sign Out
Settings
10 days left in your trial. Subscribe.
Feedback(http://community.safaribooksonline.com/)
Sign Out
oscilloscopelike manner. As the signal changes, so does the shape of the
waveform.
Note that as oscilloscopes go, this one is not going to win any prizes for
accuracy or speed, but it is kind of fun and will display waveforms up to
about 1 kHz.
COMPONENTS AND EQUIPMENT
This is the first time that we have used capacitors. C1 can be connected
either way round; however, C2 and C3 are polarized and must be
connected the correct way round or they are likely to be damaged. As with
LEDs, on polarized capacitors, the positive lead (marked as the white
rectangle on the schematic symbol) is longer than the negative lead. The
negative lead also often has a minus sign () or a diamond shape next to
the negative lead.
Hardware
Figure 72 shows the schematic diagram for Project 18 and Figure 73 the
breadboard layout.
Figure 72 Schematic diagram for Project 18.
Figure 73 Breadboard layout for Project 18.
There are two parts to the circuit. R1 and R2 are highvalue resistors that
“bias” the signal going to the analog input to 2.5V. They are just like a
voltage divider. The capacitor C1 allows the signal to pass without any
direct current (DC) component to the signal (alternating current, or AC,
mode in a traditional oscilloscope).
R3, R4, C2, and C3 just provide a stable reference voltage of 2.5V. The
reason for this is so that our oscilloscope can display both positive and
negative signals. So one terminal of our test lead is fixed at 2.5V; any
signal on the other lead will be relative to that. A positive voltage will
mean a value at the analog input of greater than 2.5V, and a negative
value will mean a value at the analog input of less than 2.5V.
The diode D1 will protect the analog input from accidental overvoltage.
Figure 74 shows the completed oscilloscope.
Figure 74 Project 18: oscilloscope.
Software
The sketch is short and simple (Listing Project 18). Its only purpose is to
read the analog input and blast it out to the USB port as fast as possible.
LISTING PROJECT 18
The first thing to note is that we have increased the baud rate to 115,200,
the highest available. To get as much data through the connection as
possible without resorting to complex compression techniques, we are
going to shift our raw 10bit value right 2 bits (>> 2); this has the effect of
dividing it by four and making it fit into a single byte.
We obviously need some corresponding software to run on our computer
so that we can see the data sent by the board (Figure 71). This can be
downloaded from
www.arduinoevilgenius.com(http://www.arduinoevilgenius.com).
To install the software, you first need to install some software called
Processing. Processing is the natural partner for writing computer
applications that communicate with an Arduino. In fact, the Arduino IDE
is written in Processing.
Like the Arduino IDE, Processing is also available for Windows, Mac, and
LINUX and can be downloaded from
www.processing.org(http://www.processing.org).
Once Processing is installed, run it. The similarities with the Arduino IDE
will be immediately apparent. Now open the file scope.pde, and click the
Play button to run it.
A window like Figure 71 should appear.
Putting It All Together
Load the completed sketch for Project 18 from your Arduino Sketchbook
and download it to the board (see Chapter 1). Install the software for your
computer as described previously, and you are ready to go.
The easiest way to test the oscilloscope is to use the one readily available
signal that permeates most of our lives, and that is the hum from the
electrical service. Home electricity oscillates at 50 or 60 Hz (depending on
where you live in the world), and every electrical appliance emits
electromagnetic radiation at this frequency. To pick it up, all you have to
do is touch the test lead connected to the analog input, and you should see
a signal similar to that of Figure 71. Try waving your arm around near
any electrical equipment and see how the signal changes.
The signal shown in Figure 71 is actually a 215 Hz sine wave supplied by a
smart phone function generator application.
Sound GenerationYou can generate sounds from an Arduino board just by turning one of its
pins on and off at the right frequency. If you do this, the sound produced
is rough and grating. This is called a square wave. To produce a more
pleasing tone, you need a signal that is more like a sine wave (Figure 75).
Figure 75 Square and sine waves.
Generating a sine wave requires a little bit of thought and effort. A first
idea may be to use the analog output of one of the pins to write out the
waveform. However, the problem is that the analog outputs from an
Arduino are not true analog outputs but pulsewidth modulated (PWM)
outputs that turn on and off very rapidly. In fact, their switching
frequency is at an audio frequency, so without a lot of care, our signal will
sound as bad as a square wave.
A better way is to use a digitaltoanalog converter (DAC). A DAC has a
number of digital inputs and produces an output voltage proportional to
the digital input value. Fortunately, it is easy to make a simple DAC—all
you need are resistors.
Figure 76 shows a DAC made from what is called an R2R resistor ladder.
Figure 76 DAC using an R2R ladder.
It uses resistors of a value R and twice R, so R might be 5K and 2R 10K.
Each of the digital inputs will be connected to an Arduino digital output.
The four digits represent the four bits of the digital number. So this gives
us 16 different analog outputs, as shown in Table 71.
TABLE 71 Analog Output from Digital Inputs
Enjoy Safari? Subscribe Today
Another way of generating a particular wave shape is to use the Arduino
analogOutput command to generate the wave shape. This uses the
technique of PWM that you first met back in Chapter 4 to control the
brightness of LEDs.
Figure 77 shows the signal from a PWM pin on the Arduino.
Figure 77 Pulsewidth modulation.
The PWM pin is oscillating at about 500 times per second (hertz), with
the relative amount of time that the pin is high varying with the value set
in the analogWrite function. So, looking at Figure 77, if the output is only
high for 5% of the time, then whatever we are driving will only receive 5%
of full power. If, however, the output is at 5V for 90% of the time, then the
load will get 90% of the power delivered to it.
When driving motors with PWM, the physical inertia of the spinning
motor means that the motor does not start and stop 500 times per second
but is just given a kick of varying strengths every fivehundredths of a
second. The net effect of this is smooth control of the motor speed.
LEDs can respond much more quickly than a motor, but the visible effect
is the same. We cannot see the LEDs turning on and off at that speed, so
to us it just looks like the brightness is changing.
We can use this same technique to create a sine wave, but to do this, there
is one problem. That is that the default frequency that Arduino uses for its
PWM pulses is around 500 Hz, which is well within the range of audible
frequencies. Fortunately, we can change this frequency in our sketch,
making it much higher and outside the range of our hearing.
Figure 78 shows two traces from an oscilloscope of a 254 Hz sine wave
being generated by writing out successive values from an array.
Figure 78 Oscilloscope trace for sine wave generation.
The array contains a series of values that, when used to set the value of
analogWrite, one after the other produce the effect of a sine wave.
The bottom trace shows the raw PWM signal, with the pulses bunched up
for the peaks and troughs of the sine wave and more spread out for the
parts of the sine wave in the middle. The top trace shows that same signal
after it has been passed through a lowpass filter that chops off the high
PWM frequency (63 kHz), leaving us with quite a wellshaped sine wave.
Project 19Tune PlayerThis project will play a series of musical notes through a miniature
loudspeaker using PWM to approximate a sine wave.
If you can get a miniature loudspeaker with leads for soldering to a
printed circuit board (PCB), then this can be plugged directly into the
breadboard. If not, you will either have to solder short lengths of solid
core wire to the terminals or, if you do not have access to a soldering iron,
carefully twist some wires round the terminals.
COMPONENTS AND EQUIPMENT
Hardware
To try to keep the number of components to a minimum, we have used an
integrated circuit (IC) to amplify the signal and drive the loudspeaker.
The TDA7052 IC provides 1 W of power output in an easytouse little 8
pin chip.
Figure 79 shows the schematic diagram for Project 19, and the
breadboard layout is shown in Figure 710.
Figure 79 Schematic diagram for Project 19.
Figure 710 Breadboard layout for Project 19.
R1 and C1 together make a lowpass filter that will filter out the high
frequency PWM noise before it is passed on to the amplifier chip.
C2 is used as a decoupling capacitor that shunts any noise on the power
lines to ground. This should be positioned as close as possible to IC1.
The variable resistor R2 is a potential divider to reduce the signal from
the resistor ladder by at least a factor of 10, depending on the setting of
the variable resistor. This is the volume control.
Software
To generate a sine wave, the sketch steps through a series of values held in
the sine array. These values are plotted on the chart in Figure 711. It is
not the smoothest sine wave in the world, but it is a definite improvement
over a square wave (see Listing Project 19).
Figure 711 A plot of the sine array.
The setup function contains the Evil Genius’s magic incantations for
changing the PWM frequency.
The playNote function is the key to generating the note. The pitch of the
note generated is controlled by the delay after each step of the signal
within the playSine function that playNote calls.
Tunes are played from an array of characters, each character
corresponding to a note and a space corresponding to the silence between
notes. The main loop looks at each letter in the song variable and plays it.
When the whole song is played, there is a pause of 5 seconds, and then the
song begins again.
LISTING PROJECT 19
The Evil Genius will find this project useful for inflicting discomfort on his
or her enemies.
Putting It All Together
Load the completed sketch for Project 19 from your Arduino Sketchbook
and download it to the board (see Chapter 1).
You might like to change the tune played from “Jingle Bells.” To do this,
just comment out the line starting with char* song = by putting // in front
of it, and then define your own array.
For a longerduration note, just repeat the note letter without putting a
space in between.
You will have noticed that the quality is not great. It is still a lot less nasty
than using a square wave but is a long way from the tunefulness of a real
musical instrument, where each note has an “envelope” in which the
amplitude (volume) of the note varies with the note as it is played.
Project 20Light HarpThis project is really an adaptation of Project 19 that uses two light
sensors (LDRs): one that controls the pitch of the sound the other that
controls the volume. This is inspired by the Theremin musical instrument
that is played by mysteriously waving your hands about between two
antennas. In actual fact, this project produces a sound more like a bagpipe
than a harp, but it is quite fun.
COMPONENTS AND EQUIPMENT
Hardware
Figures 712 and 713 show the schematic diagram and breadboard layout
for the project, and you can see the final project in Figure 714.
Figure 712 Schematic diagram for Project 20.
Figure 713 Breadboard layout for Project 20.
Figure 714 Project 20: light harp.
The LDRs, R4 and R5, are positioned away from each other to make it
easier to play the instrument with two hands.
Software
The software for this project has a lot in common with Project 19 (see
Listing Project 20).
LISTING PROJECT 20
The main differences are that the period passed to playSine is set by the
value of the analog input 0. This is then scaled to the right range using the
map function. Similarly, the volume voltage is set by reading the value of
analog input 1, scaling it using map, and then using it to scale the values
from the sine array before outputting them.
LDRs have different ranges of resistance. So you may find that you need
to tweek the values of the variables ldrDim and ldrBright to get better
ranges of pitch and volume.
Putting It All Together
Load the completed sketch for Project 20 from your Arduino Sketchbook
and download it to the board (see Chapter 1).
To play the “instrument,” use your right hand over one LDR to control the
volume of the sound and your left hand over the other LDR to control the
pitch. Interesting effects can be achieved by waving your hands over the
LDRs.
Project 21VU MeterThis project (shown in Figure 715) uses LEDs to display the volume of
noise picked up by a microphone. It uses an array of LEDs built into a
dualinline (DIL) package.
Figure 715 Project 21: VU meter.
The push button toggles the mode of the VU meter. In normal mode, the
bar graph just flickers up and down with the volume of sound. In
maximum mode, the bar graph registers the maximum value and lights
that LED, so the sound level gradually pushes it up.
Hardware
The schematic diagram for this project is shown in Figure 716. The bar
graph LED package has separate connections for each LED. These are
each driven through a currentlimiting resistor.
Figure 716 Schematic diagram for Project 21.
COMPONENTS AND EQUIPMENT
The microphone will not produce a strong enough signal on its own to
drive the analog input. So, to boost the signal, we use a simple single
transistor amplifier. We use a standard arrangement called collector
feedback bias, where a proportion of the voltage at the collector is used to
bias the transistor on so that it amplifies in a loosely linear way rather
than just harshly switching on and off.
The breadboard layout is shown in Figure 717. With so many LEDs, a lot
of wires are required. Make sure that the bargraph LED module has the
negative LED connections to the left of the breadboard as it appears in
Figure 717. If it is not labeled, then test it out using one of the 270 Ω
resistors and the 5V supply from the Arduino.
Figure 717 Breadboard layout for Project 21.
Software
The sketch for this project (Listing Project 21) uses an array of LED pins
to shorten the setup function. This is also used in the loop function, where
we iterate over each LED, deciding whether to turn it on or off.
LISTING PROJECT 21
At the top of the loop function, we check to see if the switch is depressed;
if it is, we toggle the mode. The ! command inverts a value, so it will turn
true into false and false into true. For this reason, it is sometimes referred
to as the marketing operator. After changing the mode, we reset the
maximum value to 0 and then delay for 200 ms to prevent keyboard
bounce from changing the mode straight back again.
The level of sound is read from analog pin 0, and then we use the map
function to convert from a range of 0 to 1023 down to a number between
0 and 9, which will be the top LED to be lit. This is adjusted slightly by
extending the range up to 0 to 11 and then subtracting 1. This prevents the
two bottommost LEDs from being permanently lit owing to transistor
bias.
We then iterate over the numbers 0 to 9 and use a Boolean expression
that returns true (and hence lights the LED) if i is less than or equal to the
top LED. It is actually more complicated than this because we also should
display that LED if we are in peak mode and that LED happens to be the
peakValue.
Putting It All Together
Load the completed sketch for Project 21 from your Arduino Sketchbook
and download it to the board (see Chapter 1).
SummaryThis concludes our soundbased projects. In Chapter 8 we go on to look at
how we use an Arduino board to control power—a topic always close to
the heart of the Evil Genius.
People who finished this also enjoyed:
PREV6 Light Projects
NEXT8 Power Projects
Recommended / Queue / Recent / Topics / Tutorials / Settings / Blog(http://blog.safaribooksonline.com) /Feedback(http://community.safaribooksonline.com/) / Sign Out© 2015 Safari(http://www.safaribooksonline.com/). Terms of Service / Privacy Policy
Loopsfrom: Idiot's Guides: Beginning Programming byMatt TellesReleased: August 201422 MINS
Core Programming
BOOK SECTIONὍ
Chapter 3: Allergic to Electricityfrom: Strange Electromagnetic Dimensions by LouisProudReleased: November 201468 MINS
Math & Science
BOOK SECTIONὍ
Experiment 19: Decoding Telepathyfrom: Make: More Electronics by Charles PlattReleased: May 201421 MINS
Engineering
BOOK SECTIONὍ
SECTION 7-4: Op Amp Protectionfrom: Op Amp Applications Handbook by Walt JungReleased: December 200439 MINS
Engineering
BOOK SECTIONὍ
Chapter 3: Digital WirelessCommunicationsfrom: An Introduction to LTE: LTE, LTE-Advanced,SAE, VoLTE and 4G Mobile Communications, 2ndEdition by Christopher CoxReleased: July 2014
32 MINSEngineering
BOOK SECTIONὍ
Laser Cuttingfrom: The Maker's Manual by Patrick Di Justo...Released: April 201529 MINS
DIY & Hardware
BOOK SECTIONὍ
Making some noisefrom: Arduino Essentials by Francis PereaReleased: February 201514 MINS
DIY & Hardware
BOOK SECTIONὍ
Generation Gapsfrom: The Next America by Paul TaylorReleased: March 201426 MINS
Business
BOOK SECTIONὍ
Scripting a media playerfrom: Raspberry Pi Blueprints by Dan NixonReleased: March 20155 MINS
DIY & Hardware
BOOK SECTIONὍ
L: LOVEfrom: The Dream Cafe: Lessons in the Art of RadicalInnovation by Dr Geoff Crook...Released: April 201517 MINS
Business / Personal & Professional Development
BOOK SECTIONὍ