DSP Manual Autumn 2011
DSP Manual Autumn 2011
LAB MANUAL
DEPARTMENT OF ELECTRICAL ENGINEERING FEDERAL URDU UNIVERSITY OF ARTS, SCIENCE & TECHNOLOGY, SECTOR G-7/1, ISLAMABAD
AUTUMN 2011
LIST OF EXPERIMENTS
SECTION 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
SECTION-1
EXPERIMENT NO. 1
SIGNALS IN MATLAB (CONTINUOUS TIME & DISCRETE TIME)
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.
For the last graph, add a title and axis labels with:
title('Continuous time signal plot') xlabel('t (Seconds)') ylabel('y(t)')
% 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]);
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 sequence
n = 0:40; f = 0.1; phase = 0; A = 1.5;
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;
In this operation each sample of x(n) is shifted by an amount k to obtain a shifted sequence y(n)
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.
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
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?
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
Modify program to simulate the above system and determine whether this system is time-invariant or not.
% 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.
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
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 Domain
clear 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
2000
4000
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?
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
18
z-Transform
As 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.
(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
40
40
20
20
0 -1
-0.5
0.5
0 -1
-0.5
0.5
-0.5
0.5
-0.5
0.5
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 10
10
Magnitude Spectrum of Original Sequence 1.3579 1.3579 1.3579 1.3579 1.3579 1.3579 1.3579 1.3579
x 10
10
1.3579 -1
-0.8
-0.6
-0.4
-0.2
0.2
0.4
0.6
0.8
x 10
-9
x 10
-9
-1.5 -1
22 -0.8
-0.6
-0.4
-0.2
0.2
0.4
0.6
0.8
-1.5 -1
-0.8
-0.6
-0.4
-0.2
0.2
0.4
0.6
0.8
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
-0.5
0.5
-0.5
0.5
-0.5
0.5
-0.5
0.5
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
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.
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)
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.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);
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:
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.
28
29
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 command
b = fir1(N,Wn,high)
with N an even integer, is used for designing a highpass filter. The command
b = 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 command
b = 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 is
b = 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
= fr(, i2N
ft, ps
mval,taper)
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 command
b = 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 by
ft 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 ]
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 forms
firpm(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 by
c = 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..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?
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
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
Im(DFT{x[n]})
Amplitude
0.5
1
e
1.5
0.5
-14
1
e
1.5
x 10
Im(DFT{x [n]})
Amplitude
EXPERIMENT NO. 8
39
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
Input-Output
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
10
15
20
25 30 Timeindexn OutputSequence
35
40
45
50
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
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
10
20
30
40
50 60 Timeindexn OutputSequence
70
80
90
100
2 1 Amplitude 0 -1 -2
10
15
20
25 30 Timeindexn
35
40
45
50
I.2
Interpolator
Design
and
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
10
15
20
25 30 Timeindexn OutputSequence
35
40
45
50
2 1 Amplitude 0 -1 -2
10
20
30
40
50 60 Timeindexn
70
80
90
100
Project 10.4
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
48
Digital Domain
Fig. 11.1 3.
Digital Signal Processors are programmable, i.e., the same hardware can be used for different application by writing a different code.
1.4.1
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.
A block
1.4.2
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.
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.
FIGURE 11. 5:
Build Options
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
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.
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
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 Conclusion
At 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
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 used to initialize variables at run time, and the -o option is used to name the linked executable output file sine8_LED.out. Press OK. Note that you can/should choose to store the executable file in the subfolder Debug, within the folder sine8_LED, especially during the debugging stage of a project. Again, these various compiler and linker options can be typed directly within the appropriate command windows. In lieu of adding the three library files to the project by retrieving them from their specific locations, it is more convenient to add them within the linker option
62
window Include Libraries{-l}, typing them directly, separated by a comma. However, they will not be shown in the Files window. Building and Running the Project The project sine8_LED can now be built and run. 1. Build this project as sine8_LED. Select Project Rebuild All or press the toolbar with the three down arrows.This compiles and assembles all the C files using cl6x and assembles the assembly file vectors_poll.asm using asm6x. The resulting object files are then linked with the library files using lnk6x. This creates an executable file sine8_LED.out that can be loaded into the C6713 processor and run. Note that the commands for compiling, assembling, and linking are performed with the Build option. A log file cc_build_Debug.log is created that shows the files that are compiled and assembled, along with the compiler options selected. It also lists the support functions that are used. Figure 1.5 shows several windows within CCS for the project sine8_LED.The building process causes all the dependent files to be included (in case one forgets to scan for all the file dependencies). 2. Select File Load Program in order to load sine_LED.out by clicking on it (CCS includes an option to load the program automatically after a build). It should be in the folder sine8_LED\Debug. Select Debug Run or use the toolbar with the running man. Connect a speaker to the LINE OUT connector on the DSK. Press the dip switch #0. You should hear a tone. You can also use the headphone output at the same time. The sampling rate Fs of the codec is set at 8kHz. The frequency generated is f = Fs/(number of points) = 8 kHz/8 = 1kHz. Connect the output of the DSK to an oscilloscope to verify a 1-kHz sinusoidal signal with an approximate amplitude of 0.8 V p-p (peak to peak). Correcting Program Errors 1. Delete the semicolon in the statement short gain = 10;
in the C source file sine8_LED.c. If it is not displayed, double-click on it (from the Files window). 2. Select Project Build to perform an incremental build or use the toolbar with the two (not three) arrows. The incremental build is chosen so that only the C source file sine8_LED.c is compiled.With the Rebuild option (toolbar with three arrows), files compiled and/or assembled previously would again go through this unnecessary process. 3. An error message, highlighted in red, stating that a ; is expected, should appear in the Build window of CCS (lower left). You may need to scroll up the Build window for a better display of this error message. Double-click on the highlighted error message line.This should bring the cursor to the section of code where the error occurs. Make the appropriate correction, Build again,
63
load, and run the program to verify your previous results. Monitoring the Watch Window Verify that the processor is still running (and dip switch #0 is pressed) . Note the indicator DSP RUNNING at the bottom left of CCS. The Watch window allows you to change the value of a parameter or to monitor a variable: 1. Select View Quick Watch window, which should be displayed on the lower section of CCS. Type gain, then click on Add to Watch. The gain value of 10 set in the program in Figure 1.2 should appear in the Watch window. 2. Change gain from 10 to 30 in the Watch window. Press Enter.Verify that the volume of the generated tone has increased (with the processor still running and dip switch #0 is pressed). The amplitude of the sine wave has increased from approximately 0.8 V p-p to approximately 2.5V p-p. 3. Change gain to 33 (as in step 2). Verify that a higher-pitched tone exists, which implies that the frequency of the sine wave has changed just by changing its amplitude. This is not so. You have exceeded the range of the codec AIC23. Since the values in the table are scaled by 33, the range of these values is now between 33,000. The range of output values is limited from -215 to (215 - 1), or from -32,768 to +32,767. Since the AIC23 is a stereo codec, we can send data to both 16-bit channels within each sampling period.This is introduced in Chapter 2.This can be useful to experiment with the stereo effects of output signals. In Chapter 7, we use both channels for adaptive filtering where it is necessary to input one type of signal (such as noise) on one 16-bit channel and another signal (such as a desired signal) on the other 16-bit channel. In this book, we will mostly use the codec as a mono device without the need to use an adapter that is required when using both channels. Applying the Slider Gel File The General Extension Language (GEL) is an interpretive language similar to (a subset of) C. It allows you to change a variable such as gain, sliding through different values while the processor is running. All variables must first be defined in your source program. 1. Select File Load GEL and open the file gain.gel, which you retained from the original folder, sine8_LED (that you backed up). Double-click on the file gain.gel to view it within CCS. It should be displayed in the Files window. This file is shown in Figure 1.6. By creating the slider function gain shown in Figure 1.6, you can start with an initial value of 10 (first value) for the variable gain that is set in the C program, up to a value of 35 (second value), incremented by 5 (third value). 2. Select GEL Sine Gain Gain. This should bring out the Slider window shown in Figure 1.7, with the minimum value of 10 set for the gain. 3. Press the up-arrow key to increase the gain value from 10 to 15, as displayed in the Slider window. Verify that the volume of the sine wave generated has increased. Press the up-arrow key again to continue increasing the slider, incrementing by 5 up to 30. The amplitude of the sine wave should be about 2.5 V p-p with a gain value set at 30. Now use the mouse to click directly on the Slider window and slowly increase the slider position to 31, then 32, and
/*gain.gel Create slider and vary amplitude (gain) of sinewave*/ menuitem "Sine Gain" slider Gain(10,35,5,1,gain_parameter) /*incr by 5,up to 35*/ { gain = gain_parameter; /*vary gain of sine*/ } FIGURE 1.6. GEL file to slide through different gain values in the sine generation program (gain.gel).
FIGURE 1.7. Slider window for varying the gain of generated sine wave.
64
verify that the frequency generated is still 1kHz. Increase the slider to 33 and verify that you are no longer generating a 1-kHz sine wave. The table values, scaled by the gain value, are now between 33,000 (beyond the acceptable range by the codec). Changing the Frequency of the Generated Sinusoid 1. Change the sampling frequency from 8 to 16 kHz by setting fs in the C source program to DSK6713_AIC23_FREQ_16KHZ. Rebuild (use incremental build) the project, load and run the new executable file, and verify that the frequency of the generated sinusoid is 2kHz. The sampling frequencies supported by the AIC23 codec are 8, 16, 24, 32, 44.1, 48, and 96kHz. 2. Change the number of points in the lookup table to four points in lieu of eight pointsfor example, {0, 1000, 0, -1000}. The size of the array sine_table and the loop index also need to be changed. Verify that the generated frequency is f = Fs/(number of points). Note that the sinusoid is no longer generated if the dip switch #0 is not pressed. If a different dip switch such as switch #3 is desired (in lieu of switch #0), the BSL functions DSK6713_DIP_get(3), DSK6713_LED_on(3), and DSK6713_LED_off(3) can be substituted in the C source program. Two sliders can readily be used, one to change the gain and the other to change the frequency. A different signal frequency can be generated by changing the loop index within the C program (e.g., stepping through every two points in the table). When you exit CCS after you build a project, all changes made to the project can be saved. You can later return to the project with the status as you left it before. For example, when returning to the project after launching CCS, select Project Open to open an existing project such as sine8_LED.pjt (with all the necessary files for the project already added).
65
66
( Note: Location must be c:\CCStudio_v3.1\MyProjects ). 3. Click on File NewSource File, To write the Source Code.
67
12.2 12.3
The linear convolution of two continuous time signals x(t) and h(t) is defined by
Where x(n) is the input signal and h(n) is the impulse response of the system.
% In linear convolution length of output sequence is, Length (y(n)) = length(x(n)) + length(h(n)) 1
12.4
C Program:
#include<stdio.h> main() { int m=4; /*Lenght of i/p samples sequence*/ int n=4; /*Lenght of impulse response Coefficients */ 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 Coefficients*/ /*At the end of input sequences pad 'M' and 'N' no. of zero's*/ int *y; y=(int *)0x0000100; 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]); }
68
12.5
Output:
4. Enter the source code and save the file with .C extension.
5. Right click on source, Select add files to project .. and Choose .C file Saved before.
69
6. Right Click on libraries and select add files to Project.. and choose C:\CCStudio_v3.1\C6000\cgtools\lib\rts6700.lib and click open.
70
8. Go to file and load program and load .out file into the board..
71
11. To see the Graph go to View and select time/frequency in the Graph, And give the correct Start address provided in the program, Display data can be taken as per user.
12. Green line is to choose the point, Value at the point can be seen (Highlighted by circle at the left corner). 72
EXPERIMENT NO. 12
73
74
75
13.2
AIM:
13.3
Circular Convolution:
Let x1(n) and x2(n) are finite duration sequences both of length N with DFTs X1(k) and X2(k). Convolution of two given sequences x1(n) and x2(n) is given by the equation, x3(n) = IDFT[X3(k)] X3(k) = X1(k) X2(k)
N-1
x3(n) =
x (m) x ((n-m))
1 2
m=0
13.4
Program:
void main() { int *y; y=(int *)0x0000100; 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 length of both sequences are not equal*/ { if(m>n) /* Pad the smaller sequence with zero*/ { for(i=n;i<m;i++) h[i]=0; 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++) /*folding h(n) to h(-n)*/ 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]; } } /*displaying the result*/ printf(" the circular convolution is\n"); for(i=0;i<n;i++) printf("%d ",y[i]); }
13.5
Output:
enter the length of the first sequence 4 enter the length of the second sequence 4 enter the first sequence 4321 enter the second sequence 1111 the circular convolution is 10 10 10 10 4. Enter the source code and save the file with .C extension.
77
5. Right click on source, Select add files to project .. and Choose .C file Saved before.
6. Right Click on libraries and select add files to Project.. and choose C:\CCStudio_v3.1\C6000\cgtools\lib\rts6700.lib and click open.
78
In case of any errors or warnings it will be displaye d here 8. Go to file and load program and load .out file into the board.. 79
80
81
The corresponding output will be shown on the output window as shown below
11. To see the Graph go to View and select time/frequency in the Graph, and give the correct Start address provided in the program, Display data can be taken as per user.
82
12. Green line is to choose the point, Value at the point can be seen (Highlighted by circle at the left corner).
83
84
14.1
86
14.2 AIM:
TO COMPUTE N-POINT DFT OF A GIVEN SEQUENCE AND TO PLOT MAGNITUDE AND PHASE SPECTRUM.
x(n)e
n=0
-j2nk/N
k = 0,1, . N-1
14.4 Program:
//DFT of N-point from lookup table. Output from watch window #include <stdio.h> #include <math.h> #define N 4 //number of data values float pi = 3.1416; short x[N] = {1,1,0,0}; float out[2] = {0,0};
void dft(short *x, short k, float *out) //DFT function { float sumRe = 0; //initialize real component float sumIm = 0; //initialize imaginary component int i = 0; float cs = 0; //initialize cosine component float sn = 0; //initialize sine component for (i = 0; i < N; i++) { cs = cos(2*pi*(k)*i/N); 87 //for N-point DFT //real component
sn = sin(2*pi*(k)*i/N); //imaginary component sumRe = sumRe + x[i]*cs; //sum of real components sumIm = sumIm - x[i]*sn; //sum of imaginary components } out[0] = sumRe; //sum of real components out[1] = sumIm; //sum of imaginary components printf("%f %f\n",out[0],out[1]); } void main() { int j; for (j = 0; j < N; j++) dft(x, j, out); }
14.5 Output:
2.000000 0.999996 0.000000 1.000011 0.000000 -1.000000 0.000007 1.000000
4. Enter the source code and save the file with .C extension.
5. Right click on source, Select add files to project .. and Choose .C file Saved before.
88
6. Right Click on libraries and select add files to Project.. and choose C:\CCStudio_v3.1\C6000\cgtools\lib\rts6700.lib and click open.
89
8. Go to file and load program and load .out file into the board..
90
91
11. To see the Graph go to View and select time/frequency in the Graph, And give the correct Start address provided in the program, Display data can be taken as per user.
12. Green line is to choose the point, Value at the point can be seen (Highlighted by circle at the left corner).
92
93
( Note: Location must be c:\CCStudio_v3.1\MyProjects ). 3. Click on FileNewSource File, To write the Source Code.
94
15.2
AIM:
Realization of FIR filter (any type) to meet given specifications,the input can be a signal from Function Generator/Speech signal
15.3
The FIR filters are of non-recursive type, whereby the present output sample is depending on the present input sample and previous input samples. The transfer function of a FIR causal filter is given by, N-1
H(z) =
Where
h(n)z-n
n=0
h(n) is the impulse response of the filter. The Fourier transform of h(n) is
N-1
H(ejw) = h(n)e-jwn
n=0 In the design of FIR filters most commonly used approach is using windows. The desired frequency response Hd(ejw) of a filter is periodic in frequency and can be expanded in Fourier series. The resultant series is given by,
hd(n) = (1/2)
H(ejw)ejwn dw
- And known as Fourier coefficients having infinite length. One possible way of obtaining FIR filter is to truncate the infinite Fourier series at n = [(N-1)/2] Where N is the length of the desired sequence. The Fourier coefficients of the filter are modified by multiplying the infinite impulse response with a finite weighing sequence Where
w(n) = w(-n) 0for |n| [(N-1)/2] =0 for |n| > [(N-1)/2] h(n) that
After multiplying w(n) with hd(n), we get a finite duration sequence satisfies the desired magnitude response, 95
H(ejw)
Hd(e )
jw
and
W(e )
jw
is given by,
H(ejw) = (1/2)
jw
Hd(ej) W(ej(w-) d
Program:
<stdio.h> "c6713dsk.h" "master.h" "aic23cfg.h" "dsk6713_aic23.h" <std.h> <swi.h> <log.h> <c6x.h> <csl.h> <csl_mcbsp.h>
/* Length of sine wave table */ #define SINE_TABLE_SIZE 48 // Delta /*float filter_Coeff[] ={0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00, 0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0. 00,0.00, 0.00,0.00,0.00,0.00,0.00,0.00,1.00,0.00};*/ // Low Pass Filter /*float filter_Coeff[] ={2.715297634171146e-003, 2.315819802942924e004,-1.244493581373643e-002, 7.244364917221401e-003,1.207341716154354e002, 2.734134166585232e-003, -1.941706440790678e-002, -1.729098218843226e-002,1.773008730568675e-002, 4.091495174059349e-002,2.113436751136944e-003, -6.788468549771730e-002, -6.059440700570791e-002, 8.970313256448266e-002,3.014572949374625e-001, 4.019009454299968e-001,3.014572949374625e-001, 8.970313256448266e-002, -6.059440700570791e-002, -6.788468549771730e-002,2.113436751136944e-003, 4.091495174059349e-002,1.773008730568675e-002, -1.729098218843226e-002, -1.941706440790678e-002, 2.734134166585232e-003,1.207341716154354e-002, 7.244364917221401e-003,-1.244493581373643e-002, 2.315819802942924e-004, 2.715297634171146e-003};*/ // High Pass Filter float filter_Coeff[] ={3.294316420702696e-004,3.800020076486443e003,9.822200806739014e-003,1.517265313889167e-002, 1.323547007544908e-002,2.635896986048919e-004,-1.808215737734512e-002,2.666833013269758e-002, -1.155354962270025e-002,2.448211866656400e-002,5.534101055783895e002,4.424359087198896e-002, -2.922329551555757e-002,-1.473332022689261e-001,-2.574625659073934e001,6.976203109125493e-001, -2.574625659073934e-001,-1.473332022689261e-001,-2.922329551555757e002,4.424359087198896e-002, 5.534101055783895e-002,2.448211866656400e-002,-1.155354962270025e-002,2.666833013269758e-002, -1.808215737734512e-002,2.635896986048919e-004,1.323547007544908e002,1.517265313889167e-002, 9.822200806739014e-003,3.800020076486443e-003,3.294316420702696e-004}; // Pre-generated sine wave data, 16-bit signed samples int sinetable[SINE_TABLE_SIZE] = { 0x0000, 0x10b4, 0x2120, 0x30fb, 0x3fff, 0x4dea, 0x5a81, 0x658b, 0x6ed8, 0x763f, 0x7ba1, 0x7ee5, 0x7ffd, 0x7ee5, 0x7ba1, 0x76ef,
96
0x6ed8, 0x658b, 0x5a81, 0x4dea, 0x3fff, 0x30fb, 0x2120, 0x10b4, 0x0000, 0xef4c, 0xdee0, 0xcf06, 0xc002, 0xb216, 0xa57f, 0x9a75, 0x9128, 0x89c1, 0x845f, 0x811b, 0x8002, 0x811b, 0x845f, 0x89c1, 0x9128, 0x9a76, 0xa57f, 0xb216, 0xc002, 0xcf06, 0xdee0, 0xef4c }; 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 */ \ // 0x0014 micin with 0dB boost 0x0014, /* 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 */ \ 0x008c, \ 0x0001 \ }; /* 8 DSK6713_AIC23_SAMPLERATE Sample rate control */ /* 9 DSK6713_AIC23_DIGACT Digital interface activation */
DSK6713_AIC23_CodecHandle hCodec; Int32 InitWait =1; Int32 data; Int32 Logger[1024]; Int32 LoggerIndex =0; float in_buffer[100]; main(){ int i; LED=0x0; // Filter Initialization for( i = 0 ; i < 100; i++ ) in_buffer[i]=0.0; // Initialize codec hCodec = DSK6713_AIC23_openCodec(0, &config); IRQ_globalEnable(); IRQ_enable(IRQ_EVT_RINT1); IRQ_enable(IRQ_EVT_XINT1); } void led(){ static int cc = 1; LED = cc; // To Shift Pattern if (cc == 0x03) cc = else if (cc == 0x05) else if (cc == 0x06) else cc = 0x03; //To count Binary //cc++; if (cc>0x07) 0x05; cc = 0x06; cc = 0x03; cc = 0x00;
// TO Toggle LED // *cc ^= 0x07; if ((cc !=0x00) && (cc !=0x07)) cc = 0x07; } setpll200M(){ } void read(){ int i = 0; float result; data=MCBSP_read(DSK6713_AIC23_DATAHANDLE);
97
if(data>=32768) data= data|0xffff0000; for( i = 0; i <= 29; i++) in_buffer[i] = in_buffer[i+1]; in_buffer[30]=((float)(data))/16; result = 0; for( i = 0 ; i <= 30; i++ ) result += filter_Coeff[i] * in_buffer[i]; data = (Int32)(result*512); //data = (Int32)(in_buffer[30]*16); Logger[LoggerIndex++] = data; if (LoggerIndex == 1024) LoggerIndex = 0; } void write(){ if (InitWait<1000){ InitWait++; MCBSP_write(DSK6713_AIC23_DATAHANDLE, MCBSP_write(DSK6713_AIC23_DATAHANDLE, } else{ MCBSP_write(DSK6713_AIC23_DATAHANDLE, MCBSP_write(DSK6713_AIC23_DATAHANDLE, } }
15.5
Output:
4. Enter the source code and save the file with main.c extension.
5. Right click on source, Select add files to project and Choose main.c file Saved before.
98
6. Add the other supporting .c files which configure the audio codec.
99
8. Go to file and load program and load .out file into the board.
100
101
10. To see the Graph go to View and select time/frequency in the Graph and give the correct Start address provided in the program, Display data can be taken as per user.
11. Green line is to choose the point, Value at the point can be seen (Highlighted by circle at the left corner).
12. In the graph, chose FFT magnitude as display type we will get Graph B
102
Graph 2:FFT magnitude of FIR filter. 1. The impulse response of FIR filters.
103
104
Figure 4.29 shows a listing of the program aliasing.c, which implements this project. To illustrate the effects of aliasing, the processing rate is down-sampled by a factor of 2 to an equivalent 4-kHz rate. Note that the antialiasing and reconstruction filters on the AIC23 codec are fixed and cannot be bypassed or altered.
105
Up-sampling and lowpass filtering are then needed to output the 4-kHz rate samples to the AIC23 codec sampling at 8kHz. Build this project as aliasing. Load the slider file aliasing.gel (on the CD).With antialiasing initially set to zero in the program, aliasing will occur. 1. Input a sinusoidal signal and verify that for an input signal frequency up to 2kHz, the output is essentially a loop program (delayed input). Increase the input signal frequency to 2.5 kHz and verify that the output is an aliased 1.5-kHz signal. Similarly, a 3- and a 3.5-kHz input signal yield an aliased output signal of 1 and 0.5kHz, respectively. Input signals with frequencies beyond 3.9kHz are supressed due to the AIC23 codecs antialiasing filter. 2. Change the slider position to 1, so that antialiasing at the down-sampled rate of 4 kHz is desired. For an input signal frequency up to about 1.9kHz, the output is
//Aliasing.c illustration of downsampling, aliasing, upsampling #include "DSK6713_AIC23.h" //codec-DSK support file Uint32 fs=DSK6713_AIC23_FREQ_8KHZ;//set sampling rate #include "lp33.cof" //lowpass at 1.9 kHz short flag = 0; //toggles for 2x down-sampling short indly[N],outdly[N]; //antialias and reconst delay lines float yn; int i; //filter output, index short antialiasing = 0; //init for no antialiasing filter interrupt void c_int11() //ISR { indly[0]=(float)(input_sample());//new sample to antialias filter yn = 0.0; //initialize downsampled value if (flag == 0) flag = 1; //don't discard at next sampling else { if (antialiasing == 1) //if antialiasing filter desired { //compute downsampled value for (i = 0 ; i < N ; i++) //using LP @ 1.9 kHz filter coeffs yn += (h[i]*indly[i]); //filter is implemented using float } else //if filter is bypassed yn = indly[0]; //downsampled value is input value flag = 0; //next input value will be discarded } for (i = N-1; i > 0; i--) indly[i] = indly[i-1]; //update input buffer outdly[0] = (yn); //input to reconst filter yn = 0.0; //4 kHz sample values and zeros for (i = 0 ; i < N ; i++) //are filtered at 8 kHz rate yn += (h[i]*outdly[i]); //by reconstruction lowpass filter for (i = N-1; i > 0; i--) outdly[i] = outdly[i-1]; //update delays output_sample((short)yn); //8kHz rate sample return; //return from interrupt } void main() { comm_intr(); //init DSK, codec, McBSP while(1); //infinite loop } FIGURE 4.29. Program to illustrate aliasing and antialiasing down-sampling to a rate of 4kHz (aliasing.c).
a delayed version of the input. Increase the input signal frequency beyond 1.9kHz and verify that the output reduces to zero. This is due to the 1.9-kHz (at the downsampling rate of 4 kHz) antialiasing lowpass filter, implemented using the coefficient file lp33.cof (on the CD). In lieu of a sinusoidal signal as input, you can use a swept sinusoidal input signal.
106
Figure 5.14 shows a listing of the program IIR.c that implements a generic IIR filter using cascaded second-order stages (sections). The program uses the following two equations associated with each stage (see equations 5.10 and 5.11 for a second-order): u(n) = x(n) - b1u(n - 1) - b2u(n - 2) y(n) = a0u(n) + a1u(n - 1) + a2u(n - 2) The loop section of code within the program is processed five times (the number of stages) for each value of n, or sample period. For the first stage, x(n) is the newly acquired input sample. However, for the other stages, the input x(n) is the output y(n) of the preceding stage.
107
The coefficients b[i][0] and b[i][1] correspond to b1 and b2, respectively; where i represents each stage.The delays dly[i][0] and dly[i][1] correspond to u(n - 1) and u(n - 2), respectively.
//IIR.c IIR filter using cascaded Direct Form II //Coefficients a's and b's correspond to b's and a's from MATLAB #include "DSK6713_AIC23.h" //codec-DSK support file Uint32 fs=DSK6713_AIC23_FREQ_8KHZ; //set sampling rate #include "bs1750.cof" //BS @ 1750 Hz coefficient file short dly[stages][2] = {0}; //delay samples per stage interrupt void c_int11() //ISR { short i, input; int un, yn; input = input_sample(); //input to 1st stage for (i = 0; i < stages; i++) //repeat for each stage { un=input-((b[i][0]*dly[i][0])>>15) - ((b[i][1]*dly[i][1])>>15);
yn=((a[i][0]*un)>>15)+((a[i][1]*dly[i][0])>>15)+((a[i][2]*dly[i][1])>>15);
dly[i][1] = dly[i][0]; //update delays dly[i][0] = un; //update delays input = yn; //intermed out->in to next stage } output_sample((short)yn); //output final result for time n return; //return from ISR } void main() { comm_intr(); //init DSK, codec, McBSP while(1); //infinite loop } FIGURE 5.14. IIR filter program using second-order sections in cascade (IIR.c).
Build and run this project as IIR.Verify that the output is an IIR bandstop filter centered at 1750Hz. IIR Bandpass and Lowpass 1. Rebuild this project using the coefficient file bp2000.cof (on the accompanying CD), which represents a 36th-order (18 stages) Chebyshev type 2 IIR bandpass filter centered at 2kHz. This filter was designed with MATLAB, as
//bs1750.cof IIR bandstop coefficient file, centered at 1,750 Hz #define stages 5 //number of 2nd-order stages int a[stages][3]= { //numerator coefficients {27940, -10910, 27940}, //a10, a11, a12 for 1st stage {32768, -11841, 32768}, //a20, a21, a22 for 2nd stage {32768, -13744, 32768}, //a30, a31, a32 for 3rd stage {32768, -11338, 32768}, //a40, a41, a42 for 4th stage {32768, -14239, 32768} }; int b[stages][2]= { //denominator coefficients {-11417, 25710}, //b11, b12 for 1st stage {-9204, 31581}, //b21, b22 for 2nd stage {-15860, 31605}, //b31, b32 for 3rd stage {-10221, 32581}, //b41, b42 for 4th stage {-15258, 32584} }; //b51, b52 for 5th stage FIGURE 5.15. Coefficient file for a tenth-order IIR bandstop filter designed with MATLAB in Appendix D (bs1750.cof).
shown in Figure 5.17. Verify that the filters output is an IIR bandpass filter centered at 2kHz. 2. Rebuild this project using the coefficient file lp2000.cof (on the CD), which represents an eighth-order IIR lowpass filter with a 2-kHz cutoff frequency (also designed with MATLAB).Verify the output of this IIR lowpass filter.
108