Вы находитесь на странице: 1из 101

DSP Laboratory Experiment # 1 Introduction to MATLAB

Goals for this Lab Assignment:

In this lab we would have an introduction to MATLAB and get started with working in its wonderfully simple environment. This lab, as a matter of fact, would lay the foundation for our next labs. In the following paragraphs, you are provided with a tutorial on MATLAB. In addition, we’ll go over a detailed introduction to MATLAB in our first discussion session. This would enable you to do simple but useful things in MATLAB.

Prelab

You are basically responsible for learning Matlab language on your own. So read this Experiment carefully and try to do an example of your own for each part on Matlab.

2. Solve all the exercises in this Experiment. If an exercise asks you to do an M-file, place a comment at the top of your M-file, Lab1exr#, where # refers to the exercise number.

1.

Lab

Workspace Browser

The MATLAB workspace consists of the set of variables (named arrays) built up during a MATLAB session and stored in memory. You add variables to the workspace by using functions, running M- files, and loading saved workspaces. To view the workspace and information about each variable, use the Workspace browser, or use the functions who and whos.

Double Click
Double
Click

To delete variables from the workspace, select the variable and select Delete from the Edit menu. Alternatively, use the clear function. The workspace is not maintained after you end the MATLAB session. To save the workspace to a file that can be read during a later MATLAB session, select Save Workspace As from the File menu, or use the save function. This saves the workspace to a binary file called a MAT-file, which has a .mat extension. There are options for saving to different formats. To read in a MAT-file, select Import Data from the File menu, or use the load function. You will use this function to load a wave signal later in this lab.

Array Editor

Double-click a variable in the Workspace browser to see it in the Array Editor. Use the Array Editor to view and edit a visual representation of one- or two-dimensional numeric arrays, strings, and cell arrays of strings that are in the workspace.

Change values of array elements Change the display format
Change values of array elements
Change the display format

Search Path

MATLAB uses a search path to find M-files and other MATLAB-related files, which are organized in directories on your file system. Any file you want to run in MATLAB must reside in the current directory or in a directory that is on the search path. Add the directories containing files you create to the MATLAB search path. By default, the files supplied with MATLAB and MathWorks toolboxes are included in the search path. To see which directories are on the search path or to change the search path, select Set Path from the File menu in the desktop, and use the Set Path dialog box.

Exercise#1

1. Inside the Work folder, make a new folder and give it the name dsp.

2. Select the set path from the file menu, and use the add folder option to reassign the path to this folder (dsp).

3. From this moment, any file you will be asked to do in this course will be saved in this path. DO NOT FORGET THIS!!!!!

Definition of Matrices

MATLAB is based on matrix and vector algebra; even scalars are treated as 1x1 matrices. Therefore, vector and matrix operations are as simple as common "calculator operations".

Vectors can be defined in two ways. The first method is used for arbitrary elements:

v = [1 3 5 7];

%creates a 1x4 vector with elements 1, 3, 5 and 7.

Note that commas could have been used in place of spaces to separate the elements. Additional elements can be added to the vector:

v(5) = 8;

Matrices are defined by entering the elements row by row:

M = [1 2 4; 3 6 8];

2

1

4

3

6

8

There are a number of special matrices that can be defined:

null matrix:

M = [ ];

nxm matrix of zeros:

M = zeros(n,m);

nxm matrix of ones:

M = ones(n,m);

nxn identity matrix:

M = eye(n);

Uniformly distributed random elements

M = rand(n,m);

Normally distributed random elements

M=randn(n,m);

A particular element of a matrix can be assigned:

» M(1,2) = 5;

% places the number 5 in the first row, second column.

Here are some examples.

»

Z = zeros(2,4)

Z

=

 

0

0 0 0

0

0 0 0

»

N = fix(10*rand(1,10))

N

=

 

4

9 4 4 8 5 2 6 8 0

» R = randn(4,4)

R =

1.0668

0.2944

-0.6918

-1.4410

0.0593

-1.3362

0.8580

0.5711

-0.0956

0.7143

1.2540

-0.3999

-0.8323

1.6236

-1.5937

0.6900

The Colon Operator

The colon, : , is one of the most important MATLAB operators. It occurs in several different forms.

The expression 1:10

is a row vector containing the integers from 1 to 10, i.e. 1 2 3 4 5 6 7 8 9 10

To obtain non-unit spacing, specify an increment. For example,

» 100:-7:50

% a row vector containing the integers

100 93 86 79 72 65 58 51

Subscript expressions involving colons refer to portions of a matrix.

» A(1:k,j)

» sum(A(1:4,4))

% the first k elements of the jth column of A. So

%computes the sum of the fourth column.

But there is a better way. The colon by itself refers to all the elements in a row or column of a matrix and the keyword end refers to the last row or column. So

» sum(A(:,end))

%computes the sum of the elements in the last column of A.

Exercise#2

1. Generate a matrix of size 4x4 of normally distributed random numbers.

2. Change the value of the 3 rd column to [6 9 2 5].

3. Delete the 2 nd row.

Dimension Functions

Dimensioning is automatic in MATLAB. You can find the dimensions of an existing matrix with the size. Also the command length(x) returns the length of the vector x

>> X=[1 2 3;6 7 8]

>> [m,n] = size(X)

% returns the size of matrix X in separate variables m and n.

>> x = ones(1,8);

>> n = length(x)

% will assign the value 8 to n

Concatenation:

Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your first matrix by concatenating its individual elements. The pair of square brackets, [ ], is the concatenation operator. To do so horizontally, we separate the arrays with spaces or commas:

>> [ones(2,3), zeros(2,3)]

To do so vertically, we separate the arrays with a semicolon:

>> [ones(2,3); zeros(2,3)]

Exercise#3

1. Start with the 4-by-4 square, A.

2. Then form B = [A A+32; A+48 A+16]

3. What’s the size of B?

Exercise#4

Define the following discrete time signal

[

x n

] =

0.5

0

2

0

10

15

n p

n p

n

10

15

20

Scripts and Functions

MATLAB is a powerful programming language as well as an interactive computational environment. Files that contain code in the MATLAB language are called M-files. You create M-files using a text editor, and then use them as you would use any other MATLAB function or command.

There are two kinds of M-files:

Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace.

Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.

Scripts

When you invoke a script, MATLAB simply executes the commands found in the file. Scripts can operate on existing data in the workspace, or they can create new data on which to operate. Although scripts do not return output arguments, any variables that they create remain in the workspace, to be used in subsequent computations. In addition, scripts can produce graphical output using functions like plot.

For example, create a file called modify.m that contains these MATLAB commands.

r = rand(1,10)

r(1:2:length(r))=0;

y=r

» modify

causes MATLAB to execute the commands, change the value of the odd indexed elements of vector r to zero, and assign the result to y . After execution of the file is complete, the variables y and r remain in the workspace.

Functions

Functions are M-files that can accept input arguments and return output arguments. The name of the M-file and of the function should be the same. Functions operate on variables within their own workspace, separate from the workspace you access at the MATLAB command prompt.

Global Variables

If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functions. Do the same thing at the command line if you want the base workspace to access the variable. The global declaration must occur before the variable is actually used in a function. Although it is not required, using capital letters for the names of global variables helps distinguish them from other variables. For example, create an M-file called falling.m.

function h = falling(t)

global GRAVITY

h = 1/2*GRAVITY*t.^2;

Then interactively enter the statements in MATLAB command window

» global GRAVITY

» GRAVITY = 32;

» y = falling((0:0.1:5)');

The two global statements make the value assigned to GRAVITY at the command prompt available inside the function. You can then modify GRAVITY interactively and obtain new solutions without editing any files.

It is worth mentioned that when a function returns multiple parameters, we use square brackets to retrieve them:

>> [max_value, index] = max([4.3, 2.9, 8.6, 6.3, 1.0])

Otherwise, only one parameter is returned

Structures and cells

Matlab has a number of other data types which we will use. Structures in Matlab are just like structures in C. They are basically containers that allow one to group together more than one type of data under the umbrella of one variable name. The form of a structure is variableName.field. For example:

» x.data = [1 2 3 4 5];

» x.offset = -1;

» x

x =

data: [1 2 3 4]

offset: -1

We have declared a variable x, with two fields. The data field contains an array; the offset field contains another number. Structures of this type can be useful for us in expressing sequences in Matlab. Matlab always assumes that the index of the first element of an array is 1. So, when we just say

» x = [1 2 3 4 5];

This means that x[1]=1, x[2]=2, and so on. But, what if we want to express a sequence x[-1] =1 ,

? We obviously need to provide the user with some additional information in addition to the

x[0]=2,

array data, namely an offset. An offset of -1 tells the user that "we want you to interpret the first point in the Matlab array as corresponding to x[-1] . We can use structures for this purpose.

For example let us define a shift function. This function takes the data x and original offset of the vector, w and the amount of the required shift z and outputs the new shifted vector with the new index.

function y=shift(x,w,z)

y.data=x;

y.offset=w+z;

figure

i=y.offset:1:length(y.data)+y.offset-1

stem(i,y.data)

Exercise#5

Define a new function in MATLAB named as flip. This function flips a Matlab sequence structure, x (containing data and offset). Use this function to flip the shifted sequence results from the previous example. Can we call the two functions together? i.e., Can we write this calling statement: flip(shift(x,w,3)) ?

Representing Polynomials

MATLAB represents polynomials as row vectors containing coefficients ordered by descending powers. For example, consider the equation

p

(

x

)

= x

3

2

x

5

To enter this polynomial into MATLAB, use

»

p = [1 0 -2 -5];

Polynomial Roots

The roots function calculates the roots of a polynomial.

» r = roots(p)

r =

2.0946

-1.0473 + 1.1359i

-1.0473 - 1.1359i

By convention, MATLAB stores roots in column vectors. The function poly returns to the polynomial coefficients.

» p2 = poly(r)

p2 =

1 8.8818e-16 -2 –5

So the poly and roots are inverse functions.

Polynomial Evaluation

The polyval function evaluates a polynomial at a specified value. To evaluate p at s = 5, use

» polyval(p,5)

ans =

110

It is also possible to evaluate a polynomial in a matrix sense. In this case ( )

becomes p(X ) X

example, create a square matrix X and evaluate the polynomial p at X.

p

x

= x

3

2

x

5

3

2X

=

5I

, where X is a square matrix and I is the identity matrix. For

»X = [2 4 5; -1 0 3; 7 1 5];

»Y = polyvalm(p,X)

Y =

377

179

439

111

81

136

490

253

639

Exercise#6

Consider the polynomial

p

(

x

)

= x

4

x +

5

3

7

x

10

1. Find the roots of this polynomial.

2. From these roots, reconstruct p(x).

3. Find the value of p(x) at x=3.

4. Evaluate the polynomial at X (matrix sense).

Graphics in MATALB:

Creating a Plot

The plot function has different forms, depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x.

For example, these statements use the colon operator to create a vector of x values ranging from zero to 2π, compute the sine of these values, and plot the result.

x = 0:pi/100:2*pi;

y = sin(x);

plot(x,y)

%Now label the axes and add a title. The characters \pi create the symbol .

xlabel('x = 0:2\pi')

ylabel('Sine of x')

title('Plot of the Sine Function','FontSize',12)

ylabel('Sine of x') title('Plot of the Sine Function','FontSize',12) DSP LABORATORY 9

Multiple Data Sets in One Graph

Multiple x-y pair arguments create multiple graphs with a single call to plot. MATLAB automatically cycles through a predefined list of colors to allow discrimination among sets of data. For example, these statements plot three related functions of x, each curve in a separate distinguishing color.

x= 0:pi/40:2*pi;

y= sin(x);

y2 = sin(x-0.25);

y3 = sin(x-0.5);

plot(x,y,x,y2,x,y3)

legend('sin(x)','sin(x-.25)','sin(x-.5)')

% The legend command provides an easy way to identify the individual plots.

Axis rescaling:

MATLAB provides automatic scaling. The command axis([x min. x max. ymin. y max.]) enforces the manual scaling. For example

» axis([-10 40 -inf inf])

produces an x-axis scale from - 10 to 40 and an automatic scaling for the y-axis scale. Typing axis again or axis(’auto’) resumes auto scaling.

Stem

If you wish to use information in discrete-time using the stem command can be useful. It is very similar to plot except it doesn’t connect the dots.

The following example creates a stem plot of a cosine function.

y

= linspace(0,2*pi,10);

h

= stem(cos(y),'fill','-.');

set(h(3),'Color','r','LineWidth',2) % Set base line properties

axis ([0 11 -1 1])

% Set base line properties axis ([0 11 -1 1]) DSP LABORATORY 10

Specifying Line Styles and Colors

It is possible to specify color, line styles, and markers (such as plus signs or circles) when you plot your data using the plot command.

plot(x,y,'color_style_marker') , where color_style_marker is a string containing from one to four characters (enclosed in single quotation marks) constructed from a color, a line style, and a marker type:

Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These correspond to cyan, magenta, yellow, red, green, blue, white, and black.

Linestyle strings are '-' for solid, '--' for dashed, ':' for dotted, '-.' for dash-dot. Omit the linestyle for no line.

The marker types are '+', 'o', '*', and 'x' and the filled marker types are 's' for square, 'd' for diamond, '^' for up triangle, 'v' for down triangle, '>' for right triangle, '<' for left triangle, 'p' for pentagram, 'h' for hexagram, and none for no marker.

Adding Plots to an Existing Graph

The hold command enables you to add plots to an existing graph. When you type

» hold on

MATLAB does not replace the existing graph when you issue another plotting command; it adds the new data to the current graph, rescaling the axes if necessary. To remove the effect of the hold on function you may use:

» hold off

Multiple Plots in One Figure

The subplot command enables you to display multiple plots in the same window or print them on the same piece of paper. Typing:

» subplot(m,n,p)

partitions the figure window into an m-by-n matrix of small subplots and selects the pth subplot for the current plot. The plots are numbered along first the top row of the figure window, then the second row, and so on. For example, these statements plot data in four different subregions of the figure window.

t = 0:pi/10:2*pi;

[X,Y,Z] = cylinder(4*cos(t));

subplot(2,2,1); mesh(X)

subplot(2,2,2); mesh(Y)

subplot(2,2,3); mesh(Z)

subplot(2,2,4); mesh(X,Y,Z)

Figure Windows

Graphing functions automatically open a new figure window if there are no figure windows already on the screen. If a figure window exists, MATLAB uses that window for graphics output. If there are multiple figure windows open, MATLAB targets the one that is designated the “current figure” (the last figure used or clicked in).

To make an existing figure window the current figure, you can type :

>> figure(n)

where n is the number in the figure title bar. The results of subsequent graphics commands are displayed in this window. To open a new figure window and make it the current figure, type:

>> figure

Consider the following MATLAB script:

dB=0:0.1:10;

SNR=10.^(dB./10);

Pb=0.5*erfc(sqrt(SNR))

semilogy(dB,pb) %same as plot(dB,log10(pb))

grid

xlabel(‘SNR(dB)’)

ylabel(‘Bit error rate’)

title(‘Performance of antipodal signaling over AWGN’)

Exercise#7

Using MATLAB, plot the function

f

( )

t

=

e

2 t

cos(3

t u t

π

)

( )

where t ranges from –2 to 10. Give the x-axis the title (t sec) and the y-axis the title (f(t) volts ). Repeat using stem function. Then use subplot to combine the two figures in one figure and give it the name: “ difference between plot and stem”.

The save Function

The workspace is not maintained across MATLAB sessions. When you quit MATLAB, the workspace is cleared. You can save any or all of the variables in the current workspace to a MAT-file, which is a MATLAB specific binary file. You can then load the MAT-file at a later time during the current or another session to reuse the workspace variables. MAT-files use a .mat extension.

To save all variables from the workspace in binary MAT-file, test.mat, type

» save test.mat

To save variables p and q in binary MAT-file, output.mat,

» p = rand(1,10);

» q = ones(1,10);

» save('output.mat','p','q')

The load Function

The load function reads binary files containing matrices generated by earlier MATLAB sessions, or reads text files containing numeric data. The text file should be organized as a rectangular table of numbers, separated by blanks, with one row per line, and an equal number of elements in each row. For example, outside of MATLAB, create a text file containing these four lines.

16.0

3.0

2.0

13.0

5.0

10.0

11.0

8.0

9.0

6.0

7.0

12.0

4.0

15.0

14.0

1.0

Store the file under the name data.dat. Then the statement load data.dat reads the file and creates a variable, data, containing our example matrix.

Images are represented as matrices in Matlab. So try out

>> load clown >> imagesc (X)

% axis image

Playing Sound Files from Matlab Data

Digital signal processing is widely used in speech processing for applications ranging from speech compression and transmission, to speech recognition and speaker identification. This exercise will introduce the process of reading and manipulating a speech signal.

Once you have a .wav file, you can read the data into your program using MATLAB's wavread

function

gives you the ability to hear the wave.

You must determine the file path first. After you read the wave file, the soundsc function

» [x, fs] = wavread('file path\file name');

» soundsc(x, fs);

MatLab may be used to convert the available Ascii files into .wav format. This permits the original sounds to be heard using the ‘Sound Recorder’ application, for example. If an Ascii version of a sound file is loaded into MatLab, then a .wav file may be created using the wavwrite command. The sampling frequency must be specified to use this function, for example:

» wavwrite(x,22255,'mysound.wav') % x: vector containing speech samples, 22255: sampling rate

Exercise#8

We will do this exercise on the wave file speech_dft.wav. You can find this file in

matlab13\toolbox\dspblks\dspblks\speech_dft.wav

1. Read this wave file using wavread function.

2. Listen to the wave using soundsc function.

3. Create a *.wav file that contains a flipped version of speech_dft.wav

4. What are the sampling frequency, length, and size of the wave?

are the sampling frequency, length, and size of the wave? Useful Facts in MATLAB 1. MATLAB

Useful Facts in MATLAB

1. MATLAB starts indexing its arrays from 1 rather than from 0.

2. The end keyword is exceptionally useful when indexing into arrays of unknown size. Thus, if you want to return all elements in a vector except the first and last one, you can use the command:

>> x(2:end-1) %equivalent to x(2:length(x)-1)

3. MATLAB automatically resizes arrays for you. Thus, if you want to add an element on to the end of a vector, you can use the command:

>> x(end+1) = 5;

DSP Laboratory Experiment # 2

Introduction to the TMS320C6711 DSK And Code Composer Studio

Goals

In this Experiment, our aim is to show how mathematical algorithms for digital signal processing may be encoded for implementation on programmable hardware. In this lab, you will become familiar with a development system for programming DSP hardware. You will study:

Code Composer Studio

TMS320C6711 DSP chip and supporting architecture (DSK)

The C programming language

Prelab

1. Since this lab deals with new concepts for you, you must study the following necessary introduction carefully before going to the lab. This self-study will be evaluated by a short quiz in the beginning of the lab. So BE CAREFULL!!!

2. Try to draw a flowchart for the C program in page 29.

Background and Motivation:

You will be hearing a lot about the term DSP throughout the course. What is DSP? Why is it important? Why do you want to process signals in digital instead of leaving it in analog? When should you use DSP? What are the advantages, disadvantages and tradeoffs? What are DSP processors and how are they different than microprocessors? This Experiment will discuss briefly these questions.

Digital Signal Processing

Digital Signal Processing is a technique that converts signals from real world sources (usually in analog form) into digital data that can then be analyzed. Analysis is performed in digital form because once a signal has been reduced to numbers; its components can be isolated, analyzed and rearranged more easily than in analog form.

Eventually, when the DSP has finished its work, the digital data can be turned back into an analog signal, with improved quality. For example, a DSP can filter noise from a signal, remove interference, amplify frequencies and suppress others, encrypt information, or analyze a complex wave form into its spectral components.

A/D DSP D/A
A/D
DSP
D/A

This process must be handled in real-time - which is often very quickly. For instance, stereo equipment handles sound signals of up to 20 kilohertz (20,000 cycles per second), requiring a DSP to perform hundreds of millions of operations per second.

Why Digitizing?

Why do we process signals digitally rather than working with the original signal in the analog domain? The answer depends on the system and its requirements. For some systems, working with the analog signals gives a better solution. For others, DSP is better. It is up to you, the designer, to make the decision based on materials you learn through this and other courses. Here are some things to consider in making the tradeoffs:

Reasons to go digital:

1. Flexibility: can easily change, modify and upgrade through software.

2. Reproducibility of results from one unit to another: because DSP works with binary sequences. Analog circuits have component tolerances.

3. Reliability: memory and logic don’t slowly ‘go bad’ with time and are not affected by temperature.

4. Complexity: complex algorithms can be implemented on lightweight and low power portable devices.

5. Only solution: some algorithms can only be done in the digital domain: linear phase filters, adaptive filters, data compression, and error correcting codes.

6. Low overall cost.

Disadvantages of digital − Reasons to go analog:

1. Bandwidth is limited by sampling rate and peripherals i.e. we can’t process high frequencies.

2. Initial design cost may be expensive (esp. for large BW signals).

3. Data size: a fixed number of bits means limited range and quantization and arithmetic errors (may not get theoretical performance).

Applications of DSP Who has DSP processor?

DSP technology is nowadays commonplace in such devices as mobile phones, multimedia computers, video recorders, CD players, hard disc drive controllers and modems, and will soon replace analog circuitry in TV sets and telephones. An important application of DSP is in signal compression and decompression. In CD systems, for example, the music recorded on the CD is in a compressed form (to increase storage capacity) and must be decompressed for the recorded signal to be reproduced. Signal compression is used in digital cellular phones to allow a greater number of calls to be handled simultaneously within each local "cell". DSP signal compression technology allows people not only to talk to one another by telephone but also to see one another on the screens of their PCs, using small video cameras mounted on the computer monitors, with only a conventional telephone line linking them together.

What are the typical DSP algorithms?

The Sum of Products (SOP) is the key element in most DSP algorithms. That is to say that although the mathematical theory underlying DSP techniques such as Fast Fourier and Hilbert Transforms, digital filter design and signal compression can be fairly complex, the numerical operations required to implement these techniques are in fact very simple, consisting mainly of operations that could be done on a cheap four-function calculator.

DSP Processors vs. General-purpose Microprocessors:

How do DSP processors differ from microprocessors? Like a general-purpose microprocessor, a DSP is a programmable device, with its own native instruction code. Both types of processors perform computations on digital signals. But the main difference is that DSP processors are tailored to process data signals whereas microprocessors are designed to reduce the amount of computations in a general computing environment where most signals being processed pertain to some form of program control. DSP processors are also designed to consume less power under its target applications. DSP chips are capable of carrying out up to tens of millions of samples per second, to provide real-time performance: that is, the ability to process a signal "live" as it is sampled and then output the processed signal, for example to a loudspeaker or video display. Finally you should note that the main drawback of DSP processor is its limited on-chip memory.

Parameters to consider when choosing a DSP processor:

A. Fixed vs. Floating-Point DSP’s

a. Fixed-point DSP’s represent a number in 16 or 24 bit integer format. They are cheaper and use less power but care must be taken with scaling (the data is scaled so values lie between -1 and 1) to avoid over and underflow.

b. Floating-point DSP’s stores a number as a 24 bit mantissa and an 8 bit exponent. They are easier to program and numbers are automatically scaled. But they are more complicated, can be slower than fixed-point counterparts, larger in size, expensive and have a higher power consumption. Statistics point out that 95% of DSP's market uses fixed point and only 5% for floating point DSP's.

B. Processing time measures are based on the clock (150MHz for our case)

a. MACS, multiplies and accumulates, If 2 per clock cycle, then 300 million MACs per second.

b. MFLOPS, million floating-point operations per second, If 6 units capable of doing floating-point operations, then can do 900MFLOPS.

c. MIPS, million of instructions per second, If 8 units capable of doing fixed and floating-point operations, then have a 1200MIPS system.

C. Codeword length

Sixteen-bit fixed-point DSPs are used for voice-grade systems such as phones, since they work with a relatively narrow range of sound frequencies. Hi-fidelity stereo sound has a wider range, calling for a 16-bit ADC (Analog/Digital Converter), and a 24-bit fixed point DSP. Image processing, 3-D graphics and scientific simulations have a much wider dynamic range and require a 32-bit floating-point processor.

D. Others

a. Overall cost.

b. Software development tools, simulators.

c. Commercially available DSP boards for software development and testing before the target DSP hardware is available?

d. The likelihood of having higher-performance devices with upwards-compatible software in the future.

e. Power Consumption: The most commonly used TMS320 DSP chips (in the year 2002) are the C2000, C5000, and C6000 series of chips. Due to their low power consumption (40mW to 160mW of active power), they are very attractive for power sensitive portable systems. As the dsps speed increases, so does the power consumption. This makes an accurate knowledge of the execution time critical for selecting the proper device.

Our system, Texas Instruments C6711 DSK :

General description:

We will be working with the TI TMS320C6711 DSP chip. The chip is very powerful by itself, but for development purposes, a supporting architecture is required to store programs and data, and bring signals on and off the board. In order to use this DSP chip in a lab, the chip will be on a board that contains additional appropriate components. Together, CCS, the DSP chip, and supporting hardware make up a DSP Starter Kit, or DSK. Here are few words about each element:

Codec

The codec (coder/decoder) is a chip located on-board the DSK. In this course, we will use the coder or analog-to-digital converter (ADC) and decoder or digital-to-analog converter (DAC), along with two mono headphone jacks, to interface a DSP chip to the analog world. This codec runs at a fixed rate of 8kHz and 16 bit representation. In the next lab, we will explore the codec in more depth.

C6711 chip

Floating-point DSP, 150MHz clock, 900MFLOPS, 1200MIPS

Can fetch 8 32-bit instructions per cycle.

72kB internal memory, 8 functional or execution units, 2 sets of 32-bit registers.

Capable of fixed and floating point operations.

VLIW – very long instruction word architecture.

External Memory:

The board contains 16 MB of SDRAM and 128 kB of flash ROM.

Code Composer Studio ( CCS)

CCS is a powerful integrated development environment that provides a useful transition between a high-level (C or assembly) DSP program and an on-board machine language program. CCS consists of a set of software tools and libraries for developing DSP programs, compiling them into machine code, and writing them into memory on the DSP chip and on-board external memory. It also contains diagnostic tools for analyzing and tracing algorithms as they are being implemented on-board. In this class, we will always use CCS to interface DSP hardware with a PC.

1 8V Power 16M 128K Daughter Card I/F Parallel Port C6711 TMS320C67 DSP Power D.
1 8V Power
16M
128K
Daughter
Card I/F
Parallel
Port
C6711
TMS320C67
DSP
Power
D. Card I/F
Jack
Power
LED
User
Switch
Reset
3 3V Power
Three User LEDs
16-bit codec (A/D & D/A)
Emulation
JTAG
JTAG
Line Level Input
Line Level Output

C6711 DSP Chip

The C6711 DSP chip is a floating point processor which contains a CPU (Central Processing Unit), internal memory, enhanced direct memory access (EDMA) controller, and on-chip peripherals. These peripherals include a 32-bit external memory interface (EMIF), two Multi-channel Buffered Serial Ports (McBSP), two 32-bit timers, a 16-bit host port interface (HPI), an interrupt selector, and a phase lock loop (PLL), along with hardware for `Boot Configurations' and ‘Power Down Logic’.

for `Boot Configurations' and ‘Power Down Logic’. Programming Languages Assembly language was once the most

Programming Languages

Assembly language was once the most commonly used programming language for DSP chips (such as TI's TMS320 series) and microprocessors (such as Motorola's 68MC11 series). Coding in assembly forces the programmer to manage CPU core registers (located on the DSP chip) and to schedule events in the CPU core. It is the most time consuming way to program, but it is the only way to fully optimize a program. Assembly language is specific to a given architecture and is primarily used to schedule time critical and memory critical parts of algorithms.

The preferred way to code algorithms is to code them in C. Coding in C requires a compiler that will convert C code to the assembly code of a given DSP instruction set. C compilers are very common, so this is not a limitation. In fact, it is an advantage, since C coded algorithms may be implemented on a variety platforms (provided there is a C compiler for a given architecture and instruction set). In CCS, the C compiler has four optimization levels. The highest level of optimization does not achieve the same level of optimization that programmer-optimized assembly programs does, but TI has done a good job in making the optimized C compiler produce code that is comparable to programmer- optimized assembly code.

Lastly, a cross between assembly language and C exists within CCS. It is called linear assembly code. Linear assembly looks much like assembly language code, but it allows for symbolic names and does not require the programmer to specify delay slots and CPU core registers on the DSP. Its

advantage over C code is that it uses the DSP more efficiently, and its advantage over assembly code is that it does not require the programmer to manage the CPU core registers. This will be apparent in future labs when assembly and linear assembly code are written.

Assembler Optimizer .sa *.cmd .asm .obj Text .asm .out Editor Assembler Linker .c Compiler
Assembler
Optimizer
.sa
*.cmd
.asm
.obj
Text
.asm
.out
Editor
Assembler
Linker
.c
Compiler

Debug

Profile

Graph

Watch

Timing

The DSP chip must be able to establish communication links between the CPU (DSP core) and the codecs and memory. The two McBSPs, namely serial port 0 (SP0) and serial port 1 (SP1), are used to establish asynchronous links between the CPU and the on-board codec, and between the CPU and daughter card expansion, respectively. These McBSPs use frame synchronization to communicate with external devices. Each McBSP has seven pins. Five of them are used for timing and the other two are connected to the data receive and data transmit pins on the on-board codec or daughter card. Also included in each McBSP is a 32-bit Serial Port Control Register (SPCR). This register is updated when the on-board codec (or daughter card) is ready to send data to or receive data from the CPU. The status of the SPCR will only be a concern to us when polling methods are implemented.

In this lab, we will be exploring two possible ways of establishing a real-time communication link between the CPU and the on-board codec. The idea of real-time communication is that we want a continuous stream of samples to be sent to the codec. In our case, we want samples to be sent at rate 8kHz (one sample every .125ms). This is controlled by the codec, which will signal serial port 0 (SP0), every .125ms.

Polling

The first method for establishing a real-time communication link between the CPU and the on-board codec is polling. When the on-board codec is ready to receive a sample, it sets a bit 17 of the SPCR to true. Bit 17 of the SPCR is the transmit ready (XRDY) bit, which is used to let the CPU know that it can transmit data. In a polling application, the CPU continuously checks the status of the SPCR and transmits a data sample as soon as the bit 17 of the SPCR is set true.

Upon transmission, the McBSP will reset bit 17 of the SPCR to false. The polling program will then wait until the on-board codec resets bit 17 to true before transmitting the next data sample. In this manner, a polling algorithm will maintain a constant stream of data °owing to the on-board codec.

On the DSP hardware, polling is implemented mostly in software. The on-board codec will continuously set the transmit ready bit of the SPCR and the McBSP will always reset it. However, it is up to the programmer to write an algorithm that will constantly be checking the status of the SPCR.

Fortunately, this has already been taken care of for you. This will be explained in detail later when we implement a polling example.

Interrupts

When using polling to send and receive the data from the CODEC the general processing was

WAIT for the CODEC to receive the data Retrieve the data Process the data WAIT for the CODEC to be ready to accept the data Transmit the data

This is very inefficient since there are two places in the code were processing time is used just waiting for data to arrive. It would be better if the processor could be processing data during this time. This is where interrupts can help speed things up.

An interrupt can be some event that is generated either by a an external hardware device, internal hardware device or software. When an interrupt occurs the main processing is interrupted and the processor jumps to an interrupt subroutine (ISR). This ISR is just a function that is set up to handle the event that caused the interrupt. When the ISR is done processing, the processor jumps back to where it left off when the interrupt occurred. The following shows how this can occur:

Main processing statement 1 Main processing statement 2 Main processing statement 3 Interrupt occurs Processor saves the current state of the registers, etc. Processor jumps to ISR ISR processing statement 1 ISR processing statement 2 ISR processing statement 3 ISR completes Processor restores the previously saved state of registers, etc. Main processing statement 4 Main processing statement 5 Etc.

The CODEC on the DSP board is connected to an internal device called the multichannel buffered serial port (McBSP). There is more than one McBSP on the C6711, so the CODEC is connected to the McBSP0. This device can generate an internal interrupt when it receives data from the CODEC and when it is ready to send data to the CODEC. Therefore, two ISRs will be used to send and

receive data to and from the CODEC. Since these are separate functions, there needs to be a way to get the data from one to the other. This is done here using "mailboxes." A mailbox is a way to send data from one object or task to another

The figure below shows the basic structure that can be used for many different types of signal processing applications using interrupts.

Receive ISR Receive Data Mailbox Signal McBSP0 Processi ng Task Mailbox Transmit Data Transmit ISR
Receive
ISR
Receive
Data
Mailbox
Signal
McBSP0
Processi
ng Task
Mailbox
Transmit
Data
Transmit
ISR
Inside DSP

CODEC

Audio

Inputs

Transmit Data Transmit ISR Inside DSP CODEC Audio Inputs The circles are the ISRs, the rectangle

The circles are the ISRs, the rectangle McBSP0 is the internal McBSP0 device and the rectangle CODEC shows the external CODEC device. Audio data is input to the CODEC were it is sampled. This data is sent to the McBSP0, which generates a receive interrupt. The interrupt causes the Receive ISR to run and retrieve the data. The data is put in a mailbox and sent to be processed. After processing task, the processed data will be transmitted to the Transmit ISR. When the McBSP0 is ready to transmit data to the CODEC it will generate an interrupt which will cause the Transmit ISR to run. The Transmit ISR will deliver the data to the McBSP0 which will then send it to the CODEC. Finally, the CODEC will convert the data to analog and output it.

Now, after reading this introduction, you are capable of carrying out this lab, in which we will create the first project on the DSK.

Lab

Setting up the Equipment

For every lab in this course (with a few minor exceptions for this lab), the following equipment will be needed at every lab station:

A pentium based computer with CCS version 2.0 or greater installed on it.

A C6711 DSK including power supply and parallel printer port cable.

A set of speakers or headphones.

An arbitrary waveform generator.

An oscilloscope.

For this lab, we will just be observing and listening to signals, so only the oscilloscope, headphones or speakers, and one of the 3 foot headphone-to-RF connector cables will be used. At this point, turn on the oscilloscope and connect the cable to the headphone jack on the DSK and connect the left channel (white cable) to the RF connector on the oscilloscope.

Creating the First Project on the DSK

Creating the Project File sine_gen.pjt

Inside C:\ DSP folder create another folder named as lab2, in which we will save all the files we need in our first project.

In CCS, select `Project' and then `New'. A window named `Project Creation' will appear.

In the field labeled `Project Name', enter `sine_gen'. In the field ‘Location’, click on the ‘…’ on the right side of the field and browse to the folder C:\DSP\lab2\sine_gen. For `Project Type', use `Executable (.out)'. Do not change this field. In the field `Target', make sure that the TMS32067XX is selected. Finally, click on `Finish'. The file sine_gen.pjt has been created in the folder C:\DSP\lab2\sine_gen.

has been created in the folder C:\DSP\lab2\sine_gen. Project Creation Window for sine_gen.pjt DSP LABORATORY 24

Project Creation Window for sine_gen.pjt

Adding Support Files to a Project

The next step in creating a project is to add the appropriate files.

In the CCS window, go to `Project' and then ‘Add Files to Project’. In the window that appears, click on the folder next to where it says ‘Look In:’ Make sure that you are in the folder C:\DSP\support_files. You should be able to see the file C6xdskinit.c. Notice that the `Files of type' field is 'C source code'. Click on C6xdskinit.c and then click on `Open'.

Repeat this process two more times adding the files vectors 11.asm and C6xdsk.cmd. For field, `Files of type', select `Asm Source Files (*.a*)'. Click on vectors11.asm. For field, `Files of type', select `Linker Command File (*.cmd)'. Click on C6xdsk.cmd.

The C source code file contains functions for initializing the DSP and peripherals. The vectors file contains information about what interrupts (if any) will be used and gives the linker information about resetting the CPU. This file needs to appear in the first block of program memory. The linker command file (C6xdsk.cmd) tells the linker how the vectors file and the internal, external, and flash memory are to be organized in memory. In addition, it specifies what parts of the program are to be stored in internal memory and what parts are to be stored in the external memory. In general, the program instructions and local/global variables will be stored in internal (random access) memory or IRAM.

Adding Appropriate Libraries to a Project

In addition to the support files that you have been given, there are pre-compiled files from TI that need to be included with your project. For this project, we need a run-time support library (rts6701.lib), which our support files will use to run the DSK, and a GEL (general extension language) file (dsk6211_6701.gel) to initialize the DSK. The GEL file was included when the project file sine_gen.pjt was created, but the RTS (run-time support) library must be included in the same manner used to include the previous files.

Go to `Project' and then `Add Files to Project'. For `Files of type', select `Object and Library Files (*.o*,*.l*)'. Browse to the folder C:\DSP\support_files and select the file rts6701.lib. In the left sub-window of the CCS main window, double-click on the folder 'Libraries' to make sure the file was added correctly.

These files, along with our other support files, form the black box that will be required for every project created in this class. The only files that change are the source code files that code a DSP algorithm and possibly a vectors file.

Adding Source Code Files to a Project

The last file that you need to add is your source code file. This file will contain the algorithm that will be used to internally generate a 1kHz sine wave.

Go back to `Project' and then `Add Files to Project'. Select the file sine_gen.c and add it to your project.

You may have noticed that the .h files cannot be added. These files are header files and are referenced in C6xdskinit.c.

Go to `Project' and select `Scan All Dependencies'. In CCS, double-click on `sine_gen.pjt' and then double-click on `Include'. You should see the three header files that you downloaded plus a mystery file C6x.h.

This mystery file is included with the Code Composer Studio software, and it is used to configure the board. CCS automatically included all of the header files when the file C6xdskinit.c was added to the project. Open the file C6xdskinit.c and observe that the first four lines of code include the four header files. You now have all of the files you need for this project.

Build Options

Once all of your files have been included in your project file, the compiler and linker options must be configured so that your project gets built correctly. Go to `Project', then to `Build Options', and then click on the `Compiler' tab. In the ‘Category:’, ‘Basic’, make sure the following are selected:

Target Version: 671x

Generate Debug Info: Full Symbolic Debug (-g)

Opt Speed vs. Size: Speed Most Critical (no ms)

Opt Level: None

Program Level Opt: None

In the top part of the current window, you should see:

-g -q -f r"C:\DSP\lab2\sine_gen\Debug" -d"_DEBUG"

Change it to:

-g -k -s -fr"C:\DSP\lab2\sine_gen\Debug" -d"_DEBUG" -mv6710

-k -s -fr"C:\DSP\lab2\sine_ge n\ Debug" -d"_DEBUG" -mv6710 Build Options for Compiling DSP LABORATORY 26

Build Options for Compiling

Now click on the ‘Linker’ tab on the top of the current window and make sure the following command appears in the top most window (See Figure below):

-q -c -o"

\Debug\sine_gen.out"

-x

The options -g, -k, -s in the compiler options and -g, -c, -o in the linker options do serve a purpose, but we will not be concerned with them just yet.

Your project has now been created. This process is cumbersome, but it only needs to be done once. In future projects, you will be able to copy this folder into another folder and make a few simple modifications. These modifications include altering the C code in sine_gen.c and editing one linker option. This will be demonstrated later in this lab.

linker option. This will be demonstrated later in this lab. Build Options for Linking Building and

Build Options for Linking

Building and Running the Project

Now you must build and run the project. To build the first project, go to `Project' pull-down menu in the CCS window, then select `Build' (or press the button with three red down arrows on the top toolbar in the CCS window). A new sub-window will appear on the bottom of the CCS window.

When building is complete, you should see the following message in the new sub-window:

Build Complete,

0 Errors, 0 Warnings, 0 Remarks.

When CCS “built” your project, it compiled all of the C code into assembly code, using a built-in compiler. Then it assembled the assembly code into a COFF (common object file format) file that contains the program instructions, organized into modules. Finally, the linker organizes these modules and the run-time support library (rts6701.lib) into memory locations to create an executable .out file. This executable file can be downloaded onto the DSK. When this executable file is loaded onto the DSK, the assembled program instructions, global variables, and run-time support libraries are loaded to their linker specified memory locations.

To test your program on the DSK, you must first load the program onto the board, but before you load a new program onto the board, it is good practice to reset the CPU.

To reset the the CPU, click on `Debug', then select `Reset CPU'.

Then, to load the program onto the DSK, click on `File', then select `Load Program'. In the new window that appears, double-click on the folder `Debug', select the file sine_gen, then select `Open'. This will download the executable file to the DSK. A new window will appear within CCS entitled “Disassembly”, which contains the assembled version of your program. Ignore this window for now.

Before you run this program, make sure that the cable between the 1/8th inch headphone jack on the DSK board (the J6 connector) and the oscilloscope is connected, and make sure that the oscilloscope is turned on.

In CCS, select the `Debug' pull down menu and then select `Run', or just simply click on the top \running man" on the left side toolbar. Verify a 1kHz sine wave on the oscilloscope.

Once you have verified the signal, disconnect the oscilloscope from the DSK and attach a pair of speakers or headphones to the DSK. You should hear a 1kHz pure tone.

After you have completed both of these tasks, either click on the icon of the blue `running man' with a red `X' on it or go to the `Debug' pull down menu then select `Halt'.

Generating a Sinusoid in Real-Time

In many of the communication systems that we design, we want to be able to generate a sinusoid with arbitrary frequency f o . In the first project, we generated the sinusoid

x(t)

=

sin(2πf t)

o

…….1

where f o = 1kHz. In real-time digital systems, this requires samples of the signal in eqn(1) to be sent to the codec at a fixed rate. In the case of the on-board codec, samples are being sent at rate fs = 8kHz (ts = 0.125ms). In C code, we generate samples of eqn(1), namely

x [ n

]

= x ( nt

s

)

=

sin(2

πn

f

o

f

s

)

………2

which is only defined for integer values of n. Here, the argument of the sine function,

θ[n] = 2πn

f

o

f

s

is a linear function that can be easily updated at each sample point. Specifically, at the time instance n + 1, the argument becomes

θ[n +1] = 2π[n +1]

f

o

f

s

which is the previous argument plus the offset

2π

f

o

f

s

.

=

θ [ n

]+ 2

π

f

o

f

s

This makes it possible to generate any sinusoid whose frequency is fo < 3.6kHz in eqn(2). You may have expected the maximum frequency to be fs/2 = 4kHz, but the codec requires oversampling, a point to be clarified later.

Code Analysis and Modification

Now that you have successfully implemented your first project in hardware, it is time to analyze the source code in sine_gen.c to see exactly how this 1kHz sine wave was generated. Note in C (or more precisely C++) that text following `//' on any line is regarded as a comment and is ignored when the program is compiled. Here is the sine_gen.c file.

1.)

#include <math.h>

// needed for sin() function

2.)

#define PI 3.14159265359

// define the constant PI

3.)

float f0=1000;

// sinusoid frequency

4.)

short fs=8000;

// sampling frequency of codec

5.)

float angle=0;

// angle in radians

6.)

float offset;

// offset value for next sample

7.)

short sine_value;

// value sent to codec

8.)

9.)

interrupt void c_int11()

// interrupt service routine

10.)

{

11.)

offset=2*PI*f0/fs;

// set offset value

12.)

angle = angle + offset;

// previous angle plus offset

13.)

14.)

If (angle > 2*PI)

// reset angle if > 2*PI

15.)

angle -= 2*PI;

// angle = angle - 2*PI

16.)

17.)

sine_value=(short)20000*sin(angle);

// calculate current output sample

18.)

output_sample(sine_value);

// output each sine value

19.)

return; // return from interrupt

20.)

}

21.)

22.)

void main()

23.)

{

24.)

comm_intr();

// init DSK, codec, SP0 for interrupts

25.)

while(1);

// wait for an interrupt to occur

26.)

}

It is important to notice that code is divided (via blank lines) into different sections (in this case three sections). This format is often used and it is recommended that you adopt this style of coding.

In particular, the section containing the function main() will always come last (lines 22 through 26). In C, the function main() is always the starting point of the program. The linker knows to look for this function to begin execution. A C program without a main() function is meaningless.

For ease of understanding, this code will be analyzed in this order: section one (lines 1 through 7), then section three (lines 22 through 26), and finally section two (lines 9 through 20).

Analyzing the Code

The first section of code (lines 1 through 7) is used for preprocessor directives and the definition of global variables. In C, the # sign signifies a preprocessor directive. In this course, we will primarily use only two preprocessor directives, namely #include and #define.

In line 1, the preprocessor directive, #include <math.h>, tells the preprocessor to insert the code stored in the header file math.h into the first lines of the code sine_gen.c before the compiler compiles the file. Including this header file allows us to call mathematical functions such as sin(θ), cos(θ), tan(θ), etc. as well as functions for logarithms, exponentials, and hyperbolic functions. This header file is required for the sin(θ) function line 17. To see a full list of functions available with math.h, use the help menu in CCS.

The next preprocessor directive defines the fixed point number PI, which approximates the irrational number π before compiling, the preprocessor will replace every occurrence of PI in sine gen.c with the number specified . The next five lines (4 through 7) define the global variables: f0, fs, angle, offset, and sine value. The variables fs and sine value are of type short which means they hold 16-bit signed integer values. The variables f0, angle, and offset are of type float which means they hold IEEE single precision (32-bit) floating point numbers.

Notice that all of the lines that contain statements end with a semicolon. This is standard in C code. The only lines that do not get semicolons are function names, like c_int11(), conditional statements, like if(), and opening and closing braces ({ }) associated with them.

The last section of code (lines 22 through 26) contains the function main(). The format of the main() function will NOT change from program to program. Lines 22,23 and 26 will always be the first two lines and last line, respectively. The first line in main() (line 24) calls the function comm_intr(). This function is located within the file C6xdskinit.c, which is one of the support files given to you. This function initializes the on-board codec, specifies that the transmit interrupt XINT0 will occur in SP0, initialize the interrupt INT11 to handle this interrupt, and allows interrupts INT4 through INT15 to be recognized by the DSP chip.

Now, the DSP chip and codec have been configured to communicate via interrupts, which the codec will generate every 0.125ms. The program sine_gen now waits for an interrupt from the codec, so an infinite loop keeps the processor idle until an interrupt occurs. This does not have to be the case, since an interrupt will halt the CPU regardless whether it is processing or idling. But in this program, there is no other processing, so we must keep the processor idling while waiting for an interrupt.

The middle section of code (lines 9 through 20) is used to define the interrupt service routine or ISR. When an interrupt occurs, the program branches to the ISR cint11() as specified by vectors 11.asm. This interrupt generates the current sample of the sinusoid and outputs it to the codec.

Line 11 determines the offset value

2π

f

o

f

s

. For a given fo, this value will not change, so it does not

need to be calculated every time an interrupt occurs. However, by calculating this value here, we will be able to change the value of our sinusoid using a Watch Window. This is demonstrated in the next section.

Line 12 calculates the current sample point by taking the value stored in the global variable angle and adding the offset value to it. The angle variable is, of course, the angle (in radians) that is passed to

the sine function. Remember that the C the command angle += offset; is shorthand for the command angle = angle + offset.

The sin(x) function in C approximates the value of sin(x) for any value of x, but a better and more efficient approximation will be computed if 0 <x < 2π. Therefore, lines 14 and 15 are used to reset the value of sample if it is greater than 2π. Since sin(x) is periodic 2π in x, subtracting 2π from x will not change the value of the output.

Line 17 calculates the sine value at the current sample point. The value is typecast as (short) before it is stored in the variable sine value. Typecasting tells the compiler to convert a value from one data type to another before storing it in a variable or sending it to a function. In this case, the value returned from the sin() is a single precision floating point number (between -1.0 and 1.0) that gets scaled by 20000. By typecasting this number as a short (16-bit signed integer between the values - 32768 and 32767), the CPU will round the number to the nearest integer and store it in a 16-bit signed integer format (2's complement). This value is scaled by 20000 for two reasons. First, it is needed so that rounding errors are minimized, and second, it amplifies the signal so it can be observed on the oscilloscope and heard through speakers or headphones. This scaling factor must be less than 32768 to prevent overdriving the codec.

Line 18 sends the current sine value to the codec by calling the function output_sample(). The code for output sample() is located in file C6xdskinit.c.

Upon completion of the interrupt (generating a sinusoid sample and outputting it to the on-board codec), the interrupt service routine restores the saved execution state (see the command return; in line 19). In this program, the saved execution state will always be the infinite while loop in the main() function.

Using a Watch Window

Once an algorithm has been coded, it is good to have software tools for observing and modifying the local and global variables after a program has been loaded onto the DSK. Located in CCS is a software tool called a Watch Window, which allows the user to view local variables and to view and modify global variables during execution. In this lab, we will not view any local variables, but we will view and modify global variables.

In CCS, start running the program sine_gen.out again and make sure that you have a valid output on an oscilloscope. Then click on the pull-down menu `view', and select `Watch Window'. A sub- window should appear on the bottom of the main CCS window. You should notice two tabs on the bottom left part of the new sub-window: `Watch Locals' and `Watch 1'. Click on the tab `Watch 1'. Click on the highlighted field under the label `Name', type in the variable name f0, and press Enter. In the field under the label `Value', you should see the number 1000, which is the frequency of the observed sinusoid. Click on the value 1000 and change it to 2000. You should see a 2kHz sinusoid on the oscilloscope.

Exercise#1

1. Use a watch window to change the value of f s in the program above from 8000 to 6000.

How does this affect the frequency of the observed sinusoid? Does this change the rate of your digital system (i.e. the rate of the codec changes) or does it just scale the observed frequency? Is there a benefit to setting the value of f s in your program to a value different than the rate of the codec being

used? Explain what you see and give some intuition into how the rate of this real-time digital system affects the generation of a sinusoid.

2. Use a watch window to change the value of f o from 1000 to 4000 Hz with a sampling frequency of 8000 Hz. What's the effect of changing the frequency? Comment on the results.

Generating a Sine Wave Using Polling

This section has three purposes: to demonstrate how to reuse a previously created project, create a real-time communication link between the CPU and codec using polling, and generate a sinusoid using a lookup table. To create the project sine_lookup_poll, follow these instructions:

1.

Create a folder in Windows Explorer to store this project (e.g. create the folder C:\DSP\lab2\sine_lookup_poll)

2.

Copy the files sine_gen.pjt and sine_gen.c, from th e previous project, into your newly created folder.

3.

Change the names of sine_gen.pjt and sine_gen.c to sine_lookup_poll.pjt and sine_lookup_poll.c respectively.

4.

Open sine_lookup_poll.pjt in CCS. When the window a ppears that says CCS cannot find the file sine_gen.c, select 'ignore'.

5.

In

the left-hand window of CCS, select the file sine_gen. c and press the Delete key to

remove the file from the project. Also, delete the file vectors11.asm.

6.

Add the renamed C source code file sine_lookup_poll. c to the project by selecting 'Project', then 'Add Files to Project', then select sine_lookup_poll. c, and then click 'Open'. Also add the other vectors file, vectors. asm, located in your 'support' folder.

7.

In CCS, select the pull down menu 'Project' and go to 'Build O ptions'. Click on the Linker tab and change the word sine_gen in .\Debug\sine_gen.out to sine_lookup_poll in the field 'Output Filename (-o):'. Click 'OK'

8.

In CCS, double-clicking on sine_lookup_poll. c in the left hand window. Change the

C code to the following:

Short sine_table[8] = {0,14142,20000,14142,0,-14142,-20000,-4142}; short ctr; void main() { ctr=0; comm_poll();
Short sine_table[8] = {0,14142,20000,14142,0,-14142,-20000,-4142};
short ctr;
void main()
{
ctr=0;
comm_poll();
while(1)
{
output_sample(sine_table[ctr]);
if (ctr < 7) ++ctr;
else ctr = 0;
}
}

9. Add comments to your code where appropriate and save the file in CCS.

Now, build your project by clicking on the 'rebuild all' button (the button with three red arrows). Before loading a new program onto the DSK, it is best to reset the DSP. This can be done within CCS by selecting the 'Debug' pull down menu and then selecting 'Reset CPU'. Once the DSP is reset, load your new program onto the DSK and observe a 1kHz sine wave on an oscilloscope.

Notice that the sine wave algorithm is now coded within the infinite while loop (while(1)). This is the general structure for polling. In both polling and interrupt based programs, the algorithm must be small enough to execute within .125ms (at an 8kHz rate) in order to maintain a constant output to the on-board codec. Algorithms can be coded under either scheme, using polling or interrupts. In this class, most of the algorithms will be coded using interrupts.

Exercise#2

1. Study the code above and the code in C6xdskinit .c. Pay particular attention to the functions output_sample() and msbsp0_write(). Where is the polling done? Other than the fact that polling is used instead of interrupts, how is this algorithm different from the algorithm in sine_gen.c?

2. Implement the project sine_lookup_poll.pjt using in terrupts. Re-label the project sine_lookup.pjt. Explain the procedure required to change a polling based program to an interrupt driven program. Include a copy of your C program.

3. Implement sine_gen.pjt using polling. Re-label the project: sine_gen_poll.pjt. Explain the procedure required to convert an interrupt-driven program to a polling- based program.

End Notes

This lab was used to learn how to create a project and implement it on the DSK. In all real-time DSP algorithm implementations, the processing rate of a digital signal processing system is very important. For this lab, only an 8kHz rate was used to implement algorithms.

In the next lab, we will explore the concepts of input and output, and develop the foundation for designing systems and processing signals on the C6711 DSK.

DSP Laboratory Experiment # 3 Sampling and Reconstruction

Objectives:

1. To understand the concept of sampling, aliasing, and reconstruction.

2. To demonstrate the effect of aliasing on the reconstruction process.

3. To synthesize a square wave function.

Prelab

1. Compute the Fourier series expansion for the signals below in the form

a.

x

( )

t = a +

0

n = 1

A

n

sin(2

πnf t + θ

0

k

)

x(t) 1 t
x(t)
1
t

b.

T

x(t) 1 t T
x(t)
1
t
T

Note that the function after the A n is sin(2πnf 0 t + θ k ), instead of the usual complex exponential. The formula of the complex exponential Fourier series must be modified to accommodate this.

2. Solve exercise 5 in the lab theoretically.

3. Theoretically speaking, what is the minimum sampling frequency of a square wave having f 0 = 2 kHz.

= 6 kHz is sampled with f s = 8 kHz, determine the output of the D/A

4. If a sine wave of f 0 converter.

Background

Sampling

In order to store, transmit or process analog signals using digital hardware, we must first convert them into discrete-time signals by sampling.

The processed discrete-time signal is usually converted back to analog form by interpolation, resulting in a reconstructed analog signal x r (t).

resulting in a reconstructed analog signal x r (t) . Figure (1) Sampling and Reconstruction process

Figure (1) Sampling and Reconstruction process

An ideal sampler reads the values of the analog signal x a (t) at equally spaced sampling instants. The time interval T s between adjacent samples is known as the sampling period (or sampling interval). The sampling rate, measured in samples per second, is f s =1/T s . An actual (non-ideal) sampling circuit cannot capture the value of x a (t) at a single time instant. Instead, the output of a sampling circuit is the average value of x a (t) over a short interval, as shown, where delta is much shorter than the sampling period T s .

Ideal sampling circuit x[n]= x a (nT s ) n=…, -1, 0, 1, 2, ….

Actual sampling circuit

[

x n

] =

1

2

nT +∆

s

x

a

nTs-

( )

t

dt

Sampling Theorem

The bandlimiting of x a (t) also makes it possible to reconstruct x a (t) from its samples x[n] =x a (nT s ). The sampling theorem states that an analog signal x a (t) can be exactly reconstructed from its samples by the infinite order interpolation formula

x

a

( t )

=

n =−∞

x ( n ) g ( t

nT

s

)

provided that

- The frequency content of x a (t) is ideally bandlimited to a frequency range magnitude of f is

less than or equal to f max ;

f

f

max

.

- The sampling rate f s satisfies the Nyquist condition ;

- The interpolating function g(t) is the impulse response of an analog ideal low-pass filter with a cut-off frequency f c such that f max f c <f s -f max .

f

s f

2 f

max

Aliasing

As we shall presently see, the frequency content of the analog signal x a (t) has to be limited before attempting to sample it. This means that x a (t) cannot change too fast; consequently, the average value over the interval nT s -∆ to nT s +∆ is a good approximation of the ideally sampled value x a (t) of nT s .

The need for bandlimiting the signal x a (t) is easy to demonstrate by a simple example.

The solid line describes a 0.5Hz continuous-time sinusoidal signal and the dash-dot line describes a 1.5 Hz continuous time sinusoidal signal. When both signals are sampled at the rate of f s =2 samples/sec, their samples coincide, as indicated by the circles in Figure 2. This means that x 1 [nT s ] is equal to x 2 [nT s ] and there is no way to distinguish the two signals apart from their sampled versions. This phenomenon, known as aliasing, occurs whenever f 2 ± f 1 is a multiple of the sampling rate:

in our example, f s equal f 1 + f 2 .

rate : in our example, f s equal f 1 + f 2 . Figure (2)

Figure (2) Two sinusoidal signals are indistinguishable from their

sampled versions whenever f 2 ± f 1 is a multiple of the sampling rate f s

x 1 (t)=cos(2πf 1 t)

, f 1 = 0.5 Hz

X 2 (t)=cos(2πf 2 t)

, f 2 = 1.5 Hz

f 2 =2 samples/sec

x 1 (nT s ) = x 2 (nT s ) 1 (nT s ) = x 2 (nT s )

x 1 (nT s )=cos(2πf 1 nT s )=

cos(2π ×

1

2

× n ×

1

2

)

= cos(0.5πn)

x 2 (nT s )=cos(2πf 2 nT s )=

3

1

cos(2π × × n × = cos(1.5πn) = cos(1.5πn 2πn) = cos(0.5πn)

2

2

)

Since cos(x)=cos(-x), then cos(0.5πn) = cos(0.5πn)

then cos(0.5 π n ) = c o s ( − 0 . 5 π n

x 1 (nT s ) = x 2 (nT s )

Aliasing in Frequency Domain

The sampling process can be represented by the equation

It follows that

 

P w

(

)

=

and hence,

2

π

T

s

x

s

( )

t

=

( )

x t

( )

p t

( )

p t

=

n =−∞

δ

(

t

nT

s

)

δ

n

=−∞

(

w

2

π

n

T

s

)

=

X

s

(

w

)

=

=

1

2

π

(

X w

n =−∞

X w

(

2

π

T

s

n =−∞

δ

) *

P w

(

nw

s

)

)

(

w

nw

s

)

x(t)

x(t) 1 T 2T 3T xd(t) T 2T 3T |X(w)| X(0) -WB WB 2π/T -W T
x(t) 1 T 2T 3T xd(t) T 2T 3T |X(w)| X(0) -WB WB 2π/T -W T
1 T 2T 3T xd(t) T 2T 3T
1
T
2T
3T
xd(t)
T 2T
3T
|X(w)| X(0) -WB WB 2π/T -W T 2W T
|X(w)|
X(0)
-WB
WB
2π/T
-W T
2W T

|Xd(w)|

x(t) 1 T 2T 3T xd(t) T 2T 3T |X(w)| X(0) -WB WB 2π/T -W T

X(0)/T

x(t) 1 T 2T 3T xd(t) T 2T 3T |X(w)| X(0) -WB WB 2π/T -W T
x(t) 1 T 2T 3T xd(t) T 2T 3T |X(w)| X(0) -WB WB 2π/T -W T
x(t) 1 T 2T 3T xd(t) T 2T 3T |X(w)| X(0) -WB WB 2π/T -W T
x(t) 1 T 2T 3T xd(t) T 2T 3T |X(w)| X(0) -WB WB 2π/T -W T
x(t) 1 T 2T 3T xd(t) T 2T 3T |X(w)| X(0) -WB WB 2π/T -W T
x(t) 1 T 2T 3T xd(t) T 2T 3T |X(w)| X(0) -WB WB 2π/T -W T

-W T

2W T

Figure (3) Sampling in Time and Frequency Domains

Then X d (w) consists of the periodic repetition at intervals w s of X(w). If f s does not satisfy the Nyquist rate, the different components of Xd(w) overlap and will not be able to recover x(t) exactly as shown in Figure(4). This is referred to as aliasing in frequency domain.

|Xd(w)|

|Xd(w)| X(0)/T - W S -W B W B W S |Xd(w)| X(0)/T - W S
X(0)/T
X(0)/T
|Xd(w)| X(0)/T - W S -W B W B W S |Xd(w)| X(0)/T - W S
|Xd(w)| X(0)/T - W S -W B W B W S |Xd(w)| X(0)/T - W S
- W S -W B W B W S |Xd(w)| X(0)/T - W S -W
- W S
-W B
W B
W S
|Xd(w)|
X(0)/T
- W S
-W B
W B
W S
|Xd(w)|
|Xd(w)|
X(0)/T - W S -W B W B W S
X(0)/T
- W S -W B
W B
W S
X(0)/T - W S -W B W B W S
X(0)/T
- W S -W B
W B
W S

Figure (4) Aliasing in Frequency Domain

Avoiding Aliasing

In order to avoid aliasing we must restrict the analog signal x a (t) to the frequency range, f o less than f s /2 in magnitude. This constraint guarantees that for any two individual frequencies (f 1 and f 2 ) in this range both the sum and the difference of f 1 and f 2 are bound in magnitude by the sum of the magnitudes of f 1 and f 2 and this sum is, in turn, bounded by the sampling frequency f s so that aliasing cannot occur. Thus, every sampler must be preceded by an analog low-pass filter, known as an anti- aliasing filter, with a cut-off frequency f c equals f s /2.

This means that the high frequency artifacts of the continuous-time signal will be lost. This is the cost of managing aliasing. In practice, the anti-aliasing filter will have a cutoff frequency at roughly 90% of the Nyquist frequency and use the other 10% for roll-off. The on-board codec of the DSK has a sampling rate of f s = 8 kHz and an anti-aliasing filter with cutoff frequency 3.6kHz, which is 90% of f s /2 (Nyquist Frequency).

x a (t) Anti-aliasing filter f c < f s /2 x[n] sampler f s
x a (t)
Anti-aliasing
filter
f c < f s /2
x[n]
sampler
f
s
f
f
p
f
± f
f
+
f
p f
o
1
2
1
2
s
2

Figure (5) Avoiding aliasing in signal processing

Downsampling

If the desired sampling rate is lower than the sampling rate of the available data, in this case, we may use a process called downsampling or decimation to reduce the sampling rate of the signal. Decimating, or downsampling, a signal x(n) by a factor of D is the process of creating a new signal y(n) by taking only every D th sample of x(n). Therefore y(n) is simply x(Dn).

Using this method we can resample the discrete signals with no need for reconstruction first. This process will give you the ability to vary the sampling rate of a discrete signal by discarding some of its values in the time domain depending on the desired sampling rate. For example, if we want to reduce the sampling rate to the half, we down a sample between every two samples. In this case, we downsampled the signal by 2, or ( 2 ). Similarly, ( 3 ) x[n] will produce a signal that has a sample rate equals one third the sampling rate of x[n] by taking every third sample of x[n] and discarding two samples in between.

By MATLAB, we can do this in an easy way. For example,

>> x=1:1:10

x =

1

2

3

4

5

6

7

8

9

10

>> x2=x(1:2:end)

 

x2 =

 

1

3

5

7

9

Lab

Part 1: Synthesis of Square Wave

The Fourier representations of signals involve the decomposition of the signal in terms of complex exponential functions. These decompositions are very important in the analysis of linear time- invariant (LTI) systems. The response of an LTI system to a complex exponential input is a complex exponential of the same frequency!

Only the amplitude and phase of the input signal are changed. Therefore, studying the frequency response of a LTI system gives complete insight into its behavior.

Once MATLAB is started, type “dspLab3” to bring up a library of Simulink components. Double click the icon labeled Synthesizer to bring up a model as shown in Figure 6. This system may be used to synthesize periodic signals by adding together the harmonic components of a Fourier series expansion. Each Sine Wave block can be set to a specific frequency, amplitude and phase.

The initial settings of the Sine Wave blocks are set to generate the Fourier series expansion

( )

x t

= +

0

13

k = 1 k odd

4

k

π

sin(2

kt

π

)

Figure (6) Simulink model for the synthesizer experiment. These are the first 8 terms in

Figure (6) Simulink model for the synthesizer experiment.

These are the first 8 terms in the Fourier series of the periodic square wave shown in Figure 7.

Run the model by selecting Start under the Simulation menu. A graph will pop up that shows the synthesized square wave signal and its spectrum. This is the output of the Spectrum Analyzer. After the simulation runs for a while, the Spectrum Analyzer element will update the plot of the spectral energy and the incoming waveform.

the plot of the spectral energy and the incoming waveform. Figure (7) The desired waveform for

Figure (7) The desired waveform for the synthesizer experiment.

Exercise#1:

1. Save a copy of the synthesizer file as tri_synthesizer.

2. Change the parameters of each sine wave block to the values that you obtain in your prelab for a triangular Fourier series expansion.

3. Start simulation and see the results.

Part 2: Aliasing of sinusoidal signals

Exercise#2: Aliasing in Time Domain

The signal

( )

x t

=

cos(2

πf t

0

)

can be sampled at the rate

f

s

Aliasing will be observed for various f o .

=

1

T

s

to yield

x n

(

)

=

cos(2

π

f

0

f

s

n

)

.

a. Let f s =10 kHz and f o =1 kHz. Compute and plot x[n] using stem.m. One can see the sinusoidal envelope.

b. Use subplot to plot x[n] for f o =300 Hz, 700 Hz, 1100 Hz and 1500 Hz. The frequencies increase as expected.

c. Use subplot to plot x[n] for f o =8500 Hz, 8900 Hz, 9300 Hz and 9700 Hz. Do the frequencies increase or decrease? Explain.

d. Use subplot to plot x[n] for f o =10300 Hz, 10700 Hz, 11100 Hz and 11500 Hz. Do the frequencies increase or decrease? Explain.

Exercise#3: Aliasing in Frequency domain

a. Using the blocks in the library “dsplab3”, construct the simulink model shown in Figure 8.

construct the simulink model shown in Figure 8. Figure (8) Simulink model to implement aliasing in

Figure (8) Simulink model to implement aliasing in frequency domain

b. Input a sine wave of f o =5 Hz frequency from the signal generator. Choose a sampling time of 0.01 sec for the pulse generator with a pulse duration of 1 % of the sampling period. Choose the cut-off frequency of 2π f o for the Butterworth low-pass filter.

c. Start the simulation and notice the shifted versions of the frequency domain response of the input and the output of the filter.

d. Repeat steps 2 and 3 for a sine wave with f o =95 Hz. Comment.

e. Repeat steps 2 and 3 for a sine wave with f o =105 Hz. Comment.

Exercise#4: Downsampling

a. Using MATLAB, generate a sine wave with frequency f 0 of 1300 Hz, and sampling frequency fs of 8000 Hz.

b. Save the data of the sine wave as a sound file, named as 8000.wav.

c. Listen to the tone of the 1300 Hz sine wave.

d. Downsample the data of the sine wave by 2. This will result in a sine wave with a sampling rate of 4000 Hz. Repeat steps b, c and compare the sounds.

e. Generate a sine wave with frequency f 0 of 1300 Hz, and sampling frequency fs of 4000 Hz.

f. Repeat steps b and c and compare the sounds.

Exercise#5: Sampling and Reconstruction using Simulink

Suppose we have the analog filter shown which is composed of an A/D, discrete time filter , which in our example here is a moving average type , and D/A.

a. What is the digital frequency of x[n] if x(t)= sin (2π t) ?

b. Find the steady state output, y ss (t), if x(t) is the same as in (a) ?

c. Find two other x(t)'s ,different analog frequency, that will give the same steady state output as x(t)= sin (2π t) ?

d. If the sampling frequency of the A/D converter is changed to 200 Hz, while that of the D/A is kept to 100 Hz, what is the effect on the resulted output?

e. To prevent aliasing effects a prefilter would be used on x(t) before it passes to the A/D. What type (Low-pass, high-pass, band-pass, band-reject) of filter would be used and what is the largest cutoff frequency that would work for the above specified configuration?

x(t)

x[n]

Discrete-time filter h[n]=0.5(δ[n]+ δ [n-1])

y[n]

y(t)

A/D
A/D
D/A
D/A

Sampling Frequency 100 Hz

Moving Average

Sampling Frequency 100 Hz

Figure (9) The block diagram for exercise 5

Part 3: TLC320AD535 Codec

Located onboard the DSK is the AD535 codec (coder/decoder). The coder part is implemented using a sampler, delta-sigma modulator, and a decimation filter. The output rate from the codec is 8000 16- bit words per second (fs = 8 kHz), but the sampler is over-sampling at rate 64 times fs. This is common practice when using delta-sigma modulators. A delta-sigma modulator takes the current sample and compares it with the previous sample. If the current sample is larger (or smaller) than the previous sample, it makes the current sample the previous sample plus (or minus) some fixed amplitude δ. In our case, we have a 1-bit delta-sigma modulator which means that the current sample (16-bit finite-length word) will be the previous sample plus (or minus) a binary 1 assuming that the current sample is larger (or smaller) than the previous sample. By over-sampling by a factor of 64, a good representation of the original signal is captured at each sample point, since the signal, which is essentially band-limited, will not change by more than 1 bit, or quantization level, between each sample point. Only every 64th sample point is needed to accurately represent the bandlimited signal, so decimation filter (LPF running at 8kHz) is used to decrease the word rate to the desired rate 8kHz. These 16-bit finite-length words are then transmitted to the CPU via serial port 0 on the DSP chip. Notice that the CPU will treat these 16-bit finite length words as 16-bit signed integers (-32768 to +32767).

Sampling and Reconstruction using the On-Board Codec:

A Programming Example

Real-time digital signal processing involves logical operations on an incoming stream of finite-length words to produce a processed output stream. Figure 10 illustrates this idea.

In most DSP applications, the DSP core of Figure 9 will contain local program and data memory on the chip that is used to store the algorithm being implemented, local and global variables, and processed data. We will implement the "DSP core" block as a

data. We will implement the "DSP core" block as a Figure (10) DSP Block Diagram straight

Figure (10) DSP Block Diagram

straight wire, which means that only an identity map will be implemented between the input and output of the DSP core. No local or global variables or processed data will be stored in memory, and no signal processing will be done. Only the program instructions will be stored in the program memory.

DSP Core as a Straight Wire

1. In the folder C:\DSP\Lab3 the files straight_wire.pjt and straight_wire.c that you will need for this lab are found.

2. Load the project into CCS and examine the file straight_wire.c. Notice that the file has no global (or local) variables and that whatever is read in from the codec is immediately sent back to the codec via the command output sample(input sample()).

3. Compile and load this program onto the DSK and run it.

4. Connect the signal generator and the oscilloscope to the DSK and set the signal generator to a 1 kHz sinusoid with amplitude 1Vpp (peak-to-peak voltage). Observe a 1 kHz sinusoid on the oscilloscope.

Notice that the actual peak-to-peak voltage of the signal is greater than 1V (about 1.8V). This is due to the fact that the resistance of the DSK is higher resistance than the resistance to which the signal generator has been matched.

4. Change the peak-to-peak voltage and the frequency on the signal generator and observe the effects

on the oscilloscope. If the voltage input to the codec exceeds 3.3V, then the codec will be overdriven.

When the codec is overdriven, the output on the codec will either be amplitude clipping of the input sine wave or two's compliment overflows effects (a sudden change in sign). If the voltage input is too small (around 100mV or less), then coupling effects from the internal hardware will be observed. For frequency, keep in mind that there is a lowpass filter that cuts off frequencies above 3.6 kHz.

5. Vary the frequency of the sinusoid on the signal generator and observe that sinusoids above 3.6kHz

are suppressed. (You should notice that sinusoids around 3.6 kHz are decreased in amplitude, but not fully suppressed. This is due to the fact that the anti-aliasing filter is not ideal and therefore has a non- zero roll-off around 3.6 kHz.)

Exercise#6:

a. To observe the effects of the anti-aliasing filter, use a square wave as the input. Input square waves with 100, 500, 800 and 1400 kHz. Use your knowledge of the Fourier series expansion of a square wave to explain what you see. Also, listen to this signal and explain what you hear.

b. Repeat for a triangular wave as the input.

c. Sketch the output signal in each case.

Exercise#7:

Modify straight_wire.c file such that the digital signal is processed by the moving average filter used in exercise 5.

DSP Laboratory Experiment # 4 Analog Filter Design

Objectives:

1. To know the different types of analog filters.

2. To understand the concepts of analog filter design.

Prelab

1. Study the given background on MATLAB analog filter design and try an example for each design function.

2. Solve the following problems theoretically from your textbook.

P3.5, P3.7, P3.8, and P3.10

3. Design an analog fourth-order Butterworth low-pass filter with a cut-off frequency of 500 Hz and a passband gain of 10 using a suitable number of cascade operational amplifiers and R, C components for your implementation. Let R=1kΩ. Simulate the circuit by Orcad to verify your design

Background Design of Analog Filters in MATLAB

1. Butterworth Digital and Analog Filter design

[B,A] = BUTTER(N,Wn) designs an Nth order lowpass digital Butterworth filter and returns the filter coefficients in length N+1 vectors B (numerator) and A (denominator). The coefficients are listed in descending powers of z. The cutoff frequency Wn must be 0.0 < Wn < 1.0, with 1.0 corresponding to half the sample rate.

If Wn is a two-element vector, Wn = [W1 W2], BUTTER returns an order 2N bandpass filter with passband W1 < W < W2.

[B,A] = BUTTER(N,Wn,'high') designs a highpass filter.

[B,A] = BUTTER(N,Wn,'stop') is a bandstop filter if Wn = [W1 W2].

When used with three left-hand arguments, as in

[Z,P,K] = BUTTER( gain in scalar K.

),

the zeros and poles are returned in length N column vectors Z and P, and the

When used with four left-hand arguments, as in

[A,B,C,D] = BUTTER(

),

state-space matrices are returned.

BUTTER(N,Wn,'s'), BUTTER(N,Wn,'high','s') and BUTTER(N,Wn,'stop','s') design analog Butterworth filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.

n=5; wn=.4; [b,a]=butter(n,wn,’s’);

2. BUTTORD Butterworth filter order selection.

[N, Wn] = BUTTORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital Butterworth filter that loses no more than Rp dB in the passband and has at least Rs dB of attenuation in the stopband.

Wp and Ws are the passband and stopband edge frequencies, normalized from 0 to 1 (where 1 corresponds to pi radians/sample). For example,

Lowpass:

Wp = .1,

Ws = .2

Highpass:

Wp = .2,

Ws = .1

Bandpass:

Wp = [.2 .7], Ws = [.1 .8]

Bandstop:

Wp = [.1 .8], Ws = [.2 .7]

BUTTORD also returns Wn, the Butterworth natural frequency (or, the "3 dB frequency") to use with BUTTER to achieve the specifications.

[N, Wn] = BUTTORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case Wp and Ws are in radians/second.

When Rp is chosen as 3 dB, the Wn in BUTTER is equal to Wp in BUTTORD.

w1=20; Rp=-2;

w2=30; Rs=-10;

[n,wn]=buttord(w1,w2,Rp,Rs,’s’);

[num,den]=butter(n,wn,’s’)

3. CHEBY1 Chebyshev Type I digital and analog filter design.

[B,A] = CHEBY1(N,R,Wn) designs an Nth order lowpass digital Chebyshev filter with R decibels of peak-to-peak ripple in the passband. CHEBY1 returns the filter coefficients in length N+1 vectors B (numerator) and A (denominator). The cutoff frequency Wn must be 0.0 < Wn < 1.0, with 1.0

corresponding to half the sample rate. Use R=0.5 as a starting point, if you are unsure about choosing

R.

If Wn is a two-element vector, Wn = [W1 W2], CHEBY1 returns an order 2N bandpass filter with passband W1 < W < W2.

[B,A] = CHEBY1(N,R,Wn,'high') designs a highpass filter.

[B,A] = CHEBY1(N,R,Wn,'stop') is a bandstop filter if Wn = [W1 W2].

When used with three left-hand arguments, as in

[Z,P,K] = CHEBY1( the gain in scalar K.

When used with four left-hand arguments, as in

),

the zeros and poles are returned in length N column vectors Z and P, and

[A,B,C,D] = CHEBY1(

),

state-space matrices are returned.

CHEBY1(N,R,Wn,'s'), CHEBY1(N,R,Wn,'high','s') and CHEBY1(N,R,Wn,'stop','s') design analog Chebyshev Type I filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.

4. CHEB1ORD Chebyshev Type I filter order selection.

[N, Wn] = CHEB1ORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital Chebyshev Type I filter that loses no more than Rp dB in the passband and has at least Rs dB of attenuation in the stopband.

Wp and Ws are the passband and stopband edge frequencies, normalized from 0 to 1 (where 1 corresponds to pi radians/sample).

For example,

Lowpass:

Wp = .1,

Ws = .2

Highpass:

Wp = .2,

Ws = .1

Bandpass:

Wp = [.2 .7], Ws = [.1 .8]

Bandstop:

Wp = [.1 .8], Ws = [.2 .7]

CHEB1ORD also returns Wn, the Chebyshev natural frequency to use with

specifications.

CHEBY1 to achieve the

[N, Wn] = CHEB1ORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case Wp and Ws are in radians/second.

w1=1; Rp=-2;

w2=1.3; Rs=-20;

[n,wn]=cheb1ord(w1,w2,Rp,Rs,’s’);

[numt,dent]=cheby1(n,-Rp, wn,’s’)

5.

CHEBY2 Chebyshev Type II digital and analog filter design.

[B,A] = CHEBY2(N,R,Wn) designs an Nth order lowpass digital Chebyshev filter with the stopband ripple R decibels down and stopband edge frequency Wn. CHEBY2 returns the filter coefficients in length N+1 vectors B (numerator) and A (denominator).The cutoff frequency Wn must be 0.0 < Wn < 1.0, with 1.0 corresponding to half the sample rate. Use R = 20 as a starting point, if you are unsure about choosing R.

If Wn is a two-element vector, Wn = [W1 W2], CHEBY2 returns an order 2N bandpass filter with passband W1 < W < W2.

[B,A] = CHEBY2(N,R,Wn,'high') designs a highpass filter.

[B,A] = CHEBY2(N,R,Wn,'stop') is a bandstop filter if Wn = [W1 W2].

When used with three left-hand arguments, as in

[Z,P,K] = CHEBY2( the gain in scalar K.

When used with four left-hand arguments, as in

),

the zeros and poles are returned in length N column vectors Z and P, and

[A,B,C,D] = CHEBY2(

),

state-space matrices are returned.

CHEBY2(N,R,Wn,'s'), CHEBY2(N,R,Wn,'high','s') and CHEBY2(N,R,Wn,'stop','s') design analog Chebyshev Type II filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.

6. CHEB2ORD Chebyshev Type II filter order selection.

[N, Wn] = CHEB2ORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital Chebyshev Type II filter that loses no more than Rp dB in the passband and has at least Rs dB of attenuation in the stopband.

Wp and Ws are the passband and stopband edge frequencies, normalized from 0 to 1 (where 1 corresponds to pi radians/sample).

For example,

Lowpass:

Wp = .1,

Ws = .2

Highpass:

Wp = .2,

Ws = .1

Bandpass:

Wp = [.2 .7], Ws = [.1 .8]

Bandstop:

Wp = [.1 .8], Ws = [.2 .7]

CHEB2ORD also returns Wn, the Chebyshev natural frequency to use with CHEBY2 to achieve the specifications.

[N, Wn] = CHEB2ORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case Wp and Ws are in radians/second.

7. ELLIP Elliptic or Cauer digital and analog filter design.

[B,A] = ELLIP(N,Rp,Rs,Wn) designs an Nth order lowpass digital elliptic filter with Rp decibels of peak-to-peak ripple and a minimum stopband attenuation of Rs decibels. ELLIP returns the filter

coefficients in length N+1 vectors B (numerator) and A (denominator).The cutoff frequency Wn must be 0.0 < Wn < 1.0, with 1.0 corresponding to half the sample rate. Use Rp = 0.5 and Rs = 20 as starting points, if you are unsure about choosing them.

If Wn is a two-element vector, Wn = [W1 W2], ELLIP returns an order 2N bandpass filter with passband W1 < W < W2.

[B,A] = ELLIP(N,Rp,Rs,Wn,'high') designs a highpass filter.

[B,A] = ELLIP(N,Rp,Rs,Wn,'stop') is a bandstop filter if Wn = [W1 W2].

When used with three left-hand arguments, as in

[Z,P,K] = ELLIP( gain in scalar K.

When used with four left-hand arguments, as in

),

the zeros and poles are returned in length N column vectors Z and P, and the

[A,B,C,D] = ELLIP(

),

state-space matrices are returned.

ELLIP(N,Rp,Rs,Wn,'s'), ELLIP(N,Rp,Rs,Wn,'high','s') and ELLIP(N,Rp,Rs,Wn,'stop','s') design analog elliptic filters. In this case, Wn is in [rad/s] and it can be greater than 1.0.

8. ELLIPORD Elliptic filter order selection.

[N, Wn] = ELLIPORD(Wp, Ws, Rp, Rs) returns the order N of the lowest order digital elliptic filter that loses no more than Rp dB in the passband and has at least Rs dB of attenuation in the stopband.

Wp and Ws are the passband and stopband edge frequencies, normalized from 0 to 1 (where 1 corresponds to pi radians/sample).

For example,

Lowpass:

Wp = .1,

Ws = .2

Highpass:

Wp = .2,

Ws = .1

Bandpass:

Wp = [.2 .7], Ws = [.1 .8]

Bandstop:

Wp = [.1 .8], Ws = [.2 .7]

ELLIPORD also returns Wn, the elliptic natural frequency to use with ELLIP to achieve the specifications.

[N, Wn] = ELLIPORD(Wp, Ws, Rp, Rs, 's') does the computation for an analog filter, in which case Wp and Ws are in radians/second.

NOTE: If Rs is much much greater than Rp, or Wp and Ws are very close, the estimated order can be infinite due to limitations of numerical precision.

G1=0.5;G2=30;wr=1.21;

w1=1; w2=1.21;

[n,wn]=ellipord(w1,w2,G1,G2,’s’);

[numt,dent]=ellip(n,G1,G2,wn,’s’)

9. FREQS Laplace-Transform (s-domain) Frequency Response.

H = FREQS(B,A,W) returns the complex frequency response vector H of the filter B/A:

H

(

s

)

=

B

(

s

)

A

(

s

)

=

b

 

s

nb

1

+ b s

2

ns

2

+

L

+

b

1

   

nb

a

1

s

na

1

+ a

2

s

na

2

+

L

+

a

na

given the numerator and denominator coefficients in vectors B and A.

The frequency response is evaluated at the points specified in vector W (in rad/s). The magnitude and phase can be graphed by calling FREQS(B,A,W) with no output arguments.

[H,W] = FREQS(B,A) automatically picks a set of 200 frequencies W on which the frequency response is computed.

FREQS(B,A,N) picks N frequencies.

num=1; den=[1 3 5 10]

w=linspace(0,4,400);

h=freqs(num,den,w);

mag=20*log10(abs(h));

phase=180/pi*angle(h);

subplot(211)

semilogx(w,mag)

subplot(212)

semilogx(w,phase)

10. FILTER One-dimensional digital filter.

Y = FILTER(B,A,X) filters the data in vector X with the filter described by vectors A and B to create the filtered data Y. The filter is a "Direct Form II Transposed" implementation of the standard difference equation:

A 1 y(n) = b 1 x(n) + b 2 x(n-1) +

+ b nb+1 x(n-nb)- a 2 y(n-1) -

- a na+1 y(n-na)

If a 1 is not equal to 1, FILTER normalizes the filter coefficients by a 1. When x is a matrix, FILTER

operates on the columns of x. When x is an N-D array,FILTER operates along the first non-singleton

dimension, namely dimension 1 for column vectors and non-trivial matrices, and dimension 2 for row vectors.

[Y,Zf] = FILTER(B,A,X,Zi) gives access to initial and final conditions, Zi and Zf, of the delays. Zi is

a vector of length MAX(LENGTH(A),LENGTH(B))-1, or an array of such vectors , one for each column of x.

FILTER(B,A,X,[],DIM) or FILTER(B,A,X,Zi,DIM) operates along the dimension DIM.

n=5; wn=30/50;

[b,a]=butter(n,wn); y=filter(b,a,x); %x is the input data

11. FREQZ Digital filter frequency response.

[H,W] = FREQZ(B,A,N) returns the N-point complex frequency response vector H and the N-point frequency vector W in radians/sample of the filter B/A:

H

(

z

)

=

B

(

z

)

A

(

z

)

=

b

nb +

1

z