Laboratory 5: Interfacing Circuits to Computers: Analog-to-Digital Conversion, Digital Filters, and Digital-to-Analog Conversion

Similar documents
Laboratory 4: Amplification, Impedance, and Frequency Response

EECS 216 Winter 2008 Lab 2: FM Detector Part II: In-Lab & Post-Lab Assignment

ESE 150 Lab 04: The Discrete Fourier Transform (DFT)

Electrical & Computer Engineering Technology

Laboratory Project 4: Frequency Response and Filters

ESE 150 Lab 04: The Discrete Fourier Transform (DFT)

Laboratory Assignment 2 Signal Sampling, Manipulation, and Playback

EE477 Digital Signal Processing Laboratory Exercise #13

Lab 6: Building a Function Generator

Experiment Guide: RC/RLC Filters and LabVIEW

University of North Carolina-Charlotte Department of Electrical and Computer Engineering ECGR 3157 Electrical Engineering Design II Fall 2013

EE 233 Circuit Theory Lab 3: First-Order Filters

EE 462G Laboratory #1 Measuring Capacitance

ECE 2006 University of Minnesota Duluth Lab 11. AC Circuits

Laboratory Assignment 4. Fourier Sound Synthesis

Lab 4: Analysis of the Stereo Amplifier

EE 422G - Signals and Systems Laboratory

ME 365 EXPERIMENT 8 FREQUENCY ANALYSIS

Lab 10 - INTRODUCTION TO AC FILTERS AND RESONANCE

George Mason University Signals and Systems I Spring 2016

Fourier Signal Analysis

Time-Varying Signals

EE 233 Circuit Theory Lab 2: Amplifiers

University of Michigan EECS 311: Electronic Circuits Fall 2008 LAB 2 ACTIVE FILTERS

Pre-Lab. Introduction

Group: Names: Resistor Band Colors Measured Value ( ) R 1 : 1k R 2 : 1k R 3 : 2k R 4 : 1M R 5 : 1M

Set-up. Equipment required: Your issued Laptop MATLAB ( if you don t already have it on your laptop)

11. Audio Amp. LM386 Low Power Amplifier:

Laboratory Experiment #1 Introduction to Spectral Analysis

Laboratory Assignment 1 Sampling Phenomena

ECE3204 D2015 Lab 1. See suggested breadboard configuration on following page!

Basic Signals and Systems

Laboratory 6. Lab 6. Operational Amplifier Circuits. Required Components: op amp 2 1k resistor 4 10k resistors 1 100k resistor 1 0.

Department of Electrical & Computer Engineering Technology. EET 3086C Circuit Analysis Laboratory Experiments. Masood Ejaz

AC CURRENTS, VOLTAGES, FILTERS, and RESONANCE

ECE 6416 Low-Noise Electronics Orientation Experiment

Laboratory 5: RC Circuits and Filtering

SGN Bachelor s Laboratory Course in Signal Processing Audio frequency band division filter ( ) Name: Student number:

EE2210 Laboratory Project 1 Fall 2013 Function Generator and Oscilloscope

Digital Video and Audio Processing. Winter term 2002/ 2003 Computer-based exercises

ENGR 210 Lab 6 Use of the Function Generator & Oscilloscope

EE 2274 RC and Op Amp Circuit Completed Prior to Coming to Lab. Prelab Part I: RC Circuit

Click on the numbered steps below to learn how to record and save audio using Audacity.

ENGR 210 Lab 12: Sampling and Aliasing

University of Utah Electrical Engineering Department ECE 2100 Experiment No. 2 Linear Operational Amplifier Circuits II

RLC Frequency Response

Class #3: Experiment Signals, Instrumentation, and Basic Circuits

Experiment No. 6. Audio Tone Control Amplifier

The object of this experiment is to become familiar with the instruments used in the low noise laboratory.

University of North Carolina, Charlotte Department of Electrical and Computer Engineering ECGR 3157 EE Design II Fall 2009

Final Project Stereo Audio Amplifier Final Report

Laboratory 9. Required Components: Objectives. Optional Components: Operational Amplifier Circuits (modified from lab text by Alciatore)

Experiment 9 AC Circuits

Figure 1: Block diagram of Digital signal processing

Lab 12 Laboratory 12 Data Acquisition Required Special Equipment: 12.1 Objectives 12.2 Introduction 12.3 A/D basics

DSP First Lab 08: Frequency Response: Bandpass and Nulling Filters

LLS - Introduction to Equipment

332:223 Principles of Electrical Engineering I Laboratory Experiment #2 Title: Function Generators and Oscilloscopes Suggested Equipment:

Experiment 2: Electronic Enhancement of S/N and Boxcar Filtering

An Introductory Guide to Circuit Simulation using NI Multisim 12

University of Michigan EECS 311: Electronic Circuits Fall 2009 LAB 2 NON IDEAL OPAMPS

EE-4022 Experiment 2 Amplitude Modulation (AM)

BME 3512 Bioelectronics Laboratory Six - Active Filters

EE320L Electronics I. Laboratory. Laboratory Exercise #2. Basic Op-Amp Circuits. Angsuman Roy. Department of Electrical and Computer Engineering

Laboratory 2 (drawn from lab text by Alciatore)

Testing DDX Digital Amplifiers

Sampling and Reconstruction

BME 3512 Bioelectronics Laboratory Two - Passive Filters

Notes on Experiment #1

Page 1/10 Digilent Analog Discovery (DAD) Tutorial 6-Aug-15. Figure 2: DAD pin configuration

CI-22. BASIC ELECTRONIC EXPERIMENTS with computer interface. Experiments PC1-PC8. Sample Controls Display. Instruction Manual

Combinational logic: Breadboard adders

Lab 4 An FPGA Based Digital System Design ReadMeFirst

TABLE OF CONTENTS SECTION 6.0

GE U111 HTT&TL, Lab 1: The Speed of Sound in Air, Acoustic Distance Measurement & Basic Concepts in MATLAB

Physics 303 Fall Module 4: The Operational Amplifier

Week 8 AM Modulation and the AM Receiver

Lab E5: Filters and Complex Impedance

EE 233 Circuit Theory Lab 4: Second-Order Filters

HOWTO PROPERLY SET YOUR GAINS

The Series RLC Circuit and Resonance

E40M Sound and Music. M. Horowitz, J. Plummer, R. Howe 1

PHYSICS 107 LAB #9: AMPLIFIERS

2.0 AC CIRCUITS 2.1 AC VOLTAGE AND CURRENT CALCULATIONS. ECE 4501 Power Systems Laboratory Manual Rev OBJECTIVE

ECE 201 LAB 8 TRANSFORMERS & SINUSOIDAL STEADY STATE ANALYSIS

EK307 Passive Filters and Steady State Frequency Response

2 Oscilloscope Familiarization

Experiment No. 4 The LM 741 Operational Amplifier

Spectrum Analysis: The FFT Display

AC Circuits. "Look for knowledge not in books but in things themselves." W. Gilbert ( )

Memorial University of Newfoundland Faculty of Engineering and Applied Science. Lab Manual

Frequency and Time Domain Representation of Sinusoidal Signals

A Simple Notch Type Harmonic Distortion Analyzer

UNIVERSITY OF NORTH CAROLINA AT CHARLOTTE Department of Electrical and Computer Engineering

Fundamentals of Digital Audio *

THE SPEAKER. The decibel scale is related to the physical sound intensity measured in watts/cm 2 by the following equation:

Laboratory 2. Lab 2. Instrument Familiarization and Basic Electrical Relations. Required Components: 2 1k resistors 2 1M resistors 1 2k resistor

Tektronix digital oscilloscope, BK Precision Function Generator, coaxial cables, breadboard, the crystal earpiece from your AM radio kit.

Real Analog - Circuits 1 Chapter 11: Lab Projects

Lab #2 First Order RC Circuits Week of 27 January 2015

Transcription:

ES 3: Introduction to Electrical Systems Laboratory 5: Interfacing Circuits to Computers: Analog-to-Digital Conversion, Digital Filters, and Digital-to-Analog Conversion I. GOALS: In this laboratory you will learn about the basics of incorporating computers into electrical systems. To demonstrate these ideas, you will build an automated speaker tester that evaluates the frequency response of the speaker you have built for ES3. If you have not yet completed your speaker, you may use a commercial speaker. Most loud speakers produce maximum audio output (i.e., sound level) within a limited range of frequencies. For frequencies that are much higher and much lower than this range, the speaker produces insufficient sound intensity. We often perceive this uneven frequency response as tinny or muffled sound. It is possible, however, to use a computer to compensate for poor frequency response by using digital filters. In the second part of this lab you will design a digital filter based on the measured frequency response of your speaker. This filter will then be applied to a music signal to improve the audio performance of your speaker. II. PRELAB QUESTIONS: The waveform shown in Figure 1 is sampled at a rate of f s =10 khz=10,000 samples per second. The voltage samples are converted to digital data using an analog-to-digital converter having 12-bit resolution; that is, each sample is represented as a 12-bit binary number. For this particular A/D, the number 000000000000 2 corresponds to 0 volts and 111111111111 2 corresponds to 5 volts. (In this system, only positive voltages can be converted to digital data). The waveform is stored in a computer s memory starting at t=0. What binary numbers do the first five memory locations contain? Repeat the question if f s = 5 khz and f s = 2.5 khz. What can you conclude about the minimum sampling rate needed to accurately record this signal? (Hint: what is the frequency of the triangle signal shown in Figure 1?) V(t) volts 5v 0.2 0.4 t (ms) Figure 1. Prelab question voltage signal ES 3 Laboratory #5 Page 1 of 17

III. BACKGROUND INFORMATION In past ES3 labs you have investigated only continuous, analog signals. Over the past decade, however, much of the information from analog signals is routinely converted to digital data and stored on hard drives, non-volatile memory, and optical media (CDs). A simple block diagram of the analog-to-digital conversion process is shown in Fig. 2. pressure waves in the air v(t) v(t) amplifier microphone t t Sample and Hold (44,100 per second) v(t) 000110101001 2 011001010100 2 010011000100 2 100100100100 2 Analog-to-digital converter (12 bit resolution) Memory (stored as an array) Figure 2. A block diagram of a simple analog-to-digital conversion process In this example, sound waves produced by a violin are converted into an analog electrical voltage by a microphone (see Lab #3). The voltage signal produced by the microphone is amplified in preparation for conversion to digital data. A critical component of the conversion process is the sampling of analog data. Audio data, for example, is typically sampled at least 44,100 times per second (44.1 khz) in order to ensure that the highest audio frequencies (~20 khz) are accurately captured. At this point in Fig. 2, the continuous analog signal is now a discrete set of voltages as shown in the blue inset of Fig. 2 (lower right). Each of these voltages is now converted to a binary number. In the example, a 12 bit conversion is shown. This allows one to divide the analog voltage range into 2 12 (or 4096) small bins. More precise representations of the analog data can be digitized using a larger number of bits. The binary number is represented inside the system by 12 separate voltages. Each of the 12 voltages is either high or low, and each voltage represents a single bit of data. This analog-todigital converter (A/D) produces 44,100 words per second. These 12-bit words are stored in memory. There are several different modes of storing data in memory. DRAM stores data in charged and uncharged capacitors (representing 1 and 0, respectively). Hard disks store the bits of data as magnetized regions on the surface of the disk, and CDs store data as small divots or bumps on the surface of the disk. ES 3 Laboratory #5 Page 2 of 17 t

Once analog data is stored in digital format it may be manipulated by computer programs. The study of altering digital data is called digital signal processing. Applications include reducing noise, correcting errors in the data stream, and improving the quality of the original signal (digital filtering). Later in this lab experiment, you will use digital signal processing to improve the frequency response of your speaker. When the digital data needs to be used by humans in the real world, the individual bits of data need to be converted back into an analog signal. This process is called digital-toanalog conversion (D/A). A simple D/A is shown in Fig. 3. Computer memory (an array) 100110101001 001001010100 110011000100 100100100100 etc. 44,100 binary numbers per second from memory Digital-to-Analog Converter (binary (binary number voltage) Low-Pass Filter Filter f c f = c 20kHz 20kHz amp v(t) v(t) t t Figure 3. A block diagram of a simple digital-to-analog converter Beginning with digital data that is stored in memory, the D/A system supplies data to a module that converts digital data into analog voltages. It is critical that the number of data points per second exactly matches the original sampled data rate. The output of the analog conversion process is a step-like voltage waveform as shown in the lower-left inset of Fig. 3. Typically, a low-pass filter is used to remove the rapidly changing voltage steps and provide a smooth analog signal (Fig. 3, lower-right inset). The cut-off frequency of this filter is typically one half of the sampling frequency (in this example, f c = 20 khz, the highest audible frequency). The last step is to amplify the low-level analog signal such that the appropriate actuator is driven. At this point, it is necessary to pay close attention to the Thevenin equivalent resistance of the amplifier and the equivalent impedance of the actuator, Z eq, as discussed in ES3. In this section, we have used a digital audio recorder as an example. This type of digital conversion, however, is commonly used in many other applications including digital photography, radar systems, automotive control systems, voicemail systems, and others too numerous to list. It is necessary to specify a sufficiently high sampling rate to accurately capture the signal. Rapidly changing signals require A/D converters that operate at very high rates (for example, the digital oscilloscope used in this lab as well ES 3 Laboratory #5 Page 3 of 17

as radar systems). Also, very precise voltage measurements require an A/D with a larger number of bits. One example is the precision offered by 24-bit audio. In this lab, however, we will use the A/D and D/A that nearly every PC has: the sound card. Sound cards routinely sample analog signals at 44.1 khz and are usually capable of 12- to 16- bit precision. Using a sound card or other data acquisition device requires software that allows one to control the sampling rate, the storage of the data, and the playback rate. In this laboratory you will control the data acquisition with MATLAB, a commonly used computation tool in science and engineering. For a brief tutorial on MATLAB, please refer to Appix A of this lab. IV. EXPERIMENTS: In this lab, you are asked to build a system to evaluate the frequency response of your home-built speaker. The block diagram of the experiment is shown in Fig 4. Step 1: Create tones using MATLAB The computer creates a sequence of frequencies (f) using the command tone = sin(2*pi*f*t) in MATLAB. The variable t is actually an array containing discrete values of time: t(1) = 0, t(2) = 1/44100, t(3) = 2/44100,, t(44100) = 1 second. The sin function operates on every element of t to create a new array called tone that contains a sampled sine wave with frequency f. In this example, the sampling rate is rate=44100 samples per second. amp mic Figure 4. Block diagram of the audio frequency response test system ES 3 Laboratory #5 Page 4 of 17

Step 2: Convert the numerical tone into an analog voltage Once the desired data representing a sine function has been created, the entire array is sent to the digital-to-analog converter by the MATLAB command soundsc(tone, rate) The variable rate tells the D/A system in the soundcard how many samples per second should be used during playback of the data that are stored in the array called tone. Step 3: Amplify the low-level signal and create sound waves The low-level signal that is output by the sound card is not sufficient to drive a loud speaker. Therefore, the sound card output must be connected to an audio power amplifier. Using a breadboard and your expertise from Lab #4, construct an audio amplifier using the LM386 integrated circuit. See Appix B for instructions. Use a miniature stereo phone jack (supplied by the TA) to connect the output of the sound card to the input of your amplifier. Don t forget to notice which of the two wires is the ground at the output of the sound card! Also, connect the output of the amplifier to your speaker. Please refer to Figure B1 for assistance. Step 4: Recording the sound produced by the speaker Connect a microphone to the microphone input of the sound card on the lab computer. Place the microphone close to your speaker such that the sound produced by the speaker can be recorded. The microphone signal will be amplified by the sound card and then converted into digital data (also at a rate of 44100 samples per second). Step 5: Install the software Download the MATLAB m-file called es3.m from the ES3 website. This file should be placed on your Windows Desktop. Start MATLAB by following the instructions in Appix A. Set the Current Directory to the Windows Desktop. This allows MATLAB to find the m-file called es3.m Step 6: Run the audio frequency response test Position the microphone near the speaker. Then, at the MATLAB Command prompt, type: >> es3 You will probably need to adjust the volume level using Windows so that the output is neither distorted nor too quiet (double-click the speaker icon in the lower-right corner of the screen). Explanation of the Test Methods The m-file tests the frequency response of your audio system using two different methods. The first method generates a series of tones with ascing frequency. Each ES 3 Laboratory #5 Page 5 of 17

tone is recorded by the microphone. The intensity of the recorded tone is determined and plotted. The plot of sound intensity vs. frequency graphically displays the frequency response of your audio system (i.e., the amplifier, the speaker, and the microphone). The second method uses noise to determine the frequency response of the audio system. An important property of white noise is that all frequencies are simultaneously present with equal intensities. The computer produces white noise using a random number generator. This array of random numbers is sent to the sound card and the audio system produces a hissing sound (noise). Because the audio system is not perfect, however, some of the frequencies present in the original white noise signal are not produced at full intensity by the audio system. The microphone records the noise produced by the speaker. The Fourier transform of the digital data from the recorded noise signal is used to extract the intensity of each frequency in the recorded noise. The frequency response of the system is then plotted using this extracted data. This method is much quicker than using individual tones because only a single noise burst from the computer is needed. It is, however, more susceptible to interference from external noise sources, such as the noise generated by the lab s air conditioning. Perform the frequency response test on your speaker using the m-file called es3.m Cut and paste the plot of the audio frequency response of your speaker into a document and save the document for inclusion in your lab report. (In the Figure window, select Edit>>Copy Figure then paste the figure into a Word document.) In your lab report, explain any discrepancies between the frequency response recorded by the tone method and the frequency response determined by the noise method. What range of frequencies is produced most strongly by your speaker? What ranges of frequencies are not adequately produced by your speaker? Digital Filters Most speakers will produce adequate sound levels over an intermediate range of frequencies. This range is called the bandwidth of the system. Very low frequencies and very high frequencies will not be correctly reproduced. A typical frequency response of a small, cheap speaker (from in a laptop computer) is shown in Fig. 5. Notice that frequencies between 10 3 and 4x10 3 Hz have a high intensity (blue, unfiltered curve). This uneven response makes the speaker sound tinny or brittle. ES 3 Laboratory #5 Page 6 of 17

10 2 Digital Filtering of Noise unfiltered filtered 10 1 Signal Intensity (arb.) 10 0 10-1 10-2 10 2 10 3 10 4 Frequency (Hz) Figure 5. Unfiltered and filtered frequency response from a laptop s audio speaker Filtering is a method of suppressing the frequencies of a signal that are too intense. Filtering can also be used to enhance or amplify the specific frequencies that are too weak. In Lab #4 you briefly investigated how capacitors affect the frequency response of an amplifier. This is referred to as analog filtering because the filtering is performed on continuous analog signals. Digital filtering is a method that modifies the digital samples of analog signals using computational methods. The lower curve in Fig. 5 (red) shows the frequency response of the same audio system after a digital filter was used to reduce the response of the audio signal in the vicinity of 2 khz. Notice that the response curve is much flatter. This means that all audio frequencies are produced with more or less the same intensity. For the filter demonstrated In Fig. 5, each element in the array of the filtered output signal, y(n), was calculated by summing three of the unfiltered input samples x(n), x(n-1) and x(n-2) along with two previously-computed filtered samples, y(n-1) and y(n-2). The coefficients of each sample determine the filtered frequency, the range of filtered frequencies (bandwidth) and the amount of attenuation at the center frequency. The exact equation of this particular digital filter is y(n) = 0.6641*x(n) + (-1.2747)*x(n-1) +0.6641*x(n-2) - (-1.2747)*y(n-1) 0.3282*y(n-2) where n is the index of the arrays containing the unfiltered sample, x(n), and the filtered sample, y(n). The frequency response of this digital filter is shown in Fig. 6. Notice that the signal is greatly attenuated around a normalized frequency of 0.09, which corresponds to f = 0.09*(44.1kHz / 2) = 2000 Hz. (The sampling rate is 44.1 khz). This midrange attenuation is called a notch filter and it helps to flatten the frequency response as demonstrated in Fig. 5. ES 3 Laboratory #5 Page 7 of 17

Magnitude Response Estimate 0-5 -10-15 Magnitude (db) -20-25 -30-35 -40-45 10-2 10-1 Normalized Frequency ( π rad/sample) Figure 6. The frequency response of a digital notch filter Download the m-file called es3notch.m from the ES3 website to your PC s desktop. Open the MATLAB editor by double-clicking on the file in the Current Directory window in the upper-left of the MATLAB screen. This file let s you design a simple digital filter by selecting the central frequencies to attenuate from a digital signal. It then plays the filtered and the unfiltered noise signal and calculates the frequency response of the audio system both with and without digital filtering Modify the notch frequency (notchfreq), the range of frequencies (bandwidth), and attenuation (attenuation) such that this digital filter flattens the frequency response of your audio system. Remember to save the m-file after you have made modifications! Once you are satisfied with the notch filter design, record the values for the notchfreq, bandwidth, and attenuation that give your audio system the flattest frequency response. Copy and paste the optimal frequency response plot from MATLAB into your lab report. In your lab report, briefly describe the procedure and the audible effect that the digital filter has on the noise signal. Final Test: Playback of a sound file In this final segment of this lab, you will test your complete audio system using a short segment of a sound file. Download the m-file called es3music.m from the ES3 website to your computer s desktop. Also download the file containing the audio clip called audiosample.mat to the desktop. ES 3 Laboratory #5 Page 8 of 17

At this point, you should open es3music.m in MATLAB s editor and modify the filter parameters in this m-file to exactly match the best filter parameters that you found in the previous section. Save the modified m-file. Run the m-file by typing >>es3music at the command prompt. MATLAB will load the data from the sound clip, apply the digital filter to the data contained in the sound clip, and then play the unfiltered clip, followed by the filtered version and finally the unfiltered version again. You may need to increase the volume during play back of the filtered sound clip since some of the original sound has been attenuated. Hopefully, you have designed a digital filter that significantly improves the frequency response of your audio system so that the digitally filtered music sounds better ( but not great, this is just a single home-made speaker after all!). Copy and paste the modified m-file into your lab report and comment on the sound quality with and without filtering. V. LAB REPORT: All required data, questions, and written comments can be found within the framed text blocks. Tabulate or plot all of the requested data and answer the questions in a manner that flows naturally. Complete Lab Report Guidelines are listed on the course website. ES 3 Laboratory #5 Page 9 of 17

VI. SUPPLEMENTARY INFORMATION: Appix A: MATLAB Tutorial Starting MATLAB Login to an ECE Windows PC using your ECE ID and password. Then, from the Start Menu select MATLAB R2007a. It takes several seconds for MATLAB to initialized, so please be patient. Setting a Working Directory Unless otherwise specified, all of your work will be saved in the default directory shown in the Current Directory box of the main MATLAB window. To change this directory, click on the button to the right of the Current Directory window that contains the ellipsis icon: [ ]. For this lab, it is easiest to run everything from the Windows Desktop. Select the Desktop from the list of available directories. Entering Commands (direct entry mode) You may enter MATLAB commands by typing at the >> prompt found in the Command Window. Try these exercises to get a feel for MATLAB: Type the following at the >> prompt. Finish each command by hitting Enter : >> x=3 >> y=6 >> z=y/x In this example you are storing the numerical value of 3 in the variable x, then 6 is stored in y, and finally you are assigning the variable z the value found by dividing y by x. In circuits and systems, it is common to use complex numbers. MATLAB is great for evaluating these expressions: >> clear >> a = 3 + j*3 >> b = 5 j*4 >> c = a + b >> d = (a+b)/(a-b) MATLAB recognizes both i and j as the imaginary number (-1) 1/2. You may determine the real and imaginary parts of a variable, as well as the magnitude and phase using >> real(a) >> imag(a) >> abs(a) %this is the magnitude of a >> phase(a) %the result is in radians ES 3 Laboratory #5 Page 10 of 17

Arrays and matrices of data can also be stored in MATLAB. For an array of numbers (also called a vector), a single variable name is used and each number is stored in a separately indexed variable. >> x = [1 2 3 2 1] >> k=4 >> x(k) % MATLAB displays the value stored in the 4th position of x: 2 Another useful function allows the data in an array to be plotted M-files >> plot(x) Entering data at the command line is fine for simple calculations, but MATLAB is much more than a calculator. Large collections of commands can be written in an m-file and then the entire m-file can be replayed from the command window To create a new m-file, choose File>>New,..>>M-File. This starts the m-file editor. Commands can be typed into the editor and saved (save as filename.m). Then all of the commands saved in filename.m are replayed by typing filename on the command line. Placing a semicolon at the of a line will suppress the display of the results to the screen during execution: a=2; will set the variable a equal to two but will not show the result on the screen. The true power of this technique is tapped when control structures are included in the m- file. MATLAB has a complete set of control structures, just like other programming languages. These include for loops and if else structures. A complete list of control structures can be found in the MATLAB Help section. MATLAB Commands using the Soundcard A special set of MATLAB commands have been written so that users can access the functions of the PC s soundcard. To use the soundcard as an analog-to-digital converter and store the sampled voltage waveforms in memory, the following MATLAB code is used: rate=44100; %Hz, Sampling rate of the analog-to-digital % converter (soundcard) recordtime = 1; %in sec, Length of time for recording data bits=16; %Number of bits of data stored per sample mono=1; %1=mono 2=stereo recorder = audiorecorder(rate,bits,mono); recordblocking(recorder,recordtime); audio = getaudiodata(recorder); This segment of MATLAB code specifies the sampling rate (44.1kHz), the length of time that voltages should be converted (1 sec), the resolution of the digital data (16 bits) and ES 3 Laboratory #5 Page 11 of 17

whether the analog input data is one voltage (mono) or two simultaneous voltages (stereo). The resulting digital data is stored in an array variable called audio. This variable contains 44,100 individual numbers, each number representing one in the sequence of samples taken during the one-second period of analog-to-digital conversions. To view a graph of the sampled data, simply type plot(audio). Digital-to-analog conversion from MATLAB through the soundcard uses these two commands: rate = 44100; soundsc(audio,rate) These two commands s the numerical data stored in the array audio to the digitalto-analog converter. Data is sent to the D/A at rate samples per second (44,100 samples/sec). The command soundsc performs one other useful function: the data contained in audio is automatically scaled such that the maximum voltage range of the D/A converter is not exceeded. If you do not want the data to be scaled, then use the command sound(audio,rate) Fast Fourier Transform Fourier showed that any well-behaved periodic signal can be decomposed into a sum of sinusoids. MATLAB can extract these sinusoids from an arbitrary waveform stored in an array (vector) using the Fast Fourier Transform (FFT) function. The following lines of code determine the amplitudes of the frequencies present in a waveform stored in the array called audio. audiof=fft(audio,2048); %find a 2048 point FFT of the vector audio audiomag = abs(audiof); %determine the magnitude of the FFT fr=rate*[0:1023]/2048; %determine the frequency scaling for the plot plot(fr, audiomag) %plots the frequency spectrum of the signal ES 3 Laboratory #5 Page 12 of 17

Appix B: Building an Audio Amplifier using the LM386 Chip The circuit schematic for the LM386 audio amplifier is shown in Figure B1. The input to the amplifier comes from a miniature phone jack (left side). This phone jack should be connected to the output of the PC soundcard. (This is usually marked by a headphone icon). You may adjust the output level of the sound card by double-clicking on the speaker icon in the lower-right corner of the Windows icon tray. 9 V - + 1 8 2 3 LM 386 7 6 100 uf C C 4 5 10 Ω 0.047uF Spkr 16 Ω (ground) Figure B1. The audio amplifier circuit ES 3 Laboratory #5 Page 13 of 17

Appix C: MATLAB m-files used in this laboratory es3.m %Audio Frequency Response Tester %This program requires a PC with a soundcard and a microphone. %An audio system should be connected to the output of the soundcard. %The MATLAB m-file will play user-specified tones through the soundcard and %the attached audio system. %Nearly simultaneously, the program records these tones using the microphone. %The amplitude of the recorded tone is plotted as a function of frequency. %After the program pauses, Matlab generates white noise and outputs this %noise to the soundcard. The noise is simultaneously recorded. The %Fourier transform of the noise is normalized to match the amplitudes of %the tone signals and plotted as the frequency response of the audio system. clear rate=44100; %Hz, Sampling rate of the analog-to-digital converter (soundcard) duration = 1; %sec, Length of time for each test tone bits=16; % Number of bits of data stored per sample mono=1; % 1=mono 2=stereo recordtime=duration; %Total recording time in seconds (same as the duration of the tone) t=[0:1/rate:(duration-(1/rate))]; %set up a time array [0 1/rate 2/rate... ] in seconds %All test tones are stored in the vector f; the user may modify these frequencies: tw = 2^(7/12); %the frequency interval of a perfect fifth f= [55 55*tw 110 110*tw 220 220*tw 440 440*tw 880 880*tw 1760 1760*tw 3520 3520*tw 7040 7040*tw 14080] figure for n=1:length(f) %create an array containing a sine with the frequency f(n) tone = sin(2*pi*f(n)*t); %play the tone at frequency f(n)through the digital-to-analog converter %(i.e., the soundcard output) soundsc(tone,rate) %simultaneously record the tone using the microphone using the %analog-to-digital converter (soundcard input) recorder = audiorecorder(rate,bits,mono); recordblocking(recorder,recordtime); audio = getaudiodata(recorder); pause(1.2*duration) %find the amplitude of the recorded sound by taking the Fourier %transform and select the maximum value (note: this method can %mistrack if high amplitude noise or interfering frequencies are present!) peak(n)= max(abs(fft(audio, 2048))); %display the test frequency and the resulting amplitude of the recorded %signal for each tone: f(n) peak(n) %create a log-log plot of the frequency response of the audio system loglog(f(1:n), peak, '-dr') xlabel('test Frequency (Hz)') ylabel('measured Sound Level (arb.)') title('frequency Response of an Audio System') xlim([10 20000]) hold on %create the final plot of the frequency response hold off figure loglog(f(1:n), peak, '-dr') xlabel('test Frequency (Hz)') ylabel('measured Sound Level (arb.)') title('frequency Response of an Audio System') xlim([10 20000]) pause(5) %wait 5 seconds before performing the white noise test %-------------------------------------------------------------------- %The MATLAB code below produces 'white' noise. White noise contains ALL %frequencies simultaneously and each frequeny is present in an equal amount. %The noise is recorded and the frequency response is ES 3 Laboratory #5 Page 14 of 17

%deduced from the Fourier transform of the recorded noise. rate=44100; %Hz the sampling rate for playback and recording duration = 5; %sec the duration of the white noise time=[0:1/rate:duration]; %set up a time array [0 1/rate 2/rate... duration] in seconds %make white noise: noise=0.5*random('normal',0,1,1,length(time)); soundsc(noise,rate) %record the white noise during playback bits=16; %number of bits per sample mono=1; %1=mono 2=stereo recordtime=duration; %total recording time in seconds recorder = audiorecorder(rate, bits, mono); recordblocking(recorder,recordtime); audio = getaudiodata(recorder); %find the frequency spectrum of the recorded audio using fast Fourier transform: audiof=fft(audio,2048); audiomag = abs(audiof); fr=rate*[0:1023]/2048; %sets up the correct frequency scaling for the plot! %average together data points to help smooth the freq resp curve freqresp = audiomag; smooth=5; for n=1:smooth bode(n)=freqresp(n); %skip the first 'smooth' number of points for n=smooth:length(freqresp)-smooth bode(n)=0; for m=1:smooth bode(n)=bode(n)+(1/smooth)*freqresp(n+m); %plot the noise-based frequency response on the same plot as the tone-based %measurement by turning the 'hold' function ON. hold on %make a plot of the audio system's frequency response based on the %measurement of noise loglog(fr(smooth:1024), bode(smooth:1024)*max(peak)/max(bode(smooth:1024))) %label the two plots with a leg leg('tone method', 'noise method') es3notch.m clear rate=44100; %Hz, the sampling rate for playback and recording %create the parameters needed for a notch filter notchfreq = 2000 %in Hertz, the center of the frequencies to be removed wo = notchfreq/(rate/2); %Don't mess with this! It tells the filter design routine the sampling frequency. bandwidth = 2*wo; %The bandwidth of the notch filter. bw = bandwidth*(rate/2) attenuate = -6 %in db, the amount of signal removed at the (notchfreq +/- bandwidth) [b,a] = iirnotch(wo, bandwidth, attenuate); %fvtool(b,a); %un-comment this to see the filter's freq. resp %The code below produces nearly 'white' noise %The noise is recorded and the freq response is %deduced from the Fourier transform of the recorded noise duration = 5; %sec the duration of the white noise time=[0:1/rate:duration]; %set up a time array [0 1/rate 2/rate... duration] in seconds %make white noise: noise=0.1*random('normal',0,1,1,length(time)); %the following loop is executed twice %the first time, the noise is played and recorded %after the first time, the noise is filtered %during the second and final loop the filtered noise is played and recorded %finally the two noise signals are plotted so that they may be compared for c=1:2 soundsc(noise,rate) %record the white noise during playback bits=16; %number of bits per sample mono=1; %1=mono 2=stereo recordtime=duration; %total recording time in seconds ES 3 Laboratory #5 Page 15 of 17

recorder = audiorecorder(rate, bits, mono); recordblocking(recorder,recordtime); audio = getaudiodata(recorder); %find the frequency spectrum of the recorded audio using fast Fourier transform: audiof=fft(audio,2048); audiomag = abs(audiof); fr=rate*[0:1023]/2048; %sets up the correct frequency scaling for the plot! freqresp = audiomag; smooth=5; %average together data points to help smooth the freq resp curve for n=1:smooth bode(n)=freqresp(n); %skip the first 'smooth' number of points for n=smooth:length(freqresp)-smooth bode(n)=0; for m=1:smooth bode(n)=bode(n)+(1/smooth)*freqresp(n+m); if c==1 loglog(fr(smooth:1024), bode(smooth:1024)) xlim([20 20000]) hold on %apply the notch filter to the noise signal to attenuate %frequencies surrounding the selected 'notchfreq' noisefilt = filter(b,a,noise); noise=noisefilt; %plot the filtered frequency response loglog(fr(smooth:1024), bode(smooth:1024), '-r') leg('unfiltered', 'filtered') title('digital Filtering of Noise') xlabel('frequency (Hz)') ylabel('signal Intensity (arb.)') hold off es3music.m clear load audiosample; rate=44100; %Hz the sampling rate for playback and recording %create the parameters needed for a notch filter notchfreq = 2000 %hertz, the center of the frequencies to be removed wo = notchfreq/(rate/2); %don't mess with this! It tells the filter design routine the sampling frequency. bandwidth = 2*wo; %the bandwidth of the notch filter attenuate = -6; %db, the amount of signal removed at 'notchfreq' [b,a] = iirnotch(wo,bandwidth,attenuate); %fvtool(b,a); %un-comment this to see the filter's freq. resp unfilt='this is the UNFILTERED sound file'; filt='this is the FILTERED sound file'; unfilt soundsc(spin,rate) pause(length(spin)/rate) filt spinfilt=filter(b,a,spin); soundsc(spinfilt, rate); pause(length(spin)/rate) unfilt soundsc(spin,rate) pause(length(spin)/rate) ES 3 Laboratory #5 Page 16 of 17

VII. PARTS LIST: 1 - Home-made Speaker (or a commercially produced speaker if the home-made speaker is not yet complete) From Lab #4: LM386 audio amplifier chip 100μF non polarized electrolytic capacitor 0.047μF or 0.05 μf capacitor 0.01 μf capacitor (C C ) 10 Ω resistor 9 volt battery with battery clip Breadboard for prototyping circuits Special Equipment: MATLAB (preferably version R2006a, or later) Windows-based PC with a sound card PC-compatible microphone Test Leads Miniature (3.5 mm) stereo phone plug to alligator clips (use the wires from ground and either the left or right channel to connect from the output of the soundcard to the input of the LM386 amplifier chip) ES 3 Laboratory #5 Page 17 of 17