0% found this document useful (0 votes)
23 views128 pages

New DSP Manual

Uploaded by

hotomev867
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views128 pages

New DSP Manual

Uploaded by

hotomev867
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 128

Digital Signal Processing (CE-405) SSUET/QR/114

LAB # 1
OPERATION OF SIGNALS
(MANIPULATION OF TIME PARAMETER)

Objective
To trace Operation (folding/reversal, scaling, shifting) of both analog and discrete time signals.

Theory
1. Manipulation of the Time Parameter:
In this Lab we will look at three signal operations affecting the time parameter of the signal; time shifting, time scaling
and time reversal. These operations are very common components to real-world systems and, as such, should be
understood thoroughly when learning about signals and systems.
Some common operations on signals affect the time parameter of the signal. One of these is time shifting in which a
quantity is added to the time parameter in order to advance or delay the signal. Another is the time scaling in which the
time parameter is multiplied by a quantity in order to dilate or compress the signal in time. In the event that the
quantity involved in the latter operation is negative, time reversal occurs.

1.1 Time Shifting:


Time shifting is, as the name suggests, the shifting of a signal in time. This is done by adding or subtracting a quantity
of the shift to the time variable in the function. Subtracting a fixed positive quantity from the time variable will shift
the signal to the right (delay) by the subtracted quantity, while adding a fixed positive amount to the time variable will
shift the signal to the left (advance) by the added quantity. As shown in figure 1.1, f (t−T) moves f (t) to the right by T
which is an example of delaying a signal.

Fig. 1.1: Time shifting of a signal

If a signal can be expressed in the form as shown below in equation 5.1, we say that x (t) is a time-shifted version of
s(t). An example of time shifting is also shown in figure 1.1 for graphical illustration
x(t)= s(t-t1) (1.1)

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Fig. 1.2: Time-shifting of a signal ‘s(t)’

Consider a simple function as shown in equation 1.2, when this function is shifted by t 1=2 seconds it gives the
equation 5.3 which is simply s (t) with its origin shifted to the right, or delayed, by 2 seconds.

s(t) = t 0≤t≤1 (1.2)

x (t) = s (t -2) = t - 2 0 ≤ t-2 ≤ 2


=t–2 2≤t≤3 (1.3)

Similarly, shifting the function s (t) as shown in equation 1.2, by t1 = -1 seconds yields equation 1.4 which is simply s
(t) with its origin shifted to the left, or advance in time, by 1 second.

y (t) = s (t +1) = t + 1 0 ≤ t + 1 ≤ 1
=t+1 -1 ≤ t ≤ 0 (1.4)

A positive phase indicates a shift to the left whereas a negative phase indicates a shift to the right.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

1.2 Time Scaling:


Time scaling compresses or dilates a signal by multiplying the time variable by some quantity. If that quantity is
greater than one, the signal becomes narrower and the operation is called compression, while if the quantity is less
than one, the signal becomes wider and is called dilation.

Fig. 1.3: Time scaling of a signal ‘f (t)’

1.3 Time Reversal:


A natural question to consider when learning about time scaling is: What happens when the time variable is multiplied
by a negative number? The answer to this is time reversal. This operation is the reversal of the time axis, or flipping
the signal over the y-axis.

Fig. 1.4: Reversal of the time axis

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

HOME TASK
Task 1: Write a script that delays the unit impulse by 5 samples.

Task 2: Generate a script that uses user input to shift unit impulse right or left. Use MATLAB input command to take
the number of samples to shift the signal and use switch option or If - else statement to decide whether to shift
the signal to the right (delay) or to the left (advance).

Task 3: Write a script that uses user input to advance the unit step sequence.

Task 4: Repeat task # 2 with unit step response.

Task 5: Create a function that flip the sequence first and then advance the sequence. The function will receive two
arguments as defined below, first is input signal which needs to be flipped and then advances, and second is the
number of samples by which the signal should be advanced.
[x]= flipadv (u,s)

Task 6: Generate a function that advances the sequence first and then flip the sequence. The function will receive two
arguments as defined below, first is input signal which needs to be moved and then flipped, and second is the
number of samples by which the signal should be advanced.
[x]= advflip (u,s)

Task 7: Create a Triangular wave with unit amplitude. Use subplot command to show the effect of compression and
dilation.

Task 8: Generate a Square wave with amplitude from -5 to 5. Plot the signal which shows the original signal along
with its flipped signal.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LABORATORY 2:

CONVOLUTION OF DISCRETE SIGNALS AND ITS


APPLICATION

OBJECTIVES:
 To trace linear time invariant (LTI) systems and convolution of discrete signals.

Place a check mark in the Assigned column next to the exercises your instructor has assigned to
you. Attach this cover sheet to the front of the packet of materials you submit following the
laboratory.

Activities Remarks Signature


Pre-lab Exercises
In-lab Exercises
Take Home Exercises
Any Other

THEORY:
Section A -- Convolution
A relaxed LTI system is completely characterized by a single function h(n) which is the response
of the unit impulseδ (n) .For time variant linear system, we have to evaluate h(n, k) for each value
of k. The response of LTI system is called the convolution sum which is written as:
y(n) = x(n) ∗ h(n)

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

The convolution is a function of two variables, n (the actual sample time) and k (used for delay
and as a dummy variable when evaluating the convolution for a particular value of n).

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Convolution is a mathematical way of combining two signals to form a third signal. It is the
single most important technique in Digital Signal Processing. Using the strategy of impulse
decomposition, systems are described by a signal called the impulse response. Convolution is
important because it relates the three signals of interest: the input signal, the output signal, and
the impulse response.

Convolution is used in the mathematics of many fields, such as probability and statistics. In linear
systems, impulse response is the response of the unit impulse signal as shown in Fig. 1.

Figure 1: impulse response of an LTI system

The convolution is a function of two variables, n (the actual sample time) and k (used for delay
and as a dummy variable when evaluating the convolution for a particular value of n = n 0, we
perform the following operations:

1. Folding: Fold h(k) about k = 0 to obtain h(-k).


2. Shifting: Shift h(-k) by n0 to the right (left) if n0 is positive (negative), to obtain h(n0 - k).
3. Multiplication: Multiply x(k) by h(n0 – k) to obtain the product sequence:
Vn0 (k) ≡ x(k)h(n0 – k).
4. Addition: Sum all the values of the product sequence Vn0 (k) to obtain the value of the
output at time n = n0.
It is irrelevant which of the two sequences is folded and shifted. We can assume that h(n) is the
input signal and x(n) is the response. This is called the commutative law, Hence:

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

MATLAB Code
In order to perform convolution in MATLAB, the command conv( ) is used as shown in the
following code. Note by default, MATLAB assumes that both the input signal and the impulse
response are causal.

MATLAB Code
The following program reads three images ‘test1.jpg’, ‘test2.jpg’and ‘test3.jpg’ using imread( )
command. These images are convolved with the masks shown in Fig. 5. In addition, a large size
mask of the mask in Fig. 5(a) is used to demonstrate how images become blur as a result of using

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

such larger average masks. The command used for 2-D convolution is conv2( ).

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

MATLAB Implementation
1. Implement of convolution operation between h (n ) = [1, 2,1, 1] and x(n ) = [1,2,3,1] and
↑ ↑

generate the figure above of the multiplication matrix.


x=[1,2,3,1];h_mirror=[-1,1,2,1];
x_time = [0 1 2 3];h_time = [-3 -2 -1 0];
lower = -3;
upper = 7;
n = [lower:upper];
k = [lower:upper];
G = zeros(length(n));
zero_loc = find(n==0);
h_first_element_loc = find(n==h_time(1));

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

G( h_first_element_loc:h_first_element_loc +length(h_mirror)-1 , zero_loc ) = h_mirror;


for t=zero_loc+1:length(n)
p=G(:,t-1)
G(:,t)=circshift(p,1);
G(1,t)=0

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

clear p
end
clear t p
for t=zero_loc-1:-1:1
p=G(:,t+1)
G(:,t)=circshift(p,-1);
G(length(n),t)=0
clear p
end

R = zeros(1,length(n))
x_first_element_loc = find(n==x_time(1));
R( x_first_element_loc:x_first_element_loc +length(x)-1 ) = x

Y=R*G

subplot(2,1,1)
stem(n,R)
subplot(2,1,2)
stem(n,Y,'r')

2. Removing noise from signal:

n=[0:100];
x=sin(2*pi*0.05*n); %original signal
y=wgn(1,length(n),5);%wgn noise
%noisy signalz=x+y;
%Length of the MAM=3;
%impulse response for FIR is bb=ones(1,M)/M;
z_appro = conv(b,z); %recovered signal
subplot(2,2,1)
stem(n,x)
subplot(2,2,2)
stem(n,y)
subplot(2,2,3)

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

stem(0:M-1,b)
subplot(2,2,4)
stem(z_appro(1:length(n)))

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

c. Apply convolution operation on your and yours class fellow image .

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LABORATORY 3:
ALIASING EFFECT IN TIME AND FREQUENCY DOMAIN

OBJECTIVES:
 To Trace Aliasing Effect in Time and Frequency Domain

Place a check mark in the Assigned column next to the exercises your instructor has assigned to
you. Attach this cover sheet to the front of the packet of materials you submit following the
laboratory.

Activities Remarks Signature


Pre-lab Exercises
In-lab Exercises
Take Home Exercises
Any Other

THEORY:
In order to perform Digital/DT Processing of Analog/CT signals, we need to do Analog to
Digital (A/D) Conversion. The first step in A/D conversion is CT to DT conversion.

The Sampling Process


Sampling is the first step in the process of converting a continuous analog signal to a sequence of

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

digital numbers. It is the Conversion of continuous-time signal into discrete-time signal and is
implemented by taking samples of the continuous-time signal at discrete instants of time. Nyquist
sampling theorem defines the minimum sampling rate to avoid aliasing. It says that the minimum
sampling rate must be twice that of the highest frequency component of the signal.

𝐹𝑆 ≥ 2𝐹𝑚𝑎𝑥

The Aliasing Effect


Aliasing is the phenomenon that results in loss of information when a CT signal is reconstructed
from its sample values. In principle, the original Analog signal can be reconstructed back from
the samples and aliasing can be avoided, provided that Nyquist sampling theorem was not
violated while sampling i.e. the sampling rate was at least twice the frequency of the highest
frequency component present in the signal.

Aliasing occurs when the sampling frequency is not above the Nyquist rate, i.e. twice the highest
frequency content of the signal. In the frequency domain, aliasing is expressed as high-frequency
components being present in the low-frequency range. In the time domain, aliasing is the loss of
detail in the signal, and the false perception of reading a low frequency signal. As such, aliasing is
an unwanted phenomenon, and is to be avoided.

Sketching Continuous Time and Discrete Time functions


sinccomputes the sinc function of an input vector or array, where the sinc function is:
1, 𝑡=0
𝑠𝑖𝑛𝑐(𝑡) = {𝑠𝑖𝑛𝑐(𝜋𝑡)
𝑡≠0
𝜋𝑡

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

t=linspace(-5,5,50); % generates lineraly spaced vectors. It gives direct control over the number
of points.
y=sinc(t); %returns an array y the same size as x, whose elements are the sinc function of the
element of x.
subplot(2,1,1)
plot(t,y)
subplot(2,1,2)
stem(t,y);

xlabel('Time (sec)');
ylabel('Amplitude');
title('Since Function')

Section A
Aliasing Effect in the Time Domain
With Aliasing
clf;
f=13;%frequency of sinusoid=13 Hz
T = 1/(13*1.5); %Sampling rate (1/T) is not following Nyquist sampling theorem
n = (0:T:1)';
xs = cos(2*pi*f*n);

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

t = [-0.5:0.004:1.5]';
ya = sinc((1/T)*t(:,ones(size(n))) - (1/T)*n(:,ones(size(t)))')*xs;
%This is Reconstruction lowpassfiltering,implemented in time-domain
subplot(2,1,1)
plot(n,xs,'o',t,ya);grid;%Reconstructed CT signal
xlabel('Time, sec');ylabel('Amplitude');
title('Reconstructed continuous-time signal y_{a}(t)');
axis([0 1 -1.2 1.2]);
subplot(2,1,2)
t=0:0.0005:1;
xa=cos(2*pi*f*t); %original CT Signal
plot(t,xa);grid;
xlabel('Time,sec');
ylabel('Amplitude');
title('Orignal Continuous-time signal x_{a}(t)');

axis([0 1 -1.2 1.2]);


%Note: Both Time-domain plots are not same, because of Aliasing.

Without Aliasing
clf;
f=13;%frequency of sinusoid=13 Hz
T = 1/(13*2); %Sampling rate (1/T) is following Nyquist sampling theorem
n = (0:T:1)';
xs = cos(2*pi*f*n); %cos(w0 k) where k is integer and w0
=2*pi*f*T=2.6*pi t = [-0.5:0.004:1.5]';

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

ya = sinc((1/T)*t(:,ones(size(n))) - (1/T)*n(:,ones(size(t)))')*xs;
%This is Reconstruction lowpassfiltering,implemented in time-domain
subplot(2,1,1)
plot(n,xs,'o',t,ya);grid;%Reconstructed CT signal
xlabel('Time, sec');ylabel('Amplitude');
title('Reconstructed continuous-time signal y_{a}(t)');
axis([0 1 -1.2 1.2]);

subplot(2,1,2)
t=0:0.0005:1;
xa=cos(2*pi*f*t); %original CT Signal
plot(t,xa);grid;
xlabel('Time,sec');
ylabel('Amplitude');
title('Orignal Continuous-time signal x_{a}(t)');
axis([0 1 -1.2 1.2]);

%Note: Both Time-domain plots are same, there is no of Aliasing.

Section B

Aliasing Effect in the Frequency-


Domain Sampling a Non-band limited signal
t=0:0.006:10;

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

xa=2*t.*exp(-t);
figure;
subplot(2,2,1)
plot(t,xa);grid
xlabel('Time sec');
ylabel('Amplitude');
title('Continuous-time signal x_{a} (t)');

subplot(2,2,2)
fa=0:0.001:10;
wa=2*pi*fa;
Xa=2./((1-wa.^2)+1i*2*wa); %Xa is freq. specturm (i.e CT Fourier Transform) of xa. It's a non-
bandlimited signal
plot(fa(1:1500), abs(Xa(1:1500))); grid
xlabel('Frequency, Hz');
ylabel('Amplitude');

title('Xa Frequency spectrum');

subplot(2,2,3)
T=0.5; %Sampling-Rate selected as 2 Hz
%Aliasing will always occur as this is non-bandlimited signal
n=0:T:10;
xs=2*n.*exp(-n); % Actually sampled xs=2*T*n.*exp(-T.*n)
k=0:length(n)-1;
stem(k,xs);
grid;
xlabel('Time index n');
ylabel('Amplitude');
title('Discrete-timrdignal x[n]');

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

subplot(2,2,4)
wd=0:pi/255:pi;
Xs=freqz(xs,1,wd); %Xs is Freq. spectrum (i,e. DT Fourier Transform) of xs
%CTFT of upto freq. 1 Hz(Nyquist frequency) has been captured by DTFT (and
%the rest discraded), because sampling-rate is 2 Hz.

plot(wd/(2*T*pi),T*abs(Xs));
grid;
xlabel('Frequency Hz');
ylabel('Amplitude');
title('Xs Frequency spectrum');

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Section C
Assignment Task
Aliasing Using
Simulink
Now to observe the effects of aliasing.

1. Create this Model in Simulink

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

2. Now insert the following setting in “Sine wave” block.

3. Now insert the following setting in “Sine wave1” block.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

4: Now change the axis of scope to 2 and check the results.

Explanation: Two continuous signals having two frequencies, one is 40 Hz and other
140 Hz. Both sampled at 100 samples/sec. but the plots of both signals are same. It
means that 40 Hz and 140 Hz are alias frequencies when sampled at 100 samples/sec.

EXERCISE:

1. Complete “Assignment Task” of Section C in Lab manual and print the results with your assignments.

2. Run the program of “Aliasing Effect in the Time Domain” and use “sin” signal as your signal and vary the
values of frequencies to show your practice. Also print the results.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

3. What are Alias frequencies?

4. If sampling-rate is 40 Hz and freq. of CT sinusoid (which is being sampled) is 30 Hz, what will be the
values of Alias frequency?

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LAB # 04 INTRODUCTION TO DSK C6416T & C6711


PROCESSOR AND RELATED
SOFTWARES

OBJECTIVES:
In this lab we give the brief introduction of DSP kits in which we include:
 System requirements for installing DSK contents.
 Debug hints and troubleshooting.
 DSP board components.
 Configuration parameters settings.
 DSP board features.
 Operate CCS Software.
 Practice examples of LED Dancing program.

THEORY:

C6416T Overview:

The purpose of this lab is to familiarize you with DSP Kit TMS320C6416T Simulink,
Real Time Workshop and Link for CCS and how they interact with Code Composer
Studio (CCS). This lab involves building relatively simple systems using Simulink rather
than CCS.
DSP Board: Texas Instruments TMS320C6416T (DSP Starter Kit) DSK
The 6416 DSP Starter Kit (DSK) is an all-in-one evaluation platform for the
TMS320C6416T Digital Signal Processor from Texas Instruments. It includes a target
board that can be used as a reference design for interfacing the DSP to common devices
such as SDRAM, Flash and a codec as well as a Code Composer Studio development
tools. An on-board JTAG emulator allows debug from Code Composer Studio through
your PC's USB port.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Figure 1.1: Block Diagram of TMS320C6416T Board

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

The TMS320C6416T DSK comes with a full complement of on-board devices that suit a
wide variety of application environments. Key features include:
• A Texas Instruments TMS320C6416T DSP operating at 1 Gigahertz.
• An AIC23 stereo codec
• 16 Mbytes of synchronous DRAM
• 512 Kbytes of non-volatile Flash memory
• 4 user accessible LEDs and DIP switches
• Software board configuration through registers implemented in CPLD
• Configured boot options and clock input selection
• Standard expansion connectors for daughter card use
• JTAG emulation through on-board JTAG emulator with USB host interface or external
emulator
• Single voltage power supply (+5V)

 System Requirements for installing DSK contents

 500MB of free hard disk space


 Microsoft Windows™ 2000/XP
 128MB of RAM
 16-bit color display
 CD-ROM Drive

 Testing Your Connection

If you want to test your DSK and USB connection you can launch the C6416 DSK
Diagnostic Utility from the icon on your desktop.

Figure 1.2: 6416 DSK Diagnostics icon


From the diagnostic utility, press the start button to run the diagnostics. In
approximately 30 seconds all the on-screen test indicators should turn green.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Figure 1.3: 6416 DSK Diagnostics window


 Starting Code Composer

To start Code Composer Studio, double click the 6416 DSK CCStudio icon on your
desktop.

Figure 1.4: 6416 DSK CCStudio v3.1 icon


 Debug Hints and Trouble Shooting

1. If installing on Windows XP and your PC is connected to the internet through a


firewall the USB install may take up to 15 minutes if you let it complete normally.
The work-around for this issue is to simply disconnect your network cable during the
USB hardware install.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

2. Make sure all of the Configuration Switches (SW3) are set in the off position. This
configures the DSK for the factory default settings of little endian processor mode
booting out of the on-board Flash memory.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

3. If you want to verify a successful USB driver install, open your device manager by
right clicking on the My Computer icon on your desktop and selecting Properties -->
HW --> Device Manager. You should see a new class “SD USB Based Debug Tools”
and one Spectrum Digital TMS320C6416 DSK installed.
4. The BUSY LED above the USB connector comes on when power is applied to the DSK. Do
not launch Code Composer until the LED is off.

DSP Board Components

DSP board components and their specifications are given in table below:

Components Details
TMS320C6416T DSP 1GHz MHz, fixed point, 1Mbyte internal RAM
CPLD Programmable "glue" logic

External SDRAM 16Mbytes, 64-bit interface


External Flash 512Kbytes, 8-bit interface
AIC23 Codec Stereo, 8KHz –96KHz sample rate, 16 to 32 bit samples, Mic,
line-in, line-out and speaker jacks
4 User LEDs Writable through CPLD

4 User DIP Switches Readable through CPLD


8 Configuration Switches Selects power-on configuration and boot modes
Daughter card Expansion Allows user to enhance functionality with add-on daughter
Interface cards
HPI Expansion Interface Allows high speed communication with another DSP

Embedded JTAG Emulator Provides high speed JTAG debug through widely accepted
USB host interface
Table 1.5: 6416T DSK Specifications

 Configuration Switches

The 6416T DSK has 8 configuration switches that allow users to control the operational
state of the DSP when it is released from reset. The configuration switch block is labeled
SW3 on the DSK board, next to the reset switch. Configuration switch 1 controls the

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

endianness of the DSP while switches 2 and 3 configure the boot mode that will be used
when the DSP starts executing. Configuration switches 5-8 used to configure the EMIF
and DSP frequencies.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

The default configuration settings are to have all switches off. This configures the DSK
to boot from the on-board Flash in little endian mode.

Table 1.6: Configuration switch settings

The following table shows the switch position settings for desired CPU and EMIFA
frequencies.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Table 1.7: CPU and EMIFA frequency configuration switch settings

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

 AIC23 Stereo Codec

The DSK uses a Texas Instruments AIC23 (part #TLV320AIC23) stereo codec for input
and output of audio signals. The codec samples analog signals on the microphone or line
inputs and converts them into digital data that can be processed by the DSP. When the
DSP is finished with the data it uses the codec to convert the samples back into analog
signals on the line and headphone outputs so the user can hear the output.
Four industry-standard 3.5mm stereo jack connectors are used in the audio interface:
 One jack is for connecting audio input from a microphone.
 One jack for connecting stereo audio line input.
 One jack for outputting stereo audio line output (un-amplified).
 One jack for connecting stereo audio output to a speaker (amplified).

 User LEDs

The four user controllable LEDs allow for user feedback and display of simple status
information. They are controlled by writing to the CPLD USER_REG register. They can
also be set or cleared through the LED Module of the Board Support Library.

 Status Indicators

The status indicators monitor the following functions. The PWR LED is hardwired on the
+5V supply and will illuminate whenever the power is connected. The RESET LED
illuminates when the RESET event occurs. The USB_IN_USE LED is on when USB
emulation is used and goes off when an external emulator is applied. The USB BUSY
LED indicates that a USB emulator transaction is in progress.

 DIP Switches

The four DIP switches allow simple feedback from the user. The DIP switches can be
read through the CPLD USER_REG register. They can also be read using the DIP Switch
module of the Board Support Library.

 Power Supply

An included 5V external power supply is used to power the board. On-board voltage
regulators provide the 1.4V DSP core voltage, 3.3V digital and 3.3V analog voltages. A
voltage supervisor monitors the internally generated voltage, and will hold the board in
reset until the supplies is within operating specifications and the reset button is released.
If desired, JP1, JP2 and JP4 can be used as power test points for the core, I/O and system
power supplies.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

5.1.3 DSP Board Features


The DSK supports a TMS320C6416T DSP which can operate at a clock frequency of up
to 1 GHz. The DSP core is designed for extremely high performance. Beyond the DSP

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

core, the ‘6416 integrates a number of on-chip resources that improve functionality and
minimize hardware development complexity. Features of the processor include:

 EMIFA – External Memory Interface A

A 64-bit bus on which external memories and other devices can be connected. It included
features like internal wait state generation and SDRAM control. The EMIF can interface
to both synchronous and asynchronous memories.

 EMIFB – External Memory Interface B

A 16-bit bus on which external memories and other devices can be connected. Similar to
EMIFA but with narrower bus width. Used for devices those are not as performance
critical or do not require maximum bandwidth.
 McBSPs – Multichannel buffered serial ports

Each McBSP can be used for high speed serial data transmission with external devices or
reprogrammed as general purpose I/Os. McBSP2 is used to transmit and receive audio data from
the AIC23 stereo codec. McBSP1 is used to control the codec through its serial control port.
McBSP0 is always brought out to the peripheral expansion connector. The MISC register in the
CPLD is used to select whether McBSP1 and McBSP2 are routed to the AIC23 or the expansion
connectors.

 1Mbyte Internal Memory

High speed internal memory for maximum performance.

 On-chip PLL

Generate processor clock rate from slower external clock reference.

 3 Timers

Generate periodic timer events as a function of the processor clock. Used by DSP/BIOS to create
time slices for multitasking.

 EDMA Controller

Enhanced DMA controller allows high speed data transfers without intervention from the DSP.

 Endianness

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Endianness is a term that refers to the byte ordering of multi-byte data types. Specifically,
a system is called big endian if byte 0 contains the most significant byte of the data or
little endian if byte 0 contains the least significant byte. The 6416 supports both modes
and the processor endianness can be controlled at boot time through one of the

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

configuration switches. The DSK default is little endian mode and all of the DSK specific
code examples are distributed in little endian format.
1.1.4Example of LED Dancing Program for C6416T DSK:
Program “led.c”:
*/
#include "ledcfg.h"
#include "dsk6416.h"
#include "dsk6416_led.h"
#include "dsk6416_dip.h"

/*
* main() - Main code routine, initializes BSL and runs LED application
*/

/*
* EXTRA: Pressing DIP switch #3 changes LED #3 from off to on.
*/
void main()
{
/* Initialize the board support library, must be first BSL call */
DSK6416_init();

/* Initialize the LED and DIP switch modules of the BSL */


DSK6416_LED_init();
DSK6416_DIP_init();

while(1)
{
/* Toggle LED #0 */
DSK6416_LED_toggle(0);

/* Check DIP switch #3 and light LED #3 accordingly, 0 = switch pressed */


if (DSK6416_DIP_get(3) == 0)
/* Switch pressed, turn LED #3 on
*/ DSK6416_LED_on(3);
else
/* Switch not pressed, turn LED #3 off
*/ DSK6416_LED_off(3);

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

/* Spin in a software delay loop for about 200ms


*/ DSK6416_waitusec(200000);
}
}

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Working:
This example blinks LED #0 at a rate of about 2.5 times per second using the LED
module of the DSK6416 Board Support Library. The example also reads the state of DIP
switch #3 and lights LED #3 if the switch is depressed or turns it off if the switch is not
depressed. The purpose of this example is to demonstrate basic BSL usage as well as
provide a project base for your own code. Please see the DSK6416 help file for more
detailed information.

DSP/BIOS is configured using the DSP/BIOS configuration tool. Settings for this
example are stored in a configuration file called led.cdb. At compile time, Code
Composer will auto-generate DSP/BIOS related files based on these settings. A header
file called ledcfg.h contains the results of the auto generation and must be included for
proper operation. The name of the file is taken from led.cdb and adding cfg.h.

The Board Support Library is divided into several modules, each of which has its own
include file. The file dsk6416.h must be included in every program that uses the BSL.
This example also includes dsk6416_led.h and dsk6416_dip.h because it uses the LED an
DIP modules.

C6711 Hardware

DSP Board: Texas Instruments TMS320C6711 (DSP Starter Kit) DSK

 DSP: Fixed‐point and floating‐point arithmetic, eight functional units (two


multipliers and sixALUs), 150 MHz clock (up to 900 MFLOPS), 32 general‐
purpose registers of 32‐bit word length, 64K (+2x4K) bytes internal memory,
DMA controller (16 channels),external memory interface (32‐bit address
space), multichannel serial port, host port interface.

 External Memory: 16M bytes SDRAM at 100 MHz and 128K bytes flash‐
programmable ROM.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Figure 1.8: C6711 Overview

 Troubles with CCS>Known Bugs

 CCS built and loaded the interrupt-based program successfully but it does not
run properly.
Restart the DSP program: Debug>Restart.
This problem happens very often, especially when it is first program after starting
CCS.

 Really nothing works anymore.


Close (or kill) CCS, power-down and power-up the DSP board, and start CCS again.

This problem happens when a big amount of data is transmitted through the parallel
connection (e.g. while debugging).

Quick Test of DSK

Launch CCS from the icon on the desktop. Press GEL>Check DSK>Quick Test.
The Quick Test can be used for confirmation of correct operation and installation.
The following message is then displayed:

Switches: 7
Revision: 2
Target is OK

Example of LED Dancing Program for C6711 DSK:


Since, it has been have observed that C6711 is interfaced by parallel port. The addresses
of the IO ports for the LEDs can be controlled with the help of specific code. The codes
and their respective operations are indicated in the table 9.1 as below:
Code Purpose Operation
0x07000000 To turn off all 3 LEDs
0x06000000 To turn on the first LED
0x05000000 To turn on the second LED
0x03000000 To turn on the third LED
Table 1.9: Codes and their specified operations in DSK C6711
The program based on C/C++ language is written below. This program will blink the

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LEDs so that it would look, that they are dancing. The Led 1 will glow for a moment and
as it turns off its neighbor led i.e. Led 2 will glow. As soon as the second led goes OFF
the Led 3 will start glowing and this phenomenon then continues like this on and an.

The program “led.c” is a simplified program and it requires basic skills of C language to
understand the coding. As C language is a pre-requisite to the DSP Labs so it is assumed
that every individual has a basic command on the C – language.
Program “led.c”:
#include "stdio.h"
#define LED_OFF
0x07000000 #define msec 500
void main(void)
{
Int LED[]={0x06000000,0x05000000,0x03000000};
short
i=0,toggle=0;
comm_poll();

printf("The LED
Dancing Program");
led_control(LED_OFF);
while(1)
{
led_control
(LED[i]);
delay_msec
(msec);
if(i==2)
togg
le=1
;
else
togg
le=
0
;
if(to
ggle
==0
) i+
+;
e

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

i
-
-
;
}
}

Working:
The function used in the above program i.e. “void led_control(int)” is used to
communicate with the DSK. The definition of the function shows, it could accept an
integer type data from the ‘MAIN’ for further proceedings. The data sent through ‘Led.c’
will be the appropriate code to turn on/off the LEDs according to the given syndrome.
Remember that the LEDs are connected in the common anode configuration.
Another function used in the above program i.e. “delay_msec(msec)” is generating a
relevant delay so that human eye can detect the changes easily otherwise it would not be
possible to see the differences. A delay is necessary to observe the things with naked eye.
In the delay function the ‘ms’ is the argument that represents time in milliseconds. The
unction creates a 500-millisecond time delay so that the turning on or off of an LED

would be properly visible. Actually, the delay function uses the internal 32-bit timer
(Timer 0) to create delay. The rest of the program is very simple to understand if you
properly learned the C-programming language course in the second semester. To run this
program correctly you must include the following files:
1. C6xdsk.cmd 6. Vectors.asm
2. C6xdsk.h 7. Ledcontrol.c
3. C6xinterrupts.h 8. Delay.c
4. C6xdskinit.h 9. Rts6701.lib
5. C6xdskinit.c 10. Led.c

All the files are provided by the Texas Instruments except ‘ledcontrol.c’ and ‘delay.c’
which will provide to you by instructor or alternatively can search on Google (easily
available). The description of all the files except ‘ledcontrol.c’ and ‘delay.c’ is given in
the first chapter of the Ralph Chasing. Whereas the ‘ledcontrol.c’ is used to control the

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LEDs and the ‘delay.c’ is used to produce time delay.

Configuration Parameters for C6000 Hardware

1. Launch MATLAB.
2. At the MATLAB Command line, type Simulink to launch Simulink.
3. Create a new model in Simulink.
4. To open the Configuration Parameters, select Simulation>Configuration
Parameters.
5. In the select tree, choose the Real-Time Workshop category.
6. For Target Selection, choose the file ti c6000.tlc. Real-Time Workshop will
automatically change the Make Command and Template make file selections.
7. Choose the Optimization category in the select tree. For Simulation and Code
generation, un-select Block reduction optimization and Implement logic
signals.
8. Choose the TI C6000 target selection. Set code generation target type to
C6711DSK.
9. Choose the TI C6000 compiler. Set Symbolic debugging.
10. In the select tree, choose the Debug category. Select verbose build here.
11. In the select tree, choose the Solver category. Ensure that Solver is set to
Fixed type/discrete.

EXERCISE:

Write a brief report (2 to 3 pages) about your learning, observation and understanding of this

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LABORATORY PART (B)


THE AUDIO GENERATION USING DSK C6416T Board
OBJECTIVES:
 React to Operation & controlling of MIC and speakers by using DIP switches.
 Generation of tone

THEORY:
* This example uses the AIC23 codec module of the 6416 DSK Board Support Library
to generate a 1KHz sine wave on the audio outputs for 5 seconds. The sine wave data is
pre-calculated in an array called sinetable. The codec operates at 48 KHz by default.
Since the sine wave table has 48 entries per period, each pass through the inner loop takes
1 millisecond. 5000 passes through the inner loop takes 5 seconds.
Please see the 6416 DSK help file under Software/Examples for more detailed
information.
* DSP/BIOS is configured using the DSP/BIOS configuration tool. Settings for this
example are stored in a configuration file called tone.cdb. At compile time, Code
Composer will auto-generate DSP/BIOS related files based on these settings. A header
file called tonecfg.h contains the results of the autogeneration and must be included for
proper operation. The name of the file is taken from tone.cdb and adding cfg.h.
#include "tonecfg.h"
* The 6416 DSK Board Support Library is divided into several modules, each of which
has its own include file. The file dsk6416.h must be included in every program that
uses the BSL. This example also includes dsk6416_aic23.h because it uses the AIC23
codec module.

#include "dsk6416.h"
#include
"dsk6416_aic23.h"

/* Length of sine wave table */


#define SINE_TABLE_SIZE 48

/* Codec configuration settings */


DSK6416_AIC23_Config config = {
0x0017, // 0 DSK6416_AIC23_LEFTINVOL Left line input channel volume

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

0x0017, // 1 DSK6416_AIC23_RIGHTINVOL Right line input channel volume


0x00d8, // 2 DSK6416_AIC23_LEFTHPVOL Left channel headphone volume
0x00d8, // 3 DSK6416_AIC23_RIGHTHPVOL Right channel headphone
volume 0x0011, // 4 DSK6416_AIC23_ANAPATH Analog audio path
control
0x0000, // 5 DSK6416_AIC23_DIGPATH Digital audio path control
0x0000, // 6 DSK6416_AIC23_POWERDOWN Power down control

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

0x0043, // 7 DSK6416_AIC23_DIGIF Digital audio interface


format 0x0001, // 8 DSK6416_AIC23_SAMPLERATE Sample rate
control 0x0001 // 9 DSK6416_AIC23_DIGACT Digital
interface activation
};

/* Pre-generated sine wave data, 16-bit signed samples


*/ Int16 sinetable[SINE_TABLE_SIZE] = {
0x0000, 0x10b4, 0x2120, 0x30fb, 0x3fff, 0x4dea, 0x5a81, 0x658b,
0x6ed8, 0x763f, 0x7ba1, 0x7ee5, 0x7ffd, 0x7ee5, 0x7ba1, 0x76ef,
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
};

/*
* main() - Main code routine, initializes BSL and generates tone
*/
void main()
{
DSK6416_AIC23_CodecHandle hCodec;
Int16 msec, sample;

/* Initialize the board support library, must be called first */


DSK6416_init();

/* Start the codec */


hCodec = DSK6416_AIC23_openCodec(0, &config);

/* Generate a 1KHz sine wave for 5 seconds */


for (msec = 0; msec < 5000; msec++)
{
for (sample = 0; sample < SINE_TABLE_SIZE; sample++)
{
/* Send a sample to the left channel */
while (!DSK6416_AIC23_write(hCodec, sinetable[sample]));

/* Send a sample to the right channel */

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

while (!DSK6416_AIC23_write(hCodec, sinetable[sample]));


}
}
/* Close the codec */
DSK6416_AIC23_closeCodec(hCodec);
}

EXERCSE:

Task #1: Keeping in view the theory for sinusoidal wave generation, write a polling-
based program so that once dip switch #3 is pressed, LED #3 turns on and a 666.66
Hz sinusoidal is generated for approximately 5 seconds. If it’s again turned off, the
sine wave gets grounded (zero amplitude).

Task #2: Connect MIC and Speakers to In and Out of DSP kit ports respectively. Now if
you press dip switch # 1, the MIC starts working and vice versa.

Task #3: In continuation to task 3, import a slider of volume (named as “amplitude.gel”;


available easily on Google, if not provided within CCS package). Observe the change in
audio by increasing / decreasing the slider.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LABORATORY 5:
Z-TRANSFORM & INVERSE Z-TRANSFORM
OBJECTIVES:
Z-transform
 To trace the response of various systems that gives its poles and zero diagrams
Inverse Z-transform and its applications
 To trace the use of inverse z-transform as an important tool
 some basic MATLAB commands for simple IZT.

Place a check mark in the Assigned column next to the exercises your instructor has
assigned to you. Attach this cover sheet to the front of the packet of materials you submit
following the laboratory.

Activities Remarks Signature


Pre-lab Exercises
In-lab Exercises
Take Home Exercises
Any Other

Z-transform
The z - transform technique is an important tool in the analysis of characterization of
DTS and LTI systems. The Z-transform, like many other integral transforms, can be
defined as either a one-sided or two-sided transform.
The z-transform of a discrete signal x(n) is defined as a power series:

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

or

or

Note, z is complex and X (z) is also complex.


Z transform is similar to polynomial notation with coefficients equal to the value of n at
the respective samples. Since z-transform is a power series, hence along with the
transformation, we have to define for which values of z, the resultant X(z) is finite
(converges). This is called the Region of Convergence (ROC).

Bilateral Z-transform
The bilateral or two-sided Z-transform of a discrete-time signal x[n] is the function X(z)
defined as where n is an integer and z is, in general, a complex number: z = Aejφ , where
A is the magnitude of z, and φ is the angular frequency (in radians per sample).
Unilateral Z-transform
Alternatively, in cases where x[n] is defined only for n ≥ 0, the single-sided or unilateral
Ztransform is defined as In signal processing, this definition is used when the signal is
causal. An important example of the unilateral Z-transform is the probability-generating
function, where the component x[n] is the probability that a discrete random variable
takes the value n, and the function X(z) is usually written as X(s), in terms of s = z − 1.
The properties of Z-transforms (below) have useful interpretations in the context of
probability theory.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Let the difference equation be:


x(n) = (1/4) u(n)

MATLAB Code
syms z n
a = ztrans((1/4)^n)

Find the poles and zeros of :


n=[1 -1.618 1];
d=[1 -1.5161 0.878];
roots(n)
roots(d)
zplane(n,d)
figure
pzmap(n,d)

Analysis of DT signals and systems in z-domain:


[z,p,k] = tf2zp(n,d); %to find the gain of pole-zero system
[n,d] = zp2tf(z,p,k); %to find poles and zeros from gain information

Compute z-plane function and Display the pole-zero diagram of z-function.

Example

X(Z) = (1-1.618z-1+z-2)/(1-1.516z-1+0.878z-2)

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

n = [1 -1.618 1];

d = [1 -1.516 0.878];

roots(d);

roots(n);

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

zplane(n,d);
pzmap(n,d);

IZT of X(Z) =
(z/(z-2))

Iztrans(z/(z-2)

EXERCISE

Determine the ZT of the


following sequences:
1. x(n) = 2 x 2n + 4(1/2)n
2. x(n) = (1/4)n U[n-1];
3. x(n) = -α u(-n-1)
{where α = 0.5}
4. x(n) = {1,3, 5, 6, 3,0,
0, 1, 4}

B. Determine the IZT of


the following sequences:
1. Calculate the IZT of e
(x/z)
2. Generate the pole-zero
diagram and calculate
any two ZT from your
lectures

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LAB# 06 DISCRETE FOURIER TRANSFORM

 To Trace the concept of Discrete Fourier Transformation (DFT).

Place a check mark in the Assigned column next to the exercises your instructor has
assigned to you. Attach this cover sheet to the front of the packet of materials you submit
following the laboratory.

Activities Remarks Signature


Pre-lab Exercises
In-lab Exercises
Take Home Exercises
Any Other

THEORY:
The discrete Fourier transform (DFT) is one of the specific forms of Fourier analysis. It
transforms one function into another, which is called the frequency domain
representation, or simply the DFT, of the original function (which is often a function in
the time domain). But the DFT requires an input function that is discrete and whose non-
zero values have a limited (finite) duration. Such inputs are often created by sampling a
continuous function, like a person's voice. And unlike the discrete-time Fourier transform
(DTFT), it only evaluates enough frequency components to reconstruct the finite segment
that was analyzed. Its inverse transform cannot reproduce the entire time domain, unless
the input happens to be periodic (forever). Therefore it is often said that the DFT is a
transform for Fourier analysis of finite-domain discrete-time functions. The sinusoidal
basis functions of the decomposition have the same properties.
Since the input function is a finite sequence of real or complex numbers, the DFT is ideal
for processing information stored in computers. In particular, the DFT is widely
employed in signal processing and related fields to analyze the frequencies contained in a

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

sampled signal, to solve partial differential equations, and to perform other operations
such as convolutions. The DFT can be computed efficiently in practice using a fast
Fourier transform (FFT) algorithm.

The sequence of N complex numbers x0 ….xN−1 is transformed into the sequence of N


complex numbers X0….XN−1 by the DFT according to the formula:

Where 𝑒2𝜋𝑖/𝑁is a primitive Nth root of unity

Where e is the base of the natural logarithm, 𝑙 is the imaginary unit (i2 = − 1), and π is
pi. The transform is sometimes denoted by the symbol as in:

MATLAB Code
K = 0:3;
x = [1 1 2 2];
xk = fft(x,4);
subplot(211);
stem(k,abs(x));
xlabel(‘k’);
ylabel(‘Amplitude’);
grid;
title(‘DFT’);
subplot(212);
stem(k,angle(x));
xlabel(‘k’);
ylabel(‘Phase’);

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

grid;

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Inverse Discrete Fourier Transform


The inverse discrete Fourier transform (IDFT) is given by

A simple description of these equations is that the complex numbers X k represent the
amplitude and phase of the different sinusoidal components of the input "signal" X n. The
DFT computes the Xk from the Xn, while the IDFT shows how to compute the Xn as a
sum of sinusoidal components
with frequency k/N cycles per sample.

In Matlab we can find DFT by using


following commands
FFT Discrete Fourier transform
FFT(X) is the discrete Fourier transform (DFT) of vector X. For matrices, the FFT
operation is applied to each column. For N-D arrays, the FFT operation operates on
the first non-singleton dimension.
FFT(X,N) is the N-point FFT, padded with zeros if X has less than N points and
truncated if it has more.
FFT(X,[],DIM) or FFT(X,N,DIM) applies the FFT operation across the dimension
DIM.
For length N input vector x, the DFT is a length N vector X, with elements
N
X(k) =sum x(n)*exp(-j*2*pi*(k-1)*(n-1)/N), 1 ≤ k ≤ N.
n=1
The inverse DFT (computed by IFFT) is given by
N
x(n) = (1/N) sum X(k)*exp( j*2*pi*(k-1)*(n-1)/N),
1 ≤ n ≤ N.
k=1

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

EXERCISE

Task #1: Data sequence is given as follows:


xn = {1 0 0 1}
Compute by command the DFT function Xk.
Task #2: Use FFT command to compute the DFT function for the given data sequence in
Task #1.
Task #3: Plot the magnitude and phase graphs of DFT function of Task #2 in separate
window.
Task #4: Plot ansequence. Where a=0.8 and define at n=0 to 35. Find its DFT, plot its
magnitude and phase graphs also.
Task #5: Take IDFT of the results of Task #2 and verify that it gives you the same
sequence as mention in Task #1.
Task #6: Design a DFT algorithm on MATLAB. The DFT is defined by the formula

Task#7

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Name:_____ _ _ _ _ __ RollNo:

LABORATORY 7:
OPEN ENDED LAB

Title:

1. Objective:

2. Hardware/Software required:

3. Theory:

4. Coding:

5. Results & Discussions:

6. Conclusion:

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Teacher’s Sign:

LABORATORY 8
THE LED DANCING PROGRAM FOR C6416T Board

OBJECTIVE:
 To follow the simple LED-dancing programs that will control LEDs on the DSK
board. Controlling of LEDs blinking by using DIP switches.

THEORY:
DSP/BIOS provide CCS with the capability for analysis, scheduling, and data exchange
in real time [1–5]. An application program can be analyzed while the DSP is running
(the target processor need not be stopped). Many DSP/BIOS application programming
interface (API) modules are available for real-time analysis, I/O, and so on.
As the system starts the DSP processor by default starts working in 32-bit mode. So, the
configuration setting do not needs to be changed.

C6711 DSK Processor:


Since, it has been have observed that C6711 is interfaced by parallel port. The
addresses of the IO ports for the LEDs can be controlled with the help of specific code.
The codes and their respective operations are indicated in the table 8.1 as below
Code Purpose Operation
0x07000000 To turn off all 3 LEDs
0x06000000 To turn on the first LED
0x05000000 To turn on the second LED
0x03000000 To turn on the third LED
Table 8.1: Codes and their specified operations in DSK C6711

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

The program based on C/C++ language is written below. This program will blink the
LEDs so that it would look, that they are dancing. The Led 1 will glow for a moment and
as it turns off its neighbor led i.e. Led 2 will glow. As soon as the second led goes OFF
the Led 3 will start glowing and this phenomenon then continues like this on and an.

The program “led.c” is a simplified program and it requires basic skills of C language to
understand the coding. As C language is a pre-requisite to the DSP Labs so it is assumed
that every individual has a basic command on the C – language.
Program “led.c”:

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

#include "stdio.h"
#define LED_OFF
0x07000000 #define msec 500
void main(void)
{ IntLED[]={0x06000000,0x05000000,0x03000000
};
shorti=0,toggle=0;
comm_poll();
printf("The LED
Dancing Program");
led_control(LED_OFF)
; while(1)
{
led_control
(LED[i]);
delay_msec
(msec);
if(i==2)
togg
le=1
;
else
togg
le=
0
;
if(to
ggle
==0
) i+
+;
e

l
s

i
-
-
;
}

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Working:
The function used in the above program i.e. “void led_control(int)” is used to
communicate with the DSK. The definition of the function shows, it could accept an
integer type data from the ‘MAIN’ for further proceedings. The data sent through ‘Led.c’
will be the appropriate code to turn on/off the LEDs according to the given syndrome.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Remember that the LEDs are connected in the common anode configuration.
Another function used in the above program i.e. “delay_msec(msec)” is generating a
relevant delay so that human eye can detect the changes easily otherwise it would not be
possible to see the differences. A delay is necessary to observe the things with naked eye.
In the delay function the ‘ms’ is the argument that represents time in milliseconds. The
unction creates a 500-millisecond time delay so that the turning on or off of an LED
would be properly visible. Actually, the delay function uses the internal 32-bit timer
(Timer 0) to create delay. The rest of the program is very simple to understand if you
properly learned the C-programming language course in the second semester. To run this
program correctly you must include the following files:
6. C6xdsk.cmd 6. Vectors.asm
7. C6xdsk.h 7. Ledcontrol.c
8. C6xinterrupts.h 8. Delay.c
9. C6xdskinit.h 9. Rts6701.lib
10. C6xdskinit.c 10. Led.c

All the files are provided by the Texas Instruments except ‘ledcontrol.c’ and ‘delay.c’
which will provided to you by instructor or alternatively can search on Google (easily
available). The description of all the files except ‘ledcontrol.c’ and ‘delay.c’ is given in
the first chapter of the Ralph Chasing. Whereas the ‘ledcontrol.c’ is used to control the
LEDs and the ‘delay.c’ is used to produce time delay.
The program written below will show the status of the switch. As the position of the
switch will change on the DSK, it would read that change and show the correct value of
the switch in binary format as it is indicated in table 9.2 at the end of this laboratory
exercise.

Program “Switch.c”:
#include
"stdio.h
" void
main(vo
i d)
{
unsigned
short
sw,temp=37;

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

comm_poll();
printf("The Switch value Reading Program"); while(1)
{
sw=s
w_re
a

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

d();
if(sw!
=temp
)
{
temp=sw;
printf("\nThe User Switch Value is %d",sw);
}
}
}
Working:
The function used in the above program i.e. ‘short sw_read(void)’ reads the switch value
from the user switches and return its value as a short type. To run this program correctly
you must include the following files:

1. C6xdsk.cmd 6. Vectors.asm
2. C6xdsk.h 7. Switch_read.c
3. C6xinterrupts.h 8. Rts6701.lib
4. C6xdskinit.h 9. Switch.c
5. C6xdskinit.c

All the files are provided by the Texas except ‘switch_read.c’. The description of all
the files except ‘switch_read.c’ is given in the first chapter of the Ralph Chasing,
while ‘switch_read.c’ is used to read the current status of the switch.

C6416T DSK Processor:


This example illustrates the use of the periodic function manager within the configuration
file to control the blinking rates of the four onboard LEDs of C6416. The C source
program “bios_4led.c” is written below. Create the “.cdb” configuration file using four
functions from the PRD-Periodic Function Manager: PRD_blinkLED0, . . . ,
PRD_blinkLED3 (CCS software package for C6416 will automatically create it because
it supports plug and play USB interface) with the following periods: 50, 100, 200, and
400ms and associated functions _blinkLED0, . . . , blinkLED3, respectively. Save and
add this configuration file to the project along with the BSL support library file. The
linker command file, auto generated by the configuration file, needs to be added to the
project (the other auto generated support files will be added). The necessary files for this
project are in the folder “bios4LED”. Build this project as bios_4led. Verify the different
blinking rates of each of the LEDs, ranging from approximately 50ms (LED0) to 400ms

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

(LED3). Change the blinking rates by changing the values of the periods set in the
configuration file.
//Bios_4LED.c Blinking of LEDs at different rates using
DSP/BIOS #include "bios_4ledcfg.h" //generated by .cdb file

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

#include "dsk6416.h" //BSL support


file void blinkLED0()
{
DSK6416_LED_toggle(0); //toggle LED0(50ms)
}
void blinkLED1()
{
DSK6416_LED_toggle(1); //toggle LED1(100ms)
}
void blinkLED2()
{
DSK6416_LED_toggle(2); //toggle LED2(200ms)
}
void blinkLED3()
{
DSK6416_LED_toggle(3); //toggle LED3(400ms)
}
void main()
{
DSK6416_init(); //init BSL
}

Reading the Switch Value for both C6711 and C6416 Processors:
It is also a very simple program that demonstrates how to read switch value from the
switches on the DSK board. For reading the Switches, again the DSP processor must be
in the 32-bit mode. You also need to know the address of the IO port and the data bits to
which the switches are attached. You also have to shift the bits in order to get correct
value.
The Table 8.2 indicates the relationship between the status of the switch and the
value generated in relation to it.
DIP Switch 3 DIP Switch 2 DIP Switch 1 Value
Off Off Off 000

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Off Off On 001


Off On Off 010
Off On On 011
On Off Off 100

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

On Off On 101
On On Off 110
On On On 111
Table 8.2: Switch status and its value

EXERCISE:

Following tasks are required to be performed on both the DSK processors i.e. C6711
& C6416T.

Task #1: Write a program such that the first LED blinks three times, then the second
LED blinks two times and then the third LED blinks only once. After this sequence,
reverse the order i.e. the third LED blinks for three times, then the second one blinks
two times and the first LED blinks one time. This process should continue indefinitely.

Task #2: Write a program such that when the user presses the switches the LEDs will be
turned on according to the following table:
S# Switch 3 Switch 2 Switch 1 LED 3 LED 2 LED 1
1 Off Off Off Off Off Off
2 Off Off On Off Off On
3 Off On Off Off On Off
4 Off On On Off On On
5 On Off Off On Off Off
6 On Off On On Off On
7 On On Off On On Off
8 On On On On On On

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LABORATORY 09:
BASIC OPERATIONS ON IMAGE PROCESSING

OBJECTIVES:
 Follow instructions to perform basic operations on image processing

Place a check mark in the Assigned column next to the exercises your instructor has
assigned to you. Attach this cover sheet to the front of the packet of materials you submit
following the laboratory.

Activities Remarks Signature


Pre-lab Exercises
In-lab Exercises
Take Home Exercises
Any Other

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Image reading:
The command in matlab to read an image is imread() where inside the bracket the name
of the file to be read is mentioned e.g. ‘cameraman.tif’. Matlab supports a wide variety of
image types with various parameters. See the Matlab help for full list of supported files
and diferent imread() command options. Note that we onlly need the basic command
format.
In case of reading an indexed image, color map can be read as well using the folloing
command:
[X,map] = imread(‘An indexed image name’)
where X is the image and map stores the color map. The code below reads different kind
of images. Note that there are four types of concerned images, namely, RGB (true color),

indexed image, grayscale and binary. In addition, data type of the images once read can
be of many data format incluing double, uint8 (unsigned integer 8 bit representation) and
logical (i.e. binary). The size of the image can be seen using the command size().
Code:
clear all
clc
close all

%Reading three types of images

a=imread('valley.jpg');
[b,map]=imread('sample_index.png');
c=imread('cameraman.tif');
d=imread('circles.png');

%Viewing size
[row,col]=size(a)

Some of the image types allow you to manipulate images with different parameters. The
code below shows the amount of pixel region to be read using the imread() command
with ‘PixelRegion’ parameter for Tiff images. In addition once the image is read, a
complete information about it can be extracted using the command imfinfo() which
includes bit depth, height and width, size, etc…
Basic Operations on Image Processing

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

imread: reads a grayscale or color image from the file specified by the string filename.
imshow: displays binary, grayscale and color image. For binary, displays pixels with the
value 0 as black and pixels with the value 1 as white. A color map matrix may have any
number of rows, but it must have exactly 3 columns. Each row is interpreted as a color,
with the first element specifying the intensity of red light, the second green, and the third
blue. Color intensity can be specified on the interval 0.0 to 1.0.
imnoise: adds noise of a given type to the intensity of image I. type is a string that can
have one of following values. See syntax and table below;
imnoise(I,type)
Value Descripion
'gaussian' Gaussian white noise with constant mean and variance
'localvar' Zero-mean Gaussian white noise with an intensity-
dependent variance
'poisson' Poisson noise
'salt & pepper' On and off pixels
'speckle' Multiplicative noise

imwrite: writes the image A to the file specified by filename in the format specified by
fmt.
imwrite(A,filename,fmt)

Format Full Name Variants

'bmp' Windows 1-bit, 8-bit, and 24-bit uncompressed images


Bitmap
(BMP)

'gif' Graphics 8-bit images


Interchange
Format (GIF)
'jpg' or'jpeg' Joint 8-bit, 12-bit, and 16-bit Baseline JPEG images
Photographic
Experts Note: imwrite converts indexed images to RGB
Group before writing data to JPEG files, because the
(JPEG) JPEG format does not support indexed images.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

pbm Portable Any 1-bit PBM image, ASCII (plain) or raw (binary)
Bitmap encoding
(PBM)

'pcx' Windows 8-bit images


Paintbrush
(PCX)

'pgm' Portable Any standard PGM image; ASCII (plain) encoded with
Graymap arbitrary color depth; raw (binary) encoded with up to
(PGM) 16 bits per gray value

'png' Portable 1-bit, 2-bit, 4-bit, 8-bit, and 16-bit grayscale images; 8-
Network bit and 16-bit grayscale images with alpha channels; 1-
Graphics bit, 2-bit, 4-bit, and 8-bit indexed images; 24-bit and 48-
(PNG) bit truecolor images; 24-bit and 48-bit truecolor images
with alpha channels

'tif' or'tiff' Tagged Baseline TIFF images, including 1-bit, 8-bit, 16-bit, and
Image File 24-bit uncompressed images, images with packbits
Format compression, images with LZW compression, and
(TIFF) images with Deflate compression; 1-bit images with
CCITT 1D, Group 3, and Group 4 compression;
CIELAB, ICCLAB, and CMYK images

Code:
%Image read can be done with other parameters which is different from
%format to format
a1=imread('cameraman.tif', 'PixelRegion', {[1 100],[1 100]});

%Image information
imfinfo('valley.jpg')

Pixel Extraction:
Once an image is loaded and saved in avariable, it is treated as a simple matrix and
hence, all rules and techniques for matrix manipulation can be applied directly with a
visible affect on the images. Size of matrix can vary from a single value, a vector, a 2 D
matrix or multi-dimensional matrix. Extracion information is done by indexing the
locations of pixels as shown below.
Code:

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

%Pixel extraction
a=imread('valley.jpg');
c=imread('cameraman.tif');
a_e=a(3:120,20:200,:);
c_e=c(:,[1:10:size(c,2)]);
figure, imshow(a_e)
figure, imshow(c_e)

Note that for comparing multiple images, all images can be displayed on a single figure
using a combination of subplot() and subimage() commands as schown below.
Code:
%Subimage display
[X1,map1] = imread('forest.tif');
subplot(2,2,1), subimage(b,map)
subplot(2,2,2), subimage(b,map1)
subplot(2,2,3), subimage(X1,map)
subplot(2,2,4), subimage(X1,map1)

Note that a special care has to be taked for RGB images as there are three layers of
monochromatic images aligned in a three dimensional matrix. Extraction of each layer is
done by suppressing the other layer clors by making them zero as shown below.
Code:
%RGB plane extraction
%Try this
a=imread('valley.jpg');
R_false=a(:,:,1);
figure
imshow(R_false)
%Now try this
temp = a;
temp(:,:,2:3)=0;
figure
imshow(temp)

Resolution operations:
The resolution is a term which indicated the number of spots of an image at sampling
time per unit distance. Usually is given as Dot per Inch (dpi). But image width and heigth
(resolution) indicated the number of pixels collected. The actual image size, the pixel
resolution (i.e. M × N) and dpi are related as follows:
𝑃𝑖𝑥𝑒𝑙 𝑟𝑒𝑠𝑜𝑙𝑢𝑡𝑖𝑜𝑛
𝑠𝑖𝑧𝑒 =
𝑑𝑝𝑖

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

The code below show how can dpi or any of the other two paramters mentioned in the
previous relation be changed. This is very useful in printing documents or images.
Code:
%dpi setting
Q1 = imread('riverboat.jpg');
[r1,c1] = size(Q1);
originaldpi = 300;
originalsize = [r1 c1]/originaldpi;
newsize = originalsize/2;
newdpi = [r1 c1]/newsize;
imwrite(Q1,'riverboat1.tif', 'compression', 'none', 'resolution', newdpi);
Q2 = imread('riverboat1.tif');
figure, imshow(Q1)
figure, imshow(Q2)

Now in order to perform zoom in or out, there are various methods for it. Zooming in
also called interpolation uses of the algorithms for sample interpolation such as nearest
neighbour, bilinear, cubic, etc…). Below are 4 different coded methods (i.e. zoom in and
out built in commands are not used) to perform interpolation using replica and nearest
neighbour methods.
Code:
%Resolution reduction method 1 (Zoom out)
f=imread('cameraman.tif');
[r,c]=size(f);
factor = 3; %must be integer
p = f([1:factor:r],[1:factor:c]);
figure, imshow(f)
figure, imshow(p)

%Resolution reduction method 2 (Zoom out) (Nearest neighbour)


f=imread('cameraman.tif');
[r,c]=size(f);
factor = 3.8; %Any factor
p = f(round([1:factor:r]),round([1:factor:c]));
figure, imshow(f)
figure, imshow(p)

%Resolution increment method 1 (Zoom in) (Replication)


f=imread('cameraman.tif');

[r,c]=size(f);
factor = 8; %must be integer
%Procedure to replicate in the column
direction temp1 = f';
temp2 = temp1(:)';

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

temp3 = repmat(temp2,factor,1);
temp4 = reshape(temp3,c*factor,r)'

%Procedure to replicate in the row


direction temp6 = [];
for t = 1 : r
temp6 = [temp6; repmat(temp4(t,:),factor,1)];
end
imshow(temp6)

%Resolution increment method 2 (Zoom in) (Nearest Neighbour)


f=imread('cameraman.tif');
[r,c]=size(f);
r1=r*1.5;
c1=c*3.25;

%To find the approximated location of the new pixels


index1 = round(linspace(1,r,r1));
index2 = round(linspace(1,c,c1));

%Zoomed in image
f1 = f(index1,index2)
imshow(f1)

To use a built in command, use imresize() using any algorithm, zoom in or out, by any
factor to any dimension.
Code:
%Builtin resolution command
f=imread('cameraman.tif');
A1 = imresize(f, 2);
A2 = imresize(f, 0.5);
A3 = imresize(f, [530, 600]);
A4 = imresize(f, [530, 600], 'bilinear');

Bit Resolution operations:


This referes to the number of bits per pixel. Higher this value better would be the quality
of color and grayscale shades in images. Low values results in false contours. In addition,
whenever an operation is performed on pixels, normalization is neede using mat2gray()
otherwise false result can be genrated. In other situaltions, there is no need for such
normalization. The code below shows the bits resolution effect on images with the use of
mat2gra() command.
Code:
%Bit resolution effect
f = [];

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

L = 8; %Intensity Levels
for t = 1 : L
f = [f (t-
1)*ones(500,2)]; end
imshow(f)
b=uint8(f);
figure, imshow(b)

%Normalized gray scale


c=mat2gray(b);
figure
imshow(c)

The method of normalization is indicated in the code below. The values of pixels become
0 to 1 (Grayscale) range.
Code:
%How mat2gray() works
a = [0:1:7]'
b = mat2gray(a);
c = (a - min(a)) /(max(a) - min(a));
d = [a b c]
g = imresize(c,[200,200]);
figure, imshow(g)

To compare the impact of bit resolution on images, the following code can be used.
Code:
%Bit resolution comparision
f=imread('cameraman.tif');
[r,c] = size(f);
L = [2 4 8 16 32 64 128 256];

w = f(:);
for t = 1 : length(L)
intensity = linspace(0,255,L(t));
for q = 1 : r*c
temp = abs( intensity - double(w(q)) );
h1 = find(temp==min(temp));
h2 = h1(1);
new_image(q) = h2;
clear h1 h2 temp
end
final_image = reshape(new_image,r,c);
subplot(2,4,t), subimage(mat2gray(final_image))
clear new_image final_image intensity

end

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Image data type conversion:


As mentioned before, images can be stored in differet data types. It is iprtant to take care
of these data types and to convert them from one form to another as some operations are

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

done only on same data types. The following code shows conversion from one form to
another.
Code:
%Image type conversion
a=imread('valley.jpg');
b=rgb2gray(a);
imshow(b)

c1 = im2bw(a);
c2 = im2bw(b);
c3 = im2bw(a,0.2);

figure
subplot(1,2,1), subimage(c1)
subplot(1,2,2), subimage(c1)
figure
subplot(1,2,1), subimage(c1)
subplot(1,2,2), subimage(c3)

RGB = imread('peppers.png');
[X,map] = rgb2ind(RGB,65536);
figure, imshow(RGB)
figure, imshow(X,map)

Image Location manipulation (Affine transforms):


Affine transforms such as rotation, shifting, reversing, trasnforming are geometric based
operations which are very useful in recovery of geometrically distorted images once the
distortion parameter are know (or even unknown). The codes below show some of these
trasnforms.
Code:
Code:
%Pixel location manipulation
f=imread('cameraman.tif');
[r,c]=size(f);
temp1 = f;
temp1(50:100,70:140)=0;
figure, imshow(temp1)

temp2 = f;
a=[50 160 256];

A1=temp2(:,1:a(1));
A2=temp2(:,a(1)+1:a(2));

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

A3=temp2(:,a(2)+1:a(3));
Z = [A3 A2 A1];
figure, imshow(Z)

%Image reversal
%1) Horizontally

f=imread('cameraman.tif');
[r,c]=size(f);
f1=fliplr(f);
f2=f(:,c:-1:1);
figure
subplot(1,2,1), subimage(f1)
subplot(1,2,2), subimage(f2)

%Image shifting column wise


f=imread('cameraman.tif');
[r,c]=size(f);
z=f;
shiftamount=[1:c];

for t = 1 : c
temp=[zeros(shiftamount(t),1); f(:,t)];
z(:,t)=temp(1:r);
clear temp
end
finalimage = z;
figure, imshow(finalimage)

%Image crop
f=imread('cameraman.tif');
figure, imshow(f)
[f,rect] = imcrop;

%Image rotate
f=imread('horses.jpg');
f1 = imrotate(f,45);
f2 = imrotate(f,-45);
figure, imshow(f)
figure, imshow(f1)
figure, imshow(f2)

Arithmetic operations:
Since we are dealing with matrices, all arithmetic operations can be applied with differen
effects. For instance image differencing is very good technique to see slight movements
or detect them in static images. Similarly image blending is nothing but addition of two

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

images with two different weights. The following codes demonstrate these operations.
Code:
%Image arithmetic operations
%Constant scaling
a=imread('horses.jpg');
b=imread('cameraman.tif');
a1 = a*2;
a2 = a/2;
b1 = b*2;
b2 = b/2;
figure, imshow(a)

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

figure, imshow(a1)
figure, imshow(a2)
figure, imshow(b)
figure, imshow(b1)
figure, imshow(b2)
%Image addition
A1 = imread('sml1.jpg');
A2 = imread('sml2.jpg');
B = A1 + A2;
C = imadd(A1,A2);
figure, imshow(A1)
figure, imshow(A2)
figure, imshow(B)
figure, imshow(C)
%Image blending
A1 = mat2gray(imread('circles.png'));
A2 = mat2gray(imread('testpat1.png'));
factor = 0.8;
z1 = imlincomb(factor,A1,1-factor,A2);
z2 = imlincomb(factor,A2,1-factor,A1);
figure, imshow(A1)
figure, imshow(A2)
figure, imshow(z1)
figure, imshow(z2)
%Image differencing
A1 = imread('chng1.jpg');
A2 = imread('chng2.jpg');
C = abs(A1-A2);
D = imabsdiff(A1,A2);
figure, imshow(A1)
figure, imshow(A2)
figure, imshow(C)
figure, imshow(D)
EXAMPLE
a=imread('myimage.gif');
j=imnoise(a,'gaussian',0,0.01);
s=double(j);
k=imnoise(a,'poisson');
kk=double(k);
subplot(3,2,1) imshow(a,
[]);title('Original image');
subplot(3,2,2) imshow(s,
[]);title('Gaussian noise');
subplot(3,2,3) imshow(kk,
[]);title('Poisson noise');

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

e=imnoise(a,'salt& pepper');
ee=double(e);
subplot(3,2,4)
imshow(ee,[]);title('Salt and pepper noise');

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

z=imnoise(a,'speckle');
zz=double(z);
subplot(3,2,5)
imshow(zz,[]);title('speckle noise');

EXERCISE:
Task #1: Type in the command window
>> help imdemos
This will give you a list of, amongst other things; the entire sample TIFF images
which come with the Image Processing Toolbox. Make a list of these sample images,
and for each image
(a) Determine its type (binary, grayscale or true color),
(b) Determine its size (in pixels)
(c) Give a brief description of the picture

Task #2: Pick any grayscale image. Using the imwrite function, write it to files of type
JPEG, PNG and BMP. What are the sizes of those files?

Task #3: Repeat the above question with


(a) A binary image,
(b) An indexed color image,
(c) A true color image.

Task #4: Pick any image and convert its mode to uint8 and uint16.

Task #5: Import an image ‘football.jpg’ and display it. Also convert the image formats
into:
(a) Indexed image.
(b) Intensity image.
(c) Binary image.
Use subplot command to display all formats in one figure.

Task #6: Import any color image and extract out the red, green and blue color from it.
Task #7: Design the following images through Matlab, by using loops, trigonometric
functions and matrices:
(a) (b)

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

(d) (d)

(e)

(f)

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LABORATORY 10:
AUDIO PROCESSING USING MATLAB
OBJECTIVES:
 Record the audio clip and trace different operations on it.

Place a check mark in the Assigned column next to the exercises your instructor has
assigned to you. Attach this cover sheet to the front of the packet of materials you submit
following the laboratory.

Activities Remarks Signature


Pre-lab Exercises
In-lab Exercises
Take Home Exercises
Any Other

THEORY:
To execute audio files using MATLAB commands and to observe a human generated
audio signal on time scope through Simulink

Audio signals, much like images, can under o filtering. It is somewhat easier to
understand the impact of signal processing on audio, since audio needs not be translated
from a spatial to a frequency domain. To load a wave (PCM) audio file, Matlab provides
the function wavread.

funky = wavread('funky.wav');

It's important to capture the sampling frequency at which the sound was recorded;

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

otherwise the speed of playback and result s of further processing is not guaranteed to be
correct:

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

[funky, f] = wavread( 'funky.wav');

To play a wave file at sampling frequency f:


wavplay( funky, f);

To view the waveform, plot the wave. Since audio is represented with many thousand
samples per second, it may be required to plot small portions of the waveform at a time.

SPECTROGRAM

Two‐dimensional plots of audio waves can be used to easily identify magnitude;


however, combined frequency distributions and magnitudes are more easily viewed in a
spectrogram:

specgram (funky, 512, f);

Where 512 is the number of samples that are used for the discrete Fourier Transform, and
thus a grouping factor of samples per column in the spectrogram image.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Figure 11.1: Spectrogram\

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

HUMAN GENERATED AUDIO SIGNAL

The blocks used to generate a human voice in Simulink are;

Unbuffer (DSP Block set):

Convert a frame to scalar samples output at a higher sample rate.

From Wave device ( DSP Blockset):

Reads audio data samples from a standard Windows audio device in real time.
Previously, only for Win95/98/NT. Now MATLAB versions support up till Windows 7
(64 bit editions included)

To Wave file (DSP Blockset):

Writes audio data samples to a standard Windows PCM format ".WAV" audio file.
Previously, only for Win95/98/NT. Now MATLAB versions support up till Windows 7
(64 bit editions included).

Time Scope (DSP Blockset):

Provides real time monitoring of the output signal.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Figure 11.2: Simulink blockset for human generated audio signal

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Figure 11.3: Time-scope view of human generated audio signal


EXERCISE:

Task #1: Write a MATLAB script to accomplish the following tasks:

a. Record your utterance of "we" and play it backwards. Does it sound like "you"?
b. Record your utterance of "you" and play it backwards. Does it sound like "we"?
c. Record your utterance of "We are you" and play it backwards. What does it sound
like?

Task #2: Write a MATLAB script that can read the wav file "notify.wav" and display the
following information:

a. Number of sample points.


b. Sampling rate.
c. Bit resolution
d. Time duration of the recording (in terms of seconds)

Task #3: Write a MATLAB script to record your utterance of "today is my birthday".

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Try to explain the playback effect you observe after you try the following operations on
the audio signals.

a. Multiply the audio signals by -1.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

b. Reverse the audio signals in time axis.


c. Multiply the audio signals by 10.
d. Replace each sample by its square root.
e. Replace each sample by its square.

Task #4: Write a MATLAB script to record your utterance with a sample rate of 32 KHz
and 8-bit resolution. Try to resample the audio signals at decreasing sample rates of 16
KHz, 8 KHz, 4 KHz, 2 KHz, 1 KHz, and so on. At which sample rate you start to have
difficulty in understanding the contents of the utterance?

Task #5: Write a MATLAB script to resample the audio signals in "sunday.wav" such
that new waveform has a new sample rate of 11025. Plot these two waveforms and their
absolute difference by using subplot.

Task #6: Write a MATLAB code to input file RECYCLE .WAV from your Windows
folder and generate it following spectrum.

Task #7: Write a MATLAB code to input file NOTIFY.WAV from your Windows
folder and generate it following spectrum. Also play it with different sample
frequencies.

Task #8: Repeat Task 1 and 2 with Fs = 10 KHz, 22 KHz and 44.1KHz for
RINGIN.WAV file. It is present in your root folder of Windows. Generate the following
spectrum as well.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Task #9: What you have observed by looking at spectrums of different waveforms and
listening sounds with different frequency values. Is the spectrum looks same for more
than one frequency or it changes?

Task #10: The Simulink model for human generated voice is present in theory section
(figure 9.2). Convert that Simulink model into MATLAB commands and write complete
code for it.

Task #11: Proceeding task-10, observe human generated voice on different sampled
frequencies.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LABORATORY 11

DIGITAL FILTER DESIGNING USING MATLAB TOOLS

OBJECTIVES:
 To reproduce low pass filter with eleven coefficients by using different window methods.
 To trace coefficients of FIR low pass filter by using linear phase method.

Place a check mark in the Assigned column next to the exercises your instructor has
assigned to you. Attach this cover sheet to the front of the packet of materials you submit
following the laboratory.

Activities Remarks Signature


Pre-lab Exercises
In-lab Exercises
Take Home Exercises
Any Other

THEORY:
Electronic filters are electronics circuits which perform signal processing functions,
specifically to remove unwanted frequency components from the signal and/or to
enhance wanted ones. Electronic filters can be:

 Passive or active

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

 Analog or digital
 High-pass, low-pass, band-pass, band-reject (notch), or all-pass
 Discrete time (sampled) or continuous time
 Linear or non-linear
 Infinite impulse response (IIR type) or finite impulse response (FIR type)

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

The most common types of electronic filters are linear filters, regardless of other aspects
of their design.

Digital Filters
A digital filter is a system that performs mathematical operations on a sampled, discrete-
time signal to reduce or enhance certain aspects of that signal. This is in contrast to the
other major type of electronic filter, the analog filter, which is an electronic circuit
operating on continuous-time analog signals. An analog signal may be processed by a
digital filter by first being digitized and represented as a sequence of numbers, then
manipulated mathematically, and then reconstructed as a new analog signal. In an analog
filter, the input is “directly” manipulated by the circuit.
In digital signal processing applications, it is often necessary to change the relative
amplitudes of frequency components or remove undesired frequencies of a signal. This
process is called filtering. Digital filters are used in a variety of applications. Digital filter
design requires the use of both frequency domain and time domain techniques. This is
because filter design specifications are often given in the frequency domain, but filters
are usually implemented in the time domain with a difference equation. Typically,
frequency domain analysis is done using the Z-transform and the Discrete Time Fourier
Transform (DTFT).
In general, a linear and time invariant digital filter with input x(n) and output y(n) may be
specified by its difference equation.
𝑁−1 𝑀

𝑦(𝑛) = ∑ 𝑏𝑖 𝑥(𝑛 − 𝑖) − ∑ 𝑎𝑘𝑦(𝑛 − 𝑘)


𝑖=0 𝑘=1
where bi and ak are coefficients which parameterize the filter. This filter is said to have N
zeros and M poles. Each new value of the output signal, y(n), is determined by the past
values of the output and by present and past values of the input. The impulse response,
h(n), is the response of the filter to an input of δ(n), and is therefore the solution to the
recursive difference equation.
𝑁−1 𝑀

ℎ(𝑛) = ∑ 𝑏𝑖 𝛿(𝑛 − 𝑖) − ∑ 𝑎𝑘ℎ(𝑛 − 𝑘)


𝑖=0 𝑘=1
There are two general cases of digital filters: infinite impulse response (IIR) and finite
impulse response (FIR). The FIR case occurs when a k = 0, for all k. Such a filter is said to
have no poles, only zeros. In this case the above difference equation becomes:
𝑁−1

ℎ(𝑛) = ∑ 𝑏𝑖 𝛿(𝑛 − 𝑖)
𝑖=0
FIR Design

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

There are numerous software packages available that will provide a necessary tools to
design digital filters, both FIR and IIR. In this lab, we will design our filter using the
Filter Design and Analysis Tool (fdatool) from MATLAB. The most straight forward
way to start the tool is to type “fdatool” on the command line in the main MATLAB

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

window. This tool invoke MATLAB to generate the desired filter coefficients according
to our specifications. The GUI of this tool presaented in the figure below:

Figure 13.1: FDA Tool Graphical User Interface


EXERCISE:

Task #1: Design low pass filter with eleven filter length having cutoff frequency 0.25
KHz and sampling frequency 8 KHz. Using rectangular, hamming and hanning
window method.

Task #2: Design high pass filter to meet the following specifications:
Cutoff frequency (fc) = 250Hz
Sampling frequency (fs) = 1KHz.
Filter length (N) = 8

Task #3: Design a band pass filter for following specifications:


Upper cutoff frequency (fc1) = 100Hz
Lower cutoff frequency (fc2) = 200Hz
Sampling frequency (fs) = 1KHz.
Filter length (N) = 9

Task #4: Obtain the coefficients of an FIR low pass filter to meet the following specifications
using equiripple method:
Stopband attenuation = 50dB
Passband ripple = 0.05dB

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Sampling frequency = 8KHz


Passband frequency = 600Hz
Stopband frequency = 3400Hz

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Task #5: Design a 41-tap lowpass FIR filter whose cutoff frequency is 1.6 kHz using rectangular,
triangular, hamming, hanning and blackman window functions. Assume that the sampling
frequency is 8 kHz. List the FIR filter coefficients and plot the frequency responses for each
case.

Task #6: Design a lowpass FIR filter whose cutoff frequency is 1 kHz using the Hamming
window function for the following specified filter lengths. Assume that the sampling
frequency is 8 kHz. List FIR filter coefficients for each design and compare the magnitude
frequency responses.
a) 21 filter coefficients.
b) 31 filter coefficients.
c) 41 filter coefficients.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LABORATORY 12
ANALYSIS OF DIGITAL FILTERS

OBJECTIVES:
 Follow the instructions for realization of digital filters by using MATLAB code and SIMULINK.

Activities Remarks Signature

Pre-lab Exercises

In-lab Exercises

Take Home Exercises

Any Other

THEORY:
Z-transform is discrete in nature or we can say that Z-transform operates in discrete time
domain. With the help of Z-transform we can check the stability of the systems such as
filters, speech processing systems, etc.
The Z-transform, like many integral transforms, can be defined as either a one-sided or
two-sided transform. The bilateral or two-sided Z-transform of a discrete time signal x[n]
is the function X(z) defined as
X (z) = Z {x(n)} = ∑𝑛=∞
𝑛=− 𝑥[𝑛]𝑧
-n


Where, n is an integer and z is, in general, a complex number
z = Aejφ = A (cosφ + jsinφ)
Where, A is the magnitude of z, and φis the complex argument (also referred to as angle
or phase) in radians. Alternatively in cases where x[n] is defined only for n ≥ 0, the

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

single-sided or unilateral Z-transform is defined as


X (z) = Z {x(n)} = ∑𝑛=∞
𝑛=0 𝑥[𝑛]𝑧
-n

In digital signal processing, this definition can be used to evaluate the Z-transform, of the
unit impulse response of a discrete time causal system. From the above equation we can
evaluate
X(z) = Z {x(n) r-n}
Once the poles and zeros have been found for given Z-transform, they can be plotted on
to the Z-plane. The Z-plane is a complex plane with an imaginary and real axis referring
to the complex-valued variable z. the position on the complex plane is given by re jθ and
the angle from the positive, real axis around the plane is denoted by θ. When mapping
poles and zeros on to the plane, poles are denoted by an “x” and zeros by an “o”.

Figure 8.1: Z-plane


As in this topic we are going to check the relationship between Z-transform and
frequency response. If the poles lie inside the unit circle the system said to be stable. If
the poles lie on the unit circle the system is said to be marginally stable and if the poles
lies outside the unit circle the system will be unstable. The placement of poles and zeros
in the unit circle provides us the frequency response as well as the stability of the system.

Impulse Response
In digital signal processing, the impulse response or impulse response function (IRF) is

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

the output when presented with a brief input signal, called an impulse. More generally,
the impulse response refers to the reaction of any system I response to some external
change. In both cases, the impulse response describes the reaction of the system as a

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

function of time for possibly as a function of some other independent variable that
parameterizes the dynamic behavior of the system.
In general we have two types of impulse responses; Finite Impulse Response (FIR) and
Infinite Impulse Response (IIR). FIR depends upon previous value of input, if the system
has FIR response then the value of denominator in H(z) will be 1, i.e. poles are not
present. On the other hand, IIR depends upon the previous value of output. If the system
has IIR response then the value of denominator in H(z) is other than 1, i.e. poles are
present.
FIR as mentioned above, is Finite Impulse Response filter, this means that such filter
gives finite number of pulses on output of filter and filter function can be described as
y [n] = x [n]*c0 + x [n-1]*c1 +..................+ x [n-N]*cN

where y[n] is output signal at instant n, x[n] input signal at instant n, cN is the impulse
response from 0 to N instants and N is the number of samples in the pulse response.
Similarly, the IIR response can be seen as
y[n] = a1*y[n-1] + a2*y[n-2] + ….. + ak*y[n-k] + b0*x[n] + b1*x[n-1] +.......+
bk*x[n-k]
The equation of IIR filter has a feedback element which means that output signal y[n] is
fed back to the input. IIR filter response can be created with few coefficients comparing
to FIR. So IIR requires less computing power than FIR. But on other hand FIR filter is
easier to design, but gives flat phase response. FIR filters are also unconditionally stable
while IIR can be unstable if designed poorly.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

EXERCISE:

Task #1:Generate transfer functions so that the system become stable, marginally stable
and unstable and plot their response in z-plane.By using subplot command, show
the results of each transfer function on the same plot and then analyze the results
on the basis of stability criteria. Also generates the impulse response of all the
systems on the same plot and interpret its result.

Task #2:Given a filter


H(z) = 1 + 2z-1 + z-2
___ _ _ _ _ _ _ _ _ _

1 – 0.5z-1 + 0.25z-2
a) Use MATLAB to plot its magnitude frequency response.
b) Write a program to plot its phase response.

Task #3:Given the difference equations:


i) y(n) = x(n-1) – 0.75y(n-1) – 0.125y(n-2)
a) Use the MATLAB function filter() and filtic() to calculate the system response y(n)
for n = 0,1,2,3,4 with the input of x(n) = (0.5)n u(n) and initial conditions: x(-1) = -
1, y(-2) = 2, and y(-1) = 1.
b) Use the MATLAB function filter() to calculate the system response y(n) for n =
0,1,2,3,4 with the input of x(n) = (0.5)n u(n) and initial conditions: x(-1) = 0, y(-2)
= 0, and y(-1) = 0.
ii) y(n) = 2x(n) – 25x(n-2) – 11y(n-1) – 28y(n-2)
a) Use the MATLAB function filter() and filtic() to calculate the system response y(n)
for n = 0,1,2,3,4 with the input of x(n) = (0.75)n u(n) and initial conditions: x(-2) =
-10, y(-2) = 2.5, and y(-1) = 5.
b) Use the MATLAB function filter() to calculate the system response y(n) for n =
0,1,2,3,4 with the input of x(n) = (0.5)n u(n) and initial conditions: x(-2) = 0, y(-2)
= 0, and y(-1) = 0.
Task #4:Given a filter
i) H(z) = z
___ _ _

z-0.5

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

ii) H(z) = 1 –0.5z-1

iii) H(z) = 0.5z2– 0.32


__________________________

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

z2– 0.5z +0.25


iv) H(z) = 1 –0.9z-1 +0.81z-2

1 – 0.6z-1 + 0.36z-2
a) Plot the poles and zeros on z-plane using MATLAB.
b) State whether the system is FIR or IIR.
c) Plot the magnitude frequency response and phase response using MATLAB.
d) Specify the corresponding filter type, such as highpass, lowpass, bandstop and
bandpass.

Task #5: Given the filter:


i) H(z) = 1 –0.9z-1 - 0.1z-2

1 + 0.3z-1 - 0.04z-2
ii) H(z) = 0.5 – 0.5z-2

1 + 1.3z-1 + 0.36z-2
Make the SIMULINK model for the following forms:
a) Direct – form 1.
b) Direct – form 2.
c) Cascade (series) form via first order sections
d) Parallel form via first order sections

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

LAB NO: 13 DSP Design on FPGA using XILINX


system generator

 Matlab 2008b or newer version

 Xilinx ISE 12.1 or newer version


 Xilinx FPGA device
DESCRIPTION:

Xilinx offers a variety of high-quality state of the art products for DSP design.
We will work with field- programmable gate arrays (FPGAs). In order to do
so, we need Simulink for development and verification of the design and after
functional verification by simulations, Xilinx System Generator will translate
our design into FPGAs. XSG will create the project files (HDL) that we can
then synthesize, simulate, implement and download to the FPGA with Xilinx
ISE Project Navigator.

We will become familiar with the Xilinx tools using an example-based


approach. For this purpose, we will implement a digital filter using The
Multiplier Accumulator (MAC) unit which is the basic element to implement a
Digital filter on a FPGA.
Use XSG under Simulink environment in Matlab to implement FIR Digital Filter.
 Type-I FIR Lowpass filter
 Filter of 6th order
 Use of multiple MACs to implement design.

STARTING SYSTEM GENERATOR:


 To Start Xilinx System Generator, select Start͢ Programs ͢
Development Xilinx ISE ͢ Design
Suite 12.4 or latest ͢ System Generator ͢ Xilinx
System Generator.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

 This will start MATLAB and Simulink simulation environment as shown in


Figure 5.1.
 The Simulink library browser shows a list of all the different Toolboxes
installed withinMATLAB. Xilinx System Generator components will
appear under three categories:

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

1. Xilinx Blockset
2. Xilinx Reference Blockset
3. Xilinx XtremeDSP Kit

 The category Xilinx Blockset contains all the basic blocks used
in various numbers ofapplications and will be used in this lab.
 Create a new Simulink model by selecting File͢͢͢͢ New ͢ Model

Figure 5.1: Simulink Model


 In the library browser window, expand the Simulink Library, and click Sources
 Add the Sine Wave source on the worksheet: Scroll through the library
to find the Sine Wave, leftclick Sine Wave, and drag it onto the
worksheet
 Add the Scope sink element and write it to the Sine Wave source on the
worksheet: From Simulink Simulink → Sinks, add the Scope block,
and draw a wire from the Sine Wave to theScope block
 Assign a frequency of 2*pi*(1/150) to the Sine Wave element, show
port data types, and changesimulation parameter’s stop time to inf
(infinity)
1. Double-click the Sine Wave block
i. The Block Parameters dialog box opens.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

2. Change the frequency to 2*pi*(1/150) and click OK to close the dialog box
3. On the worksheet, go to Format → Port/Signal Displays and click Port
Data Types.
i. The signal width is displayed on the wire as shown in the following picture
4. From your project sheet, pull down the Simulation menu and select
ConfigurationParameters

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

5. From the Simulation Parameters dialog box, select Solver in the left
hand window andchange the stop time to inf, and click OK.This allows
your simulation to run to infinity (until you manually stop the simulation).
 Parameterize the Scope block, and run the simulation
1. Double-click the Scope block
2. Click the Scope Parameters button
3. In the Scope Parameters box, set the time range to 500, and click OK
4. Run the simulation: From your Simulink project worksheet, click
Start Simulationbutton, or use Simulation → Start
5. On the Scope display, click Autoscale button so the output will fit into the Scope
6. View the Scope output
7. A smooth sine wave should fit into your space window. This is what you
would expectbecause you are running double-precision software simulation

Figure 5.2 Simulink Scope


THE XILINX BLOCK SET, GATEWAYS:
Use the Xilinx Gateway In, Gateway Out, System Generator, and MUX
blocks, as shownbelow, which provide interface to Xilinx Blocksets in
Simulink.

1. Using Simulation → Configuration Parameters dialog box, set the stop


time to 500, and click OK.
2. From the Xilinx Blockset (in the Simulink Library Browser), open Basic
Elements and drag the Gateway In block onto the design sheet. Droop it
on the connection between the Sine Wave and the output Scope. It will
automatically insert itself.
3. Note: The Gateway In/Out blocks are required to convert double-precision

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

floating point numbers used by Simulink in a simulation to bit fix point


numbers used by Xilinx blocks. Thus, a conversion is required when
communicating with Xilinx blocks and Simulink blocks.
4. Double-click Gateway In to open the Block Parameters

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

5. Set the Number of bits to 8 and Binary Point to 2


6. Similarly, drag a Gateway Out block onto the sheet, and drop it between
the Gateway Inblock and the output Scope block
7. Add and connect a Simulink MUX between the Gateway Out and the
Scope by usingSimulink → Signal Routing
8. Add an additional net between the Sine Wave and the MUX
9. Note: This will make the scope display both the double-precision sine
wave and the user-defined precision sine wave that has gone into and back
out of the Xilinx gateways
10. Add a system generator token from the Xilinx Blockset →
Basic Elements library to thedesign
11. To view the number of signals going into the MUX, select Wide
nonscalar lines, Signaldimensions, and Port data types under the
Format
→ Port/Signal Displays menu
12. Save above model with under File Save As with name sine_wave.

Figure 5.3: Port display settings


Note: Now look at your port types. Notice that the gateway in block has
changed the signals from double-precision to fixed-point types. Fixed-point
looks like Fix_8_2 in this case.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Figure 5.4: View Signal on Simulink

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

ANALYZE PRECISION, QUANTIZATION AND SAMPLE RATE:


Run the simulation with default settings and understand and understand the output.
Change the data type and simulate, and analyze the simulation output. Change the
sampling period from one to five and see effect on the quantization.

PREPARING SYSTEM GENERATOR FOR HARDWARE /


SOFTWARECO-SIMULATION:
In the previous section we verified the functionality of our simple DSP system
using Simulink simulation models. Usually several issues may arise when
the model is transformed into
hardware. System Generator provides several methods to transform the
models built using Simulink into hardware. One of these methods is called
Hardware/Software co-simulation. Hardware/Software co-simulation enables
building a hardware version of the model and using the flexible simulation
environment of Simulink. We can perform several tests to verify the
functionality of the system in hardware. HW/SW Co-simulation supports
FPGAs from Xilinx on boards that support JTAG or Ethernet connectivity.
Several boards are predefined on System Generator for co-simulation, rest can
be defined by including required board files.. Follow following steps to setup
chosen platform for HW/SW Co-Simulation.

 Double click on the System Generator block. A dialogue box will show up as
shown in Figure 5.5. This dialogue box allows you to select the type of the
hardware generated usingsystem generator.
 In the compilation list select Hardware Co-Simulation Chosen FPGA JTAG.
 Click Generate to build the hardware system. This step will generate a
bitstream that will later be used to configure the FPGA. ISE flow is used by
System Generator to build this bitstream. The progress of the process is
displayed in the Compilation Status window

-Department of Computer Engineering-


-Sir FigureUniversity
Syed 5.5: Compilation Status window
of Engineering
Technology-&
Digital Signal Processing (CE-405) SSUET/QR/114

 When the compilation is complete, a new library is created including one


block as shown in Figure 5.6. The library name should be
“sine_wave_hwcosim_lib" and the block name should be
“sine_wave_hwcosim" The block has one input and one output as required
by the DSP system. This block includes all the functionality required for the
system to be executedon the FPGA.
 Now we are ready to perform HW/SW Co-Simulation for our DSP system.
 Make a copy of the model generated “sine_wave_hwcosim" to the model
sine_wave replaceall components as shown in figure 5.6.

 Double click on the “sine_wave_hwcosim"block. The block properties


window will appear as shown in Figure 5.6. Under the cable tab select
Xillinx Platform USB. Click OK.
 Now the design is ready for Co-Simulation. Click the Start Simulation button
in the model window toolbar to start the Co-Simulation. The System
Generator will first download the bitstream associated with the block
“sine_wave_hwcosim”.
 When the download completes, System Generators reads the inputs from
Simulink simulation environment and send them to the design on the board
using the JTAG connection. System Generator then reads the output back
from JTAG and sends it to Simulink for displayed.
 After the simulation is completed the results should be displayed. We can
verify the resultsby comparing the simulation output to the expected output

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

Figure 5.6: JTAG cosimulation

IMPLEMENT A TYPE-I FIR FILTER:


Implement a Type-I FIR Filter using Xilinx Blockset in Simulink. The
design characteristicsare the following:

 Separate multiplier and accumulator per filter coefficient


 Low Pass Filter of order 6
 Coefficients generated using the FDA Xilinx Tool
 Sampling frequency of 1kHz
1. In the project sheet, select File → New → Model
2. A new Simulink project opens.
3. Add two Sine inputs to the worksheet.
4. Add the Sum block from the Simulink Math Operations Library and
connect it to thesine blocks.

Figure 5.7 FIR Filter model

5. Add the Xilinx Gateway in block.


6. Add the Delay block from the Basic Elements library of the Xilinx Blockset.
7. Add the Xilinx Constant Block from the Basic Elements Xilinx Blockset.
8. Add the Xilinx Multiplier Block form the Index Xilinx Blockset.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405) SSUET/QR/114

9. Repeat step 5, 6, 7.
10. Add the Xilinx Adder/Substractor from the Index Xilinx Blockset.
11. Repeat steps 5, 6, 7, 8 until the design looks like figure 5.7.
12. Add the Xilinx Gateway Out block
13. Add two Scope blocks and connect one to the sine inputs and the other to the

output ofthe Gateway out and the output of the Sum block.
14. To increase the number of inputs to the scope, double-click on it, on the
menu click onParameters and change the number of axis.
15. Wire all the blocks and add the System Generator token from the Xilinx
Basic ElementsLibrary as well as the FDA Tool from the Xilinx DSP
Library.
16. The final diagram should look like Figure 5.7.

SIMULATE THE TYPE-I FIR FILTER USING SIMULINK:


Configure the inputs and simulation parameters as specified below. Next, simulate the
Filterin Simulink and verify the design functionality.

 Two Sine inputs: low and high frequencies.


 16 bit input: signed data (2’s complement) binary point 13, and sampling
period of 0.001seconds.
 Multiplier Block latency of 1 and Full precision.
 Lowpass Type-I FIR filter of order 6.
 Simulation parameters: Stop time 0.5 seconds.
2. Set the frequencies of the sine inputs. One to 5Hz and the other to 300 Hz
3. Configure the inputs by double-clicking the Gateway In blocks to
open their Parametersdialog box.
4. Set the Number of bits to 16 and the Binary Point to 14.
5. Set the Overflow to Saturate and Sample period to 0.001 seconds.
6. Design the 6th order low pass filter by double-clicking on the FDA Tool block
7. On Response Type choose Lowpass.
8. Set the Design Method to FIR and from the bottom down menu select Least-squares.
9. Set the Filter Order to 6.
10. On Frequency Specifications select Normalized for the units and set the
wpass to 0.1and the wstop to 0.25.
11. Click on the Design Filter button.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405)
SSUET/QR/114

Digital Signal Processing (CE-405) SSUET/QR/114

12. Click on the File menu → Export and the Export


window appears. Choose Export toWorkspace and set
the Variable Names to filter_coeff.
13. Click on Export botton.
14. On the Matlab workspace, double click the filter_coeff variable.
15. Click the View Menu → Numerical Array Format → long on Matlab.
16. Double click on the Xilinx Constant Block, set the
Number of bits to 16, the BinaryPoint to 14 and
Signed (2’s complement) type of data
17. On the same block, edit the Constant value to the values
of the filter_coeff variable accordingly to their position in
the array.
18. Note: Do this for the seven coefficients. Do not change the
order of the coefficients since each one of them is
associated to a specific delay value and keep in mind that
Matlab index start at 1 that corresponds to the first
coefficient value which has no delay.
19. Double click on the System Generator block and se the
Simulink System Period to 1/1000.
20. Save the design on your work directory as Lowpass.mdl
and run the simulation by clicking on the Start Simulation
button.
21. The graphs of the input and output should look like figure 7.9.
22. For Hardware/Software co-simulation follow the steps
discussed in Preparing System Generator for
Hardware/Software Co-Simulation section.

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405)
SSUET/QR/114

Figure 5.9: Signal view

EXERCISE:

Task # 1:Implement the following Moving average


filter on FPGA using XSG andverify using hardware
in a loop.

In z-1 z-1 z-1 a


Gateway In a +b X >> 2 Out
Random b Gateway Out
Source Delay Delay1 Delay2
AddSub Shift

a a Out Time
Scope
a +b a +b Gateway Out1
b b
Sy stem
Generator AddSub1 AddSub2

Gateway Out
Resource JTAG
Estimator Gateway In Time
Co-sim
Scope1
Gateway Out1

Mov_avg_rand_noise hwcosim

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405)
SSUET/QR/114

Name:_____ _ _ _ _ __ RollNo:

LABORATORY 14: OPEN ENDEDLAB

Title:

1. Objective:

2. Hardware/Software required:

3. Theory:

4. Coding:

5. Results & Discussions:

6. Conclusion:

Teacher’s Sign:

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-
Digital Signal Processing (CE-405)
SSUET/QR/114

-Department of Computer Engineering-


-Sir Syed University of Engineering & Technology-

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy