Top Banner

of 108

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

DIGITAL SIGNAL PROCESSING

LAB MANUALDEPARTMENT OF ELECTRICAL ENGINEERING FEDERAL URDU UNIVERSITY OF ARTS, SCIENCE & TECHNOLOGY, SECTOR G-7/1, ISLAMABAD

AUTUMN 2011

LIST OF EXPERIMENTSSECTION NO. 1 (Software) EXPERIMENT NO. 1: Signals in Matlab (Continuous time & Discrete time) EXPERIMENT NO. 2: Discrete Time Systems EXPERIMENT NO. 3: Sampling, A/D Conversion and D/A Conversion EXPERIMENT NO. 4: Z-Transform, DTFT EXPERIMENT NO. 5: Digital Filter Structure EXPERIMENT NO. 6: Digital Filter Design EXPERIMENT NO. 7: DFT EXPERIMENT NO. 8: Interpolation & Decimation SECTION NO. 2 (Hardware) EXPERIMENT NO. 9: Introduction to TMS320C6713 DSK EXPERIMENT NO. 10: Sine Generation using Eight points with DIP Switches Control on TMS320C6713 EXPERIMENT NO. 11: Performing Linear Convolution on TMS320C6713 DSK EXPERIMENT NO. 12: Performing Circular Convolution on TMS320C6713 DSK EXPERIMENT NO. 13: Performing N-point DFT on TMS320C6713 DSK EXPERIMENT NO. 14: FIR Filter on TMS320C6713 DSK EXPERIMENT NO. 15: Illustration of Aliasing Effect with Down-sampling on TMS320C6713 EXPERIMENT NO. 16: IIR Filter Implementation on TMS320C6713

2

SECTION-1

3

EXPERIMENT NO. 1SIGNALS IN MATLAB (CONTINUOUS TIME & DISCRETE TIME)

4

Signals are broadly classified into two classifications: a. Continuous Time Signals b. Discrete Time Signals A continuous time signal will be denoted by x(t), in which the variable t can represent any physical quantity. A discrete time signal will be denoted x[n], in which the variable n is integer value. In this lab we will learn to represent and operate on signals in MATLAB.

1. Continuous Time SignalsFor the following: Run the following lines and explain why the plots are different. Provide the snapshots of the plots for each step given below.close all, clear all t = 0:2*pi; plot(t,sin(t)) figure t = 0:0.2:2*pi; plot(t,sin(t)) figuret = 0:0.02:2*pi; plot(t,sin(t))

For the last graph, add a title and axis labels with:title('Continuous time signal plot') xlabel('t (Seconds)') ylabel('y(t)')

Change the axis with:axis([0 2*pi -1.2 1.2])

Put two plots on the same axist = 0:0.2:2*pi; plot(t,sin(t),t,sin(2*t))

Produce a plot without connecting the pointst = 0:0.2:2*pi; plot(t,sin(t),'.')

Try the following commandt = 0:0.2:2*pi; plot(t,sin(t),t,sin(t),'g.')

Question 1: What does g do?

2. Discrete Time SignalsUse stem to plot the discrete time signals. Provide the snapshots of the step below.close all clear all n = -10: 10; f = n >= 0; stem(n,f)

5

3. Elementary sequences in digital signal processingFor each part below, provide an example using any input and also provide the plots of input and output sequences using subplot. a. Unit sample sequence

% Generate a vector from -10 to 20 n = -10:20; % Generate the unit sample sequence u = [zeros(1,10) 1 zeros(1,20)]; % Plot the unit sample sequence stem(n,u); xlabel('Time index n'); ylabel('Amplitude'); title('Unit Sample Sequence'); axis([-10 20 0 2]);

b. Unit step sequence

y=ones(1,100); figure stem(n,y); title('UNIT STEP FUNCTION');

c. Real Valued Exponential sequence

n = 0:35; a = 1.2; K = 0.2; x = K*a.^+n; stem(n,x); xlabel('Time index n'); ylabel('Amplitude');

d. Complex valued exponential sequence

c = -(1/12)+(pi/6)*i; K = 2; n = 0:40; x = K*exp(c*n); subplot(2,1,1); stem(n,real(x)); xlabel('Time index n'); ylabel('Amplitude'); title('Real part'); subplot(2,1,2); stem(n,imag(x)); xlabel('Time index n'); ylabel('Amplitude'); title('Imaginary part');

e. Sinusoidal sequencen = 0:40; f = 0.1; phase = 0; A = 1.5;

6

arg = 2*pi*f*n - phase; x = A*cos(arg); stem(n,x); % Plot the generated sequence axis([0 40 -2 2]); grid; title('Sinusoidal Sequence'); xlabel('Time index n'); ylabel('Amplitude'); axis;

f. Operations on sequence: Shifting

In this operation each sample of x(n) is shifted by an amount k to obtain a shifted sequence y(n)

If we let m = n-k, then n = m+k the above operation is given by

For this we can use the following codes=1:100; subplot(2,1,1) stem(s) title('Sequence'); axis([0 100 0 100]); s_new=[zeros(1,10) s]; subplot(2,1,2) stem(s_new); axis([0 100 0 100]); title('Delayed sequence');

Folding

In this operation each sample of x(n) is flipped around its axis to obtain a folded sequence y(n)

For this the following code is shown. Exercise: Generate and plot each of the following sequences over the indicated interval. Provide the scripts used to generate the plots. Ex.1: a. b. Ex.2: Let x(n) = {1,2,3,4,5,6,7,6,5,4,3,2,1}, Determine and plot the following sequences. a. b.

7

EXPERIMENT NO. 2 (Discrete Time Systems)

8

DSP LAB # 3: Discrete Time SystemsTo provide an overview of discrete time signals and systems on MATLAB, to analyze various properties of discrete time systems and verify them on MATLAB. Introduction: Mathematically, a discrete-time system is described as an operator T[.] that takes a sequence x(n) called excitation and transforms it into another sequence y(n) (called response). Discrete time systems can be classified into two categories i) LTI systems ii) NON-LTI systems. A discrete system T[.] is a linear operator L[.] if and only if L[.] satisfies the principle of superposition, namely

A discrete system is time-invariant if shifting the input only causes the same shift in the output. A system is said to be bounded-input bounded-output (BIBO) stable if every bounded input produces a bounded output.

An LTI system is BIBO stable if and only if its impulse response is absolutely summable.

A system is said to be causal if the output at any istant depends only on the present & past values only. An LTI system is causal if and only if the impulse response is

1. Linearity and Non-Linearity:We now investigate the linearity property of a causal system of described by the following equation.

Following program simulates the above mentioned equation.clear all, close all n = 0:40; a = 2; b = -3; x1 = cos(2*pi*0.1*n); x2 = cos(2*pi*0.4*n); x = a*x1 + b*x2; num = [2.2 2.3 2.4]; den = [1 -0.4 0.75]; ic = [0 0]; % Set zero initial conditions y1 = filter(num,den,x1,ic); % Compute the output y1[n] y2 = filter(num,den,x2,ic); % Compute the output y2[n] y = filter(num,den,x,ic); % Compute the output y[n] yt = a*y1 + b*y2; d = y - yt; % Compute the difference output d[n] % Plot the outputs and the difference signal subplot (3,1,1) stem(n ,y); ylabel('Amplitude'); title('Output Due to Weighted Input'); subplot(3,1,2) stem(n,yt); ylabel('Amplitude'); title('Weighted Output');

9

Question 1: Run above program and compare y[n] obtained with weighted input with yt[n] obtained by combining the two outputs y1[n] and y2[n] with the same weights. Are these two sequences equal? Is this system linear? Excercise 1: Consider another system described by y[n] = x[n] x[n 1]. Modify given program to compute the output sequences y1[n], y2[n], and y[n] of the above system. Compare y[n] with yt[n]. Are these two sequences equal? Is this system linear?

2. Time-Invariant and Time-Varying Systems:We next investigate the time-invariance property. Following program simulates following difference equation

Two input sequence x[n] and x[n-D], are generated and corresponding output sequences y1[n],y2[n] are plotted.

close all, clear all n = 0:40; D = 10;a = 3.0;b = -2; x = a*cos(2*pi*0.1*n) + b*cos(2*pi*0.4*n); xd = [zeros(1,D) x]; num = [2.2 2.3 2.4]; den = [1 -0.4 0.75]; ic = [0 0];% Set initial conditions % Compute the output y[n] y = filter(num,den,x,ic); % Compute the output yd[n] yd = filter(num,den,xd,ic); % Compute the difference output d[n] d = y - yd(1+D:41+D); % Plot the outputs subplot(3,1,1) stem(n,y); ylabel('mplitude'); title('Output y[n]');grid; subplot(3,1,2) stem(n,yd(1:41)); ylabel('Amplitude'); title(['Output Due to Delayed Input x[n , num2str(D),]']);grid; subplot(3,1,3) stem(n,d); xlabel('Time index n'); ylabel('Amplitude'); title('Difference Signal');grid;

10

Exercise 2: Consider another system described by:

Modify program to simulate the above system and determine whether this system is time-invariant or not.

3. Impulse Response ComputationFollowing equation computes impulse response of following difference equation

% Compute the impulse response y close all, clear all N = 40; num = [2.2 2.3 2.4]; den = [1 -0.4 0.75]; y = impz(num,den,N); % Plot the impulse response stem(y); xlabel('Time index n'); ylabel('Amplitude'); Exercise 3: Write MATLAB program to generate and plot the step response of title('Impulse Response'); grid; a causal LTI system.

Using this program compute and plot the first 40 samples of the step response above mentioned LTI system.

4. Stability of LTI System:close all, clear all x = [1 zeros(1,40)];% Generate the input n = 0:40; % Coefficients of 4th-order system clf; num = [1 -0.8]; den = [1 1.5 0.9]; N = 200; h= impz(num,den,N+1); parsum = 0; for k = 1:N+1; parsum = parsum + abs(h(k)); if abs(h(k)) < 10^(-6), break, end end % Plot the impulse response n = 0:N; stem(n,h), xlabel('Time index n'); ylabel('Amplitude'); % Print the value of abs(h(k)) disp('Value =');disp(abs(h(k)));

Exercise 4: What is the discrete-time system whose impulse response is being determined by above program? Run program to generate the impulse response. Is this system stable? If |h[k]| is not smaller than 10-6 but the plot

11

shows a decaying impulse response, run the program again with a larger value of N. Exercise 5: Consider the following discrete-time system characterized by the difference equation Modify the program to compute and plot the impulse response of the above system. Is this system stable?

12

EXPERIMENT NO. 3 (SAMPLING, A/D CONVERSTION & D/A CONVERSION)

The Sampling Process in the Time Domain The purpose of this section is to study the relation in the time domain between a continuous-time signal xa (t) and the discrete-time signal x[1] generated by a periodic sampling of xa (t). 1. Sampling Signal of a Sinusoidal

In this project you will investigate the sampling of a continuous-time sinusoidal signal xa (t) at various sampling rates. Since MATLAB cannot strictly generate a continuous-time signal, you will generate a sequence {xa (nTH )} from xa (t) by sampling it at a very high rate, 1/TH , such that the samples are very close to % Program 4_1 each Illustration of the (nTH ) using the plot command will then look like a % other. A plot of xa Sampling Process continuous-time signal. % in the Time Domainclear all; close all; clc; t = 0:0.0005:1; f = 13; xa = cos(2*pi*f*t); subplot(2,1,1) plot(t,xa,'LineWidth',1.5); xlabel('Time, msec');ylabel('Amplitude'); title('Continuous-time signal x_{a}(t)'); axis([0 1 -1.2 1.2]) subplot(2,1,2); T = 0.1; n = 0:T:1; xs = cos(2*pi*f*n); k = 0:length(n)-1; stem(k,xs,'r'); xlabel('Time index n');ylabel('Amplitude'); title('Discrete-time signal x[n]'); axis([0 (length(n)-1) -1.2 1.2])

13

2. Aliasing Effect in the Time Domain In this project you will generate a continuous-time equivalent ya (t) of the discrete-time signal x[1] generated in Program P4_1 to investigate the relation between the frequency of the sinusoidal signal xa (t) and the sampling period. To generate the reconstructed signal ya (t) from x[1], we pass x[1] through an ideal lowpass filter that in turn can be implemented according to Eq. (4.1). If Eq. (4.1) is computed at closely spaced values of t, a plot of ya (t) will resemble a continuous-time signal. In order to implement this equation on MATLAB, the summation in Eq. (4.1) needs to be replaced with a finite sum, and hence we can generate only an approximation to the desired reconstructed continuoustime signal ya (t).

(4.1)% Program P4_2 % Illustration of Aliasing Effect in the Time Domain clear all; close all; clc; T = 0.1; f = 13; n = (0:T:1)'; xs = cos(2*pi*f*n); t = linspace(-0.5,1.5,500)'; ya = sinc((1/T)*t(:,ones(size(n))) - (1/T)*n(:,ones(size(t)))')*xs; plot(n,xs,'bo',t,ya, 'r','Linewidth',1.5);grid; xlabel('Time, msec');ylabel('Amplitude'); title('Reconstructed continuous-time signal y_{a}(t)'); axis([0 1 -1.2 1.2]); % Program P4_3 %3. Effect of Sampling in the Frequency Domain Illustration of the Aliasing Effect % Effect Frequency Domain Aliasing in the in the Frequency Domain close all; clc; The clear all; relation between the continuous-time Fourier transform (CTFT) of an t = 0:0.005:10; arbitrary band- limited continuous-time signal and the discrete-time Fourier xa = 2*t.*exp(-t); transform (DTFT) of the discrete-time signal is investigated next in this project. subplot(2,2,1) plot(t,xa);grid In order to convert a continuous-time signal xa (t) into an equivalent discretetime xlabel('Time, msec');ylabel('Amplitude'); in the frequency domain. To signal x[1], the former must be band-limited title('Continuous-time signal x_{a}(t)'); illustrate the effect of sampling in the frequency domain we choose an subplot(2,2,2) wa = 0:10/511:10; exponentially decaying continuous-time signal with a CTFT that is approximately ha = freqs(2,[1 2 1],wa); band-limited. plot(wa/(2*pi),abs(ha));grid; xlabel('Frequency, kHz');ylabel('Amplitude'); title('|X_{a}(j\Omega)|'); axis([0 5/pi 0 2]); subplot(2,2,3) T=1 ; n = 0:T:10; xs = 2*n.*exp(-n); k = 0:length(n)-1; stem(k,xs);grid; xlabel('Time index n');ylabel('Amplitude'); title('Discrete-time signal x[n]'); subplot(2,2,4) wd = 0:pi/255:pi; hd = freqz(xs,1,wd); 14 plot(wd/(T*pi), T*abs(hd));grid; xlabel('Frequency, kHz');ylabel('Amplitude'); title('|X(e^{j\omega})|'); axis([0 1/T 0 2])

4. Analog Lowpass Filters Analog lowpass filters are employed as anti-aliasing filters and as anti-imaging filters in the digital processing of continuous-time signals. Design of Analog Lowpass Filters The first step in the design of any of these filters is the determination of the filter order N and the appropriate cutoff frequency C. These parameters can be determined using the MATLAB commands buttord for the Butterworth filter, cheb1ord for the Type 1 Chebyshev filter, cheb2ord for the Type 2 Chebyshev filter, and ellipord for the elliptic filter. C is the 3-dB cutoff frequency for the Butterworth filter, the passband edge for the Type 1 Chebyshev filter, the stopband edge for the Type 2 Chebyshev filter, and the passband edge for the elliptic filter. For the design of filters MATLAB commands are butter for the Butterworth filter, cheby1 for the Type 1 Chebyshev filter, cheby2 for the Type 2 Chebyshev filter, and ellip for the elliptic filter. Program P4 4 can be used for the design of the Butterworth lowpass filter.% Program P4_4 % Design of Analog Lowpass Filter clear all; close all; clc; Fp = 3500;Fs = 4500; Wp = 2*pi*Fp; Ws = 2*pi*Fs; [N, Wn] = buttord(Wp, Ws, 0.5, 30,'s'); [b,a] = butter(N, Wn, 's'); wa = 0:(3*Ws)/511:3*Ws; h = freqs(b,a,wa); plot(wa/(2*pi), 20*log10(abs(h)),'r', 'LineWidth',1.5);grid xlabel('Frequency, Hz');ylabel('Gain, dB'); title('Gain response'); axis([0 3*Fs -60 5]);

15

Gain response 0

-10

-20 Gain, dB

-30

-40

-50

-60

0

2000

4000

6000 8000 Frequency, Hz

10000

12000

Excercise 1 2 3 Run Program P4_1 to generate both the continuous-time signal and its sampled version, and display them. What is the frequency in Hz of the sinusoidal signal? What is the sampling period in seconds? Run Program P4_1 for four other values of the sampling period with two lower and two higher than that listed in Program P4_1. Comment on your results. Repeat Program P4 1 by changing the frequency of the sinusoidal signal to 3 Hz and 7 Hz, respectively. Is there any difference between the corresponding equivalent discrete-time signals and the one generated in Question Q4.1? If not, why not? Run Program P4_2 to generate both the discrete-time signal x[1] and its continuous- time equivalent ya (t), and display them. What is the range of t and the value of the time increment in Program P4_2? What is the range of t in the plot? Change the range of t so as to display the full range ya (t) being computed in the above program and run Program P4_2 again. Comment on the plot generated after this change. Restore the original display range and repeat Program P4_2 by changing the frequency of the sinusoidal signal to 3 Hz and 7 Hz, respectively. Is there any difference between the corresponding equivalent discrete-time signals and the one generated in Question Q 5? If not, why not? What is the continuous-time function xa (t) in Program P4_3? How is the CTFT of xa (t) being computed? Run Program P4_3 to generate and display both the discrete-time signal and its continuous-time equivalent, and their respective Fourier transforms. Is there any visible effect of aliasing?

4

5

6

7

8

9

16

10 Repeat Program P4_3 by increasing the sampling period to 1.5. Is there any visible effect of aliasing? 11 Modify Program P4 3 for the case of xa (t) = et2 and Q 9 and Q 10.2

12 What are the passband ripple Rp in dB and the minimum stopband attenuation Rs in dB in Program P5 4? What are the passband and the stopband edge frequencies in Hz? 13 Run Program P4_4 and display the gain response. Does the filter as designed meet the given specifications? What is the filter order N and the 3-dB cutoff frequency in Hz of the filter as designed? 14 Using cheb1ord and cheby1 modify Program P4_4 to design a Type 1 Chebyshev lowpass filter meeting the same specifications as in Program P4_4. Run the modified program and display the gain response. Does the filter as designed meet the given specifications? What is the filter order N and the passband edge frequency in Hz of the filter as designed? 15 Using cheb2ord and cheby2 modify Program P4_ 4 to design a Type 2 Chebyshev lowpass filter meeting the same specifications as in Program P4_4. Run the modified program and display the gain response. Does the filter as designed meet the given specifications? What is the filter order N and the stopband edge frequency in Hz of the filter as designed? 16 Using ellipord and ellip modify Program P4_ 4 to design an elliptic lowpass filter meeting the same specifications as in Program P7_ 4. Run the modified program and display the gain response. Does the filter as designed meet the given specifications? What is the filter order N and the passband edge frequency in Hz of the filter as designed?

17

EXPERIMENT NO. 4 (Z-TRANSFORM & DFT)

18

z-TransformAs in the case of the discrete-time Fourier transform, we restrict our attention here to a transform G(z) of a sequence g[n] that is a rational function of the complex variable z1 and expressed in the form of a ratio of polynomials in z1 or in factored form as shown below.

Factored form:

Some of the operations that are of interest in practice are as follows. (1) Evaluate the z-transform G(z) on the unit circle, that is, evaluate G(ej ) (2) Develop the pole-zero plot of G(z) (3) Develop the factored form of G(z) (4) Determine the inverse-transform g[n] of G(z) (5) Make a partial-fraction expansion of G(z). In the next two projects you will learn how to perform the above operations using MATLAB. Project 6.2 Analysis of z-Transforms

The function freqz can be used to evaluate the values of a rational z-transform on the unit circle. To this end, Program P6_1 can be used without any modifications,% Program P6_7 % Evaluation of the zTransform clear all; close all; clc % Compute the frequency samples w = -4*pi:8*pi/511:4*pi; num = [2 1];den = [1 -0.6]; h = freqz(num, den, w); % Plot the zTransform subplot(2,1,1) plot(w/pi,real(h));grid title('Real part of H(z)') xlabel('\omega /\pi'); ylabel('Amplitude'); subplot(2,1,2) % plot the imaginary part in the same way your self and give it title pause subplot(2,1,1) % In this subplot plot magnitude of zTransform your self subplot(2,1,2) % In this subplot plot magnitude of zTransform your self

Using Program P6_7 evaluate the following z-transform on the unit circle:

(6.1) The pole-zero plot of a rational z-transform G(z) can be readily obtained using the function zplane. 1. There are two versions of this function. If the z-transform is given in the form of a rational function as in Eq. (6.1), the command to use is zplane(num, den) where num and den are row vectors containing the coefficients of the numerator and denominator polynomials of G(z) in ascending powers of z1. 2. On the other hand, if the zeros and poles of G(z) are given, the command to use is zplane(zeros, poles) where zeros and poles are column vectors. In the pole-zero plot generated by MATLAB, the 19

location of a pole is indicated by the symbol and the location of a zero is indicated by the symbol . The function tf2zp can be used to determine the zeros and poles of a rational ztransform G(z) . The program statement to use is [z, p, k] = tf2zp(num,den) where num and den are row vectors containing the coefficients of the numerator and denominator polynomials of G(z) in ascending powers of z1 and the output file contains the gain constant k and the computed zeros and poles given as column vectors z and p, respectively. The factored form of the z-transform can be obtained from the zero-pole description using the function sos = zp2sos(z,p,k). The function computes the coefficients of each second-order factor given as an L 6 matrix sos where

where the lth row contains the coefficients of the numerator and the denominator of the lth second-order factor of the z-transform G(z):

The reverse process of converting a z-transform given in the form of zeros, poles, and the gain constant to a rational form can be implemented using the function zp2tf. The program statement to use is [num,den] = zp2tf(z,p,k).

Project 6.3

Inverse z-Transform

The inverse g[n] of a rational z-transform G(z) can be computed using MATLAB in basi-cally two different ways . To this end, it is necessary to know a priori the ROC of G(z). The function impz provides the samples of the time-domain sequence, which is assumed to be causal. There are three versions of this function: [g,t] = impz(num,den), [g,t] impz(num,den, L), and [g,t] = impz(num,den, L, FT), where num and den are row vectors containing the coefficients of the numerator and denominator polynomials of G(z) in ascending powers of z1, L is the desired number of the samples of the inverse transform, g is the vector containing the samples of the inverse transform starting with the sample at n = 0, t is the length of g, and FT is the specified sampling frequency in Hz with default value of unity. A closed-form expression for the inverse of a rational z-transform can be obtained by first performing a partial-fraction expansion using the function residuez and then determining the inverse of each term in the expansion by looking up a table of z-transforms. The function residuez can also be used to convert a z-transform given in the form of a partial-fraction expansion to a ratio of polynomials in z1.

Discrete-Time Fourier TransformThe discrete-time Fourier transform (DTFT) X(ej ) of a sequence x[n] is a continuous function of . Since the data in MATLAB is in vector form, X(ej ) can only be evaluated at a prescribed set of discrete frequencies. Moreover, only a class of the DTFT that is expressed as a rational function in ej in the form

(5.1) 20

can be evaluated. In the following two projects you will learn how to evaluate and plot the DTFT and study certain properties of the DTFT using MATLAB. DTFT Computation The DTFT X(ej ) of a sequence x[n] of the form of Eq. (5.1) can be computed easily at a prescribed set of L discrete frequency points = using the MATLAB function freqz. Since X(ej ) is a continuous function of , it is necessary to make L as large as possible so that the plot generated using the command plot provides a reasonable replica of the actual plot of the DTFT. In MATLAB, freqz computes the L-point DFT of the sequences {p0 p1 . . . PM } and {d0 d1 . . . dM }, and then forms their ratio to arrive at X(ejl ), l = 1, 2, . . . , L. For faster computation, L should be chosen as a power of 2, such as 256 or 512. Program P5_1 can be used to evaluate and plot the DTFT of the form of Eq. (5.1). Program P5_1 %% Evaluation of the DTFT clear all; close all; clc % Compute the frequency samples of the DTFT w = -4*pi:8*pi/511:4*pi; num = [2 1];den = [1 -0.6]; h = freqz(num, den, w); % Plot the DTFT subplot(2,1,1) plot(w/pi,real(h));grid title('Real part of H(e^{j\omega})') xlabel('\omega /\pi'); ylabel('Amplitude'); subplot(2,1,2) % plot the imaginary part in the same way your self and give it title pause subplot(2,1,1) % In this subplot plot magnitude of FFT your self subplot(2,1,2) % In this subplot plot magnitude of FFT your self

DTFT Properties Most of the properties of the DTFT can be verified using MATLAB. Since all data in MATLAB have to be finite-length vectors, the sequences being used to verify the properties are thus restricted to be of finite length. Program P5_2 can be used to verify the time-shifting property of the DTFT.% Program P5_2 % Time-Shifting Properties of DTFT close all; clear all; clc w = -pi:2*pi/255:pi; wo = 0.4*pi;D=10; num=[1 2 3 4 5 6 7 8 9]; h1 = freqz(num, 1, w); h2 = freqz([zeros(1,D) num], 1, w); subplot(2,2,1) plot(w/pi,abs(h1));grid title('Magnitude Spectrum of Original Sequence') subplot(2,2,2) plot(w/pi,abs(h2));grid title('Magnitude Spectrum of Time-Shifted Sequence') subplot(2,2,3) plot(w/pi,angle(h1));grid title('Phase Spectrum of Original Sequence') subplot(2,2,4) plot(w/pi,angle(h2));grid title('Phase Spectrum of Time-Shifted Sequence')

21

Magnitude Spectrum of Original Sequence Magnitude Spectrum of Time-Shifted Sequence 60 60

40

40

20

20

0 -1

-0.5

0

0.5

1

0 -1

-0.5

0

0.5

1

Phase Spectrum of Original Sequence 4 2 0 -2 -4 -1

Phase Spectrum of Time-Shifted Sequence 4 2 0 -2 -4 -1

-0.5

0

0.5

1

-0.5

0

0.5

1

Program P5_3 can be used to verify the frequency-shifting property of the DTFT.% Program P5_3 % Frequency-Shifting Properties of DTFT clear all; close all; clc w = -pi:2*pi/255:pi; wo = 0.4*pi; num1=[13579111315 17]; L = length(num1); h1 = freqz(num1, 1, w); n = 0:L-1; num2 = exp(wo*i*n).*num1; h2 = freqz(num2, 1, w); subplot(2,2,1) plot(w/pi,abs(h1));grid title('Magnitude Spectrum of Original Sequence') subplot(2,2,2) plot(w/pi,abs(h2));grid title('Magnitude Spectrum of Frequency-Shifted Sequence') subplot(2,2,3) plot(w/pi,angle(h1));grid title('Phase Spectrum of Original Sequence') subplot(2,2,4) plot(w/pi,angle(h2));grid title('Phase Spectrum of Frequency-Shifted Sequence')1.3579 1.3579 1.3579 1.3579 1.3579 1.3579 1.3579 1.3579 1.3579 -1 -0.8 -0.6 -0.4 -0.2 0 0.2 0.4 0.6 0.8 1 x 1010

Magnitude Spectrum of Original Sequence 1.3579 1.3579 1.3579 1.3579 1.3579 1.3579 1.3579 1.3579

x 10

10

Magnitude Spectrum of Frequency-Shifted Sequence

1.3579 -1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

1.5 1 0.5 0 -0.5 -1

x 10

-9

Phase Spectrum of Original Sequence 1.5 1 0.5 0 -0.5 -1

x 10

-9

Phase Spectrum of Frequency-Shifted Sequence

-1.5 -1

22 -0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

-1.5 -1

-0.8

-0.6

-0.4

-0.2

0

0.2

0.4

0.6

0.8

1

Program P5_4 can be used to verify the convolution property of the DTFT.% Program P5_4 % Convolution Property of DTFT close all; clear all; clc w = -pi:2*pi/255:pi; x1=[1 3 5 7 9 11 13 15 17]; x2=[1 -23 -21]; % convolve x1 and x2 yourself h1 = freqz(x1, 1, w); % compute freqz of x2 at w points and save it in h2 yourself hp = h1.*h2; h3 = freqz(y,1,w); subplot(2,2,1) plot(w/pi,abs(hp));grid title('Product of Magnitude Spectra') subplot(2,2,2) plot(w/pi,abs(h3));grid title('Magnitude Spectrum of Convolved Sequence') subplot(2,2,3) plot(w/pi,angle(hp));grid title('Sum of Phase Spectra') subplot(2,2,4) plot(w/pi,angle(h3));grid title('Phase Spectrum of Convolved Sequence')

Program P5_5 can be used to verify the modulation property of the DTFT.% Program P5_5 % Modulation Property of DTFT close all; clear all; clc w = -pi:2*pi/255:pi; x1=[1 3 5 7 9 11 13 15 17]; x2=[1 -1 1 -1 1 -1 1 -1 1]; y = x1.*x2; h1 = freqz(x1, 1, w); h2 = freqz(x2, 1, w); % similarly compute freqz of y and save it in h3 yourself subplot(3,1,1) plot(w/pi,abs(h1));grid title('Magnitude Spectrum of First Sequence') subplot(3,1,2) plot(w/pi,abs(h2));grid title('Magnitude Spectrum of Second Sequence') subplot(3,1,3) Program P5_6 can be used to verify the time-reversal property of the DTFT. plot(w/pi,abs(h3));grid title('Magnitude Spectrum of Product Sequence')

% Program P5_6 % Time-Reversal Property of DTFT close all; clear all; clc w = -pi:2*pi/255:pi; num=[1 2 3 4]; L = length(num)-1; h1 = freqz(num, 1, w); h2 = freqz(fliplr(num), 1, w); h3 = exp(w*L*1i).*h2; subplot(2,2,1) plot(w/pi,abs(h1));grid title('Magnitude Spectrum of Original Sequence') subplot(2,2,2) plot(w/pi,abs(h3));grid title('Magnitude Spectrum of Time-Reversed Sequence') subplot(2,2,3) plot(w/pi,angle(h1));grid title('Phase Spectrum of Original Sequence') subplot(2,2,4) plot(w/pi,angle(h3));grid title('Phase Spectrum of Time-Reversed Sequence')

23

Magnitude Spectrum of Original Sequence Magnitude Spectrum of Time-Reversed Sequence 10 10 8 6 4 2 -1 8 6 4 2 -1

-0.5

0

0.5

1

-0.5

0

0.5

1

Phase Spectrum of Original Sequence 4 2 0 -2 -4 -1

Phase Spectrum of Time-Reversed Sequence 4 2 0 -2 -4 -1

-0.5

0

0.5

1

-0.5

0

0.5

1

5.1 Lab Task1. What is the expression of the DTFT being evaluated in Program P5_1? What is the function of the MATLAB command pause? 2. Run Program P5_1 and compute the real and imaginary parts of the DTFT, and the magnitude and phase spectra. Is the DTFT a periodic function of ? If it is, what is the period? Explain the type of symmetries exhibited by the four plots. Modify Program P5_1 to evaluate in the range 0 the following DTFT:

3.

and repeat Question 2. Comment on your results. Can you explain the jump in the phase spectrum? The jump can be removed using the MATLAB command, unwrap. Evaluate the phase spectrum with the jump removed. 4. Modify ProgramP3 1 to evaluate the DTFT of the following nite-length sequence: g[n] = [1 3 5 7 9 11 13 15 17] and repeat Question 2. Comment on your results. Can you explain the jumps in the phase spectrum? How would you modify Program P5_1 to plot the phase in degrees? 5. Modify Program P5_2 by adding appropriate comment statements and program statements for labeling the two axes of each plot being generated by the program. Which parameter controls the amount of time-shift? 6. Run the modified program P5_2 and comment on your results. 7. Repeat the above question for a different value of the time-shift. 8. Modify Program P5_3 by adding appropriate comment statements and program statements for labeling the two axes of each plot being generated by the program. Which parameter controls the amount of frequency-shift? 9. Repeat Question Q 8 for a different value of the frequency-shift. 24

10.Repeat Question Q 9 for two different sequences of varying lengths and two different frequency-shifts. 11.Modify Program P5_4 by adding appropriate comment statements and program statements for labeling the two axes of each plot being generated by the program. 12.Run the modified program and comment on your results. 13.Repeat the above Question for two different sets of sequences of varying lengths. 14.Modify Program P5_5 by adding appropriate comment statements and program statements for labeling the two axes of each plot being generated by the program. 15.Modify Program P5_6 by adding appropriate comment statements and program statements for labeling the two axes of each plot being generated by the program. Explain how the program implements the time-reversal operation. 16.Run the modified program and comment on your results.

25

EXPERIMENT NO. 5 (DIGITAL FILTER STRUCTURE)

26

A structural representation using interconnected basic building blocks is the first step in the hardware or software implementation of an LTI digital filter. The structural representation provides the relations between some pertinent internal variables with the input and the output that in turn provide the keys to the implementation. This lab considers the development of structural representations of causal IIR and FIR transfer functions in the form of block diagrams.

7.1 Realization of FIR Transfer FunctionsProject 8.1 Cascade Realization

The factored form of a causal FIR transfer function H (z) of order M 1, as given in Eq. (8.1) can be determined from its polynomial form representation given by Eq. (8.2) which can then be utilized to realize H (z) in a cascade form. To this end, a modified form of Program P6 1 that uses the function zp2sos can be employed.

(8.1)

% Program P8_1 % Conversion of a rational transfer function % to its factored form num = input(Numerator coefficient vector = ); den = input(Denominator coefficient vector = ); [A, B] = eqtflength(num, den); [z,p,k] = tf2zp(A, B); sos = zp2sos(z,p,k)

(8.2)

7.2 Realization of IIR Transfer FunctionsProject 8.2 Cascade and Parallel Realizations

The factored form of a causal IIR transfer function H (z) of order N as given in Eq. (8.3) can be determined from its rational form representation given by Eq. (8.4), which then can be used to realize H (z) in a cascade form. To this end, Program P6 1 can be employed.

(8.3)

(8.3) There are two parallel-form realizations of a causal IIR transfer function. Parallel Form I is based on its partial-fraction expansion in z 1 as in Eq. (8.4), which can be obtained using MATLAB function residuez . Parallel Form II is based on the partial-fraction expansion in z as in Eq. (8.5), which is obtained using the function residue . Program P8_2 develops both types of parallel realizations.

(8.4) In the above, for a real pole 2k = 1k = 0. 27

H (z) expressed in the parallel form II

(8.5)% Program P8_2 % Parallel Form Realizations of an IIR Transfer Function num = input(Numerator coefficient vector = ); den = input(Denominator coefficient vector = ); [r1,p1,k1] = residuez(num,den); [r2,p2,k2] = residue(num,den); disp(Parallel Form I) disp(Residues are);disp(r1); disp(Poles are at);disp(p1); disp(Constant value);disp(k1); disp(Parallel Form II) disp(Residues are);disp(r2); disp(Poles are at);disp(p2); disp(Constant value);disp(k2);

7.3 Lab Task1 Using Program P8_1, develop a cascade realization of the following FIR transfer function:

Sketch the block diagram of the cascade realization. phase transfer function? 2

Is H1 (z) a linear-

Using Program P8 1 develop a cascade realization of the following FIR transfer function:

Sketch the block diagram of the cascade realization. Is H2(z)

a linear-

phase transfer function? Develop a cascade realization of H 2 (z) with only 4 multipliers. Show the block diagram of the new cascade structure. 3 Using Program P8_ 1, develop a cascade realization of the following causal IIR transfer function:

Sketch the block diagram of the cascade realization 4 Using Program P8_1, develop a cascade realization of the following causal IIR transfer function:

Sketch the block diagram of the cascade realization. 5 Using Program P8_2, develop the two different parallel-form realizations of the causal IIR transfer function of the equation given in Question 3. Sketch the block diagrams of both realizations. Using Program P8_2, develop the two different parallel-form realizations of the causal IIR transfer function of the equation given in Question 4. Sketch the block diagrams of both realizations.

6

28

EXPERIMENT NO. 6 (DIGITAL FILTER DESIGN)

29

1.1 FIR Filter DesignConceptually the simplest approach to FIR filter design is to simply truncate to a finite number of terms the doubly infinite-length impulse response coefficients obtained by computing the inverse discrete-time Fourier transform of the desired ideal frequency response. However, a simple truncation results in an oscillatory behavior in the respective magnitude response of the FIR filter, which is more commonly referred to as the Gibbs phenomenon.The Gibbs phenomenon can be reduced by windowing the doubly infinite-length impulse response coefficients by an appropriate finite-length window function. The functions fir1 and fir2 can be employed to design windowed FIR digital filters in MATLAB. Both functions yield a linear-phase design. The function fir1 can be used to design conventional lowpass, highpass, bandpass, and bandstop linear-phase FIR filters. The commandb = fir1(N,Wn)

returns in vector b the impulse response coefficients, arranged in ascending powers of z 1 , of a lowpass or a bandpass filter of order N for an assumed sampling frequency of 2 Hz. For lowpass design, the normalized cutoff frequency is specified by a scalar W n a number between 0 and 1. For bandpass , design, W n is a two-element vector [Wn1, Wn2] containing the specified passband edges where 0 < Wn1 < Wn2 < 1. The commandb = fir1(N,Wn,high)

with N an even integer, is used for designing a highpass filter. The commandb = fir1(N,Wn,stop)

with W n a two-element vector, is employed for designing a bandstop FIR filter. If none is specified, the Hamming window is employed as a default. The commandb = fir1 (N, Wn, t p r ae)

makes use of the specified window coefficients of length N+ 1 in the vector taper . However, the window coefficients must be generated a priori using an appropriate MATLAB function such as blackman, hamming, hanning, chebwin, or kaiser . The commands to use are of the following forms:taper taper = blackman(N) = chebwin(N) taper taper = hamming(N) = kaiser(N, taper beta) = hanning(N)

The function fir2 can be used to design linear-phase FIR filters with arbitrarily shaped magnitude responses. In its basic form, the command isb = fr(, i2N ft, ps mval)

which returns in the vector b of length N+ 1 the impulse response coefficients, arranged in ascending powers of z 1 . fp ts is the vector of specified frequency points, arranged in an increasing order, in the range 0 to 1 with the first frequency point being 0 and the last frequency point being 1. As before, the sampling frequency is assumed to be 2 Hz. mval is a vector of specified magnitude values at the specified frequency points and therefore must also be of the same length as fp . The Hamming window is used as a default. To ts make use of other windows, the command to use is

30

b

= fr(, i2N

ft, ps

mval,taper)

where the vector taper

contains the specified window coefficients.

A more widely used linear-phase FIR filter design is based on the Parks McClellan algorithm, which results in an optimal FIR filter with an equiripple weighted error (w) defined in Eq. (9.1). (9.1) It makes use of the Remez optimization algorithm and is available in MATLAB as the function firpm. This function can be used to design any type of single-band or multiband filter, the differentiator, and the Hilbert transformer. In its basic form, the commandb = firpm(N,fpts,mval)

returns a vector b of length N+ 1 containing the impulse response coefficients of the desired FIR filter in ascending powers of z 1 . fp ts is the vector of specified frequency points, arranged in increasing order, in the range 0 to 1 with the first frequency point being 0 and the last frequency point being 1. As before, the sampling frequency is assumed to be 2 Hz. The desired magnitudes of the FIR filter frequency response at the specified band edges are given by the vector mval, with the elements given in equal-valued pairs. The desired magnitudes between two specified consecutive frequency points f(k ) and f(k+1) are determined according to the following rules. For k odd, the val(k), fp ts(k) } and magnitude is a line segment joining the points {m {mval(k+1), fpts(k+ 1) }, whereas, for k even, it is unspecified with the frequency range [fp (k ts ), fpts(k+ 1)] being a transition or dont care region. The vectors fp ts and mval must be of the same length with the length being even. Figure 7.4 illustrates the relationship between the vectors fp ts and mval given byft ps mval = [0 0.2 0.4 0.7 0.8 1.0] = [0.5 0.5 1.0 1.0 0.3 0.3 ]

FIGURE 9.1: ILLUSTRATION OF RELATIONSHIP BETWEEN VECTORS FPTS AND MVAL

The desired magnitude responses in the passband(s) and the stopband(s) can be weighted by an additional vector wgts included as the argument of the function firpm . The function can be used to design equiripple Types 1, 2, 3, and 4 linear-phase FIR filters. Types 1 and 2 are the default designs for order N even and odd, respectively. Types 3 (N even) and 4 (N odd) are used for specialized filter designs, the Hilbert transformer and the differentiator. To design these two types of FIR filters the fiags h e ilb rt and d re tia r iffe n to are used for ftype in the last two versions of firpm. The command 31

b = firpm(N,fpts,mval,wgts)

is used to design an FIR filter weighted in each band by the elements of the weight vector wgts whose length is thus half that of fp . The elements of ts the vector wgts can be determined from the specified passband and stopband ripples by dividing the maximum ripple value by the ripple values. To design a Hilbert transformer or a differentiator, use the formsfirpm(N,fpts,mval,ftype) firpm(N,fpts,mval,wgts,ftype)

where ftype is the string h e ilb rt or d re tia r iffe n to . In the case of a Hilbert transformer design, the smallest element in fp ts should not be a 0. The order N of the FIR filter to meet the given specifications can be estimated using either Kaisers formula of Eq. (9.2).

(9.2)The MATLAB function kaiord given below implements Kaisers formula:function N = kaiord(Fp, Fs, dp, ds, FT) % Computation of the length of a linear-phase % FIR multiband filter using Kaisers formula % dp is the passband ripple % ds is the stopband ripple % Fp is the passband edge in Hz % Fs is the stopband edge in Hz % FT is the sampling frequency in Hz. % If none specified default value is 2 % N is the estimated FIR filter order if nargin == 4, F T=2 ; end if length(Fp) > 1, TBW = min(abs(Fp(1) - Fs(1)), abs(Fp(2) - Fs(2))); else TBW = abs(Fp - Fs); end num = -20*log10(sqrt(dp*ds)) - 13; den = 14.6*TBW/FT; N = ceil(num/den);

The function kaiserord in the Signal Processing Toolbox can also be used for estimating the filter order using Kaisers formula. It can be used in one of the following forms:[N, Wn, beta, ftyp e] [N, Wn, beta, ftyp e] c = kaiserord(fedge, = kaiserord(fedge, = kaiserord(fedge, aval, dev, FT, aval, aval, el) cl dev) dev,

FT)

where FT is the sampling frequency in Hz whose default value is 2 Hz if not specified; fedge is a vector of bandedge frequencies in Hz, in increasing order between 0 and FT/2; and aval is a vector specifying the desired values of the magnitude response at the specified bandedges given by fedge. The length of fedge is 2 less than twice the length of aval and therefore must be even. dev is a vector of maximum deviations or ripples in dB allowable for each band. If the deviations specified are unequal, the smallest one is used for all bands. The output data are in the desired format for use in fir1 , with normalized bandedges W n and the parameter beta used for computing the window coefficients as given in Eq. (7.36). The string ftype specifies the filter type for 32

fir1 . It is high for highpass filter design, and stop for bandstop filter design. The last form of kaiserord specifies a cell array whose elements are parameters to fir1 . The MATLAB function firpmord implements the formula of Eq. (7.8). It can be used in one of the following forms:

[N,fts,mval,wgts] [N,fts,mval,wgts]

= firpmord(fedge,aval,dev) = firpmord(fedge,aval,dev,FT)

where FT is the sampling frequency in Hz whose default value is 2 Hz if not specified, fedge is a vector of bandedge frequencies in Hz, in increasing order between 0 and FT/2; and aval is a vector specifying the desired values of the magnitude response at the specified bandedges given by fedge. The length of fedge is 2 less than twice the length of aval and therefore must be even. dev is a vector of maximum deviations or ripples in dB allowable for each band. A third form of firpmord is given byc = firpmord(fedge,aval,dev,FT, el) cl

and specifies a cell array whose elements are the parameters to firpm. In some cases, the order N determined using either method may not result in an FIR filter meeting the original specifications. If it does not, the order should either be increased or decreased by 1 gradually until the specifications are met. Moreover, the order estimates may be highly inaccurate for very narrowband or very wideband FIR filters.

1.2 Lab task1.2..1 Using MATLAB determine the lowest order of a digital IIR lowpass filter of all four types. The specifications are as follows: sampling rate of 40 kHz, passband edge frequency of 4 kHz, stopband edge frequency of 8 kHz, passband ripple of 0.5 dB, and a minimum stopband attenuation of 40 dB. Comment on your results. Using MATLAB determine the lowest order of a digital IIR highpass filter of all four types. The specifications are as follows: sampling rate of 3,500 Hz, passband edge frequency of 1,050 Hz, stopband edge frequency of 600 Hz, passband ripple of 1 dB, and a minimum stopband attenuation of 50 dB. Comment on your results. Using MATLAB determine the lowest order of a digital IIR bandpass filter of all four types. The specifications are as follows: sampling rate of 7 kHz, passband edge frequencies at 1.4 kHz and 2.1 kHz, stopband edge frequencies at 1.05 kHz and 2.45 kHz, passband ripple of 0.4 dB, and a minimum stopband attenuation of 50 dB. Comment on your results. Using MATLAB determine the lowest order of a digital IIR bandstop filter of all four types. The specifications are as follows: sampling rate of 12 kHz, passband edge frequencies at 2.1 kHz and 4.5 kHz, stopband edge frequencies at 2.7 kHz and 3.9 kHz, passband ripple of 0.6 dB, and a minimum stopband attenuation of 45 dB. Comment on your results.

1.2..2

1.2..3

1.2..4

33

1.2..5

Design the Butterworth bandstop filter by running Program P9_1. Write down the exact expression for the transfer function generated. What are the filter specifications? Does your design meet the specifications? Using MATLAB, compute and plot the filters unwrapped phase response and the group delay response. Modify Program P9_1 to design a Type 1 Chebyshev lowpass filter meeting the given specifications of Question Q 1. Write down the exact expression for the transfer function generated. Does your design meet the specifications? Using MATLAB, compute and plot the filters unwrapped phase response and the group delay response. Modify Program P9_1 to design a Type 2 Chebyshev highpass filter meeting the specifications given in Question Q 2. Write down the exact expression for the transfer function generated. Does your design meet the specifications? Using MATLAB, compute and plot the filters unwrapped phase response and the group delay response. Modify Program P9_1 to design an elliptic bandpass filter meeting the specifications given in Question Q 3. Write down the exact expression for the transfer function generated. Does your design meet the specifications? Using MATLAB, compute and plot the filters unwrapped phase response and the group delay response. Using the function kaiord , estimate the order of a linear-phase lowpass FIR filter with the following specifications: passband edge = 2 kHz, stopband edge = 2.5 kHz, passband ripple p = 0.005, stopband ripple S = 0.005, and sampling rate of 10 kHz. What are the purposes of the commands c il and nargin in the function e kaiord ? Repeat the above question for the following cases: (a) sampling rate of 20 kHz, (b) p = 0.002 and S = 0.002, and (c) stopband edge = 2.3 kHz. Compare the filter length obtained in each case with that obtained in the above question. Comment on the effect of the sampling rate, ripples, and the transition bandwidth on the filter order. Repeat Question Q 9 using the function kaiserord . Compare the value of the filter order obtained with that obtained in Question Q 9. Using the function kaiord , estimate the order of a linear-phase bandpass FIR filter with the following specifications: passband edges = 1.8 and 3.6 kHz, stopband edges 1.2 and 4.2 kHz, passband ripple p = 0.1, stopband ripple S = 0.02, and sampling rate of 12 kHz. Using the function fir1 , design a linear-phase FIR lowpass filter meeting the specifications given in Question Q 9 and plot its gain and phase responses. Use the order estimated using Kaisers formula in Question Q 9. Show the filter coefficients in a tabular form. Does your design meet the specifications? If it does not, adjust the filter order until the design meets the specifications. What is the order of the filter meeting the specifications? Repeat the above question using each of the following windows: Hanning, Blackman, and DolphChebyshev windows.

1.2..6

1.2..7

1.2..8

1.2..9

1.2..10

1.2..11

1.2..12

1.2..13

1.2..14

34

1.2..15

Using fir2 design an FIR filter of order 95 with three different constant magnitude levels: 0.4 in the frequency range 0 to 0.25, 1.0 in the frequency range 0.3 to 0.45, and 0.8 in the frequency range 0.5 to 1.0. Plot the magnitude response of the filter designed. Does your design meet the specifications?

EXPERIMENT NO. 7 (DISCRETE FOURIER TRANSFORM)35

The discrete Fourier transform (DFT) X[k] of a finite-length sequence x[n] can be easily computed in MATLAB using the function fft. There are two versions of this function. fft(x) computes the DFT X[k] of the sequence x[n] where the length of X[k] is the same as that of x[n]. fft(x,L) computes the L-point DFT of a sequence x[n] of length N where L N . If L > N , x[n] is zero-padded with L N trailing zero-valued samples before the DFT is computed. The inverse discrete Fourier transform (IDFT) x[n] of a DFT sequence X[k] can likewise be computed using the function ifft, which also has two versions. Project 6.1 DFT Properties

Two important concepts used in the application of the DFT are the circular-shift of a sequence and the circular convolution of two sequences of the same length. As these operations are needed in verifying certain properties of the DFT, we implement them as MATLAB functions circshift1 and circonv as indicated below:function y = circshift1(x,M) % Develops a sequence y obtained by % circularly shifting a finite-length % sequence x by M samples if end if end y = end M M < = 0 M abs(M) > length(x) M = rem(M,length(x));

+

length(x); x(1:M)];

[x(M+1:length(x))

function y = circonv(x1,x2) L1 = length(x1); L2 = length(x2); if L1 ~= L2, error('Sequences of unequal lengths'), end y = zeros(1,L1); x2tr = [x2(1) x2(L2:-1:2)]; for k = 1:L1 sh = circshift1(x2tr,1-k); h = x1.*sh;

36

y(k) end

=

sum(h);

Program P6_1 can be used to illustrate the concept of circular shift of a finitelength sequence. It employs the function circshift1% Program P6_1 % Illustration of Circular Shift of a Sequence clear all; close all; clc M=6; a=[0 1 2 3 4 5 6 7 8 9]; b = circshift1(a,M); L = length(a)-1; n = 0:L; subplot(2,1,1); stem(n,a);axis([0,L,min(a),max(a)]); title('Original Sequence'); subplot(2,1,2); stem(n,b);axis([0,L,min(a),max(a)]); title(['Sequence Obtained by Circularly Shifting by ',num2str(M),'Samples']);

Program P6_2 can be used to illustrate the circular time-shifting property of the DFT. It employs the function circshift1.% Program P3_2 % Circular Time-Shifting Property of DFT close all; clear all; clc x=[0 2 4 6 8 10 12 14 16]; N = length(x)-1; n = 0:N; y = circshift1(x,5); XF = fft(x); YF = fft(y); subplot(2,2,1) stem(n,abs(XF)); grid title('Magnitude of DFT of Original Sequence'); subplot(2,2,2) stem(n,abs(YF)); grid title('Magnitude of DFT of Circularly Shifted Sequence'); subplot(2,2,3) stem(n,angle(XF)); grid title('Phase of DFT of Original Sequence'); subplot(2,2,4) stem(n,angle(YF)); grid title('Phase of DFT of Circularly Shifted Sequence');Magnitude of DFT of Original Sequence Magnitude of DFT of Circularly Shifted Sequence 80 80 60 40 20 0 60 40 20 0

0

2

4

6

8

0

2

4

6

8

Phase of DFT of Original Sequence 4 2 0 -2 -4

Phase of DFT of Circularly Shifted Sequence 4 2 0 -2 -4

0

2

4

6

8

0

2

4

6

8

Program P6_3 can be used to illustrate the circular convolution property of the DFT. It employs the function circonv.% Program P6_3 % Circular Convolution Property of DFT clear all; close all; clc g1=[1 2 3 4 5 6]; g2=[1 -2 3 3 -2 1]; ycir = circonv(g1,g2);

37

disp('Result of circular convolution = '); disp(ycir) G1 = fft(g1); % similarly compute fft of g2 and save in G2 yc = real(ifft(G1.*G2)); disp('Result of IDFT of the DFT products = '); disp(yc)

Program P6_4 can be used to illustrate the relation between circular and linear convolutions% Program P6_4 % Linear Convolution via Circular Convolution close all; clear all; clc g1=[1 2 3 4 5]; g2 = [2 2 0 1 1]; g1e = [g1 g2e = [g2 zeros(1,length(g2)-1)]; zeros(1,length(g1)-1)];

%Do circular convolution of g1e and g2e and save in ylin yourself disp('Linear convolution via circular convolution = '); disp(ylin); y = conv(g1, g2); disp('Direct linear convolution = ');disp(y)

Program P6_5 can be used to verify the relation between the DFT of a real sequence, and the DFTs of its periodic even and the periodic odd parts.% Program P6_5 % Relations between the DFTs of the Periodic Even % and Odd Parts of a Real Sequence close all; clear all; clc x=[1 2 4 2 6 32 6 4 2 zeros(1,247)]; x1 = [x(1) x(256:-1:2)]; xe = 0.5 *(x + x1); XF = fft(x); XEF = fft(xe); k = 0:255; subplot(2,2,1); plot(k/128,real(XF)); grid ylabel('Amplitude'); title('Re(DFT\{x[n]\})'); subplot(2,2,2); plot(k/128,imag(XF)); grid ylabel('Amplitude'); title('Im(DFT\{x[n]\})'); subplot(2,2,3); plot(k/128,real(XEF)); grid xlabel('Time index n'); ylabel('Amplitude'); title('Re(DFT\{x_{e}[n]\} )'); subplot(2,2,4); plot(k/128,imag(XEF)); grid xlabel('Time index n');ylabel('Amplitude'); title('Im(DFT\{x_{e}[n]\})');

38

Re(DFT{x[n]}) 100 50 0 -50 100 50 Amplitude 0 -50 -100 0

Im(DFT{x[n]})

Amplitude

0

0.5

1e

1.5

2

0.5-14

1e

1.5

2

Re(DFT{x [n]} ) 100 50 0 -50 0.5 Amplitude 0 -0.5

x 10

Im(DFT{x [n]})

Amplitude

0

0.5 1 1.5 Time index n

2

0

0.5 1 1.5 Time index n

2

Parsevals relation can be verified using the following program.% Program P6_6 % Parseval's Relation x = [(1:128) (128:-1:1)]; XF = fft(x); % Take square of vector x and then add all its % entries and save in a . Do yourself b = round(sum(abs(XF).^2)/256)

EXPERIMENT NO. 839

(DECIMATION & INTERPOLATION)

The digital signal processing structures discussed so far belong to the class of single-rate systems as the sampling rates at the input and the output and all internal nodes are the same. There are applications where it is necessary and often convenient to have unequal rates of sampling at various parts of the system including the input and the output. In this laboratory exercise you will investigate first using MATLAB the properties of the up-sampler and the downsampler, the two basic components of a multi-rate system. You will then investigate their use in designing more complex systems, such as interpolators and decimators, and filter banks.

I.1

Basic Sampling Rate Alteration DevicesThe objective of this section is to investigate using MATLAB the operations of the up- sampler and the down-sampler both in the time domain and in the frequency domain.

Project 10.1 Relations in the Time-Domain

Input-Output

Program P10_1 can be used to study the operation of a up-sampler.%Program10_1 %Illustration of Up-Sampling by an Integer Factor % close all; clear all; clc n=0:50; x=sin(2*pi*0.12*n);

40

y=zeros(1,3*length(x)); y([1:3:length(y)])=x; subplot(2,1,1) stem(n,x); title('InputSequence'); xlabel('Timeindexn');ylabel('Amplitude'); subplot(2,1,2) stem(n,y(1:length(x))); title('OutputSequence'); xlabel('Timeindexn');ylabel('Amplitude');InputSequence 1 0.5 Amplitude 0 -0.5 -1

0

5

10

15

20

25 30 Timeindexn OutputSequence

35

40

45

50

1 0.5 Amplitude 0 -0.5 -1

0

5

10

15

20

25 30 Timeindexn

35

40

45

50

41

%ProgramP10_2 %Illustration of Down-Sampling by an Integer Factor % close all; clear all; clc n = 0:49; m = 0:50*3-1; x = sin(2*pi*0.042*m); y = x([1:3:length(x)]); subplot(2,1,1) stem(n,x(1:50));axis([0 50 -1.2 1.2]); title('InputSequence'); xlabel('Timeindexn'); ylabel('Amplitude'); subplot(2,1,2) stem(n,y);axis([0 50 -1.2 1.2]); title('OutputSequence'); xlabel('Timeindexn'); ylabel('Amplitude');

The Signal Processing Toolbox includes three M-functions which can be employed to design and implement an interpolator or a decimator. The three Mfunctions are decimate , in rp , and resample. te Each function is available with several options. In this section you will study the decimation and interpolation operation using these functions.

Project 10.2

Decimator Design and Implementation

Program P10_3 illustrates the use of the M-function decimate in the design and implementation of a decimator with an integer-valued decimation factor M. In the option utilized in this program, decimate designs and uses a lowpass decimation filter with a stopband edge.%ProgramP10_3 %Illustration of Decimation Process % clear all; close all; clc M=input('Down-samplingfactor='); n=0:99; x=sin(2*pi*0.043*n)+sin(2*pi*0.031*n); y=decimate(x,M,'fir'); subplot(2,1,1); stem(n,x(1:100)); title('InputSequence'); xlabel('Timeindexn');ylabel('Amplitude'); subplot(2,1,2); m=0:(100/M)-1; stem(m,y(1:100/M)); title('OutputSequence'); xlabel('Timeindexn');ylabel('Amplitude');

42

InputSequence 2 1 Amplitude 0 -1 -2

0

10

20

30

40

50 60 Timeindexn OutputSequence

70

80

90

100

2 1 Amplitude 0 -1 -2

0

5

10

15

20

25 30 Timeindexn

35

40

45

50

I.2

Decimator and Implementation

Interpolator

Design

and

Project 10.3 and Implementation

Interpolator

Design

Program P10_4 illustrates the use of the M-function in rp in the design and te implementation of an interpolator with an integer-valued interpolation factor L. in rp designs and uses a lowpass interpolation filter with a stopband edge te satisfying Eq. (10.1).

(10.1)%ProgramP10_4 %Illustration of Interpolation Process % clear all; close all; clc L=input('Up-samplingfactor='); % Generate the input sequence n=0:49; x=sin(2*pi*0.043*n)+sin(2*pi*0.031*n); % Generate the interpolated output sequence y=interp(x,L); % Plot the input and the output sequences subplot(2,1,1); stem(n,x(1:50)); title('InputSequence'); xlabel('Timeindexn');ylabel('Amplitude'); subplot(2,1,2); m=0:(50*L)-1; stem(m,y(1:50*L)); title('OutputSequence'); xlabel('Timeindexn');ylabel('Amplitude');

43

InputSequence 2 1 Amplitude 0 -1 -2

0

5

10

15

20

25 30 Timeindexn OutputSequence

35

40

45

50

2 1 Amplitude 0 -1 -2

0

10

20

30

40

50 60 Timeindexn

70

80

90

100

Project 10.4

Fractional-Rate Sampling Rate Alteration

Program P10_5 illustrates the use of the M-function resample in the design and implementation of an interpolator with a fractional-rate interpolation factor L/M. Resample designs and uses a lowpass interpolation filter with a stopband edge.% Program10_5 % Illustration of Sampling Rate Alteration by % a Ratio of Two Integers % close all; clear all; clc L=input('Up-samplingfactor='); M=input('Down-samplingfactor='); n=0:29; x=sin(2*pi*0.43*n)+sin(2*pi*0.31*n); y=resample(x,L,M); subplot(2,1,1); stem(n,x(1:30));axis([0 29 -2.2 2.2]); title('InputSequence'); xlabel('Timeindexn');ylabel('Amplitude'); subplot(2,1,2); m=0:(30*L/M)-1; stem(m,y(1:30*L/M));axis([0 (30*L/M)-1 -2.2 2.2]); title('OutputSequence'); xlabel('Timeindexn');ylabel('Amplitude');

I.3

Lab Task

1. What is the angular frequency in radians of the sinusoidal sequence in Program P10_1? What is its length? What is the up-sampling factor L? 2. How is the up-sampling operation implemented in Program P10_1? 3. Modify Program P10_1 to study the operation of an up-sampler on a ramp sequence. 4. Program P10_2 can be used to study the operation of a down-sampler

44

5. What is the angular frequency in radians of the sinusoidal sequence Program P10_2? What is its length? What is the down-sampling factor M? 6. How is the down-sampling operation implemented in Program P10_2? 7. What are the frequencies of the two sinusoidal sequences forming the input sequence in Program P10_3? What is the length of the input? 8. What are the type and order of the decimation filter? 9. Run Program P10_3 for M = 4 and comment on the results. 10.Change the frequencies of the two sinusoidal sequences in Program P10_3 in the input signal to 0.045 and 0.029, and the length of the input to 120. Run the modified Program P10 5 for M = 3. Comment on your results. 11.What are the frequencies of the two sinusoidal sequences in Program P10_4 forming the input sequence? What is the length of the input? What are the type and order of the interpolation filter? 12.Run Program P10_4 for L = 2 and comment on the results. 13.Change the frequencies of the two sinusoidal sequences in the input signal to 0.045 and 0.029, and the length of the input to 40. Run the modified Program P10_4 for L = 3. Comment on your results. 14.What are the frequencies of the two sinusoidal sequences in Program P10_5 forming the input sequence? What is the length of the input? What are the type and order of the band-limiting filter? 15.Run Program P10 5 for L = 5 and M = 3. Comment on the results. 16.Change the frequencies of the two sinusoidal sequences in the input signal to 0.045 and 0.029, and the length of the input to 40. Run the modified Program P10 7 for L = 3 and M = 5. Comment on your results.

45

SECTION-1

46

EXPERIMENT NO. 9 (INTRODUCTION TO TMS320C6713 DSP STARTER KIT & CODE COMPOSER STUDIO)

47

Introduction to Hardware of TMS320C6713 DSKDigital Signal Processors (DSPs) are used for a wide range of applications, from communications and controls to speech and image processing. Many consumer products have embedded DSPs such as cellular phones, fax/modems, hearing aids, printers, radio, MP3 players, digital cameras, etc. In this lab, a block sinewave generator function is used to create the data samples, which is a simple for loop generating individual sine values to be graphed later. The focus of Lab 1 is to introduce and familiarize the students with the TMS320C6713 DSK and the Code Composer Studio. All the steps required to create, build and execute a complete project are discussed in detail.

1.1 Lab OutlineThe goal of this lab is to generate and graph a sine wave through the following procedure. 1. Getting acquainted with DSK6713 and Code Composer Studio 2. Build and load a program onto the DSK6713 3. Run the program and examine the results 4. Use the CCS graphing feature to verify the results

1.2 Theoretical BackgroundDigital Signal Processors (DSPs) are fast microprocessors with both the architecture and the instruction set designed to suit different signal processing applications. In this course, we will use the Texas Instruments (TI) DSP TMS320C6713 to implement various exercises for real time digital signal processing. The family of C6x processors is the TIs most powerful DSP since it is based on Very Long Instruction Word (VLIW) architecture.

1.3 Digital Signal ProcessingIn the real world phenomenon, the signals encountered are analog (i.e., continuous in time and amplitude) in general. To process this analog signal in digital domain, the first step is converting it into a digital signal (i.e., discrete in both time and amplitude) achieved by sampling and quantizing the corresponding analog signal through an Analog-to-Digital Converter (ADC). Digital Signal Processing (DSP) involves the manipulation of such digital signals in a useful manner. After the processing has been done, the resultant digital signal is converted back to the analog form through a Digital-to-Analog Converter (DAC). Fig.11. 1 shows the main components of a DSP system, consisting of ADC, DSP and DAC devices. A few reasons behind processing the digital signals instead of the original analog signals are: 1. Unlike analog signals, digital signals can be reproduced exactly. All that that has to be done is make sure that a zero does not get turned into a one or vice versa, which can be achieved by making the physical signals for zero and one quite different and by building in redundancy. Therefore, digital circuits provide more stable and tolerant output than analog signals under various environmental conditions. 2. Digital signals can be manipulated easily. Since the signal is just a sequence of zeros and ones, and since a computer (or other similar devices) can do anything specifiable to such a sequence, a great number of operations can be performed on the digital signals. This is called Digital Signal Processing.

48

Analog to Digital Converter (ADC) Analog Input

Digital Signal Processor (DSP)

Digital to Analog Converter (DAC) Analog Output

Digital Domain

Real World Analog Domain

Fig. 11.1 3.

A DSP system comprising of ADC, DSP and DAC

Digital Signal Processors are programmable, i.e., the same hardware can be used for different application by writing a different code.

1.4 TMS320C6713 DSPMain features of TMS320C6713 DSP are the following. 1. It is based on VLIW architecture suitable for computation intensive applications 2. A total of 8 instructions can be fetched every cycle 3. 264kB of internal memory (8kB as L1P and L1D Cache and 256kB as L2 memory shared between program and data space) 4. 8 execution units composed of 6 Arithmetic Logic Units (ALU) and 2 multiplier units 5. 32-bit address bus 6. Two sets of 32-bit general-purpose registers

1.4.1

TMS320C6713 DSP Support Kit (DSK)

Figure 11. 2: TMS320C6713 DSK

49

The TMS320C6713 DSK board, shown in Figure 11.2 consists of the following components. 1. TMS320C6713 floating-point DSP 2. 32 bit stereo codec TLV320AIC23 (AIC23) for I/O providing ADC and DAC, which connects to a 12 MHz system cock and can sample the data from 8 to 96 KHz 3. Two 80 pin connectors for external peripheral and external memory interfaces (EMIF) 4. 16 MB of Synchronous Dynamic Random Access Memory (SDRAM) 5. 256 KB of flash memory 6. Four connectors for I/O: MIC IN for microphone input, LINE IN for line input, LINE OUT for line output, and HEADPHONE for a headphone output (multiplexed with the line output) 7. Four dip switches for feedback control interface 8. Voltage regulators providing 1.26V for C6713 and 3.3V for memory and peripherals A block diagram of TMS320C6713 DSK is shown in Figure 11.3 below.

FIGURE 11. 3: diagram for C6713

A block

1.4.2

Code Composer Studio (CCS)The Code Composer Studio (CCS) provides an Integrated Development Environment (IDE) to incorporate all the software tools for DSP development. CCS includes 1. Tools for code generation such as C compiler, assembler and linker: The C compiler compiles a C source program with extension .c to produce an assembly source file with extension .asm. The assembler assembles the .asm source file to produce a machine language object file with extension .obj. The linker combines object files and object libraries as input producing an executable file with extension .out. This executable file can be loaded and directly run on the C6713 processor. 2. Real time debugging: The program being run on the C6713 processor can be debugged in real time by the help of features included in CCS such as setting breakpoints and watching variables in a window, viewing the processor memory and registers, stepping in, out and over the program, etc. When Real Time Data eXchange (RTDX) is used for data transfer between the target DSK and the host PC, CCS helps in monitoring the key statistics and performance in real time. 3. Graphical capabilities: The results of the program can be graphed and execution time of the program can be monitored using CCS.

50

In short, it is a complete user friendly software tool to build, debug and monitor the programs for the DSPs. Figure 11.4 shows a snapshot of actual CCS window

on the startup.

FIGURE 11.4 : Code Composer Studio on startup

1. 2. 3. 4.

CCS works within a project paradigm. A project, with its information stored in a .pjt file, essentially stores all the information required to build the executable file, e.g., Source files Header files Program build options Target systems memory map

51

When TI developed CCS, it added a number of capabilities to the environment. Not only the code generation tools (compiler, assembler, linker as mentioned above) were added but the simulator and the DSP/BIOS were also included. DSP/BIOS is a real-time kernel consisting of three main features: a real-time, pre-emptive scheduler, real-time capture and analysis and the real-time I/O.

1.4.2.1 Build OptionsBuild options in a project are used for handling code generation tools (i.e., compiler, assembler, linker) to create the code according to our systems needs. Figure 11. 5 shows a Graphical User Interface (GUI) for various build options provided by CCS, which makes the task of choosing the build options a lot easier. There is a one-to-one relationship between the items typed in the textbox and the GUI box selections. User can select different general options, Compiler options or Linker options according to the program needs. The Compiler alone has around 100 different options to tune the codes performance, size, etc., but the most important ones are the following. 1. mv6700 Generate C67x code 2. fr Directory for object/output files 3. fs Directory for assembly files 4. q Quite mode (display less info while compiling) 5. s Interlist C statements into assembly listing 6. g Enables src-level symbolic debugging

FIGURE 11. 5:

Build Options

1.5 Lab ProcedureThe complete programming procedure for this lab consists of the following steps. 1. Since CCS has already been installed on the workstations, you only have to connect the DSK to the PC. Plug the AC power cord into the power supply and then plug the power cable into the board. Connect the USB cable to your PC. When the DSK board is powered on, a program stored in Flash Memory called POST.c (Power On Self Test) is run to test the DSK. It tests the memories (internal, external and flash), Direct Memory Access (DMA), two Multichannel Buffered Serial Ports (McBSP), onboard codec, and the LEDs. If all the tests are successful, all four LEDs blink three times and then stop while remaining on. 2. For testing the DSK as well as the USB connection, launch 6713 DSK Diagnostics Utility from the icon on the desktop. From the diagnostic utility, press the start button to run the diagnostics. In approximately 30 seconds, all the test indicators, namely USB, Emulation, DSP, External Memory, Flash, Codec, LED and dip switches, should turn green as shown in Figure 11. 7.

52

FIGURE 11.7: C6713 DSK Diagnostics Utility 3. Launch the CCS from the icon on the desktop. Press GEL -> Check DSK -> Quick Test. Check if the message regarding Switches shows 15, assuming that all the four dip switches are in the up position. Now make any combination by turning some of the switches on and off and verify if the correct value is displayed. 4. To create a new project, open the CCS and select Project -> New as shown in Figure 11. 8. A window as in Figure 11. 8 will appear. To be consistent, you should name the project as Lab_1 and make sure that the project location is C:\CCStudio_v3.1\MyProjects. Project type should be Executable (.out) and choose the correct target according to the DSK being used (TMS320C67XX in this lab).

FIGURE 11.8: Creating a new project. Choose the appropriate target 5. Click on the + sign next to the Projects folder in the Project View Window to check whether the project has been created correctly or not. 6. Click on File -> New -> Source File and save it as Introduction.c.

7. For the purpose of this lab, a .c file Introduction.c will be provided to run the code, so that you can understand the main features of DSK6713 and CCS. 8. Now add the following files to your project. You can either do it by right clicking on the project icon in the Project Explorer Window, or by dragging and dropping files from the Windows Explorer onto the project icon, or by selecting Project -> Add Files to Project. Folder Support must be copied in MyProjects folder first. Introduction.c (provided by the instructor) The file with I/O support functions Support -> c6713dskinit.c ASM source file Support -> vectors_poll.asm Linker Command File Support -> c6713dsk.cmd

i. ii. iii. iv.

53

Click on the + symbol to left of the Project Files window within CCS to expand and verify that these source files have been added to the project. vi. Library support file rts6700.lib from C:\CCStudio_v3.1\C6000\cgtools\lib vii. Board Support Library file dsk6713bsl.lib from C:\CCStudio_v3.1\C6000\dsk6713\lib viii. Chip Support Library file csl6713.lib from C:\CCStudio_v3.1\C6000\csl\lib 9. For verification of correct addition of files, the project should look like Figure 11.9 at this stage.

v.

FIGURE 11.9: Files view in the project 10. The dependant files can be included in the project by right-clicking Lab_1.pjt and selecting Scan All File Dependencies or doing the same from Project menu bar. 11. Select the following options from Project -> Build Options: a. Basic -> Target Version C671x b. Preprocessor -> Pre-Define Symbol (-d) CHIP_6713 c. Preprocessor -> Include Search C:\CCStudio_v3.1\MyProjects\Support

Path

(-i)

12. Examine the main C code once again by inspecting Lab_1.c by double clicking on the file name in the Project Window. 13. Build the program to create an executable file (Lab_1.out) by either using the Rebuild All toolbar icon or selecting Project -> Rebuild All. Check the Build Output Window at the bottom of the CCS. Make sure that there are no errors and warnings. 14. If any of the following warnings appear after compilation, apply the correspond remedy as follows: a. >> warning: creating .stack section with default size of 400 (hex) words. Since we did not define any stack size, it is just informing us that it is going to default the stack size to 1K (= 400H). Go to Project -> Build Options -> Linker -> Stack Size (-stack) and set it equal to 400H. b. >> warning: Detected a near (.bss section relative) data reference to the symbol _DSK6713_AIC23_codecdatahandle defined in section .far. The reference occurs in C:\CCStudio_v3.1\MyProjects\Introduction\Debug\c6713dskinit.obj, section .text, SPC offset 00000058. Either make the symbol near data by placing it in the .bss section, 54

or make the references to the symbol far. For C/C++ code use 'far' or 'near' modifiers on the type definition of the symbol or compile with the --mem_model:data switch. Go to Project -> Build Options -> Advanced -> Memory Models and set memory model data = far. c. >> warning: last line of file ends without a newline. Just add an empty line after the closing bracket } of the function main (). 15. Load the executable file Introduction.out onto the DSP by choosing the option File -> Load Program. Had the option of Load Program after Build been enabled, CCS would have automatically loaded the program onto the DSP after encountering 0 errors during compilation. At this point, the program counter should be pointing to the beginning of main() function as shown in Figure 11. 10.

FIGURE 11. 10: Program counter arrow pointing at the beginning of main () This is because the option of Perform Go Main Automatically has been enabled which causes CCS to run to main after being loaded. Had this not been the case, you could do it manually using the Debug -> Go Main option. Although main () is the start of the program, many initialization steps occur between reset and main program which are run until the program counter reaches the start of main(). 16. Any variable values can be monitored by adding those variables to the Watch Window. The programmer can see the value of those variables being updated during various steps of the program. For this lab, select and highlight different variables in the program, right click on the variable and select Add to Watch Window and a window like Figure 11.11 will appear as a result.

FIGURE 11. 11: Watch Window in CCS 55

a. b. c. d.

17. The contents of the memory (e.g., value of individual elements in an array) can be viewed by selecting View -> Memory and type the following. Title Name of variable Address Name of variable Q-Value 0 Format Any style Before the program is run, random values will be present at the memory location at that time. 18. For initializing a variable in the memory, select Edit -> Memory -> Fill and fill in the required information in the window. 19. Debugging the program includes stepping into the code lines, stepping over, stepping out, etc. Multiple Operations toolbar can also be used for executing many operations from a single command on the toolbar. 20. Single stepping into the code is slow and not required at all times. A good technique to quickly reach a desired area of concern (e.g., on the last line in this lab) by executing the previous code is to set a breakpoint at that location, which can be accomplished by any of the following ways. a. Place the cursor on the line and click on the toolbar icon . b. Right click the line and choose Toggle Breakpoint c. Double click in the gray area next to the line 21. a. b. c. The code can be run through CCS by any of the following ways. Use the toolbar icon Select Debug -> Run Press F5

22. Press DIP switch # 0 and check if LED # 0 is turned on. Simultaneously, keep the DIP switch # 0 pressed, and connect speakers to line out or headphone out of the DSK 6713. Can you hear a tone? 23. The Watch Window will show the new values of the variables set for monitoring. The highlighted values in red are the ones changed with the last update. 24. Although Watch Window is a great resource to watch the variables values, but it is better to view them in a graph (e.g., to confirm in our experiment that sine_table is a sine wave). CCS provides this capability of graphing the available data. Select View -> Graph -> Time/Frequency and modify the following. a. Graph Title Name of variable b. Start Address Name of variable c. Acquisition Buffer Size As required d. Display Data Size As required e. DS Data Type As required f. Sampling Rate As required Click OK and the graph should look like Figure 11.12. CCS supports many graphing features such as time frequency, FFT magnitude, dual-time, constellation, etc.

56

FIGURE 11.12: Graph in CCS showing sine_table

25. Use the FFT magnitude plot to check the fundamental frequencies of this wave. Right-click on the graph, select Properties and change the display type to FFT magnitude. Click OK and see the frequency spectrum of the since wave. What do you see?

1.6 ConclusionAt the end of this lab, the students should have learnt about an overview of c6713 DSK, the hardware of TMS320C6713 DSP, the Code Composer Studio, building a project, loading and running a program and verifying the results.

57

EXPERIMENT NO. 10 (SINE GENERATION USING EIGHT POINTS WITH DIP SWITCHES CONTROL ON TMS320C6713)

This example generates a sinusoid using a table lookup method. More important, it illustrates some features of CCS for editing, building a project, accessing the code generation tools, and running a program on the C6713 processor. The C source program sine8_LED.c shown in Figure 1.2 implements the sine generation and is included in the folder sine8_LED. Program Consideration Although the purpose is to illustrate some of the tools, it is useful to understand the program sine8_LED.c. A table or buffer sine_table is created and filled with eight points representing sin(t), where t = 0, 45, 90, 135, 180, 225, 270, and 315 degrees //Sine8_LED.c Sine generation with DIP switch control #include "dsk6713_aic23.h" //support file for codec,DSK Uint32 fs = DSK6713_AIC23_FREQ_8KHZ; //set sampling rate short loop = 0; //table index short gain = 10; //gain factor short sine_table[8]={0,707,1000,707,0,-707,-1000,-707};//sine values 58

void main() { comm_poll(); //init DSK, codec, McBSP DSK6713_LED_init(); //init LED from BSL DSK6713_DIP_init(); //init DIP from BSL while(1) //infinite loop { if(DSK6713_DIP_get(0)==0) //=0 if switch #0 pressed { DSK6713_LED_on(0); //turn LED #0 ON output_sample(sine_table[loop]*gain); //output every Ts (SW0 on) if (++loop > 7) loop = 0; //check for end of table } else DSK6713_LED_off(0); //LED #0 off } //end of while (1) } //end of main FIGURE 1.2. Sine generation program using eight points with dip switch control (sine8_LED.c).

(scaled by 1000). Within the function main, another function, comm_poll, is called that is located in the communication and initialization support file c6713dskinit.c. It initializes the DSK, the AIC23 codec onboard the DSK, and the two McBSPs on the C6713 processor.Within c6713dskinit.c, the function DSK6713_init initializes the BSL file, which must be called before the two subsequent BSL functions, DSK6713_LED_init and DSK6713_DIP_init, are invoked that initialize the four LEDs and the four dip switches. The statement while (1) within the function main creates an infinite loop. When dip switch #0 is pressed, LED #0 turns on and the sinusoid is generated. Otherwise, DSK6713_DIP_get(0) will be false (true if the switch is pressed) and LED #0 will be off. The function output_sample, located in the communication support file C6713dskinit.c, is called to output the first data value in the buffer or table sine_table[0] = 0. The loop index is incremented until the end of the table is reached, after which it is reinitialized to zero. Every sample period T = 1/Fs = 1/8000 = 0.125ms, the value of dip switch #0 is tested, and a subsequent data value in sine_table (scaled by gain = 10) is sent for output.Within one period, eight data values (0.125 ms apart) are output to generate a sinusoidal signal. The period of the output signal is T = 8(0.125 ms) = 1ms, corresponding to a frequency of f = 1/T = 1kHz.Create Project In this section we illustrate how to create a project, adding the necessary files for building the project sine8_LED. Back up the folder sine8_LED (change its name) or delete its content (which can be retrieved from the book CD if needed), keeping only the C source file sine8_LED.c and the file gain.gel in order to recreate the content of that folder. Access CCS (from the desktop). 1. To create the project file sine8_LED.pjt. Select Project New. Type sine8_LED for the project name, as shown in Figure 1.3. This project file is saved in the folder sine8_LED (within c:\c6713\myprojects).The .pjt file stores project information on build options, source filenames, and dependencies. 2. To add files to the project. Select Project Add Files to Project. Look in the folder support, Files of type C Source Files. Double-click on the C source file C6713dskinit.c to add it to the project. Click on the + symbol to the left of the Project Files window within CCS to expand and verify that this C source file has been added to the project. 3. Repeat step 2, use the pull-down menu for Files of type, and select ASM Source Files. Double-click on the assembly source vector file vectors_poll.asm to add it to the project. Repeat again and select Files of type: Linker Command File, and add C6713dsk.cmd to the project.

59

4. To add the library support files to the project. Repeat the previous step, but select files of type: Object and Library Files. Look in c:\c6713\c6000\cgtools\lib and select the runtime support library file rts6700.lib (which supports the C67x architecture) to add to the project. Continue this process to add the BSL file dsk6713bsl.lib located in c:\c6713\c6000\dsk6713\lib, and the chip support library (CSL) file

60

csl6713.lib located in c:\c6713\c6000\bios\lib. 5. Verify from the Files window that the project (.pjt) file, the linker command (.cmd) file, the three library (.lib) files, the two C source (.c) files, and the assembly (.asm) file have been added to the project. The GEL file dsk6713.gel is added automatically when you create the project. It initializes the C6713 DSK invoking the BSL to use the phase-locked loop (PLL) to set the central processing unit (CPU) clock to 225MHz (otherwise, the C6713 runs at 50 MHz by default). 6. Note that there are no include files yet. Select Project Scan All File Dependencies. This adds/includes the header files c6713dskinit.h, along with several board and chip support header files included with CCS. The Files window in CCS should look as in Figure 1.3b. Any of the files (except the library files) from CCSs Files window can be displayed by clicking on it. You should not add header or include files to the project. They are added to the project automatically when you select: Scan All File Dependencies. (They are also added when you build the project.) It is also possible to add files to a project simply by dragging the file (from a different window) and dropping it into the CCS Project window. Code Generation and Options Various options are associated with the code generation tools: C compiler and linker to build a project. Compiler Option Select Project Build Options. Figure 1.4a shows the CCS window Build Options for the compiler. Select the following for the compiler option with Basic (for Category): (1) c671x{mv6710} (for Target Version), (2) Full Symbolic Debug (for Generate Debug Info), (3) Speed most critical (for Opt Speed vs. Size), and (4)None (for Opt Level and Program Level Opt). Select the Preprocessor Category and type for Define Symbols{d}: CHIP_6713, and from the Feedback Category, select for Interlisting: OPT/C and ASM{-s}. The resulting compiler option is -g -s The -g option is used to enable symbolic debugging information, useful during the debugging process, and is used in conjunction with the option -s to interlist the C

FIGURE 1.4. CCS Build options: (a) compiler; (b) linker.

61

source file with the assembly source file sine8_LED.asm generated (an additional option, -k, can be used to retain the assembly source file). The -g option disables many code optimizations to facilitate the debugging process. Press OK. Selecting C621x or C64xx for Target Version invokes a fixed-point implementation. The C6713-based DSK can use either fixed- or floating-point processing. Most examples implemented in this book can run using fixed-point processing. Selecting C671x as Target Version invokes a floating-point implementation. If No Debug is selected (for Generate Debug Info) and -o3:File is selected (for Opt Level), the Compiler option is automatically changed to -s -o3

The -o3 option invokes the highest level of optimization for performance or execution speed. For now, speed is not critical (neither is debugging). Use the compiler options -gs (which you can also type directly in the compiler command window). Initially, one would not optimize for speed but to facilitate debugging. A number of compiler options are described in Ref. 28. Linker Option Click on Linker (from CCS Build Options).The output filename sine8_LED.out defaults to the name of the .pjt filename, and Run-time Autoinitialization defaults for Autoinit Model. The linker option should be displayed as in Figure 1.4b. The map file can provide useful information for debugging (memory locations of functions, etc.).The -c option is