Fft Computation and Generation of Spectrogram

download Fft Computation and Generation of Spectrogram

of 32

Transcript of Fft Computation and Generation of Spectrogram

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    1/32

    COMPUTATION OF FFT AND

    GENERATION OF SPECTROGRAM

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    2/32

    CONTENTS

    1. SYNOPSIS2. INTRODUCTION3. MATLAB4. DAQ IN MATLAB5. THE PROJECT DESIGN6. PROJECT IMPLEMENTATION7. CODING8. CONCLUSION9. REFERENCES

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    3/32

    Synopsis

    This project attempts to compute the FFT of an acquired signal and generate the corresponding

    spectrogram and its graphic representation. The electronic analog data is captured using

    MATLAB DAQ engine at a pre-determined sampling rate and is stored as digital data for future

    analysis. This digital signal is divided into convenient slices and the FFT of each slice is

    computed using MATLAB FFT function and arranged as a 2D matrix. This when viewed using

    image processing functions of MATLAB, the spectral representation of the signal, the

    spectrogram is ready for signal analysis. This spectrogram becomes a very handy tool for

    detailed analysis of an analog signal.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    4/32

    Introduction

    Acquisition of electronic data and its processing is an essential part of every electronic

    experiment. Hardware interfaces like CROs are currently being used for this purpose in

    electronic labs and its utility is limited to simple measurement of signal parameters like

    amplitude and frequency. Processing of the signal is to be carried out manually. Advanced

    equipments like Digital Storage Oscilloscope (DSO) can be used to overcome this problem to a

    certain extent, but not completely.

    Signal processing is mainly concerned with the analysis of the signal, and involves the

    determination of parameters like frequency components, amplitude, phase relationships etc. This

    is usually done manually and is obviously time consuming. Signal processing theory is a highly

    developed one and there are very efficient algorithms for the fast computation of frequency

    content (like FFT). Computation of FFT is possible only if the signal data is made available to

    the processing software in the computer. Simple Hardware/Software interfaces can be developed

    for this purpose. Through this project work , we attempt the design of a software method using

    MATLAB with out any extra cost if a computer system and a technical computing software like

    MATLAB is available.It is an interactive software for numerical computations and graphics.

    Matlab has a rich set of functions for signal processing and data acquisition.

    For developing this project we use the computing software MATLAB since it is equippedwith sufficient tools for Data Acquisition and Signal Processing. MATLAB performs

    dataprocessing using matrix methods. MATLAB is an Object Oriented Language. It integrates

    computation ,visualization, and programming in an easy-to-use environment where problems and

    solutions are expressed in familier mathematical notations. Typical uses include MATLAB is an

    interactive system whose basic data element is an array that doesnot require dimensioning.

    MATLAB features a family of applications-

    specific solutions called toolboxes.

    Areas in which toolboxes are available include signal processing, control systems, neural

    networks, fuzzy logic, wavelets, simulation, and many others.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    5/32

    Data Acquisition Toolbox

    The Data Acquisition Toolbox is a collection of M-file (nothing more than a text file with

    extention .m) functions and MEX-file dynamic link libraries (DLLs) built on the MATLAB

    technical computing environment. The toolbox provides us with these main features:

    A framework for bringing live, measured data into MATLAB using PC-compatible plug-in data acquisition hardware

    Support for analog input (AI), analog output (AO), and digital I/O (DIO)subsystems including simultaneous analog I/O conversions

    Support for these popular hardware vendors/devices: National Instruments boards that use NI-DAQ software

    Parallel ports LPT1-LPT3 Windows sound cards Additionally, we can use the Data Acquisition Toolbox Adaptor Kit to

    interface unsupported hardware devices to the toolbox. Event-driven

    acquisitions .

    Project requirements:

    The windows sound card is used as the hardware for data acquisition MATLAB DAQ TOOLBOX as the software for data acquisition and also for graphical

    display of signals

    MATLAB SIGNAL PROCESSING TOOL BOX for the analysis part MATLAB IMAGE PROCESSING TOOL BOX for data visualization

    In this project systems are developed for FFT computation and spectrogram visualization, the

    following interfaces and functions are developed in MATLAB.

    o Data Acquisition interface for capturing,observing and saving periodic, aperiodic or non-periodic analog signals.

    o Functions forsegmenting captured signals and the segments FFT computation.o Scripts for combining segment FFTs to form a matrix that represents spectrogram data.o Matlab image processing functions are used for visualizing the spectrogram data.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    6/32

    MATLAB

    MATLAB is a high-performance language for technical computing. It integrates computation,

    visualization, and programming in an easy-to-use environment where problems and solutions are

    expressed in familiar mathematical notation. Typical uses include:

    Math and computation Algorithm development Modeling, simulation, and prototyping Data analysis, exploration, and visualization Scientific and engineering graphics Application development, including Graphical User Interface building

    The MATLAB System

    The MATLAB system consists of five main parts:

    The MATLAB language.

    This is a high-level matrix/array language with control flow statements, functions, data

    structures, input/output, and object-oriented programming features. It allows creating complete

    large and complex application programs.

    The MATLAB working environment.

    This is the set of tools and facilities that one work with as the MATLAB user or

    programmer. It includes facilities for managing the variables in the workspace and importing and

    exporting data. It also includes tools for developing, managing, debugging, and profiling M-files,

    MATLAB's applications.

    Handle Graphics.

    This is the MATLAB graphics system. It includes high-level commands for two-dimensional

    and three-dimensional data visualization, image processing, animation, and presentation

    graphics. It also includes low-level commands that allow one to fully customize the appearance

    of graphics as well as to build complete Graphical User Interfaces on your MATLAB

    applications.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    7/32

    The MATLAB mathematical function library.

    This is a vast collection of computational algorithms ranging from elementary functions

    like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix

    inverse, matrix eigen-values, Bessel functions, and fast Fourier transforms.

    The MATLAB Application Program Interface (API).

    This is a library that allows one to write C and Fortran programs that interact with

    MATLAB. It include facilities for calling routines from MATLAB (dynamic linking), calling

    MATLAB as a computational engine, and for reading and writing MAT-files.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    8/32

    DAQ in MATLAB

    Data Acquisition

    For each new data acquisition experiment, one needs to perform these tasks: System setup Calibration Trials

    System Setup

    The first step in any data acquisition experiment is to install the hardware and software.

    Hardware installation consists of plugging a board into the computer or installing modules into

    an external chassis.

    Software installation consists of loading hardware drivers and application software onto

    your computer. After the hardware and software are installed, one can attach sensors.

    Calibration

    After the hardware and software are installed and the sensors are connected, the data

    acquisition hardware should be calibrated. Calibration consists of providing a known input to the

    system and recording the output.

    Trials

    After the hardware is set up and calibrated, the data acquiring session can be started. One

    needs to experiment with different hardware and software configurations. In other words,

    multiple data acquisition trials should be performed.

    The Data Acquisition and Analysis System

    We can think of a data acquisition system as a collection of software and hardware that

    connects us to the physical world. A typical data acquisition system consists of these

    components:

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    9/32

    Data acquisition hardware

    At the heart of any data acquisition system lies the data acquisition hardware. The main

    function of this hardware is to convert analog signals to digital signals, and to convert digital

    signals to analog signals.

    Sensors and actuators (transducers)

    Sensors and actuators can both be transducers. A transducer is a device that converts

    input energy of one form into output energy of another form. For example, a microphone is a

    sensor that converts sound energy (in the form of pressure) into electrical energy, while a

    loudspeaker is an actuator that converts electrical energy into sound energy.

    The computer

    The computer provides a processor, a system clock, a bus to transfer data, and memory

    and disk space to store data. Software Data acquisition software allows us to exchange

    information between the computer and the hardware. For example, typical software allows us to

    configure the sampling rate of the board, and acquire a predefined amount of data. The

    dataacquisition components, and their relationship to each other, are shown below. The figure

    depicts the two important features of a data acquisition system: Signals are input to a sensor,

    conditioned, converted into bits that a computer can read, and analyzed to extract meaningful

    information. For example, sound level data is acquired from a microphone, amplified, digitized

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    10/32

    by a sound card, and stored in MATLAB for subsequent analysis of frequency content.

    Data from a computer is converted into an analog signal and output to an actuator. For example,

    a vector of data in MATLAB is converted to an analog signal by a sound card and output to a

    loudspeaker.

    Creating a Device Object

    Device objects are the toolbox components used to access the hardware device. They provide a

    gateway to the functionality of the hardware, and allows to control the behavior of the data

    acquisition application. Each device object is associated with a specific hardware subsystem. To

    create a device object, call M-file functions called object creation functions (or object

    constructors). These M-files are implemented using the object-oriented programming capabilities

    provided by MATLAB

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    11/32

    Creating an Analog Input Object

    An analog input object can be created with the analoginput function. The analoginput

    accepts the adaptor name and the hardware device ID as input arguments. The device ID is

    optional for sound cards with an ID of 0. Use the daqhwinfo function to determine the available

    adaptors and device IDs. Each analog input object is associated with one board and one analog

    input subsystem.

    To create an analog input object associated with a sound card with device ID 0:

    ai = analoginput('winsound',0);

    Adding Channels to an Analog Input Object

    After creating the analog input object, hardware channels must be added to it. We add

    channels to an analog input object with the addchannel function. The addchannel requires the

    device object and at least one hardware channel ID as input arguments.

    To add two hardware channels to the device object ai created in the preceding section:

    chans = addchannel(ai,0:1);

    The Sampling Rate

    We control the rate at which an analog input subsystem converts analog data to digital

    data with the SampleRate property. SampleRate must be specified as samples per second.

    To set the sampling rate for each channel of your sound card to 44100 samples per

    second (44100 Hz)

    ai = analoginput('winsound',0);

    addchannel(ai,0:1);

    set(ai,'SampleRate',44100)

    Trigger Types

    For analog input objects, a trigger is defined as an event that initiates data logging to

    memory or to a disk file. Defining an analog input trigger involves specifying the trigger type

    with the TriggerType property.

    In the project, in most of the situations, a manual trigger is issued by the command;

    start(obj)

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    12/32

    To stop the device object;

    Stop(obj) is issued.

    The Samples to Acquire per Trigger

    When a trigger executes, a predefined number of samples are acquired for each channel

    group member and logged to the engine or a disk file. Specify the number of samples to acquire

    per trigger with the SamplesPerTrigger property.

    The default value of SamplesPerTrigger is calculated by the engine such that 1 second of

    data is collected.

    To acquire 5 seconds of data per trigger for each channel contained by ai:

    set(ai,'SamplesPerTrigger',500000)

    where 100000 is the sample rate.

    Acquiring Data

    After we configure the analog input object, we can acquire data. Acquiring data involves

    these three steps:

    Starting the analog input object Logging data Stopping the analog input object

    Starting the Analog Input Object

    We start an analog input object with the start function.For example, to start the analog inputs

    object ai:

    ai = analoginput('winsound')

    addchannel(ai,1:2)

    start(ai)

    After start is issued, the Running property is automatically set to On, and both the device object

    and hardware device execute according to the configured and default property values. While we

    are acquiring data with an analog input object, we can preview the data with the peekdata

    function. Thepeekdata takes a "snapshot" of the most recent data but does not remove data from

    the engine.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    13/32

    For example, to preview the most recent 500 samples acquired by each channel contained

    by ai:

    data = peekdata(ai,500);

    Clean up

    When the ai no longer needed it should be removed from memory and from the

    MATLAB workspace.

    delete(AI)

    clear AI

    Extracting Data from the Engine

    Many data acquisition applications require that data is acquired at a fixed (often high) rate, and

    that the data is processed in some way immediately after it is collected. For example, one might

    want to perform an FFT on the acquired data . If acquired data is not extracted in a timely

    fashion,It can be overwritten. Data is extracted from the engine with the getdata function. For

    example, to extract 1000 samples for the analog input object ai:data = getdata(ai,1000);

    PEEKDATA FUNCTION

    There is another very important function that is used to preview incoming signal data., whose

    functionality is described below

    peekdata Preview most recent acquired data.

    Syntax data = peekdata(obj,samples)

    Arguments

    Obj -An analog input object.samplesThe number of samples to preview for each channel

    contained by obj.data

    An m-by-n matrix where m is the number of samples and n is the number of channels.

    Description

    data = peekdata(obj,samples) returns the latest number of samples specified by samples to data.

    Remarks about usingpeekdata

    Unlike getdata, peekdata is a nonblocking function that immediately returns control to

    MATLAB. Because peekdata does not block execution control, data might be missed or

    repeated. peekdata takes a "snapshot" of the most recent acquired data and does not remove

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    14/32

    samples from the data acquisition engine. Therefore, the SamplesAvailable property value is not

    affected when peekdata is called.

    Rules for Usingpeekdata

    You can call peekdata before a trigger executes. Therefore, peekdata is useful for previewing

    data before it is logged to the engine or to a disk file. In most cases, you will call peekdata while

    the device object is running. However, you can call peekdata once after the device object stops

    running. If samples is greater than the number of samples currently acquired, all available

    samples are returned with a warning message stating that the requested number of samples were

    not available.

    Create the analog input object ai for a windows sound card, add one input channel, and configure

    ai for a two second acquisition.

    ai = analoginput('winsound);

    addchannel(ai,1);

    set(ai,'SampleRate',8000)

    set(ai,'SamplesPerTrigger',16000)

    After issuing the start function, you can preview the data.

    start(ai)

    data = peekdata(ai,100);

    peekdata returns 100 samples to data for all eight channel group members. If 100 samples are not

    available, then whatever samples are available will be returned and a warning message is issued.

    The data is not removed from the data acquisition engine.

    An example of preview is given below.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    15/32

    In the upper window the incoming data is dynamically displayed and the total signal captured is

    at the lower window at the end of the session.

    THE SPECTROGRAM

    For a non-periodic signal it is more meaningful to get its spectrum rather than the FFT. For non-

    periodic signals the frequency components are varying with respect to time. To study such

    signals there is a function called specgramdemo. When the signal data is given as argument to

    this function the spectrogram of the signal can be obtained. This function is useful for a

    superficial study of any signal but has so many constraints that prevents a detailed study. In This

    project a spectrogram function is developed which is more flexible compared to

    specgramdemo

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    16/32

    THE PROJECT DESIGN

    The FFT

    The key element in the design of a spectrogram is the computation of FFT. The concept

    of FFT is briefly explained below.

    The Fast Fourier Transform is one of the most important topics in Digital Signal Processing.

    The Fast Fourier Transform (FFT) is simply a fast (computationally efficient) way to

    calculate the Discrete Fourier Transform (DFT). By making use of periodicities in the sines that

    are multiplied to do the transforms, the FFT greatly reduces the amount of calculation required.

    Here's a little overview.

    Principle of FFT

    Functionally, the FFT decomposes the set of data to be transformed into a series of

    smaller data sets to be transformed. Then, it decomposes those smaller sets into even smaller

    sets. At each stage of processing, the results of the previous stage are combined in special way.

    Finally, it calculates the DFT of each small data set. For example, an FFT of size 32 is broken

    into 2 FFTs of size 16, which are broken into 4 FFTs of size 8, which are broken into 8 FFTs of

    size 4, which are broken into 16 FFTs of size 2. Calculating a DFT of size 2 is trivial.

    Here's a slightly more rigorous explanation: It turns out that it is possible to take the DFT

    of the first N/2 points and combine them in a special way with the DFT of the second N/2 points

    to produce a single N-point DFT. Each of these N/2-point DFTs can be calculated using smaller

    DFTs in the same way. One (radix-2) FFT begins, therefore, by calculating N/2 2-point DFTs.

    These are combined to form N/4 4-point DFTs. The next stage produces N/8 8-point DFTs, and

    so on, until a single N-point DFT is produced.

    Efficiency of FFTThe DFT takes N^2 operations for N points. Since at any stage the computation required

    to combine smaller DFTs into larger DFTs is proportional to N, and there are log2(N) stages (for

    radix 2), the total computation is proportional to N * log2(N). Therefore, the ratio between a

    DFT computation and an FFT computation for the same N is proportional to N / log2(n). In cases

    where N is small this ratio is not very significant, but when N becomes large, this ratio gets very

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    17/32

    large. (Every time you double N, the numerator doubles, but the denominator only increases by

    1.)

    FFTs and the powers of 2

    The most common and familiar FFTs are "radix 2". However, other radices are

    sometimes used, which are usually small numbers less than 10. For example, radix-4 is

    especially attractive because the "twiddle factors" are all 1, -1, j, or -j, which can be applied

    without any multiplications at all.

    Also, "mixed radix" FFTs also can be done on "composite" sizes. In this case, you break a non-

    prime size down into its prime factors, and do an FFT whose stages use those factors. For

    example, an FFT of size 1000 might be done in six stages using radices of 2 and 5, since

    1000 = 2 * 2 * 2 * 5 * 5 * 5. It might also be done in three stages using radix 10, since 1000 = 10

    * 10 * 10.

    FFT Terminology

    FFT "radix"

    The "radix" is the size of an FFT decomposition. In the example above, the radix was 2. For

    single-radix FFTs, the transform size must be a power of the radix. In the example above, the

    size was 32, which is 2 to the 5th power.

    Twiddle factors

    "Twiddle factors" are the coefficients used to combine results from a previous stage to form

    inputs to the next stage.

    Bit reversal

    "Bit reversal" is just what it sounds like: reversing the bits in a binary word from left to right.

    Therefore the MSBs become LSBs and the LSBs become MSBs. But what does that have to do

    with FFTs? Well, the data ordering required by radix-2 FFTs turns out to be in "bit reversed"

    order, so bit-reversed indexes are used to combine FFT stages. It is possible (but slow) to

    calculate these bit-reversed indices in software; however, bit reversals are trivial when

    implemented in hardware. Therefore, almost all DSP processors include a hardware bit-reversal

    indexing capability (which is one of the things that distinguishes them from other

    microprocessors.)

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    18/32

    Decimation-in-time versus decimation-in-frequency

    FFTs can be decomposed using DFTs of even and odd points, which is called a Decimation-In-

    Time (DIT) FFT, or they can be decomposed using a first-half/second-half approach, which is

    called a "Decimation-In-Frequency" (DIF) FFT. Generally, the user does not need to worry

    which type is being used.

    FFT Implementation

    Except as a learning exercise, one generally will never have to know. Many good FFT

    implementations are available in C, Fortran, MATLAB and other languages, and microprocessor

    manufacturers generally provide free optimized FFT implementations in their processors'

    assembly code, Therefore, it is not so important to understand how the FFT really works, as it is

    to understand how to use it.

    Usually, a spectrum analyzer displays a power spectrum over a given frequency range, changing

    the display as the properties of the signal change. There is a trade-off between how quickly the

    display can be updated and the frequency resolution, which is for example relevant for

    distinguishing frequency components that are close together. With a digital spectrum analyzer,

    the frequency resolution is = 1 / T, the inverse of the time Tover which the waveform is

    measured and Fourier transformed (according to Uncertainty principle). With an analog spectrum

    analyzer, it is dependent on the bandwidth setting of the bandpass filter. Choosing a wider

    bandpass filter will improve the signal-to-noise ratio at the expense of a decreased frequency

    resolution.

    Spectrum Analyzer

    With Fourier transform analysis in a digital spectrum analyzer, it is necessary to sample

    the input signal with a sampling frequency Fs that is at least twice the highest frequency that is

    present in the signal, due to the Nyquist limit. A Fourier transform will then produce a spectrum

    containing all frequencies from zero to Fs / 2.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    19/32

    Acoustic usesThe Spectrogram

    The above figure represents a sample spectrogram of the sound ho-ho-ho-ho-.

    The vertical axis represents linear frequency from 0 to 5.5 kHz, and the horizontal axisrepresents the passage of 700 milliseconds. In this 2D image each point represents the strength of

    the frequency by color code. The color map on the right represents the color code. Red stands for

    strong component whereas blue for weak .

    In acoustics, the spectrum analyzer is also referred to as a spectrograph, and it converts a

    sound wave into a sound spectrogram. The first acoustic spectrograph was developed II at Bell

    Telephone Laboratories, and was widely used in speech science, acoustic phonetics and

    audiology research, before eventually being superseded by digital signal processing techniques.

    The modern day acoustic spectrograph or spectrum analyzer benefits from the

    advancements made in the capabilities of personal computers. The relatively low frequency

    content of common acoustic signals such as speech or music (typically between 0 and 20 kHz)

    can be sampled with the existing sound card hardware built in to most personal computers. Since

    specialized hardware is not required, an acoustic spectrum analyzer can be fully implemented in

    software. Unlike radio frequency spectrum analyzers, software based audio spectrum analyzers

    are available at low cost, providing easy access not only to industry professionals, but also to

    academicians, students and the lay hobbyist.

    The acoustic spectrogram generated by the spectrum analyzer provides an acoustic signature

    of the source. The acoustic signature of human speech can be characterized and used to identify

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    20/32

    the originator. This is of particular interest in the fields of law enforcement and forensic analysis.

    Similarly, analysis of the acoustic signature of a musical instrument may be used to characterize

    the sometimes subtle differences between a fine instrument and one that might be considered

    more mediocre.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    21/32

    PROJECT IMPLEMENTATION

    For achieving the final goal-the design of the spectrogram- the project implements the

    following two stages:

    1. Analog data acquisition2. FFT calculation and Spectrogram generationFor analog data acquisition two programs(scripts) are written in MATLAB that uses its

    TOOLBOX functions.

    First Program daqsession.m Second Program peekdatafft.m

    These scripts are the interfaces for capturing, displaying and analyzing an analog input

    signal applied at the input of the sound card. The following facilities in MATLAB are used for

    the design:

    DAQ TOOL BOX SIGNAL PROCESSING FUNCTIONS MATLAB GRAPHICS THE MATLAB PROGRAMMING ENVIRONMENT The data acquisition session

    For data acquisition, a script is prepared using DAQ functions. The first script

    when executed captures the analog input signal, displays graphically its FFT plot and

    saves the digital data of the analog input signal in a file with name *.mat.

    FIRST PROGRAM: SCRIPT FOR DAQ AND FFT (daqsession.m)

    Algorithm

    1. Define analog input object AI2. Set channel, sample rate,duration, etc.3. Start AI, Trigger AI (Start capturing signal)4. Store data into the variable data.5. Plot the data captured6. Calculate the fft of data into the variable xfft7. Plot xfft8. Save data into a mat file

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    22/32

    SECOND PROGRAM: SCRIPT FOR DAQ ,PREVIEW& FFT(peekfft.m)

    Algorithm

    1. Define analog input object AI2.

    Set channel, sample rate, duration, etc.

    3. Start AI, Trigger AI (Start capturing signal)4. Store data into the variable data.5. Preview plot of signal using peekdata6. Preview plot of fft of the signal7. Save data into a mat file

    FFT calculation and Spectrogram generation

    The most important part of the project work is writing the program for the

    generation of the spectrogram. There are many implementations of spectrogram in different

    languages. Most of these implementation divides a digital signal into segments of equal

    length. This length will be of the order of milliseconds. The FFT of each segment is

    calculated and is arranged as the columns of a matrix. The image of the matrix gives the

    spectrogram, frequency along the vertical axis and time along the horizontal axis.

    Segmenting the signal causes sharp boundaries and adds additional frequencies which are

    originally not present in the signal. In order to overcome this prior to computation of FFT the

    segments edges are smoothened using smoothening windows which may cause a

    modification in the original signal. Due to this some additional frequencies may be present in

    the spectrogram or some frequencies may be missing. In order to solve this a different

    method for segmenting the signal is tried, that is the method of slicing the signal at zero-

    crossing points.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    23/32

    Slicing the signal at zero-crossing points

    In the sample signal given above it can be noted that the signal oscillates between positive and

    negative values and crosses the zero value each time it oscillates. The vertical lines mark the zero

    crossing points for a full cycle.

    Program for Spectrogram-myspectrum.m

    Before executing the program myspectrum.m

    The program daqsession.m or peekfft.m should be executed to obtain the signal data

    (maydata.mat in this example)

    Algorithm

    1. Load mydata.mat2. Save data to the variable d3. Find the peaks and valleys of the signal4. Find the point at which the signal crosses zero point5. Extract segment data between alternate zero points and store the data in the column

    of the matrix starting from the first segment

    6. Do the same for the next segment and so on7. Display the matrix using image Command8. Use data cursor on command for Reading frequency from the

    Spectrogram

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    24/32

    CODING

    SCRIPT FOR DAQ AND FFT (daqsession.m)

    %The program daqsession.mAI = analoginput('winsound');

    chan = addchannel(AI,1);

    duration = 1; %1 second acquisition

    set(AI,'SampleRate',16384)

    %ActualRate = get(AI,'SampleRate');

    set(AI,'SamplesPerTrigger',16384)

    set(AI,'TriggerType','Manual')

    %blocksize = get(AI,'SamplesPerTrigger');

    %Fs = ActualRate;

    start(AI)

    trigger(AI)

    wait(AI,duration + 1)

    data = getdata(AI);

    plot(data(500:1000);

    figure;

    delete(AI)

    clearAI

    xfft = abs(fft(data));

    % Avoid taking the log of 0.

    index = find(xfft == 0);

    xfft(index) = 1e-17;

    mag = 20*log10(xfft);

    mag = mag(1:4048);

    f = (0:length(mag)-1);

    f = f(:);

    plot(f,mag)

    grid on

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    25/32

    ylabel('Magnitude (dB)')

    xlabel('Frequency (Hz)')

    title('Frequency Components of The signal')

    save('SampleSignal.mat','data');

    A sample signal captured using the above program is given below

    The fft plot of the above signal

    The above program displays the plot only after the capturing is over. There is no way to observe

    the signal as and when it comes.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    26/32

    SCRIPT FOR DAQ ,PREVIEW& FFT(peekfft.m)

    AI = analoginput('winsound');

    chan = addchannel(AI,1);

    duration = 5; % Ten second acquisition

    set(AI,'SampleRate',16384)

    ActualRate = get(AI,'SampleRate');

    Fs=ActualRate;

    set(AI,'SamplesPerTrigger',duration*ActualRate)

    preview = duration*ActualRate/100;

    subplot(211)

    set(gcf,'doublebuffer','on')

    P = plot(zeros(preview,1)); grid on

    title('Preview Data')

    xlabel('Samples')

    ylabel('Signal Level (Volts)')

    subplot(212)

    set(gcf,'doublebuffer','on')Pfft = plot(zeros(preview,1)); grid on

    title('FFT')

    xlabel('Frequency -Hz')

    ylabel('Amplitude')

    start(AI)

    while AI.SamplesAcquired < preview

    end

    while AI.SamplesAcquired < duration*ActualRate

    data = peekdata(AI,preview);

    set(P,'ydata',data)

    xfft=abs(fft(data,16384));

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    27/32

    xfft=xfft(1:4000);

    set(Pfft,'ydata',xfft)

    drawnow

    end

    %dt=1/8000;

    %t=(0:dt:(1/20-dt))';

    %subplot(313)

    %plot(diff(data)./diff(t));

    data=data(1:16384);

    save('music1.mat','data');

    delete(AI)

    clearAI

    A sample figure obtained by executing the script is given below.

    The figure contains both the preview of the incoming signal as well as its fft.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    28/32

    Program for Spectrogram-myspectrum.m

    load 'mydata.mat';

    %d=data;

    %len=length(data);d=data;

    cleardata;

    %%%%%%%%%%%%%%%%%%%%

    %find peaks and valleys

    %%%%%%%%%%%%%%%%%%%%%%%

    i=1;

    j=1;

    p=[];%location of peaks and valleys

    %q=[];%values of peaks and valleys

    %q(1)=d(1);

    p(1)=1;

    while(id(i))&&(d(i+1)>d(i+2))%find peaks

    p(j+1)=i+1;

    %q(j+1)=d(i+1);

    j=j+1;

    else

    if(d(i+1)

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    29/32

    end

    p(j+1)=16384;

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    len=max(diff(p));

    N=length(p);

    seg=zeros(len,N-1); % 2-D matrix of data segments

    forn=1:N-1

    r=p(n+1)-p(n);

    seg((1:r),n)=d(p(n):(p(n+1)-1));

    end

    fftdata=abs(fft(seg,16384));

    image(fftdata,'CDataMapping','scaled');

    set(gca,'YDir','normal')

    datacursormode on;

    title('Spectrogram');

    ylabel('Frequency-Hz');

    xlabel('Time -sec');

    The Signals and the outputs

    Ho-ho signal

    This is human voice captured using the program daqsession.m .The signal is not presented here.

    The FFT plot is given below.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    30/32

    The peaks represents the major frequency components present during the whole life time of the

    signal. The FFT is meaningless for such a non-periodic signal but spectrogram make sense as it

    gives an idea about the frequency distribution with respect to time.

    Ho spectrogram

    The spectrogram of the signal is obtained by executing the script

    myspectrum.m.

    The spectrogram gives details of the spectral distribution and the

    Frequency can be determined by placing the mouse cursor over the

    Figure. The frequency, magnitude and time point can be noted by

    placing the cursor at the desired point.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    31/32

    CONCLUSION

    Thus this project attempts to compute the FFT of an acquired signal and generate the

    corresponding spectrogram and its graphic representation.

  • 7/29/2019 Fft Computation and Generation of Spectrogram

    32/32

    REFERENCES

    1. MATLAB Online Manual2. www.math.mtu.edu3. www.maths.uq.edu.au4. www.ew.usna.edu5. MATLAB Helpdesk

    http://www.math.mtu.edu/http://www.maths.uq.edu.au/http://www.maths.uq.edu.au/http://www.math.mtu.edu/