MALLA REDDY INSTITUTE OF TECHNOLOGY & SCIENCE

Maisammaguda, Dulapally, Post via Hakimpet, Secunderabad – 500 014.

CONTENTS
1. To study the architecture of DSP chips – TMS 320C 5X/6X Instructions 2. To verify linear convolution (ALP using 6711 instructions). 3. To verify circular convolution.

4. To design FIR(low pass/high pass)using windowing Technique. A) Using rectangular window b) Using triangular window c) Using Kaiser window 5. 6. 7. 8. To design IIR filter (LP/HP). To find the FFT of given 1-d signal and plot To compute power density spectrum of a sequence Matlab program to generate sum of sinusoidal signals.

9. Matlab program to find frequency response of analog lp/hp filters. 10. Matlab program to generate fir filter (lp/hp) using rectangular windowing technique. 11. Matlab program to generate fir filter (lp/hp) using hamming windowing technique. 12. Matlab program to generate fir filter (lp/hp) using kaiser Windowing technique. 13. To find the fft of given 1-d signal and plot a. Mini project

Digital Signal Processing Lab

.

1. Architecture of DSP chips- TMS320C6713 DSK
1.1 Package Contents

The C6713 DSK builds on TI's industry-leading line of low cost, easy-to-use DSP Starter Kit (DSK) development boards. The high-performance board features the TMS320C6713 floating-point DSP. Capable of performing 1350 million floating-point operations per second (MFLOPS), the C6713 DSP makes the C6713 DSK the most powerful DSK development board. The DSK is USB port interfaced platform that allows efficiently developing and testing applications for the C6713. The DSK consists of a C6713-based printed circuit board that will serve as a hardware reference design for TI’s customers’ products. With extensive host PC and target DSP software support, including bundled TI tools, the DSK provides ease-of-use and capabilities that are attractive to DSP engineers.

Lab-Incharge

2

HOD

Digital Signal Processing Lab The following checklist details items that are shipped with the C6711 DSK kit.  TMS320C6713 DSK TMS320C6713 DSK development board  Other hardware External 5VDC power supply IEEE 1284 compliant male-to-female cable  CD-ROM Code Composer Studio DSK tools

The C6713 DSK has a TMS320C6713 DSP onboard that allows full-speed verification of code with Code Composer Studio. The C76713 DSK provides: • • • • • A USB Interface SDRAM and ROM An analog interface circuit for Data conversion (AIC) An I/O port Embedded JTAG emulation support

Connectors on the C6713 DSK provide DSP external memory interface (EMIF) and peripheral signals that enable its functionality to be expanded with custom or third party daughter boards. The DSK provides a C6713 hardware reference design that can assist you in the development of your own C6713-based products. In addition to providing a reference for interfacing the DSP to various types of memories and peripherals, the design also addresses power, clock, JTAG, and parallel peripheral interfaces. The C6711 DSK includes a stereo codec. This analog interface circuit (AIC) has the following characteristics: High-Performance Stereo Codec • 90-dB SNR Multibit Sigma-Delta ADC (A-weighted at 48 kHz) • 100-dB SNR Multibit Sigma-Delta DAC (A-weighted at 48 kHz) • 1.42 V – 3.6 V Core Digital Supply: Compatible With TI C54x DSP Core Voltages • 2.7 V – 3.6 V Buffer and Analog Supply: Compatible Both TI C54x DSP Buffer Voltages • 8-kHz – 96-kHz Sampling-Frequency Support Software Control Via TI McBSP-Compatible Multiprotocol Serial Port • I 2 C-Compatible and SPI-Compatible Serial-Port Protocols • Glueless Interface to TI McBSPs • Lab-Incharge 3 HOD

Digital Signal Processing Lab Audio-Data Input/Output Via TI McBSP-Compatible Programmable Audio Interface • I 2 S-Compatible Interface Requiring Only One McBSP for both ADC and DAC • Standard I 2 S, MSB, or LSB Justified-Data Transfers • 16/20/24/32-Bit Word Lengths

TMS320C6713 DSK Overview Block Diagram

1.2 The C6713DSK has the following features: The 6713 DSK is a low-cost standalone development platform that enables customers to evaluate and develop applications for the TI C67XX DSP family. The DSK also serves as a hardware reference design for the TMS320C6713 DSP. Schematics, logic equations and application notes are available to ease hardware development and reduce time to market. The DSK uses the 32-bit EMIF for the SDRAM (CE0) and daughtercard expansion interface (CE2 and CE3). The Flash is attached to CE1 of the EMIF in 8-bit mode. An on-board AIC23 codec allows the DSP to transmit and receive analog signals. McBSP0 is used for the codec control interface and McBSP1 is used for data. Analog Lab-Incharge 4 HOD

Digital Signal Processing Lab audio I/O is done through four 3.5mm audio jacks that correspond to microphone input, line input, line output and headphone output. The codec can select the microphone or the line input as the active input. The analog output is driven to both the line out (fixed gain) and headphone (adjustable gain) connectors. McBSP1 can be re-routed to the expansion connectors in software. A programmable logic device called a CPLD is used to implement glue logic that ties the board components together. The CPLD has a register based user interface that lets the user configure the board by reading and writing to the CPLD registers. The registers reside at the midpoint of CE1. The DSK includes 4 LEDs and 4 DIPswitches as a simple way to provide the user with interactive feedback. Both are accessed by reading and writing to the CPLD registers. An included 5V external power supply is used to power the board. On-board voltage regulators provide the 1.26V DSP core voltage, 3.3V digital and 3.3V analog voltages. A voltage supervisor monitors the internally generated voltage, and will hold the board in reset until the supplies are within operating specifications and the reset button is released. If desired, JP1 and JP2 can be used as power test points for the core and I/O power supplies. Code Composer communicates with the DSK through an embedded JTAG emulator with a USB host interface. The DSK can also be used with an external emulator through the external JTAG connector. 1.3 TMS320C6713 DSP Features Highest-Performance Floating-Point Digital Signal Processor (DSP):  Eight 32-Bit Instructions/Cycle  32/64-Bit Data Word  300-, 225-, 200-MHz (GDP), and 225-, 200-, 167-MHz (PYP) Clock Rates  3.3-, 4.4-, 5-, 6-Instruction Cycle Times  2400/1800, 1800/1350, 1600/1200, and 1336/1000 MIPS /MFLOPS  Rich Peripheral Set, Optimized for Audio  Highly Optimized C/C++ Compiler  Extended Temperature Devices Available  Advanced Very Long Instruction Word (VLIW) TMS320C67x™ DSP Core  Eight Independent Functional Units:  Two ALUs (Fixed-Point)  Four ALUs (Floating- and Fixed-Point)  Two Multipliers (Floating- and Fixed-Point)  Load-Store Architecture With 32 32-Bit General-Purpose Registers  Instruction Packing Reduces Code Size  All Instructions Conditional

Lab-Incharge

5

HOD

Digital Signal Processing Lab

  

Instruction Set Features  Native Instructions for IEEE 754  Single- and Double-Precision  Byte-Addressable (8-, 16-, 32-Bit Data)  8-Bit Overflow Protection  Saturation; Bit-Field Extract, Set, Clear; Bit-Counting; Normalization L1/L2 Memory Architecture  4K-Byte L1P Program Cache (Direct-Mapped)  4K-Byte L1D Data Cache (2-Way)  256K-Byte L2 Memory Total: 64K-Byte L2 Unified Cache/Mapped RAM, and 192K-Byte Additional L2 Mapped RAM Device Configuration  Boot Mode: HPI, 8-, 16-, 32-Bit ROM Boot  Endianness: Little Endian, Big Endian 32-Bit External Memory Interface (EMIF)  Glueless Interface to SRAM, EPROM, Flash, SBSRAM, and SDRAM  512M-Byte Total Addressable External Memory Space Enhanced Direct-Memory-Access (EDMA) Controller (16 Independent Channels) 16-Bit Host-Port Interface (HPI) Two Multichannel Audio Serial Ports (McASPs)  Two Independent Clock Zones Each (1 TX and 1 RX)  Eight Serial Data Pins Per Port: Individually Assignable to any of the Clock Zones  Each Clock Zone Includes:  Programmable Clock Generator  Programmable Frame Sync Generator  TDM Streams From 2-32 Time Slots  Support for Slot Size: 8, 12, 16, 20, 24, 28, 32 Bits  Data Formatter for Bit Manipulation  Wide Variety of I2S and Similar Bit Stream Formats

Integrated Digital Audio Interface Transmitter (DIT) Supports:  S/PDIF, IEC60958-1, AES-3, CP-430 Formats  Up to 16 transmit pins  Enhanced Channel Status/User Data  Extensive Error Checking and Recovery  Two Inter-Integrated Circuit Bus (I2C Bus™) Multi-Master and Slave Interfaces  Two Multichannel Buffered Serial Ports:  Serial-Peripheral-Interface (SPI)  High-Speed TDM Interface

Lab-Incharge

6

HOD

Digital Signal Processing Lab AC97 Interface Two 32-Bit General-Purpose Timers Dedicated GPIO Module With 16 pins (External Interrupt Capable) Flexible Phase-Locked-Loop (PLL) Based Clock Generator Module  IEEE-1149.1 (JTAG ) Boundary-Scan-Compatible  Package Options:  208-Pin PowerPAD™ Plastic (Low-Profile) Quad Flatpack (PYP)  272-BGA Packages (GDP and ZDP)  0.13-µm/6-Level Copper Metal Process  CMOS Technology
     

3.3-V I/Os, 1.2 -V Internal (GDP & PYP) 3.3-V I/Os, 1.4-V Internal (GDP)(300 MHz only)

1.4 INSTALLATION SYSTEM REQUIREMENTS Minimum 233MHz or Higher PentiumCompatible CPU 600MB of free hard disk space 128MB of RAM SVGA (800 x 600 ) display Internet Explorer (4.0 or later) or Netscape Navigator (4.7 or later) Local CD-ROM drive • • • • • Recommended 500MHz or Higher Pentium – Compatible CPU 128MB RAM 16bit Color

• • • • • • •

• • •

Supported Operating Systems Windows® 98 Windows NT® 4.0 Service Pack 4 or higher Windows® 2000 Service Pack 1 Windows® Me Windows® XP

Lab-Incharge

7

HOD

Digital Signal Processing Lab 1.4.1 DSK HARDWARE INSTALLATION

• • •

Shut down and power off the PC Connect the supplied USB port cable to the board Connect the other end of the cable to the USB port of PC Note: If you plan to install a Microphone, speaker, or Signal generator/CRO these must be plugged in properly before you connect power to the DSK

• • • • •

Plug the power cable into the board Plug the other end of the power cable into a power outlet The user LEDs should flash several times to indicate board is operational When you connect your DSK through USB for the first time on a Windows loaded PC the new hardware found wizard will come up. So, Install the drivers (The CCS CD contains the require drivers for C5416 DSK). Install the CCS software for C5416 DSK.

Troubleshooting DSK Connectivity If Code Composer Studio IDE fails to configure your port correctly, perform the following steps: • Test the USB port by running DSK Port test from the start menu

Use StartProgramsTexas InstrumentsCode Composer StudioCode Composer Studio C5416 DSK ToolsC5416 DSK Diagnostic Utilities • • • • • • The below Screen will appear Select StartSelect 6713 DSK Diagnostic Utility Icon from Desktop The Screen Look like as below Select Start Option Utility Program will test the board After testing Diagnostic Status you will get PASS

Lab-Incharge

8

HOD

Digital Signal Processing Lab

If the board still fails to detect Go to CMOS setup Enable the USB Port Option (The required Device drivers will load along with CCS Installation) 1.4.2 SOFTWARE INSTALLATION You must install the hardware before you install the software on your system. The requirements for the operating platform are; • Insert the installation CD into the CD-ROM drive An install screen appears; if not, goes to the windows Explorer and run setup.exe • Choose the option to install Code Composer Sutido If you already have C6000 CC Studio IDE installed on your PC, do not install DSK software. CC Studio IDE full tools supports the DSK platform Lab-Incharge 9 HOD

Digital Signal Processing Lab

Respond to the dialog boxes as the installation program runs. The Installation program automatically configures CC Studio IDE for operation with your DSK and creates a CCStudio IDE DSK icon on your desktop. To install, follow these instructions: 1.5 INTRODUCTION TO CODE COMPOSER STUDIO Code Composer is the DSP industry's first fully integrated development environment (IDE) with DSP-specific functionality. With a familiar environment liked MS-based C+ +TM, Code Composer lets you edit, build, debug, profile and manage projects from a single unified environment. Other unique features include graphical signal analysis, injection/extraction of data signals via file I/O, multi-processor debugging, automated testing and customization via a C-interpretive scripting language and much more. CODE COMPOSER FEATURES INCLUDE: • • • • • • • • • • • • Note : Documents for Reference: spru509  Code Composer Studio getting started guide. spru189  TMS320C6000 CPU & Instruction set guide spru190  TMS320C6000 Peripherals guide slws106d  codec(TLV320AIC23) Data Manual. spru402  Programmer’s Reference Guide. sprs186j  TMS320C6713 DSP Soft Copy of Documents are available at : c:\ti\docs\pdf. Lab-Incharge 10 HOD IDE Debug IDE Advanced watch windows Integrated editor File I/O, Probe Points, and graphical algorithm scope probes Advanced graphical signal analysis Interactive profiling Automated testing and customization via scripting Visual project management system Compile in the background while editing and debugging Multi-processor debugging Help on the target DSP

Digital Signal Processing Lab

Procedure to work on Code Composer Studio
To create the New Project Project  New (File Name. pjt , Eg: Vectors.pjt) To Create a Source file File  New  Type the code (Save & give file name, Eg: sum.c). To Add Source files to Project Project  Add files to Project  sum.c To Add rts.lib file & Hello.cmd: Project  Add files to Project rts6700.lib Library files: rts6700.lib(Path: c:\ti\c6000\cgtools\lib\rts6700.lib) Note: Select Object & Library in(*.o,*.l) in Type of files Project  Add files to Project hello.cmd CMD file – Which is common for all non real time programs. (Path: c:\ti\tutorial\dsk6713\hello1\hello.cmd) Note: Select Linker Command file(*.cmd) in Type of files Compile: To Compile: Project  Compile To Rebuild: Project  rebuild, which will create the final .out executable file.(Eg. Vectors.out). Procedure to Load and Run program: Load the program to DSK: File  Load program  Vectors. out To Execute project: Debug  Run.

Lab-Incharge

11

HOD

Digital Signal Processing Lab

sum.c
# include<stdio.h> main() { int i=0; i++; printf("%d",i); } To Perform Single Step Debugging: 1. Keep the cursor on the on to the line from where u want to start single step debugging.(eg: set a break point on to first line int i=0; of your project.) To set break point select icon from tool bar menu.

2. Load the Vectors. out file onto the target. 3. Go to view and select Watch window. 4. Debug  Run. 5. Execution should halt at break point. 6. Now press F10. See the changes happening in the watch window. 7. Similarly go to view & select CPU registers to view the changes happening in CPU registers. 8. Repeat steps 2 to 6.

Lab-Incharge

12

HOD

Digital Signal Processing Lab

2. LINEAR CONVOLUTION
Aim: To verify the linear convolution using DSK6713 processor Software: CCStudio Theory:

‘C’ PROGRAM TO IMPLEMENT LINEAR CONVOLUTION
#include<stdio.h> main() { int m=4; /*Lenght of i/p samples sequence*/ int n=4; /*Lenght of impulse response Co-efficients */ int i=0,j; int x[10]={1,2,3,4,0,0,0,0}; /*Input Signal Samples*/ int h[10]={1,2,3,4,0,0,0,0}; /*Impulse Response Co-efficients*/

/*At the end of input sequences pad ‘M’ and ‘N’ no. of zero’s*/
int y[10]; for(i=0;i<m+n-1;i++) { y[i]=0; for(j=0;j<=i;j++) y[i]+=x[j]*h[i-j]; } for(i=0;i<m+n-1;i++) printf("%d\n",y[i]); }

Note: 1. To execute the above program follow “ procedure to work on code composer studio” 2. To view graphical output follow the below procedure. PROCEDURE:  Open Code Composer Studio, make sure the DSP kit is turned on.  Start a new project using ‘Project-new ‘ pull down menu, save it in a separate directory(c:\ti\myprojects) with name lconv.pjt.  Add the source files conv.asm  to the project using ‘Projectadd files to project’ pull down menu. Lab-Incharge 13 HOD

Digital Signal Processing Lab  Add the linker command file hello.cmd . (Path: c:\ti\tutorial\dsk6713\hello1\hello.cmd)  Add the run time support library file rts6700.lib (Path: c:\ti\c6000\cgtools\lib\rts6700.lib)  Compile the program using the ‘Project-compile’ pull down menu or by clicking the shortcut icon on the left side of program window.  Build the program using the ‘Project-Build’ pull down menu or by clicking the shortcut icon on the left side of program window.  Load the program(lconv.out) in program memory of DSP chip using the ‘File-load program’ pull down menu.  To View output graphically Select view  graph  time and frequency. Configure the graphical window as shown below INPUT x[n] = h[k] = OUTPUT: y[i] =

3

Lab-Incharge

14

HOD

Digital Signal Processing Lab

3. Circular Convolution
Aim: To verify the Circular Convolution using DSK6713 Processor. Software: CCStudio. Theory: Steps for Cyclic Convolution Steps for cyclic convolution are the same as the usual convolution, except all index calculations are done "mod N" = "on the wheel" Steps for Cyclic Convolution Step1: “Plot f[m] and h[−m]

Subfigure 1.1 Subfigure 1.2 Step 2: "Spin" h[−m] n times Anti Clock Wise (counter-clockwise) to get h[n-m] (i.e. Simply rotate the sequence, h[n], clockwise by n steps)

Figure 2: Step 2 Step 3: Pointwise multiply the f[m] wheel and the h[n−m] wheel. sum=y[n] Step 4: Repeat for all 0≤n≤N−1

Example 1: Convolve (n = 4)

Lab-Incharge

15

HOD

Digital Signal Processing Lab

Subfigure 3.1 Subfigure 3.2 Figure 3: Two discrete-time signals to be convolved.

h[−m] =

Figure 4 Multiply f[m] and sum to yield: y[0] =3

h[1−m]

Figure 5 Multiply f[m] and sum to yield: y[1] =5

h[2−m]

Figure 6 Multiply f[m] and sum to yield: y[2] =3

h[3−m]

Lab-Incharge

16

HOD

Digital Signal Processing Lab

Figure 7 Multiply f[m] and sum to yield: y[3] =1 Program to Implement Circular Convolution
#include<stdio.h> int m,n,x[30],h[30],y[30],i,j,temp[30],k,x2[30],a[30]; void main() { printf(" enter the length of the first sequence\n"); scanf("%d",&m); printf(" enter the length of the second sequence\n"); scanf("%d",&n); printf(" enter the first sequence\n"); for(i=0;i<m;i++) scanf("%d",&x[i]); printf(" enter the second sequence\n"); for(j=0;j<n;j++) scanf("%d",&h[j]); if(m-n!=0) { if(m>n) { for(i=n;i<m;i++) h[i]=0; /* Pad the smaller sequence with zero*/ /*If length of both sequences are not equal*/

Lab-Incharge

17

HOD

Digital Signal Processing Lab
n=m; } for(i=m;i<n;i++) x[i]=0; m=n; } y[0]=0; a[0]=h[0]; for(j=1;j<n;j++) a[j]=h[n-j]; /*Circular convolution*/ for(i=0;i<n;i++) y[0]+=x[i]*a[i]; for(k=1;k<n;k++) { y[k]=0; /*circular shift*/ for(j=1;j<n;j++) x2[j]=a[j-1]; x2[0]=a[n-1]; for(i=0;i<n;i++) { a[i]=x2[i]; y[k]+=x[i]*x2[i]; } /*folding h(n) to h(-n)*/

Lab-Incharge

18

HOD

Digital Signal Processing Lab
} /*displaying the result*/ printf(" the circular convolution is\n"); for(i=0;i<n;i++) printf("%d \t",y[i]);

} IN PUT: Eg: OUT PUT x[4]={3, 2, 1,0} h[4]={1, 1, 0,0} y[4]={3, 5, 3,0}

PROCEDURE:  Open Code Composer Studio, make sure the DSP kit is turned on.  Start a new project using ‘Project-new ‘ pull down menu, save it in a separate directory(c:\ti\myprojects) with name cir conv.pjt.  Add the source files Circular Convolution.C  to the project using ‘Projectadd files to project’ pull down menu.  Add the linker command file hello.cmd . (Path: c:\ti\tutorial\dsk6713\hello1\hello.cmd)  Add the run time support library file rts6700.lib (Path: c:\ti\c6000\cgtools\lib\rts6700.lib)  Compile the program using the ‘Project-compile’ pull down menu or by clicking the shortcut icon on the left side of program window.  Build the program using the ‘Project-Build’ pull down menu or by clicking the shortcut icon on the left side of program window.  Load the program(lconv.out) in program memory of DSP chip using the ‘File-load program’ pull down menu.

Lab-Incharge

19

HOD

Digital Signal Processing Lab

TMS320C6713 DSK CODEC (TLV320AIC23) Configuration Using Board Support Library
1.0 Unit Objective: To configure the codec TLV320AIC23 for a talk through program using the board support library. 2.0 Prerequisites TMS320C6713 DSP Starter Kit, PC with Code Composer Studio, CRO, Audio Source, Speakers and Signal Generator. 3.0 Discussion on Fundamentals: Refer BSL API Module under, help  contents  TMS320C6713 DSK. 4.0 Procedure • All the Real time implementations covered in the Implementations module follow code Configuration using board support library. • The board Support Library (CSL) is a collection of functions, macros, and symbols used to configure and control on-chip peripherals. • The goal is peripheral ease of use, shortened development time, portability, hardware abstraction, and some level of standardization and compatibility among TI devices. • BSL is a fully scalable component of DSP/BIOS. It does not require the use of other DSP/BIOS components to operate. Source Code: codec.c Steps: 1. Connect CRO to the Socket Provided for LINE OUT. 2. Connect a Signal Generator to the LINE IN Socket. 3. Switch on the Signal Generator with a sine wave of frequency 500 Hz. 4. Now Switch on the DSK and Bring Up Code Composer Studio on the PC. 5. Create a new project with name XXXX.pjt. 6. From the File Menu  new  DSP/BIOS Configuration select “dsk6713.cdb” and save it as “YYYY.cdb” and add it to the current project. 7. Add the generated “YYYYcfg.cmd” file to the current project. 8. Add the given “codec.c” file to the current project which has the main function and calls all the other necessary routines. 9. View the contents of the generated file “YYYYcfg_c.c” and copy the include header file ‘YYYYcfg.h’ to the “codec.c” file. 10. Add the library file “dsk6713bsl.lib” from the location “C:\ti\C5400\dsk6713\lib\dsk6713bsl.lib” to the current project Lab-Incharge 20 HOD

Digital Signal Processing Lab 11. Build, Load and Run the program. 12. You can notice the input signal of 500 Hz. appearing on the CRO verifying the codec configuration. 13. You can also pass an audio input and hear the output signal through the speakers. 14. You can also vary the sampling frequency using the DSK6713_AIC23_setFreq Function in the “codec.c” file and repeat the above steps. 5.0 Conclusion: The codec TLV320AIC23 successfully configured using the board support library and verified.

Lab-Incharge

21

HOD

Digital Signal Processing Lab

codec.c
#include "filtercfg.h" #include "dsk6713.h" #include "dsk6713_aic23.h" /* Codec configuration settings */ DSK6713_AIC23_Config config = { \ 0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Left line input channel volume */ \ 0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume */\ 0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */ \ 0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */ \ 0x0011, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */ \ 0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */ \ 0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */ \ 0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */ \ 0x0081, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */ \ 0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \ }; /* main() - Main code routine, initializes BSL and generates tone */ void main() { DSK6713_AIC23_CodecHandle hCodec; int l_input, r_input,l_output, r_output; /* Initialize the board support library, must be called first */ DSK6713_init(); /* Start the codec */ hCodec = DSK6713_AIC23_openCodec(0, &config); /*set codec sampling frequency*/ DSK6713_AIC23_setFreq(hCodec, 3); while(1) { /* Read a sample to the left channel */ while (!DSK6713_AIC23_read(hCodec, &l_input)); /* Read a sample to the right channel */ while (!DSK6713_AIC23_read(hCodec, &r_input)); /* Send a sample to the left channel */ while (!DSK6713_AIC23_write(hCodec, l_input)); /* Send a sample to the right channel */ while (!DSK6713_AIC23_write(hCodec, l_input)); } /* Close the codec */ DSK6713_AIC23_closeCodec(hCodec); }

Lab-Incharge

22

HOD

Digital Signal Processing Lab

4. Finite Impulse Response (FIR) Filter Implementation
Aim: To design FIR filter (LP/HP) using windowing technique and verify using the DSP processor Using rectangular window Using triangular window Using Kaiser Window Software: 1.CCStudio 2. Matlab2008a version Components required: 1.CRO 2. Function generator Theory: DESIGNING AN FIR FILTER: Following are the steps to design linear phase FIR filters Using Windowing Method. I. Clearly specify the filter specifications. Eg: Order = 30; Sampling Rate = 8000 samples/sec Cut off Freq. = 400 Hz. Compute the cut-off frequency Wc Eg: Wc = 2*pie* fc / Fs = 2*pie* 400/8000 = 0.1*pie Compute the desired Impulse Response h d (n) using particular Window Eg: b_rect1=fir1(order, Wc , 'high',boxcar(31)); Convolve input sequence with truncated Impulse Response x (n)*h (n)

II.

III. IV.

USING MATLAB TO DETERMINE FILTER COEFFICIENTS: Using FIR1 Function on Matlab B = FIR1(N,Wn) designs an N'th order lowpass FIR digital filter and returns the filter coefficients in length N+1 vector B. The cut-off frequency Wn must be between 0 < Wn < 1.0, with 1.0 corresponding to half the sample rate. The filter B is real and Lab-Incharge 23 HOD

Digital Signal Processing Lab has linear phase, i.e., even symmetric coefficients obeying B(k) = B(N+2-k), k = 1,2,...,N+1. If Wn is a two-element vector, Wn = [W1 W2], FIR1 returns an order N bandpass filter with passband W1 < W < W2. B = FIR1(N,Wn,'high') designs a highpass filter. B = FIR1(N,Wn,'stop') is a bandstop filter if Wn = [W1 W2]. If Wn is a multi-element vector, Wn = [W1 W2 W3 W4 W5 ... WN], FIR1 returns an order N multiband filter with bands 0 < W < W1, W1 < W < W2, ..., WN < W < 1. B = FIR1(N,Wn,'DC-1') makes the first band a passband. B = FIR1(N,Wn,'DC-0') makes the first band a stopband. For filters with a passband near Fs/2, e.g., highpass and bandstop filters, N must be even. By default FIR1 uses a Hamming window. Other available windows, including Boxcar, Hanning, Bartlett, Blackman, Kaiser and Chebwin can be specified with an optional trailing argument. For example, B = FIR1(N,Wn,kaiser(N+1,4)) uses a Kaiser window with beta=4. B = FIR1(N,Wn,'high',chebwin(N+1,R)) uses a Chebyshev window. By default, the filter is scaled so the center of the first pass band has magnitude exactly one after windowing. Use a trailing 'noscale' argument to prevent this scaling, e.g. B = FIR1(N,Wn,'noscale'), B = FIR1(N,Wn,'high','noscale'), B = FIR1(N,Wn,wind,'noscale'). Matlab Program to generate ‘FIR Filter-Low Pass’ Coefficients using FIR1
% FIR Low pass filters using rectangular, triangular and kaiser windows % sampling rate - 8000 order = 30; cf=[500/4000,1000/4000,1500/4000]; cf--> contains set of cut-off frequencies[Wc ]

% cutoff frequency - 500 b_rect1=fir1(order,cf(1),boxcar(31)); Rectangular b_tri1=fir1(order,cf(1),bartlett(31)); Triangular b_kai1=fir1(order,cf(1),kaiser(31,8)); Kaisar [Where 8-->Beta Co-efficient] % cutoff frequency - 1000 b_rect2=fir1(order,cf(2),boxcar(31)); b_tri2=fir1(order,cf(2),bartlett(31)); b_kai2=fir1(order,cf(2),kaiser(31,8)); % cutoff frequency - 1500

Lab-Incharge

24

HOD

Digital Signal Processing Lab
b_rect3=fir1(order,cf(3),boxcar(31)); b_tri3=fir1(order,cf(3),bartlett(31)); b_kai3=fir1(order,cf(3),kaiser(31,8)); fid=fopen('FIR_lowpass_rectangular.txt','wt'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -400Hz'); fprintf(fid,'\nfloat b_rect1[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect1); fseek(fid,-1,0); fprintf(fid,'};'); fprintf(fid,'\n\n\n\n'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -800Hz'); fprintf(fid,'\nfloat b_rect2[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect2); fseek(fid,-1,0); fprintf(fid,'};'); fprintf(fid,'\n\n\n\n'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -1200Hz'); fprintf(fid,'\nfloat b_rect3[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect3); fseek(fid,-1,0); fprintf(fid,'};'); fclose(fid); winopen('FIR_highpass_rectangular.txt');

T.1 : Matlab generated Coefficients for FIR Low Pass Kaiser filter:
Cutoff -500Hz float b_kai1[31]={-0.000019,-0.000170,-0.000609,-0.001451,-0.002593,-0.003511,0.003150,0.000000,0.007551,0.020655,0.039383,0.062306,0.086494,0.108031,0.122944, 0.128279,0.122944,0.108031,0.086494,0.062306,0.039383,0.020655,0.007551,0.000000, -0.003150,-0.003511,-0.002593,-0.001451,-0.000609,-0.000170,-0.000019}; Cutoff -1000Hz float b_kai2[31]={-0.000035,-0.000234,-0.000454,0.000000,0.001933,0.004838,0.005671, -0.000000,-0.013596,-0.028462,-0.029370,0.000000,0.064504,0.148863,0.221349,0.249983, IMPLEMENTATION OF AN FIR FILTER : 0.221349,0.148863,0.064504,0.000000,-0.029370,-0.028462,-0.013596,-0.000000,0.005671, 0.004838,0.001933,0.000000,-0.000454,-0.000234, -0.000035}; ALGORITHM TO IMPLEMENT : Cutoff to realize We need -1500Hz an advance FIR filter by implementing its difference equation as per float b_kai3[31]={-0.000046,-0.000166,0.000246,0.001414,0.001046,-0.003421,-0.007410, the specifications. A direct form I implementation approach is taken. (The filter 0.000000,0.017764,0.020126,-0.015895,-0.060710,-0.034909,0.105263,0.289209,0.374978, coefficients are taken as ai as generated by the Matlab program.) 0.289209,0.105263,-0.034909,-0.060710,-0.015895,0.020126,0.017764,0.000000,-0.007410, -0.003421,0.001046,0.001414,0.000246,-0.000166, -0.000046}; Lab-Incharge HOD 25

Digital Signal Processing Lab

T.2 :Matlab generated Coefficients for FIR Low Pass Rectangular filter
Cutoff -500Hz float b_rect1[31]={-0.008982,-0.017782,-0.025020,-0.029339,-0.029569,-0.024895, -0.014970,0.000000,0.019247,0.041491,0.065053,0.088016,0.108421,0.124473,0.134729, 0.138255,0.134729,0.124473,0.108421,0.088016,0.065053,0.041491,0.019247,0.000000, -0.014970,-0.024895,-0.029569,-0.029339,-0.025020,-0.017782,-0.008982}; Cutoff -1000Hz float b_rect2[31]={-0.015752,-0.023869,-0.018176,0.000000,0.021481,0.033416,0.026254,0.000000,-0.033755,-0.055693,-0.047257,0.000000,0.078762,0.167080,0.236286,0.262448, 0.236286,0.167080,0.078762,0.000000,-0.047257,-0.055693,-0.033755,-0.000000,0.026254, 0.033416,0.021481,0.000000,-0.018176,-0.023869,-0.015752}; Cutoff -1500Hz float b_rect2[31]={-0.020203,-0.016567,0.009656,0.027335,0.011411,-0.023194,-0.033672, 0.000000,0.043293,0.038657,-0.025105,-0.082004,-0.041842,0.115971,0.303048,0.386435, 0.303048,0.115971,-0.041842,-0.082004,-0.025105,0.038657,0.043293,0.000000,-0.033672, -0.023194,0.011411,0.027335,0.009656,-0.016567,-0.020203}; FLOWCHART FOR FIR :

T.3 : Matlab generated Coefficients for FIR Low Pass Triangular filter
Cutoff -500Hz float b_tri1[31]={0.000000,-0.001185,-0.003336,-0.005868,-0.007885,-0.008298,-0.005988, 0.000000,0.010265,0.024895,0.043368,0.064545,0.086737,0.107877,0.125747,0.138255, 0.125747,0.107877,0.086737,0.064545,0.043368,0.024895,0.010265,0.000000,-0.005988, -0.008298,-0.007885,-0.005868,-0.003336,-0.001185,0.000000}; Cutoff -1000Hz float b_tri2[31]={0.000000,-0.001591,-0.002423,0.000000,0.005728,0.011139,0.010502, -0.000000,-0.018003,-0.033416,-0.031505,0.000000,0.063010,0.144802,0.220534,0.262448, 0.220534,0.144802,0.063010,0.000000,-0.031505,-0.033416,-0.018003,-0.000000,0.010502, 0.011139,0.005728,0.000000,-0.002423,-0.001591,0.000000}; Cutoff -1500Hz float b_tri3[31]={0.000000,-0.001104,0.001287,0.005467,0.003043,-0.007731,-0.013469, 0.000000,0.023089,0.023194,-0.016737,-0.060136,-0.033474,0.100508,0.282844,0.386435, 0.282844,0.100508,-0.033474,-0.060136,-0.016737,0.023194,0.023089,0.000000,-0.013469, -0.007731,0.003043,0.005467,0.001287,-0.001104,0.000000};

Lab-Incharge

26

HOD

Digital Signal Processing Lab MATLAB Program to generate ‘FIR Filter-High Pass’ Coefficients using FIR1
% FIR High pass filters using rectangular, triangular and kaiser windows % sampling rate - 8000 order = 30; cf=[400/4000,800/4000,1200/4000]; frequencies[Wc] ;cf--> contains set of cut-off

% cutoff frequency - 400 b_rect1=fir1(order,cf(1),'high',boxcar(31)); b_tri1=fir1(order,cf(1),'high',bartlett(31)); b_kai1=fir1(order,cf(1),'high',kaiser(31,8)); Where Kaiser(31,8)--> '8'defines the value of 'beta'. % cutoff frequency - 800 b_rect2=fir1(order,cf(2),'high',boxcar(31)); b_tri2=fir1(order,cf(2),'high',bartlett(31)); b_kai2=fir1(order,cf(2),'high',kaiser(31,8)); % cutoff frequency - 1200 b_rect3=fir1(order,cf(3),'high',boxcar(31)); b_tri3=fir1(order,cf(3),'high',bartlett(31)); b_kai3=fir1(order,cf(3),'high',kaiser(31,8)); fid=fopen('FIR_highpass_rectangular.txt','wt'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -400Hz'); fprintf(fid,'\nfloat b_rect1[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect1); fseek(fid,-1,0); fprintf(fid,'};'); fprintf(fid,'\n\n\n\n'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -800Hz'); fprintf(fid,'\nfloat b_rect2[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect2); fseek(fid,-1,0); fprintf(fid,'};'); fprintf(fid,'\n\n\n\n'); fprintf(fid,'\t\t\t\t\t\t%s\n','Cutoff -1200Hz'); fprintf(fid,'\nfloat b_rect3[31]={'); fprintf(fid,'%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,\n',b_rect3); fseek(fid,-1,0); fprintf(fid,'};'); fclose(fid); winopen('FIR_highpass_rectangular.txt');

Lab-Incharge

27

HOD

Digital Signal Processing Lab

T.1: MATLAB generated Coefficients for FIR High Pass Kaiser filter:
Cutoff -400Hz float b_kai1[31]={0.000050,0.000223,0.000520,0.000831,0.000845,-0.000000,-0.002478, -0.007437,-0.015556,-0.027071,-0.041538,-0.057742,-0.073805,-0.087505,-0.096739, 0.899998,-0.096739,-0.087505,-0.073805,-0.057742,-0.041538,-0.027071,-0.015556, -0.007437,-0.002478,-0.000000,0.000845,0.000831,0.000520,0.000223,0.000050}; Cutoff -800Hz float b_kai2[31]={0.000000,-0.000138,-0.000611,-0.001345,-0.001607,-0.000000,0.004714, 0.012033,0.018287,0.016731,0.000000,-0.035687,-0.086763,-0.141588,-0.184011,0.800005, IMPLEMENTATION OF AN FIR FILTER : -0.184011,-0.141588,-0.086763,-0.035687,0.000000,0.016731,0.018287,0.012033,0.004714, -0.000000,-0.001607,-0.001345,-0.000611,-0.000138,0.000000}; ALGORITHM TO IMPLEMENT : Cutoff -1200Hz We need to realize an advance FIR filter by implementing its difference equation as per float b_kai3[31]={-0.000050,-0.000138,0.000198,0.001345,0.002212,-0.000000,-0.006489, the specifications. A direct form I implementation approach is taken. (The filter -0.012033,-0.005942,0.016731,0.041539,0.035687,-0.028191,-0.141589,-0.253270,0.700008, coefficients are taken as ai as generated by the Matlab program.) -0.253270,-0.141589,-0.028191,0.035687,0.041539,0.016731,-0.005942,-0.012033,-0.006489, -0.000000,0.002212,0.001345,0.000198,-0.000138,-0.000050}; • •

T.2 :MATLAB generated Coefficients for FIR High Pass Rectangular filter
Cutoff -400Hz float b_rect1[31]={0.021665,0.022076,0.020224,0.015918,0.009129,-0.000000,-0.011158, -0.023877,-0.037558,-0.051511,-0.064994,-0.077266,-0.087636,-0.095507,-.100422,0.918834, -0.100422,-0.095507,-0.087636,-0.077266,-0.064994,-0.051511,-0.037558,-0.023877, -0.011158,-0.000000,0.009129,0.015918,0.020224,0.022076,0.021665}; Cutoff -800Hz float b_rect2[31]={0.000000,-0.013457,-0.023448,-0.025402,-0.017127,-0.000000,0.020933, 0.038103,0.043547,0.031399,0.000000,-0.047098,-0.101609,-0.152414,-0.188394,0.805541, -0.188394,-0.152414,-0.101609,-0.047098,0.000000,0.031399,0.043547,0.038103,0.020933, -0.000000,-0.017127,-0.025402,-0.023448,-0.013457,0.000000}; Cutoff -1200Hz float b_rect3[31]={-0.020798,-0.013098,0.007416,0.024725,0.022944,-0.000000,-0.028043, -0.037087,-0.013772,0.030562,0.062393,0.045842,-0.032134,-0.148349,-0.252386,0.686050, -0.252386,-0.148349,-0.032134,0.045842,0.062393,0.030562,-0.013772,-0.037087,-0.028043, -0.000000,0.022944,0.024725,0.007416,-0.013098,-0.020798}; Lab-Incharge 28 HOD

Digital Signal Processing Lab

T.3 : MATLAB generated Coefficients for FIR High Pass Triangular filter
Cutoff -400Hz float b_tri1[31]={0.000000,0.001445,0.002648,0.003127,0.002391,-0.000000,-0.004383, -0.010943,-0.019672,-0.030353,-0.042554,-0.055647,-0.068853,-0.081290,-0.092048, 0.902380,-0.092048,-0.081290,-0.068853,-0.055647,-0.042554,-0.030353,-0.019672, -0.010943,-0.004383,-0.000000,0.002391,0.003127,0.002648,0.001445,0.000000}; Cutoff -800Hz float b_tri2[31]={0.000000,-0.000897,-0.003126,-0.005080,-0.004567,-0.000000,0.008373, 0.017782,0.023225,0.018839,0.000000,-0.034539,-0.081287,-0.132092,-0.175834,0.805541, -0.175834,-0.132092,-0.081287,-0.034539,0.000000,0.018839,0.023225,0.017782,0.008373, -0.000000,-0.004567,-0.005080,-0.003126,-0.000897,0.000000}; Cutoff -1200Hz float b_tri3[31]={0.000000,-0.000901,0.001021,0.005105,0.006317,-0.000000,-0.011581, -0.017868,-0.007583,0.018931,0.042944,0.034707,-0.026541,-0.132736,-0.243196,0.708287, -0.243196,-0.132736,-0.026541,0.034707,0.042944,0.018931,-0.007583,-0.017868,-0.011581, -0.000000,0.006317,0.005105,0.001021,-0.000901,0.000000};

Lab-Incharge

29

HOD

Digital Signal Processing Lab

FLOW CHART TO IMPLEMENT FIR FILTER:

Start Start Start
Initialize the DSP Board.

Take a new input in ‘data’ from the analog in of codec in ‘data’

Initialize Counter = 0 Initialize Output = 0 , i = 0 Output += coeff[Ni]*val[i] Shift the input value by one

No

Is the loop Cnt = order Yes Output += coeff[0]*data Put the ‘data’ in ‘val’ array.

Poll the ready bit, when asserted proceed.

Write the value ‘Output’ to Analog output of the codec Lab-Incharge 30 HOD

Digital Signal Processing Lab

C PROGRAM TO IMPLEMENT FIR FILTER:

fir.c
#include "filtercfg.h" #include "dsk6713.h" #include "dsk6713_aic23.h" float filter_Coeff[] ={0.000000,-0.001591,-0.002423,0.000000,0.005728, 0.011139,0.010502,-0.000000,-0.018003,-0.033416,-0.031505,0.000000, 0.063010,0.144802,0.220534,0.262448,0.220534,0.144802,0.063010,0.000000, -0.031505,-0.033416,-0.018003,-0.000000,0.010502,0.011139,0.005728, 0.000000,-0.002423,-0.001591,0.000000 }; static short in_buffer[100]; DSK6713_AIC23_Config config = {\ 0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Leftline input channel volume */\ 0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume*/\ 0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */\ 0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */\ 0x0011, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */\ 0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */\ 0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */\ 0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */\ 0x0081, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */\ 0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \ }; /* * main() - Main code routine, initializes BSL and generates tone */ void main() { DSK6713_AIC23_CodecHandle hCodec; Uint32 l_input, r_input,l_output, r_output; /* Initialize the board support library, must be called first */ DSK6713_init(); /* Start the codec */ hCodec = DSK6713_AIC23_openCodec(0, &config); DSK6713_AIC23_setFreq(hCodec, 1); while(1) { /* Read a sample to the left channel */ while (!DSK6713_AIC23_read(hCodec, &l_input)); /* Read a sample to the right channel */ while (!DSK6713_AIC23_read(hCodec, &r_input));

Lab-Incharge

31

HOD

Digital Signal Processing Lab

l_output=(Int16)FIR_FILTER(&filter_Coeff ,l_input); r_output=l_output; /* Send a sample to the left channel */ while (!DSK6713_AIC23_write(hCodec, l_output)); /* Send a sample to the right channel */ while (!DSK6713_AIC23_write(hCodec, r_output)); } /* Close the codec */ DSK6713_AIC23_closeCodec(hCodec); } signed int FIR_FILTER(float * h, signed int x) { int i=0; signed long output=0; in_buffer[0] = x; /* new input at buffer[0] */ for(i=30;i>0;i--) in_buffer[i] = in_buffer[i-1]; /* shuffle the buffer */ for(i=0;i<32;i++) output = output + h[i] * in_buffer[i]; return(output); }

PROCEDURE :
#include "dsk6713.h" #include "dsk6713_aic23.h" /* Codec configuration settings */ DSK6713_AIC23_Config config = { \ 0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Left line input channel volume */ \ 0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume */\ 0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */ \ 0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */ \ 0x0011, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */ \ 0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */ \ 0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */ \ 0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */ \ 0x0081, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */ \ 0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \ }; /* main() - Main code routine, initializes BSL and generates tone */ void main() { DSK6713_AIC23_CodecHandle hCodec;

Lab-Incharge

32

HOD

Digital Signal Processing Lab
int l_input, r_input,l_output, r_output; /* Initialize the board support library, must be called first */ DSK6713_init(); /* Start the codec */ hCodec = DSK6713_AIC23_openCodec(0, &config); /*set codec sampling frequency*/ DSK6713_AIC23_setFreq(hCodec, 3); while(1) { /* Read a sample to the left channel */ while (!DSK6713_AIC23_read(hCodec, &l_input)); /* Read a sample to the right channel */ while (!DSK6713_AIC23_read(hCodec, &r_input)); /* Send a sample to the left channel */ while (!DSK6713_AIC23_write(hCodec, l_input)); /* Send a sample to the right channel */ while (!DSK6713_AIC23_write(hCodec, l_input)); } /* Close the codec */ DSK6713_AIC23_closeCodec(hCodec); }

 Switch on the DSP board.  Open the Code Composer Studio.  Create a new project Project  New (File Name. pjt , Eg: FIR.pjt)  Initialize on board codec. “Kindly refer the Topic Configuration of 6713 Codec using BSL”  Add the given above ‘C’ source file to the current project (remove codec.c source file from the project if you have already added).  Connect the speaker jack to the input of the CRO.  Build the program.  Load the generated object file(*.out) on to Target board.  Run the program using F5.  Observe the waveform that appears on the CRO screen.

Lab-Incharge

33

HOD

Digital Signal Processing Lab

MATLAB GENERATED FREQUENCY RESPONSE High Pass FIR filter(Fc= 800Hz).

Low Pass FIR filter (Fc=1000Hz)

Lab-Incharge

34

HOD

Digital Signal Processing Lab

5. Implementation of Infinity Impulse Response Filter
Aim: To design IIR filter (LP/HP) using Low pass Butterworth and Chebyshev filters technique and verify using the DSP processor Software: 1.CCStudio 2. Matlab2008a version Components required: 1.CRO 2. Function generator Theory: IIR filter Designing Experiments GENERAL CONSIDERATIONS: In the design of frequency – selective filters, the desired filter characteristics are specified in the frequency domain in terms of the desired magnitude and phase response of the filter. In the filter design process, we determine the coefficients of a causal IIR filter that closely approximates the desired frequency response specifications. Lab-Incharge 35 HOD

Digital Signal Processing Lab

IMPLEMENTATION OF DISCRETE-TIME SYSTEMS: Discrete time Linear Time-Invariant (LTI) systems can be described completely by constant coefficient linear difference equations. Representing a system in terms of constant coefficient linear difference equation is it’s time domain characterization. In the design of a simple frequency–selective filter, we would take help of some basic implementation methods for realizations of LTI systems described by linear constant coefficient difference equation. UNIT OBJECTIVE: The aim of this laboratory exercise is to design and implement a Digital IIR Filter & observe its frequency response. In this experiment we design a simple IIR filter so as to stop or attenuate required band of frequencies components and pass the frequency components which are outside the required band. BACKGROUND CONCEPTS: An Infinite impulse response (IIR) filter possesses an output response to an impulse which is of an infinite duration. The impulse response is "infinite" since there is feedback in the filter, that is if you put in an impulse ,then its output must produced for infinite duration of time. PREREQUISITES:
Ω Ω Ω

Concept of Discrete time signal processing. Analog filter design concepts. TMS320C6713 Architecture and instruction set.

EQUIPMENTS NEEDED:
Ω Ω Ω

Host (PC) with windows(95/98/Me/XP/NT/2000). TMS320C6713 DSP Starter Kit (DSK). Oscilloscope and Function generator.

ALGORITHM TO IMPLEMENT: We need to realize the Butter worth band pass IIR filter by implementing the difference equation y[n] = b0x[n] + b1x[n-1]+b2x[n-2]-a1y[n-1]-a2y[n-2] where b0 – b2, a0-a2 are feed forward and feedback word coefficients respectively [Assume 2nd order of filter].These coefficients are calculated using MATLAB.A direct form I implementation approach is taken. • Step 1 - Initialize the McBSP, the DSP board and the on board codec. 36 HOD

Lab-Incharge

Digital Signal Processing Lab “Kindly refer the Topic Configuration of 6713Codec using BSL” • • Step 2 - Initialize the discrete time system , that is , specify the initial conditions. Generally zero initial conditions are assumed. Step 3 - Take sampled data from codec while input is fed to DSP kit from the signal generator. Since Codec is stereo , take average of input data read from left and right channel . Store sampled data at a memory location. Step 4 - Perform filter operation using above said difference equation and store filter Output at a memory location . Step 5 - Output the value to codec (left channel and right channel) and view the output at Oscilloscope. Step 6 - Go to step 3.

• • •

FLOWCHART FOR IIR IMPLEMENTATION:

Start

Initialize the DSP Board. Set initial conditions of discrete time system by making x[0]-x[2] and y[0]-y[2] equal to zeros and a0-a2,b0-b2 with MATLAB filter coefficients

Take a new input and store it in x[0].

Lab-Incharge

37

HOD

Digital Signal Processing Lab

Do y[-3] = y[-2],y[-2]=y[-1] and Y[-1] = output . x[-3] = x[-2], x[-2]=x[-1]

output = x[0]b0+x[-1]b1+ x[-2]b2 - y[-1]a1 - y[-2]a2

x[-1]=x[0]

Write ‘output’ to analog i/o.

F.1 : Flowchart for implementing IIR filter.

Stop

MATLAB PROGRAM TO GENRATE FILTER CO-EFFICIENTS

% IIR Low pass Butterworth and Chebyshev filters % sampling rate - 24000 order = 2; cf=[2500/12000,8000/12000,1600/12000]; % cutoff frequency - 2500 [num_bw1,den_bw1]=butter(order,cf(1)); [num_cb1,den_cb1]=cheby1(order,3,cf(1)); % cutoff frequency - 8000 [num_bw2,den_bw2]=butter(order,cf(2)); [num_cb2,den_cb2]=cheby1(order,3,cf(2)); fid=fopen('IIR_LP_BW.txt','wt'); fprintf(fid,'\t\t-----------Pass band range: 0-2500Hz----------\n'); fprintf(fid,'\t\t-----------Magnitude response: Monotonic-----\n\n\'); fprintf(fid,'\n float num_bw1[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',num_bw1); fprintf(fid,'\nfloat den_bw1[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',den_bw1); fprintf(fid,'\n\n\n\t\t-----------Pass band range: 0-8000Hz----------\n'); fprintf(fid,'\t\t-----------Magnitude response: Monotonic-----\n\n'); fprintf(fid,'\nfloat num_bw2[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',num_bw2);

Lab-Incharge

38

HOD

Digital Signal Processing Lab
fprintf(fid,'\nfloat den_bw2[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',den_bw2); fclose(fid); winopen('IIR_LP_BW.txt'); fid=fopen('IIR_LP_CHEB Type1.txt','wt'); fprintf(fid,'\t\t-----------Pass band range: 2500Hz----------\n'); fprintf(fid,'\t\t-----------Magnitude response: Rippled (3dB) -----\n\n\'); fprintf(fid,'\nfloat num_cb1[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',num_cb1); fprintf(fid,'\nfloat den_cb1[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',den_cb1); fprintf(fid,'\n\n\n\t\t-----------Pass band range: 8000Hz----------\n'); fprintf(fid,'\t\t-----------Magnitude response: Rippled (3dB)-----\n\n'); fprintf(fid,'\nfloat num_cb2[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',num_cb2); fprintf(fid,'\nfloat den_cb2[9]={'); fprintf(fid,'%f,%f,%f,%f,%f,\n%f,%f,%f,%f};\n',den_cb2);

fclose(fid); winopen('IIR_LP_CHEB Type1.txt'); %%%%%%%%%%%%%%%%%% figure(1); [h,w]=freqz(num_bw1,den_bw1); w=(w/max(w))*12000; plot(w,20*log10(abs(h)),'linewidth',2) hold on [h,w]=freqz(num_cb1,den_cb1); w=(w/max(w))*12000; plot(w,20*log10(abs(h)),'linewidth',2,'color','r') grid on legend('Butterworth','Chebyshev Type-1'); xlabel('Frequency in Hertz'); ylabel('Magnitude in Decibels'); title('Magnitude response of Low pass IIR filters (Fc=2500Hz)'); figure(2); [h,w]=freqz(num_bw2,den_bw2); w=(w/max(w))*12000; plot(w,20*log10(abs(h)),'linewidth',2) hold on [h,w]=freqz(num_cb2,den_cb2); w=(w/max(w))*12000; plot(w,20*log10(abs(h)),'linewidth',2,'color','r') grid on legend('Butterworth','Chebyshev Type-1 (Ripple: 3dB)'); xlabel('Frequency in Hertz'); ylabel('Magnitude in Decibels');

Lab-Incharge

39

HOD

Digital Signal Processing Lab
title('Magnitude response in the passband'); axis([0 12000 -20 20]);

IIR_CHEB_LP FILTER CO-EFFICIENTS:
CoEffici ents B0 B1 B2 A0 A1 A2

Fc=2500Hz
Floating Point Values 0.044408 0.088815 0.044408 1.000000 -1.412427 0.663336 Fixed Point Values(Q15) 1455 1455[B1/2] 1455 32767 -23140[A1/2] 21735

Fc=800Hz
Floating Point Values 0.005147 0.010295 0.005147 1.000000 -1.844881 0.873965 Fixed Point Values(Q15) 168 168[B1/2] 168 32767 -30225[A1/2] 28637

Fc=8000Hz
Floating Point Values 0.354544 0.709088 0.354544 1.000000 0.530009 0.473218 Fixed Point Values(Q15) 11617 11617[B1/2] 11617 32767 8683[A1/2] 15506

Note: We have Multiplied Floating Point Values with 32767(215) to get Fixed Point Values.

IIR_BUTTERWORTH_LP FILTER CO-EFFICIENTS:
CoEffici ents B0 B1 B2 A0 A1 A2

Fc=2500Hz
Floating Point Values 0.072231 0.144462 0.072231 1.000000 -1.109229 0.398152 Fixed Point Values(Q15) 2366 2366[B1/2] 2366 32767 -18179[A1/2] 13046

Fc=800Hz
Floating Point Values 0.009526 0.019052 0.009526 1.000000 -1.705552, 0.743655 Fixed Point Values(Q15) 312 312[B1/2] 312 32767 -27943[A1/2] 24367

Fc=8000Hz
Floating Point Values 0.465153 0.930306 0.465153 1.000000 0.620204 0.240408 Fixed Point Values(Q15) 15241 15241[B1/2] 15241 32767 10161[A1/2] 7877

Note: We have Multiplied Floating Point Values with 32767(215) to get Fixed Point Values.

IIR_CHEB_HP FILTER CO-EFFICIENTS:
CoEffici ents B0 B1 B2 A0 A1 A2

Fc=2500Hz
Floating Point Values 0.388513 -0.777027 0.388513 1.000000 -1.118450 0.645091 Fixed Point Values(Q15) 12730 -12730[B1/2] 12730 32767 -18324[A1/2] 21137

Fc=4000Hz
Floating Point Values 0.282850 -0.565700 0.282850 1.000000 -0.451410 0.560534 Fixed Point Values(Q15) 9268 -9268[B1/2] 9268 32767 -7395[A1/2] 18367

Fc=7000Hz
Floating Point Values 0.117279 -0.234557 0.117279 1.000000 0.754476 0.588691 Fixed Point Values(Q15) 3842 -3842[B1/2] 3842 32767 12360[A1/2] 19289

Lab-Incharge

40

HOD

Digital Signal Processing Lab
Note: We have Multiplied Floating Point Values with 32767(215) to get Fixed Point Values.

IIR_BUTTERWORTH_HP FILTER CO-EFFICIENTS:
CoEffici ents B0 B1 B2 A0 A1 A2

Fc=2500Hz
Floating Point Values 0.626845 -1.253691 0.626845 1.000000 -1.109229 0.398152 Fixed Point Values(Q15) 20539 -20539[B1/2] 20539 32767 -18173[A1/2] 13046

Fc=4000Hz
Floating Point Values 0.465153 -0.930306 0.465153 1.000000 -0.620204 0.240408 Fixed Point Values(Q15) 15241 -15241[B1/2] 15241 32767 -10161[A1/2] 7877

Fc=7000Hz
Floating Point Values 0.220195 -0.440389 0.220195 1.000000 0.307566 0.188345 Fixed Point Values(Q15) 7215 -7215[B1/2] 7215 32767 5039[A1/2} 6171

Note: We have Multiplied Floating Point Values with 32767(215) to get Fixed Point Values.

‘C’ PROGRAM TO IMPLEMENT IIR FILTER
#include "filtercfg.h" #include "dsk6713.h" #include "dsk6713_aic23.h" const signed int filter_Coeff[] = { //12730,-12730,12730,2767,-18324,21137 /*HP 2500 */ //312,312,312,32767,-27943,24367 /*LP 800 */ //1455,1455,1455,32767,-23140,21735 /*LP 2500 */ //9268,-9268,9268,32767,-7395,18367 /*HP 4000*/ 7215,-7215,7215,32767,5039,6171, /*HP 7000*/ }; /* Codec configuration settings */ DSK6713_AIC23_Config config = { \ 0x0017, /* 0 DSK6713_AIC23_LEFTINVOL Left line input channel volume */ \ 0x0017, /* 1 DSK6713_AIC23_RIGHTINVOL Right line input channel volume */\ 0x00d8, /* 2 DSK6713_AIC23_LEFTHPVOL Left channel headphone volume */ \ 0x00d8, /* 3 DSK6713_AIC23_RIGHTHPVOL Right channel headphone volume */ \ 0x0011, /* 4 DSK6713_AIC23_ANAPATH Analog audio path control */ \ 0x0000, /* 5 DSK6713_AIC23_DIGPATH Digital audio path control */ \ 0x0000, /* 6 DSK6713_AIC23_POWERDOWN Power down control */ \ 0x0043, /* 7 DSK6713_AIC23_DIGIF Digital audio interface format */ \ 0x0081, /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */ \ 0x0001 /* 9 DSK6713_AIC23_DIGACT Digital interface activation */ \ }; /*

Lab-Incharge

41

HOD

Digital Signal Processing Lab
* main() - Main code routine, initializes BSL and generates tone */ void main() { DSK6713_AIC23_CodecHandle hCodec; int l_input, r_input, l_output, r_output; /* Initialize the board support library, must be called first */ DSK6713_init(); /* Start the codec */ hCodec = DSK6713_AIC23_openCodec(0, &config); DSK6713_AIC23_setFreq(hCodec, 3); while(1) { /* Read a sample to the left channel */ while (!DSK6713_AIC23_read(hCodec, &l_input)); /* Read a sample to the right channel */ while (!DSK6713_AIC23_read(hCodec, &r_input)); l_output=IIR_FILTER(&filter_Coeff ,l_input); r_output=l_output; /* Send a sample to the left channel */ while (!DSK6713_AIC23_write(hCodec, l_output)); /* Send a sample to the right channel */ while (!DSK6713_AIC23_write(hCodec, r_output)); } /* Close the codec */ DSK6713_AIC23_closeCodec(hCodec); } signed int IIR_FILTER(const signed int * h, signed int x1) { static signed int x[6] = { 0, 0, 0, 0, 0, 0 }; /* x(n), x(n-1), x(n-2). Must be static */ static signed int y[6] = { 0, 0, 0, 0, 0, 0 }; /* y(n), y(n-1), y(n-2). Must be static */ int temp=0; temp = (short int)x1; /* Copy input to temp */ x[0] = (signed int) temp; /* Copy input to x[stages][0] */ temp = ( (int)h[0] * x[0]) ; /* B0 * x(n) */ temp += ( (int)h[1] * x[1]); temp += ( (int)h[1] * x[1]); temp += ( (int)h[2] * x[2]); /* B1/2 * x(n-1) */ /* B1/2 * x(n-1) */ /* B2 * x(n-2) */

temp -= ( (int)h[4] * y[1]); /* A1/2 * y(n-1) */ temp -= ( (int)h[4] * y[1]); /* A1/2 * y(n-1) */ temp -= ( (int)h[5] * y[2]); /* A2 * y(n-2) */

Lab-Incharge

42

HOD

Digital Signal Processing Lab
/* Divide temp by coefficients[A0] */ temp >>= 15; if ( temp > 32767 ) { temp = 32767; } else if ( temp < -32767) { temp = -32767; } y[0] = temp ; /* Shuffle values along one place for next time */ y[2] = y[1]; /* y(n-2) = y(n-1) */ y[1] = y[0]; /* y(n-1) = y(n) */ x[2] = x[1]; /* x(n-2) = x(n-1) */ x[1] = x[0]; /* x(n-1) = x(n) */ /* temp is used as input next time through */ return (temp<<2); }

PROCEDURE:  Switch on the DSP board.  Open the Code Composer Studio.  Create a new project Project  New (File Name. pjt , Eg: FIR.pjt)  Initialize on board codec. “Kindly refer the Topic Configuration of 6713 Codec using BSL”  Add the given above ‘C’ source file to the current project (remove codec.c source file from the project if you have already added).  Connect the speaker jack to the input of the CRO.  Build the program.  Load the generated object file(*.out) on to Target board.  Run the program using F5.  Observe the waveform that appears on the CRO screen.

Lab-Incharge

43

HOD

Digital Signal Processing Lab

Lab-Incharge

44

HOD

Digital Signal Processing Lab

6.Fast Fourier Transforms (FFT)
Aim: To verify the FFT using DSP processor Software: CCStudio Theory: The DFT Equation

Twiddle Factor In the Definition of the DFT, there is a factor called the Twiddle Factor

Lab-Incharge

45

HOD

Digital Signal Processing Lab

where N = number of samples. If we take an 8 bit sample sequence we can represent the twiddle factor as a vector in the unit circle. e.g.

Note that 1. It is periodic. (i.e. it goes round and round the circle !!) 2. That the vectors are symmetric 3. The vectors are equally spaced around the circle.

Why the FFT? If you look at the equation for the Discrete Fourier Transform you will see that it is quite complicated to work out as it involves many additions and multiplications involving complex numbers. Even a simple eight sample signal would require 49 complex multiplications and 56 complex additions to work out the DFT. At this level it is still manageable, however a realistic signal could have 1024 samples which requires over 20,000,000 complex multiplications and additions. As you can see the number of calculations required soon mounts up to unmanageable proportions. The Fast Fourier Transform is a simply a method of laying out the computation, which is much faster for large values of N, where N is the number of samples in the sequence. It is an ingenious way of achieving rather than the DFT's clumsy P^2 timing. The idea behind the FFT is the divide and conquer approach, to break up the original N point sample into two (N / 2) sequences. This is because a series of smaller problems is easier to solve than one large one. The DFT requires (N-1)^2 complex multiplications Lab-Incharge 46 HOD

Digital Signal Processing Lab and N(N-1) complex additions as opposed to the FFT's approach of breaking it down into a series of 2 point samples which only require 1 multiplication and 2 additions and the recombination of the points which is minimal. For example Seismic Data contains hundreds of thousands of samples and would take months to evaluate the DFT. Therefore we use the FFT. FFT Algorithm The FFT has a fairly easy algorithm to implement, and it is shown step by step in the list below. Thjis version of the FFT is the Decimation in Time Method 1. Pad input sequence, of N samples, with Zero’s until the number of samples is the nearest power of two. e.g. 500 samples are padded to 512 (2^9) 2. Bit reverse the input sequence. e.g. 3 = 011 goes to 110 = 6 3. Compute (N / 2) two sample DFT's from the shuffled inputs. See "Shuffled Inputs" 4. Compute (N / 4) four sample DFT's from the two sample DFT's. See "Shuffled Inputs" 5. Compute (N / 2) eight sample DFT's from the four sample DFT's. See "Shuffled Inputs"

Lab-Incharge

47

HOD

Digital Signal Processing Lab 6. Until the all the samples combine into one N-sample DFT

Shuffled Inputs The process of decimating the signal in the time domain has caused the INPUT samples to be re-ordered. For an 8 point signal the original order of the samples is 0, 1, 2, 3, 4, 5, 6, 7 But after decimation the order is 0, 4, 2, 6, 1, 5, 3, 7 At first it may look as if there is no order to this new sequence, BUT if the numbers are represented as binary a patter soon becomes apparent.

Lab-Incharge

48

HOD

Digital Signal Processing Lab

What has happened is that the bit patterns representing the sample number has been reversed. This new sequence is the order that the samples enter the FFT.

ALGORITHM TO IMPLEMENT FFT: • • • • • Step 1 - Select no. of points for FFT(Eg: 64) Step 2 – Generate a sine wave of frequency ‘f ‘ (eg: 10 Hz with a sampling rate = No. of Points of FFT(eg. 64)) using math library function. Step 3 - Take sampled data and apply FFT algorithm . Step 4 – Use Graph option to view the Input & Output. Step 5 - Repeat Step-1 to 4 for different no. of points & frequencies.

‘C’ PROGRAM TO IMPLEMENT IIR FILTER

Lab-Incharge

49

HOD

Digital Signal Processing Lab Main.c (fft 256.c): #include <math.h> #define PTS 64 #define PI 3.14159265358979 //# of points for FFT

typedef struct {float real,imag;} COMPLEX; void FFT(COMPLEX *Y, int n); //FFT prototype float iobuffer[PTS]; //as input and output buffer float x1[PTS]; //intermediate buffer short i; //general purpose index variable short buffercount = 0; //number of new samples in iobuffer short flag = 0; //set to 1 by ISR when iobuffer full COMPLEX w[PTS]; //twiddle constants stored in w COMPLEX samples[PTS]; //primary working buffer main() { for (i = 0 ; i<PTS ; i++) // set up twiddle constants in w { w[i].real = cos(2*PI*i/(PTS*2.0)); //Re component of twiddle constants w[i].imag =-sin(2*PI*i/(PTS*2.0)); //Im component of twiddle constants } for (i = 0 ; i < PTS ; i++) //swap buffers { iobuffer[i] = sin(2*PI*10*i/64.0);/*10- > freq, 64 -> sampling freq*/ samples[i].real=0.0; samples[i].imag=0.0; }

for (i = 0 ; i < PTS ; i++) //swap buffers { samples[i].real=iobuffer[i]; //buffer with new data } for (i = 0 ; i < PTS ; i++) samples[i].imag = 0.0; //imag components = 0 Lab-Incharge 50 HOD

Digital Signal Processing Lab

FFT(samples,PTS);

//call function FFT.c

for (i = 0 ; i < PTS ; i++) //compute magnitude { x1[i] = sqrt(samples[i].real*samples[i].real + samples[i].imag*samples[i].imag); } } //end of main

fft.c:
#define PTS 64 //# of points for FFT typedef struct {float real,imag;} COMPLEX; extern COMPLEX w[PTS]; //twiddle constants stored in w void FFT(COMPLEX *Y, int N) //input sample array, # of points { COMPLEX temp1,temp2; //temporary storage variables int i,j,k; //loop counter variables int upper_leg, lower_leg; //index of upper/lower butterfly leg int leg_diff; //difference between upper/lower leg int num_stages = 0; //number of FFT stages (iterations) int index, step; //index/step through twiddle constant i = 1; //log(base2) of N points= # of stages do { num_stages +=1; i = i*2; }while (i!=N); leg_diff = N/2; //difference between upper&lower legs step = (PTS*2)/N; //step between values in twiddle.h for (i = 0;i < num_stages; i++) //for N-point FFT { index = 0; for (j = 0; j < leg_diff; j++) { for (upper_leg = j; upper_leg < N; upper_leg += (2*leg_diff)) { lower_leg = upper_leg+leg_diff; temp1.real = (Y[upper_leg]).real + (Y[lower_leg]).real; temp1.imag = (Y[upper_leg]).imag + (Y[lower_leg]).imag; temp2.real = (Y[upper_leg]).real - (Y[lower_leg]).real; Lab-Incharge 51 HOD

Digital Signal Processing Lab temp2.imag = (Y[upper_leg]).imag - (Y[lower_leg]).imag; (Y[lower_leg]).real = temp2.real*(w[index]).real -temp2.imag*(w[index]).imag; (Y[lower_leg]).imag = temp2.real*(w[index]).imag +temp2.imag*(w[index]).real; (Y[upper_leg]).real = temp1.real; (Y[upper_leg]).imag = temp1.imag; } index += step; } leg_diff = leg_diff/2; step *= 2; } j = 0; for (i = 1; i < (N-1); i++) { k = N/2; while (k <= j) { j = j - k; k = k/2; } j = j + k; if (i<j) { temp1.real = (Y[j]).real; temp1.imag = (Y[j]).imag; (Y[j]).real = (Y[i]).real; (Y[j]).imag = (Y[i]).imag; (Y[i]).real = temp1.real; (Y[i]).imag = temp1.imag; } } return; }

//bit reversal for resequencing data

Input:
Lab-Incharge 52 HOD

Digital Signal Processing Lab

Output:

Lab-Incharge

53

HOD

Digital Signal Processing Lab HOW TO PROCEED  Open Code Composer Studio, make sure the DSP kit is turned on.  Start a new project using ‘Project-new ‘ pull down menu, save it in a separate directory(c:\ti\myprojects) with name “FFT.pjt”.  Add the source files “FFT256.c“ and “FFT.C” in the project using ‘Projectadd files to project’ pull down menu.  Add the linker command file “hello.cmd”  Add the rts file “rts6700.lib”  Compile the program using the ‘Project-compile’ pull down menu or by clicking the shortcut icon on the left side of program window.  Load the program in program memory of DSP chip using the ‘File-load program’ pull down menu.  Run the program and observe output using graph utility.

Lab-Incharge

54

HOD

Digital Signal Processing Lab

7. POWER SPECTRUM
Aim: To verify the power spectrum using DSP processor. Software: CCStudio Theory: The total or the average power in a signal is often not of as great an interest. We are most often interested in the PSD or the Power Spectrum. We often want to see is how the input power has been redistributed by the channel and in this frequency-based redistribution of power is where most of the interesting information lies. The total area under the Power Spectrum or PSD is equal to the total avg. power of the signal. The PSD is an even function of frequency or in other words To compute PSD: The value of the auto-correlation function at zero-time equals the total power in the signal. To compute PSD We compute the auto-correlation of the signal and then take its FFT. The auto-correlation function and PSD are a Fourier transform pair. (Another estimation method called “period gram” uses sampled FFT to compute the PSD.) E.g.: For a process x(n) correlation is defined as:

R (τ Ex n τ ) =( xn ) { )+ } (

=lim

N→ ∞

1 N + ) ( nxn ( x ∑ ) N n= 1

τ

Power Spectral Density is a Fourier transform of the auto correlation.

S (ω = (τ( )) lim τ R ( ) ˆ ) FT R = e ∑
N→ ∞

N− 1

− jω τ

τ= N 1 −+

− R (τ) = FT (ω )) S1( =

ωS ( ω d ) e 2π ∫

1

jω τ

ALGORITHM TO IMPLEMENT PSD: Lab-Incharge 55 HOD

Digital Signal Processing Lab • • • • • • Step 1 - Select no. of points for FFT(Eg: 64) Step 2 – Generate a sine wave of frequency ‘f ‘ (eg: 10 Hz with a sampling rate = No. of Points of FFT(eg. 64)) using math library function. Step 3 - Compute the Auto Correlation of Sine wave Step4 - Take output of auto correlation, apply FFT algorithm . Step 4 - Use Graph option to view the PSD. Step 5 - Repeat Step-1 to 4 for different no. of points & frequencies.

‘C’ Program to Implement PSD: Lab-Incharge 56 HOD

Digital Signal Processing Lab

PSD.c:
/************************************************************* * FILENAME * Non_real_time_PSD.c * DESCRIPTION * Program to Compute Non real time PSD * using the TMS320C6711 DSK. *************************************************************** * DESCRIPTION * Number of points for FFT (PTS) * x --> Sine Wave Co-Efficients * iobuffer --> Out put of Auto Correlation. * x1 --> use in graph window to view PSD /*===========================================================*/ #include <math.h> #define PTS 128 #define PI 3.14159265358979 typedef struct {float real,imag;} COMPLEX; void FFT(COMPLEX *Y, int n); //FFT prototype float iobuffer[PTS]; //as input and output buffer float x1[PTS],x[PTS]; //intermediate buffer short i; //general purpose index variable short buffercount = 0; //number of new samples in iobuffer short flag = 0; //set to 1 by ISR when iobuffer full float y[128]; COMPLEX w[PTS]; //twiddle constants stored in w COMPLEX samples[PTS]; //primary working buffer main() { float j,sum=0.0 ; int n,k,i,a; for (i = 0 ; i<PTS ; i++) // set up twiddle constants in w { w[i].real = cos(2*PI*i/(PTS*2.0)); /*Re component of twiddle constants*/ w[i].imag =-sin(2*PI*i/(PTS*2.0)); /*Im component of twiddle constants*/ } /****************Input Signal X(n) *************************/ for(i=0,j=0;i<PTS;i++) { x[i] = sin(2*PI*5*i/PTS); // Signal x(Fs)=sin(2*pi*f*i/Fs); samples[i].real=0.0; samples[i].imag=0.0;

//# of points for FFT

Lab-Incharge

57

HOD

Digital Signal Processing Lab
} /********************Auto Correlation of X(n)=R(t) ***********/ for(n=0;n<PTS;n++) { sum=0; for(k=0;k<PTS-n;k++) { sum=sum+(x[k]*x[n+k]); } iobuffer[n] = sum; }

// Auto Correlation R(t)

/********************** FFT of R(t) ***********************/ for (i = 0 ; i < PTS ; i++) //swap buffers { samples[i].real=iobuffer[i]; //buffer with new data } for (i = 0 ; i < PTS ; i++) samples[i].imag = 0.0; FFT(samples,PTS); //imag components = 0 //call function FFT.c

/******************** PSD ********************/ for (i = 0 ; i < PTS ; i++) //compute magnitude { x1[i] = sqrt(samples[i].real*samples[i].real + samples[i].imag*samples[i].imag); } } FFT.c: #define PTS 128 //# of points for FFT //end of main

typedef struct {float real,imag;} COMPLEX; extern COMPLEX w[PTS]; //twiddle constants stored in w

void FFT(COMPLEX *Y, int N) //input sample array, # of points { COMPLEX temp1,temp2; //temporary storage variables int i,j,k; //loop counter variables int upper_leg, lower_leg; //indexof upper/lower butterfly leg

Lab-Incharge

58

HOD

Digital Signal Processing Lab
int leg_diff; //difference between upper/lower leg int num_stages = 0; //number of FFT stages (iterations) int index, step; //index/step through twiddle constant i = 1; //log(base2) of N points= # of stages do { num_stages +=1; i = i*2; }while (i!=N); leg_diff = N/2; //difference between upper&lower legs step = (PTS*2)/N; //step between values in twiddle.h// 512 for (i = 0;i < num_stages; i++) //for N-point FFT { index = 0; for (j = 0; j < leg_diff; j++) { for (upper_leg = j; upper_leg < N; upper_leg += (2*leg_diff)) { lower_leg = upper_leg+leg_diff; temp1.real = (Y[upper_leg]).real + (Y[lower_leg]).real; temp1.imag = (Y[upper_leg]).imag + (Y[lower_leg]).imag; temp2.real = (Y[upper_leg]).real - (Y[lower_leg]).real; temp2.imag = (Y[upper_leg]).imag - (Y[lower_leg]).imag; (Y[lower_leg]).real = temp2.real*(w[index]).real -temp2.imag*(w[index]).imag; (Y[lower_leg]).imag = temp2.real*(w[index]).imag +temp2.imag*(w[index]).real; (Y[upper_leg]).real = temp1.real; (Y[upper_leg]).imag = temp1.imag; } index += step; } leg_diff = leg_diff/2; step *= 2; } j = 0; for (i = 1; i < (N-1); i++) //bit reversal for resequencing data { k = N/2; while (k <= j) { j = j - k; k = k/2; } j = j + k; if (i<j) { temp1.real = (Y[j]).real; temp1.imag = (Y[j]).imag; (Y[j]).real = (Y[i]).real; (Y[j]).imag = (Y[i]).imag; (Y[i]).real = temp1.real; (Y[i]).imag = temp1.imag;

Lab-Incharge

59

HOD

Digital Signal Processing Lab
} } return; }

HOW TO PROCEED  Open Code Composer Studio, make sure the DSP kit is turned on.  Start a new project using ‘Project-new ‘ pull down menu, save it in a separate directory(c:\ti\myprojects) with name “PSD.pjt”.  Add the source files “PSD.c“ and “FFT.c” in the project using ‘Projectadd files to project’ pull down menu.  Add the linker command file “hello.cmd” .  Add the rts file “rts6700.lib”  Compile the program using the ‘Project-compile’ pull down menu or by clicking the shortcut icon on the left side of program window.  Load the program in program memory of DSP chip using the ‘File-load program’ pull down menu.  Run the program and observe output using graph utility. OUT PUT:

Lab-Incharge

60

HOD

Digital Signal Processing Lab

Lab-Incharge

61

HOD

Digital Signal Processing Lab

Generation of SINE Wave
Aim: Write a MATLAB program to generate sinusoidal signals. Program: t=0: .01:pi; y=sin(2*pi*t); subplot(2,1,1); plot (t,y); ylabel('amplitude-------->'); xlabel('(a)n------->'); Procedure: 1.Open the Matlab 7.0. 2.Go to the new open M-file and write the code. 3.Save the code and viewrun 4.Observe the waveforms.

OUTPUT: Sine wave:

Lab-Incharge

62

HOD

Digital Signal Processing Lab

Generation of COSINE Wave: Aim:
Write a MATLAB program to generate cosine signal.

Program:
t=0:.01:pi; y=cos(2*pi*t); subplot(2,1,2); plot(t,y); ylabel('amplitude----->'); xlabel('(b)n-------->');

OUTPUT:

Cosine wave:

Lab-Incharge

63

HOD

Digital Signal Processing Lab

8. Generation Of SUM OF SINUSOIDAL Signals
Aim: Write a Matlab program to generate sum of sinusoidal signals Software: Matlab R2008a Version Theory: A continuous-time signal x(t) is said to be periodic with period T if it satisfy the condition x (t+T) = x(t) for all t -∞ < t < + ∞

A signal is periodic if the above condition is not satisfied for at least one value of T. The smallest value of T that satisfy the above condition is known as fundamental period. Complex exponential and sinusoidal signals are examples for continuous-time periodic signals. Consider a sinusoidal signal x(t) = A sin (wt+θ) Where A is tha amplitude, w is tha frequency in radians per second (rad/sec), and θ the phase in radians. The frequency f0 in hertz is given by f0 = w 2Π For periodic signal we have X (t+T) = x(t) For x (t) = Asin (wt+ θ) X (t+T) = Asin [w(t+T)+ θ)] = Asin [wt+wT+ θ] Equation 5 and 2 are equal if wT = 2Π T = 2Π w Thu the sinusoidal is periodic with period 2Π/w The sum of two periodic signals x1(t) and x2(t) with periods T1 and T2 respectively may or may not be periodic, then the ratio T1/T2 can be written as the ratio a/b of two integers a and b. If T1/T2 = a/b, then bT1 = aT2, and since a and b are integers, x1(t) and x2(t) are periodic with period bT1. If a and b are co prime (i. e. a and b have no common integer factors other than 1) then T = bT1 is the fundamental period of the sum of two signals. Lab-Incharge 64 HOD

Digital Signal Processing Lab

Program:
clc; clear all; close all; t=0: .2:10; x1=(4/pi)*sin(t); subplot(2,2,1); plot(t,x1); title('4/pi sint'); x2=(4/pi)*1/3*sin(3*t); xa=x1+x2; subplot(2,2,2); plot(t,xa); title('(4/pi)sint+(4/3pi)sin3t'); x3=(4/pi)*1/5*sin(5*t); xb=x1+x2+x3; subplot(2,2,3); plot(t,xb); title('(4/pi)sint+(4/3pi)sin3t+(4/5pi)sin5t'); x4=4/pi*1/7*sin(7*t); xc=x1+x2+x3+x4; subplot(2,2,4); plot(t,xc); title('(4/pi)sint+(4/3pi)sin3t+(4/5pi)sin5t+(4/7pi)sin7t');

Lab-Incharge

65

HOD

Digital Signal Processing Lab

OUTPUT: Sine waves:

Lab-Incharge

66

HOD

Digital Signal Processing Lab

9. Frequency Response of analog (LP/HP) filter
Aim: 1) To determine the frequency response of Butterworth (LP/HP) filter. 2) To determine the frequency response of Chebyshev (LP/HP) filter. Software: MatlabR2008a Theory: Butterworth filter:
1

The typical prototype is the low-pass filter, which can be modified into a high-pass filter, or placed in series with others to form band-pass and band-stop filters, and higher order versions of these. The gain G(ω) of an n-order Butterworth low pass filter is given in terms of the transfer function H(s) as:

where
• • •

n = order of filter ωc = cutoff frequency (approximately the -3dB frequency) G0 is the DC gain (gain at zero frequency)

It can be seen that as n approaches infinity, the gain becomes a rectangle function and frequencies below ωc will be passed with gain G0, while frequencies above ωc will be suppressed. For smaller values of n, the cutoff will be less sharp. We wish to determine the transfer function H(s) where s = σ + jω. Since H(s)H(-s) evaluated at s = jω is simply equal to |H(jω)|2, it follows that:

The poles of this expression occur on a circle of radius ωc at equally spaced points. The transfer function itself will be specified by just the poles in the negative real half-plane of s. The k-th pole is specified by:

Lab-Incharge

67

HOD

Digital Signal Processing Lab and hence,

The transfer function may be written in terms of these poles as:

The denominator is a Butterworth polynomial in s. The group-delay is defined as the derivative of the phase with respect to angular frequency and is a measure of the distortion in the signal introduced by phase differences for different frequencies. Chebyshev filter: Type I Chebyshev Filters: These are the most common Chebyshev filters. The gain (amplitude) response as a function of angular frequency ω of the nth order low pass filter is

where ε is the ripple factor, ω0 is the cutoff frequency and Tn() is a Chebyshev polynomial of the nth order. The passband exhibits equiripple behavior, with the ripple determined by the ripple factor ε. In the passband, the Chebyshev polynomial alternates between 0 and 1 so the filter gain will alternate between maxima at G=1 and minima at . At the cutoff frequency ω0 the gain again has the value but continues to drop into the stop band as the frequency increases. This behavior is shown in the diagram on the right. (note: the common definition of the cutoff frequency to −3 dB does not hold for Chebyshev filters!) The order of a Chebyshev filter is equal to the number of reactive components (for example, inductors) needed to realize the filter using analog electronics. The ripple is often given in dB: Ripple in dB = so that a ripple of 3 dB results from ε = 1. Lab-Incharge 68 HOD

Digital Signal Processing Lab

Gain and group delay of a fifth order type I Chebyshev filter with ε=0.5. The group delay is defined as the derivative of the phase with respect to angular frequency and is a measure of the distortion in the signal introduced by phase differences for different frequencies.

The gain and the group delay for a fifth order type I Chebyshev filter with ε=0.5 are plotted in the graph on the left. It can be seen that there are ripples in the gain and the group delay in the passband but not in the stop band

Type II Chebyshev Filters: Also known as inverse Chebyshev, this type is less common because it does not roll off as fast as type I, and requires more components. It has no ripple in the passband, but does have equiripple in the stopband. The gain is: The gain is:

In the stop band, the Chebyshev polynomial will oscillate between 0 and 1 so that the gain will oscillate between zero and

Lab-Incharge

69

HOD

Digital Signal Processing Lab and the smallest frequency at which this maximum is attained will be the cutoff frequency ω0. The parameter ε is thus related to the stopband attenuation γ in decibels by:

For a stopband attenuation of 5dB, ε = 0.6801; for an attenuation of 10dB, ε = 0.3333. The frequency fC = ωC/2 π is the cutoff frequency. The 3dB frequency fH is related to fC by:

To design a Butterworth low pass filter for the specifications a).passband attenuation in db=4. Lab-Incharge 70 HOD

Digital Signal Processing Lab b).stopband attenuation in db=30. c). passband frequency in Hz=400. d).stopband frequency in Hz=800. e).sampling frequency in Hz=2000. Program clear all; alphap=.4; %passband attenuation in db alphas=30; %stopband attenuation in db fp=400; %passband frequency in Hz fs=800; %stopband frequency in Hz F=2000; %sampling frequency in Hz omp=2*fp/F; oms=2*fs/F; %frequency in radians %to find cutoff frequency and ordr of the filter [n,wn]=buttord(omp,oms,alphap, alphas); %system function of the filter [b,a]=butter(n,wn); w=0:.01:pi; [h,om]=freqz(b,a,w,'whole'); m=20*log10(abs(h)); an=angle(h); subplot(2,1,1);plot(om/pi,m);grid; ylabel('gain in db');xlabel('normalised frequency'); subplot(2,1,2);plot(om/pi,an);grid; xlabel('normalised frequency'); ylabel('phase in radians');

Lab-Incharge

71

HOD

Digital Signal Processing Lab

100 0 gain in db -100 -200 -300

0

0.1

0.2

0.3

0.4 0.5 0.6 normalised frequency

0.7

0.8

0.9

1

4 phase in radians 2 0 -2 -4

0

0.1

0.2

0.3

0.4 0.5 0.6 normalised frequency

0.7

0.8

0.9

1

Result: The Program has been written that designs the Butterworth lowpass filter for the given specifications To design a Chebyshev-I Lowpass filter using Matlab. following specification. a). passband attenuation in db=1. b). stopband attenuation in db=15. c). passband frequencies in rad d). stopband frequencies in rad Program: %to design a Chebyshev-I lowpass filter for the %given specifications clear all; alphap=1; %passband attenuation in db alphas=15; %stopband attenuation in db wp=.2*pi; %passband frequency in rad ws=.3*pi; %stopband frequency in rad %order and cutoff frequency of the filter [n,wn]=cheb1ord(wp/pi,ws/pi,alphap,alphas); %system function of the filter [b,a]=cheby1(n,alphap,wn); w=0:.01:pi; [h,ph]=freqz(b,a,w); Lab-Incharge 72 HOD

Digital Signal Processing Lab m=20*log10(abs(h)); an=angle(h); subplot(2,1,1); plot(ph/pi,m);grid; ylabel('gain in db');xlabel('normalised frequency'); subplot(2,1,2);plot(ph/pi,an);grid; xlabel('normalised frequency'); ylabel('phase in radians'); [b,a]=cheby1(n,alphap,wn)

0

gain in db

-100

-200

-300

0

0.1

0.2

0.3

0.4 0.5 0.6 normalised frequency

0.7

0.8

0.9

1

4 phase in radians 2 0 -2 -4

0

0.1

0.2

0.3

0.4 0.5 0.6 normalised frequency

0.7

0.8

0.9

1

To design a chebyshev-II lowpass filter using Matlab. for following specification. a). passband attenuation in db=1. b). stopband attenuation in db=20. c). passband frequencies in rad d). stopband frequencies in rad

Lab-Incharge

73

HOD

Digital Signal Processing Lab Program: %To design a chebyshev-II lowpass filter %for the given specifications clear all; alphap=1; %passband attenuation in db alphas=20; %stopband attenuation in db wp=.2*pi; %passband frequency in rad ws=.3*pi; %stopband frequency in rad %calculation of order and cutoff frequency of the filter [n,wn]=cheb2ord(wp/pi,ws/pi,alphap,alphas); %system function of the filter [b,a]=cheby2(n,alphas,wn) w=0:.01:pi; [h,ph]=freqz(b,a,w); m=20*log10(abs(h)); an=angle(h); subplot(2,1,1); plot(ph/pi,m);grid; ylabel('gain in db');xlabel('normalised frequency'); subplot(2,1,2); plot (ph/pi,an);grid; xlabel('normalised frequency'); ylabel('phase in radians');

50

gain in db

0

-50

-100

0

0.1

0.2

0.3

0.4 0.5 0.6 normalised frequency

0.7

0.8

0.9

1

4 phase in radians 2 0 -2 -4

0

0.1

0.2

0.3

0.4 0.5 0.6 normalised frequency

0.7

0.8

0.9

1

Lab-Incharge

74

HOD

Digital Signal Processing Lab % FIR Filter using RECTANGULAR Window:

Aim:
MATLAB program to generate FIR filter (LP/HP) using Rectangular windowing technique.

Program:
clear all; N=25; alpha=(N-1)/2; n=0:1:N-1; hd=cos(pi*(n-alpha))./(n-alpha); hd(alpha+1)=0; wr=Boxcar(N); hn=hd.*wr'; w=0:.01:pi; h=freqz(hn,1,w); plot(w/pi,abs(h)); hold on wh=hanning(N); hn=hd.*wh'; w=0:.01:pi; h=freqz(hn,1,w); plot(w/pi,abs(h),'-.'); ylabel('magnitude'); xlabel('normalized frequency'); hold off

Lab-Incharge

75

HOD

Digital Signal Processing Lab

OUTPUT: Waveform:

Lab-Incharge

76

HOD

Digital Signal Processing Lab

%FIR filter using HAMMING Window:

Aim:
MATLAB program to generate FIR filter (LP/HP) using Hamming windowing technique.

Program:
clear all; wc=.5*pi; N=25; b=fir1(N,wc/pi,hamming(N+1)); w=0:.01:pi; h=freqz(b,1,w); plot(w/pi,abs(h)); hold on b=fir1(N,wc/pi,blackman(N+1)); w=0:.01:pi; h=freqz(b,1,w); plot(w/pi,abs(h),'-.'); ylabel('magnitude'); xlabel('normalized frequency'); hold off

Lab-Incharge

77

HOD

Digital Signal Processing Lab

OUTPUT:

Waveform:

Lab-Incharge

78

HOD

Digital Signal Processing Lab

% FIR Filter using KAISER Window: Aim: MATLAB program to generate FIR filter (LP/HP) using Kaiser windowing technique. Program: clear all; wc=.5*pi; N=25; b=fir1(N,wc/pi,kaiser(N+1,.5)); w=0:.01:pi; h=freqz(b,1,w); plot(w/pi,20*log10(abs(h))); hold on b=fir1(N,wc/pi,kaiser(N+1,3.5)); w=0:.01:pi; h=freqz(b,1,w); plot(w/pi,20*log10(abs(h)),'-.'); hold on b=fir1(N,wc/pi,kaiser(N+1,8.5)); w=0:.01:pi; h=freqz(b,1,w); plot(w/pi,20*log10(abs(h))); ylabel('magnitude in db'); xlabel('normalized frequency'); hold off

Lab-Incharge

79

HOD

Digital Signal Processing Lab

OUTPUT:

Waveform:

Lab-Incharge

80

HOD

Digital Signal Processing Lab % FAST FOURIER TRANSFORM: Aim: To find the FFT of given 1-D signal and plot. Program: clc; clear all; close all; x=[0,1,2,3,4,5,6,7]; n=8; y=fft(x,n); stem(y); ylabel('imaginary axis'); xlabel('real axis'); title('FAST FOURIER TRANSFORM');

Input: x(n) = { 1,2,3,4,4,3,2,1}. Output: X (k) = {20,-5.828-j2.414,0,-0.172-j0.414,0,-0.172+j0.414,0,-5.828+j2.414}.

OUTPUT: Waveform:

Lab-Incharge

81

HOD

Digital Signal Processing Lab

MINI PROJECT (DISCRETE COSINE TRANSFORM)

The Discrete Cosine Transform
Introduction
The discrete cosine transform (DCT) helps separate the image into parts (or spectral subbands) of differing importance (with respect to the image's visual quality). The DCT is similar to the discrete Fourier transform: it transforms a signal or image from the spatial domain to the frequency domain. With an input image, A, the coefficients for the output "image," B, are: Lab-Incharge 82 HOD

Digital Signal Processing Lab

The input image is N2 pixels wide by N1 pixels high; A(i,j) is the intensity of the pixel in row i and column j; B(k1,k2) is the DCT coefficient in row k1 and column k2 of the DCT matrix. All DCT multiplications are real. This lowers the number of required multiplications, as compared to the discrete Fourier transform. The DCT input is an 8 by 8 array of integers. This array contains each pixel's gray scale level; 8 bit pixels have levels from 0 to 255. The output array of DCT coefficients contains integers; these can range from -1024 to 1023. For most images, much of the signal energy lies at low frequencies; these appear in the upper left corner of the DCT. The lower right values represent higher frequencies, and are often small - small enough to be neglected with little visible distortion.

IMPLEMENTATION OF DCT
 DCT-based codecs use a two-dimensional version of the transform.  The 2-D DCT and its inverse (IDCT) of an N x N block are shown below: 2-D DCT:
N −1 N −1 2 (2 x + 1)uπ (2 y + 1)vπ F (u , v) = C (u )C (v)∑∑ f ( x, y ) cos[ ] cos[ ] N 2N 2N y =0 x =0

2-D IDCT: Lab-Incharge 83 HOD

Digital Signal Processing Lab
N −1 N −1 v =0 u =0

2 f ( x, y ) = N

∑∑ C (u )C (v) F (u, v) cos[

(2 x + 1)uπ (2 y + 1)vπ ] cos[ ] 2N 2N

 One of the properties of the 2-D DCT is that it is separable meaning that it can be separated into a pair of 1-D DCTs. To obtain the 2-D DCT of a block a 1-D DCT is first performed on the rows of the block then a 1-D DCT is performed on the columns of the resulting block.  The same applies to the IDCT.  This process is illustrated below.

 Precalculate the DCT coefficients and scale them

Lab-Incharge

84

HOD

Digital Signal Processing Lab

Note that the values in the decimal format does not include the factor [Sqrt(2/n)=>sqrt(2/8)=>1/2]. The reason for this is that dividing the coefficients by 2 before converting to Q12 may result in some loss in precision. More precision can be obtained by ignoring this division and then multiplying by 211 (instead of 212 ) to convert to Q12. The reason for using Q12 instead of Q15 (as one would expect) is as follows. Referring to Equation [3], we notice that the DCT calculation involves a summation of N terms. Looking at the DCT coefficients in Figure 1, we observe that the terms entering in the summation may be close to 1. Thus, such summation may cause overflows. To avoid this, each term must be scaled down by 1/N. For N=8, this can be achieved by working in Q12 format instead of Q15 format.

Lab-Incharge

85

HOD

Digital Signal Processing Lab

HOW TO PROCEED:  Open Code Composer Studio, make sure the DSP kit is turned on.  Start a new project using ‘Project-new ‘ pull down menu, save it in a separate directory(c:\ti\myprojects) with name “image.pjt”.  From the File Menu  new  DSP/BIOS Configuration  select “dsk6713.cdb” and save it as “image1.cdb” and add it to the project.  Add the source files “main.c“ ,”dct.c” and “idct.c” in the project using ‘Projectadd files to project’ pull down menu.  Add the linker command file “MY_LNK_CMD.cmd” to your project  Copy the header files “scenary.h” and “dct.h” and paste it in your project folder.  Compile the program using the ‘Project-compile’ pull down menu or by clicking the shortcut icon on the left side of program window.  Load the program in program memory of DSP chip using the ‘File-load program’ pull down menu.  Run the program and observe output using image utility.

Lab-Incharge

86

HOD

Digital Signal Processing Lab

Main.c:
#include <stdio.h> #include <stdlib.h> #include "dct.h" #include "scenary.h" /* Header file containing input image as a 1D array */

#pragma DATA_SECTION (image_in,"ext_sdram") #pragma DATA_SECTION (image_out,"ext_sdram") /* 1D array to hold output image */ unsigned char image_out[IMAGE_SIZE]; /* 1D array to hold the current block */ short block[BLOCK_SIZE]; /* Q12 DCT coefficients (actual coefficient x 2^12 ) */ const short coe[8][8]= { 4096, 4096, 4096, 4096, 4096, 4096, 4096, 4096, 5681, 4816, 3218, 1130, -1130, -3218, -4816, -5681, 5352, 2217, -2217, -5352, -5352, -2217, 2217, 5352, 4816, -1130, -5681, -3218, 3218, 5681, 1130, -4816, 4096, -4096, -4096, 4096, 4096, -4096, -4096, 4096, 3218, -5681, 1130, 4816, -4816, -1130, 5681, -3218, 2217, -5352, 5352, -2217, -2217, 5352, -5352, 2217, 1130, -3218, 4816, -5681, 5681, -4816, 3218, -1130 }; extern void dct(void); extern void idct(void); void main() { int i,x; /* Perform block by block processing */ for(i=0;i<IMAGE_SIZE;i+=BLOCK_SIZE) { /* Get the block from the input image */ for(x=0;x<BLOCK_SIZE;++x) { block[x] = (short) image_in[i+x]; } /* Perform DCT on this block */ dct(); /* Perform IDCT on this block */ idct();

Lab-Incharge

87

HOD

Digital Signal Processing Lab

/* Store block to output image */ for(x=0;x<BLOCK_SIZE;++x) { if(block[x]<0) { image_out[i+x]=(unsigned char) (-block[x]); /* Quick fix for errors occuring due to negative a values occuring after IDCT! */ } else { image_out[i+x]=(unsigned char) block[x]; } } } //for (;;); } /* Wait */

dct.c:
/*********************************************************************/ /* dct.c Function to perform a 8 point 2D DCT /* DCT is performed using direct matrix multiplication /*********************************************************************/ #include "dct.h" extern unsigned char image_in[IMAGE_SIZE]; extern unsigned char image_out[IMAGE_SIZE]; extern short block[BLOCK_SIZE]; extern const short coe[8][8]; void dct(void) { int i,j,x,y; int value[8]; /* Perform 1D DCT on the columns */ for(j=0;j<8;j++) { for(y=0;y<8;++y) { value[y]=0; for(x=0;x<8;++x) { value[y] += (int)(coe[y][x]*block[j+(x*8)]); } } */ */

Lab-Incharge

88

HOD

Digital Signal Processing Lab
for(y=0;y<8;++y) { block[j+(y*8)] = (short)(value[y]>>12); } } /* Perform 1D DCT on the resulting rows */ for(i=0;i<64;i+=8) { for(y=0;y<8;++y) { value[y] = 0; for(x=0;x<8;++x) { value[y] += (int)(coe[y][x]*block[i+x]); } } for(y=0;y<8;++y) { block[i+y] = (short)(value[y]>>15); } } }

idct.c:
/*********************************************************************/ /* idct.c performs a 8 point 2D Inverse DCT function */ /*********************************************************************/ #include "dct.h" extern unsigned char image_in[IMAGE_SIZE]; extern unsigned char image_out[IMAGE_SIZE]; extern short block[BLOCK_SIZE]; extern const short coe[8][8]; void idct(void) { int i,j,x,y; int value[8]; /* Perform 1D IDCT on the columns */ for(j=0;j<8;j++) { for(y=0;y<8;++y) { value[y] = 0; for(x=0;x<8;++x) { value[y] += (int)(coe[x][y]*block[j+(x*8)]);

Lab-Incharge

89

HOD

Digital Signal Processing Lab
} } for(y=0;y<8;++y) { block[j+(y*8)] = (short)(value[y]>>12); } } /* Perform 1D IDCT on the resulting rows */ for(i=0;i<64;i+=8) { for(y=0;y<8;++y) { value[y] = 0; for(x=0;x<8;++x) { value[y] += (int)(coe[x][y]*block[i+x]); } } for(y=0;y<8;++y) { block[i+y] = (short)(value[y]>>15); } } }

MY_LNK_CMD.cmd:
-l imagecfg.cmd SECTIONS { mydata mycode > ext_sdram > } > SDRAM SDRAM SDRAM

Lab-Incharge

90

HOD

Digital Signal Processing Lab

image_in:

image_out:

Lab-Incharge

91

HOD

Digital Signal Processing Lab

Lab-Incharge

92

HOD

Sign up to vote on this title
UsefulNot useful