49
Page 1 Communications II LABORATORY : Lab1- Signal Statistics, an Introduction to Simulink and FM Introduction: In today's lab we have three parts. Throughout the first part we will develop tools for analyzing, modifying, processing and extracting information from signals mathematically. One of the most basic (and sometimes most useful) methods involves the calculation of signal statistics. Calculating signals statistics provides us a substantial amount of useful information about a signal. These statistics allow us to determine “how much” signal is present (i.e., the signal strength), how long a signal lasts, what values the signal takes on, and so on. We will use signal statistics to develop measures of signal quality (with respect to a reference signal). The second part gives you a quick glance to the fundamentals of Simulink. It talks about the simulation parameters and clarify each parameter. Also it introduces you away to estimate the power spectral density and bandwidth of a given signal. The third part is an application on Simulink. It gives you the ability to simulate an Analog communication system that uses frequency modulation (FM). It discusses the bandwidth and the waveform of the message throughout baseband stage, modulation stage and reconstruction stage. Part I, Signal Statistics and Quality: Application: you can easily perform signal detection (by determining when a signal contains useful information rather than just background noise). “The Question” How can I quantitatively determine a signal’s “quality”? Background 1. Signal Statistics When dealing with a signal, it is often useful to obtain a rough sense of the range of values it takes and of the average size of its values. We do this by computing one or more signal statistics. The following lists a number of common signal statistics. It gives the defining formula for each for both continuous-time and discrete-time signals. Also included is MATLAB code for calculating the statistic for a discrete-time signal. If we wish to compute a statistic for a continuous-time signal when we only have a sampled representation, we can use the discrete-time statistic to approximate the continuous statistic. The formulas needed for this approximation are included here with the label sampled.” (In most cases, this approximation becomes better as the sampling interval T s decreases.) For completeness, signal support and duration are also defined below. 1. Support Interval. A signal’s support interval (also occasionally known as just the (signal’s support or its interval) is the smallest interval that includes all non-zero values of the signal. Continuous-time: t 1 t t 2 Discrete-time: n 1 n n 2 MATLAB: n=n 1 :n 2 for a signal s.

Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

  • Upload
    lyhanh

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 1

Communications II LABORATORY : Lab1- Signal Statistics, an Introduction to Simulink and FM

Introduction:

In today's lab we have three parts. Throughout the first part we will develop tools for analyzing,

modifying, processing and extracting information from signals mathematically. One of the most

basic (and sometimes most useful) methods involves the calculation of signal statistics.

Calculating signals statistics provides us a substantial amount of useful information about a signal.

These statistics allow us to determine “how much” signal is present (i.e., the signal strength), how

long a signal lasts, what values the signal takes on, and so on. We will use signal statistics to

develop measures of signal quality (with respect to a reference signal).

The second part gives you a quick glance to the fundamentals of Simulink. It talks about the

simulation parameters and clarify each parameter. Also it introduces you away to estimate the

power spectral density and bandwidth of a given signal.

The third part is an application on Simulink. It gives you the ability to simulate an Analog

communication system that uses frequency modulation (FM). It discusses the bandwidth and the

waveform of the message throughout baseband stage, modulation stage and reconstruction stage.

Part I, Signal Statistics and Quality:

Application: you can easily perform signal detection (by determining when a signal contains

useful information rather than just background noise).

“The Question” How can I quantitatively determine a signal’s “quality”?

Background

1. Signal Statistics When dealing with a signal, it is often useful to obtain a rough sense of the range of values it takes

and of the average size of its values. We do this by computing one or more signal statistics.

The following lists a number of common signal statistics. It gives the defining formula for each for

both continuous-time and discrete-time signals. Also included is MATLAB code for calculating

the statistic for a discrete-time signal.

If we wish to compute a statistic for a continuous-time signal when we only have a sampled

representation, we can use the discrete-time statistic to approximate the continuous statistic. The

formulas needed for this approximation are included here with the label “sampled.” (In most

cases, this approximation becomes better as the sampling interval Ts decreases.) For completeness,

signal support and duration are also defined below.

1. Support Interval. A signal’s support interval (also occasionally known as just the (signal’s

support or its interval) is the smallest interval that includes all non-zero values of the signal.

Continuous-time: t1 ≤ t ≤ t2

Discrete-time: n1 ≤ n ≤n2

MATLAB: n=n1:n2 for a signal s.

Page 2: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 2

2. Duration. The duration of a signal is simply the length of the support interval.

Continuous-time: t2 - t1

Discrete-time: n2 - n1 + 1

MATLAB: Assumed length(s) for a signal s

Sampled: (t2 - t1) = (n2 - n1 + 1)*Ts

3. Periodicity. The key formulas are included here.

Continuous-time: s(t) =s(t + T )

Discrete-time: s[n] =s[n + N]

Sampled: T ≈ NTs

4. Maximum and Minimum Value. These values are the largest and smallest values that a signal

takes on over some interval defined by n1 and n2. In MATLAB these values are found using the

min and max commands.

MATLAB: Maximum(s) =max(s)

MATLAB: Minimum(s) =min(s)

5. Average Value. The average value, M, is the value around which the signal is “centered” over

some interval

])[())(( Sampled

)()( Matlab

][1

1])[( timeDiscrete

)(1

))(( timeContinuous

2

1

2

1

12

12

nsMtsM

smeansM

nsnn

nsM

dttstt

tsM

n

n

t

t

.

6. Mean-squared value. The mean-squared value (or MSV) of a signal, MS, is defined as the

average squared valued of the signal over an interval. The MSV is also called the average power,

because the squared value of a signal is considered to be the instantaneous power of the signal.

])[())(( Sampled

)2.^()( Matlab

][1

1])[( timeDiscrete

)(1

))(( timeContinuous

2

1

2

1

2

12

2

12

nsMtsMS

smeansMS

nsnn

nsMS

dttstt

tsMS

n

n

t

t

7. Root mean squared value. The root mean squared value (or RMS value) of a signal over some

interval is simply the square root of mean squared value.

])[())((R Sampled

))2.^(()(R Matlab

][1

1])[(R timeDiscrete

)(1

))((R timeContinuous

2

1

2

1

2

12

2

12

nsRMtsMS

smeansqrtsMS

nsnn

nsMS

dttstt

tsMS

n

n

t

t

Page 3: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 3

8. Signal Energy. The energy of a signal, E, indicates the strength of a signal is present over some

interval. Note that energy equals the average power times the length of the interval.

s

n

n

t

t

TnsEts

ssums

nsns

dttsts

])[())((E Sampled

)2.^()(E Matlab

][])[(E timeDiscrete

)())((E timeContinuous

2

1

2

1

2

2

9. Signal Value Distribution. The signal value distribution is a plot indicating the relative

frequency of occurrence of values in a signal. There is no closed-form definition of the signal

value distribution, but it can be approximated using a histogram. A histogram counts the number

of samples that fall within particular ranges, or bins. Note that the y-axis is effectively arbitrary,

and that the coarseness of the approximation is determined by the number of histogram bins that

are used. Figure 1 shows an example of a signal value distribution and the histogram

approximation to that distribution. MATLAB: hist(s,num_bins);

Figure 1 Signal Value Distribution

PrelabQ1: Generate a vector of 2000 random numbers that are normally distributed. Hint: try randn( )

Estimate the signal value distribution (use 250 bins)

2. Measuring signal distortion and error Suppose that we wish to transmit a signal from one location to another. This is a common task in

communication systems. A common problem is that the signal is often modified or distorted in the

communication process. Thus, the received signal is not the same as the transmitted signal.

Typically, we want to reduce the amount of distortion as much as possible. However, this requires

that we have a method of measuring the amount of distortion in a signal. In order to develop such a

measure, we’ll look at a signal plus noise model of signal distortion.

Suppose we are transmitting a signal s[n] over FM radio. Someone tunes in to our radio station and

receives a modified version of our signal, r[n]. We can represent this modification mathematically

as the addition of an error signal, v[n], like this:

][][][ nvnsnr

Assuming that we have both s[n] and r[n], we can easily calculate v[n] as

Page 4: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 4

][][][ nsnrnv

Note that if s[n] and r[n] are identical, v[n] will be zero for all n. This suggests that we can simply

measure the signal strength of v[n] by using one of the energy or power statistics.

Mean squared value is a natural choice because it normalizes the error with respect to the length of

the signal. Sometimes, though, the RMS value is more desirable because it produces error values

that are directly comparable to the values in v[n]. When we measure the MSV of an error signal,

we sometimes call it the mean squared error or MSE. Similarly, the RMS value of an error signal

is often called the root mean squared error or RMSE.

In MATLAB, we will usually want to calculate the MSE or RMSE over the entire length of the

signals that we have. Supposing that we are given a signal s and a modified version s_mod (with

the same size), we can calculate the MSE and RMSE like this:

));2mod).^_(((

);2mod).^_((

ssmeansqrtrmse

ssmeanmse

Notice that we could also subtract s from s_mod, the order doesn’t matter because of the square

operation. Also note that you must include the period before the exponentiation operator in order to

correctly square each sample.

PrelabQ2: A simple signal and its statistics

Use the following MATLAB commands to create a signal: >> n = 1:50;

>> s = sin(2*pi*n/50);

(a) Use stem to plot the signal. Make sure that you include:

The figure itself.

An x-axis label and a y-axis label.

A figure number and a caption that describes the figure.

(b) Calculate the following statistics over the length of the signal (i.e., let n1=1 and n2 =

length(s)), and include your results in your report.

Maximum value

Minimum value

Mean value

Mean squared value

RMS value

Energy

(c) Suppose that s is the result of sampling a continuous-time signal with a sampling

interval Ts = 1=100. Use the discrete-time statistics to estimate the following statistics

for the continuous-time signal s(t) = sin(4πt):

Signal duration

Energy

Average power

RMS Value

Page 5: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 5

Laboratory Assignment

1. Statistics of real-world signals Download the file lab1_data.mat from the W:\lab1utilities\statistics. Place it in the present

working directory or in a directory on the path, and type

>> load lab1_data

This file contains two signals which will be loaded into your workspace. You will use the signal

clarinet in this problem and in Problem 2.

(a) Estimate the “fundamental period” of clarinet.

Include your estimate for the discrete-time signal (in samples).

Include your estimate for the original continuous-time signal (in seconds).

(b) Use the hist command to estimate the signal value distribution of clarinet. Use 50 bins.

Include the figure (with axis labels, code, etc.) in your report.

From the histogram, make an educated guess of the MSV and RMSV. Explain how you

arrived at these guesses.

(c) Calculate the following (discrete-time) statistics over the length of the signal:

Mean value

Energy

Mean squared value

RMS value

2. Looking at and measuring signal distortion In this problem, we’ll measure the amount of distortion introduced to a signal by two “systems.”

Download the two files lab1_sys1.m and lab1_sys2.m. Apply each system to the variable

clarinet using the following commands:

>> sys1_out = lab1_sys1(clarinet);

>> sys2_out = lab1_sys2(clarinet);

(a) (Examine the effects of the systems) Use plot and MATLAB’s zoom capabilities to display roughly

one “period” of:

The input and output of lab1_sys1 on the same figure.

The input and output of lab1_sys2 on the same figure.

(b) (Describe the effects of the systems) What happens to the signal when it is passed through these

two systems? Look at your plots from the previous section and describe the effect of: lab1_sys1.m on clarinet.

lab1_sys2.m on clarinet.

(c) (Measure the distortion) Calculate the RMS error introduced by each system.

RMS error introduced by lab1_sys1.

RMS error introduced by lab1_sys2.

Which system introduces the least error? Is this what you would have expected from your

plots?

Page 6: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 6

Part II, Introduction to Simulink:

In this experiment and others to follow, we will use the Simulink extension to Matlab. Simulink is

an icon-driven dynamic simulation package that allows the user to represent a system or a process

by a block diagram. By the term dynamic systems, we refer to systems whose outputs change over

time. Once the representation is completed, Simulink may be used to digitally simulate the

behavior of the continuous or discrete-time system.

Simulink inputs can be Matlab variables from the workspace, or waveforms or sequences

generated by Simulink itself. These Simulink-generated inputs can represent continuous-time or

discrete-time sources. The behavior of the simulated system can be monitored using Simulink's

version of common lab instruments: scopes, spectrum analyzers and network analyzers. The

outputs of these "devices" are displayed in graph windows. The output of a system can be viewed

using one of the monitoring devices listed above, or it may be saved to a variable created in the

Matlab workspace.

Background: Power Spectral Density (PSD) is the frequency response of a random or periodic signal. It tells us

where the average power is distributed as a function of frequency.

The PSD of a random time signal x(t) can be expressed in one of two ways that are equivalent to

each other:

The PSD is the average of the Fourier transform magnitude squared, over a large time

Interval.

2

2

x )(2

1)(S lim

T

T

tj

T

dtetxT

Ef

The PSD is the Fourier transform of the auto-correlation function.

)()()(

)()(S

*

2

x

txtxER

deRf

x

T

T

tj

x

Getting Started with Simulink In this section, we will learn the basics of Simulink and build a simple system.

Figure 2 Power Spectral Density of sinusoidal signal

In order to familiarize yourself with Simulink, you will first build the system shown in Fig. 2. This

system consists of a function generator that feeds a scope and a Spectrum Analyzer block.

Page 7: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 7

1. Open a window for a new system by using the New option from the File pull-down menu,

and select Model.

2. Drag the Signal Generator and Scope, from the simulink (library) → sources and simulink

(library) → sinks, respectively into the new window you created.

3. Copy the spectrum analyzer block (W:\lab1utilities\spectrum_analyzer) into your working

communication folder. Drag the Spectrum Analyzer block from the File→ open→ (path of

spectrum analyzer block), this block stores up a buffer of the input points and then displays the time domain representation along with the frequency content of the buffer in the graph window using FFT.

4. Now you need to connect these three blocks. Your system should look like Fig. 2.

5. Double click on the Scope block to make the plotting window for the scope appear.

6. Set the simulation parameters by selecting Simulation parameters from the Simulation pull-

down menu. Under the Solver tab, set the Stop time to 50, and the Max step size to 0.02.

Then select OK. This will allow the Power Spectral Density block to make a more accurate

calculation.

7. Start the simulation by using the Start option from the Simulation pull-down menu.

8. A standard Matlab figure window will pop up showing the output of the Spectrum

Analyzer.

9. Change the frequency of the sine wave to π5 rad/sec by double clicking on the Sine

Wave icon and changing the number in the Frequency. Restart the simulation.

10. Observe the change in the waveform and its spectral density. If you want to change the

time scaling in the plot generated by the spectrum analyzer, from the Matlab prompt use

the subplot(2,1,1) and axis( ) commands.

11. To estimate the BW of the input signal, use subplot(2,1,2) and crosshair( )-you can find this

function in W:\Lab1Utilities\crosshair.

12. When you are done, close the system window you created by using the Close option from

the File pull-down menu.

PrelabQ3: Sketch the PSD of sin wave having ωc = π5 rad/sec and compare it with the output

of the simulation result.

A word about the Simulation Parameters Dialog Box:

Simulation Time

You can change the start time and stop time for the simulation by entering new values in the Start

time and Stop time fields. Simulation time and actual clock time are not the same. For example,

running a simulation for 10 seconds usually does not take 10 seconds. The amount of time it takes

to run a simulation depends on many factors, including the model's complexity, the solver's step

sizes, and the computer's speed.

Solvers

Simulation of a Simulink model entails computing its inputs, outputs, and states at intervals from

the simulation start time to the simulation end time. Simulink uses a solver to perform this task. No

one method for solving a model is suitable for all models. Simulink therefore provides an

assortment of solvers, each geared to solving a specific type of model. The Solver pane allows you

to select the solver most suitable for your model

Page 8: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 8

Fixed-step continuous solvers

These solvers compute a model's continuous states at equally spaced time steps from the

simulation start time to the simulation stop time.

Variable-step continuous solvers

These solvers decrease the simulation step size to increase accuracy when a system's continuous

states are changing rapidly and increase the step size to save simulation time when a system's

states are changing slowly.

Step Sizes

For variable-step solvers, you can set the maximum and suggested initial step size parameters.

Maximum step size

The Max step size parameter controls the largest time step the solver can take. The default is

determined from the start and stop times. If the time span of the simulation is very long, the default

step size might be too large for the solver to find the solution.

Important Facts about Simulink:

Many block parameters are tunable. A tunable parameter is a parameter whose value can change

while Simulink is executing a model this is which called Matlab has Tunable Parameters.

Also you should note that the sample time is not a tunable parameter i.e. you cannot change the

Sample Time parameter of a block while a simulation is running. If you want to change a block's

sample time, you must stop and restart the simulation for the change to take effect.

Another important note is that Simulink uses separate windows to display a block library browser,

a block library, a model, and graphical (scope) simulation output. These windows are not

MATLAB figure windows and cannot be manipulated using Handle Graphics® commands i.e. you

can not use the command axis( ) , subplot( ),….etc to modify the simulation output of a simulink

block. Can you explain what we have done in page7 step 10?

Page 9: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 9

Part III, Simulink and Frequency Modulation (FM):

The objective of this section is to increase the students’ familiarity with both simulink and

frequency modulation (FM) signals. Where we will do the following:

Create an FM signal by modulating a message signal onto a carrier.

Examine the spectrum of the modulated carrier.

Background: Angle modulation is a process in which the angle of the modulating sinusoidal carrier wave is

varied according to the baseband signal. In this method of modulation, the amplitude of the carrier

wave is maintained constant. An important feature of angle modulation is that it can provide better

discrimination against noise and interference than amplitude modulation. However, this

improvement in performance is achieved at the expense of increased transmission bandwidth; that

is, angle modulation provides us with a practical means of exchange channel bandwidth for

improved noise performance. Such a trade off is not possible with amplitude modulation,

regardless of its form.

The most commonly used methods to vary the angle of the carrier signal in accordance to the

message are phase modulation (PM) and frequency modulation (FM). In our experiment we will

consider FM. FM is that form of angle modulation in which the instantaneous frequency fi(t) is

varied linearly with the message signal m(t) as shown by: fi(t)=fc+ Kf m(t) , where kf denotes a

scaling factor, limiting the maximum frequency deviation of signal

∆ω= kf )(tf max ))(cos()(0

dmktAtS

t

fc

As you know, from communications I class, the theoretical bandwidth of FM signals is infinity.

Anyway, we can approximate the BW of the FM signal using Carson’s rule, which is defined as

)..(2.. )(tmFM WBfWB

where f is the peak frequency deviation.

In this part you will benefit from the spectrum analyzer block in displaying the frequency contents

of the modulated signal and thus to estimate the signal bandwidth.

PrelabQ4:

a. State in clear points the advantages and disadvantages of using FM.

b. Write the mathematical expressions and plot the waveforms of FM modulated

carriers given that the modulating signal is:

1) m(t)=Sin(ωm* t) 2) Square wave

c. Plot the amplitude spectrum of a tone modulated carrier i.e. m(t)= Sin(ωm* t)

assuming ωm =2π x 7.5 r/s and ωc=2π x75 r/s.

d. Calculate the bandwidth of FM modulated carriers given that the modulating

signal as in part (b), where ωm=2π * 7.5 r/s and square wave period Tc=1/7.5 s

[Hint: assume that the Bandwidth of the square wave is 3 * fc (fc = 1/ Tc)]

Page 10: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 10

Laboratory Assignment:

Design problem: We intend to build a communication system that has the following design specifications

Modulation type: Frequency modulation Modulating signal: sine wave Modulating frequency: 7.5 Hz Amplitude of modulating signal: 2Vpp Carrier frequency: 75 Hz Amplitude of carrier signal: 2Vpp

Building Frequency Modulation (FM) Model 1. Start Simulink by typing simulink in the Matlab workspace.

2. Open a new model window (File → New→ Model).

3. Create the following FM model.

Figure 3 FM communication system

4. Set the parameters of the different blocks as follows:

Signal generator Waveform: Sine Amplitude: 1 Frequency: 2.5 Units: Hertz

Select checkbox (interpret vector parameter as 1-D)

FM modulator passband Carrier frequency: 75 Initial phase:0 Modulation constant: 25

Symbol time: 0.001 Symbol interval: Inf

FM demodulator Passband: Lowpass filter numerator: [ 4.57 9.14 4.57].* 0.01

Lowpass filter denominator: [1 -1.3108 0.4936]

Analog Filter design: Desired method: Butterworth Filter type: Lowpass

Filter order: 5 Passband edge frequency: 350

Spectrum Analyzer Number of sample points: 512 Sample period: 0.001

Plotting period: 10

Simulation parameters

(Simulation → simulation parameters), Select solver tab

a. Start time 0.0 Stop time 10

b. Type: fixed step Ode5 (Dormand-price)

c. Fixed step size:0.001 Mode: Auto

Page 11: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 11

5. Run the simulation and answer the following:

Use the scope to display the input signal and the modulated signal.

From Spectrum Analyzer window, determine the Bandwidth of the modulating signal

(message). Use crosshair( )

Estimate the Bandwidth of the modulated FM signal. Use crosshair( )

What is the purpose of the lowpass filter in our model?

Is the reconstructed signal (the signal at the demodulator output) the same as the input

signal?

Now if we change the input to a square wave, then the frequency of the carrier signal will change

back and forward between two different frequencies. This is a type of digital modulation

techniques called Binary Frequency Shift Keying (BFSK). In this method, the symbol 1 and 0 are

distinguished from each other by the frequency of the carrier (modulated) signal. Here you are

invited to simulate this system and don't worry about the details, later we will study such a system

in depth.

6. Change the input message from a sine wave to a square wave

Display the signal after the modulator stage in time domain.

Estimate the B.W. of the modulated signal. Use crosshair( )

Is the reconstructed signal (the signal at the demodulator output) the same as the input

signal?

Important notes about FM modulator and demodulator blocks:

Typically, an appropriate Carrier frequency value is much higher than the highest frequency of the

input signal. To avoid having to use a high carrier frequency and consequently a high sampling

rate, you can use baseband simulation (FM Modulator Baseband block) instead of passband

simulation. By the Nyquist sampling theorem, the reciprocal of the Sample time parameter must

exceed twice the Carrier frequency parameter.

In the course of demodulating, the block uses a filter whose transfer the lowpass filter numerator

describes function and Lowpass filter denominator parameters, which are listed in order of

descending powers of s.

Page 12: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 12

Lab 2- Sampling, Quantization, and Pulse Code Modulation

(PCM)

Introduction:

Although a significant portion of communication today is in analog form, it is being replaced

rapidly by digital communication. Within the next decade most of communication will become

digital, with analog communication playing a minor role.

Today's lab may be viewed as a transition from analog to digital communications; it will consider

the first important step in any digital communication system, transforming the source information

to a form that is compatible with a digital system. We will treat various aspects of sampling,

quantization (both uniform and nonuniform), and pulse code modulation (PCM). Finally, as an

application, we will build a complete digital system that deals with a speech signal to investigate

the effect of the system parameters on the quality of the reconstructed speech signal.

Prelab

1. How many bits would be required to represent an analog signal with values ranging from (-1)

to 1 Volt if the resulting quantized signal is to have a resolution of 0.125 V? (round to the

nearest bit)

2. Assuming a maximum source coding data rate of 50 kbits/sec, what is the maximum signal

bandwidth we can transmit using PCM with the number of bits found in question 1? What is

the corresponding Nyquist rate?

3. For the results in questions 1 and 2, compute the Signal to Quantization Noise Ratio (SQNR)

of the system assuming the message signal has a peak to average power ratio Pav

V 2maxof 3 dB

and 14 dB.

4. Derive the the SQNR for a sine wave in term of the number of levels.

5. Use the simulink to draw the characteristic of a quantizer having the following I/O relation:

5.075.0

05.025.0

5.0025.0

5.075.0

x

x

x

x

y

6. For the system shown in page 10, calculate theoretically:

a. the first 5 samples b. quantized samples

c. PCM code words d. the decoded quantized samples for the PCM

7. Repeat the above question if the system having a μ-law compandor (compressor & expander)

with μ=255.

Sampling process:

The sampling process is usually described in the time domain. It is an operation that is basic to

digital signal processing and digital communication. Through the use of the sampling process, an

Page 13: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 13

analog signal is converted into corresponding sequence of samples that is usually spaced uniformly

in time i.e. discrete in time. Clearly, for such a procedure to have a practical utility, it is necessary

that we choose the sampling rate properly so that the sequence of samples uniquely defines the

original analog signal. The sampling theorem is the basis for determining the proper sampling rate

for a given band-limited signal. It states that,

A band-limited signal of finite energy, which has no frequency component higher than W hertz, is

completely described by specifying the values of the signal at instants of time separated by 1/2W seconds

(i.e. at a rate of 2W samples per second).

The process of reconstructing a continuous-time signal from its samples is also known as

interpolation. In which we pass the sampled signal through an ideal low-pass filter of bandwidth W

Hz. As you may note, the use of a sampling rate higher than the Nyquist rate has a beneficial effect

of easing the design of the reconstruction filter used to recover the original signal from its sampled

version

Time-Division Multiplexing:

The sampling theorem provides the basis for transmitting the information contained in a band-

limited message signal as a sequence of samples. An important feature of the sampling process is

conservation in time. That is, the transmission of the message samples engages the communication

channel for only a fraction of the sampling interval on a periodic basis, and in this way some of the

time interval between adjacent samples is cleared for use by other independent message source on

a time-shared basis. We thereby obtain a time-division multiplex (TDM) system, which enable the

joint utilization of a common communication channel by allowing all signals to share the

transmission link, with each signal connected to the link for only a short time.

The rate of the commutator (electronic switching circuit) at the transmitter side also obeys the

sampling theorem:

fs=N* 2*W, where N is the number of messages and W= max(Wi) , i=1,2,…N .

It is clear that the use of TDM introduces a bandwidth expansion factor N, because the scheme

must squeeze N samples derived from N independent message sources into a time slot equal to one

sampling interval.

At the receiving end of the system, the received signal is applied to a pulse demodulator which

consists of a decommutator and a LPF. The decommutator is in synchronization with the

commutator in the transmitter.

Quantization:

A continuous time signal, such as voice, has a continuous range of amplitudes and therefore its

samples have a continuous amplitude range i.e. they are only discrete in time not in amplitude. In

other words, within the finite amplitude range of the signal, we find an infinite number of

amplitude levels. It is not necessary in fact to transmit the exact amplitude of the samples. Any

human sense (the ear or the eye), as ultimate receiver, can detect only finite intensity differences.

This means that the original continuous time signal may be approximated by a signal constructed

of discrete amplitudes selected on a minimum error basis from an available set. Clearly, if we

assign the discrete amplitude levels with sufficiently close spacing we may take the approximated

signal practically indistinguishable from the original continuous signal.

Amplitude quantization is defined as the process of transforming the sample amplitude m(nTs) of a

message signal m(t) at time t=nTs into a discrete amplitude v(nTs) taken from a finite set of

possible amplitudes.

The existence of a finite number of discrete amplitude levels is a basic condition of pulse code

modulation. So Quantization is an important stage in forming the PCM signal where the output of

Page 14: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 14

the sampling process is quantized to provide a new representation that is discrete in both time and

amplitude.

Quantization can be of a uniform or nonuniform type. In a uniform quantizer, the representation

levels are uniformly spaced; otherwise, the quantizer is nonuniform. In system that uses uniform

quantizer, the quantization noise is the same for all signal magnitude. Therefore, in uniform

quantization, the SNR is worse at low level signals than for high level signals. In telephone

systems, it was found that for most voice communication channel, very low speech volumes

predominate; 50% of the time, the voltage characterizing detected speech energy is less than 1/4 of

the rms voltage. Large amplitude values are relatively rare; only 15% of the time does the voltage

exceeds the rms value. Also as you may have noticed that the quantization noise depends on the

step size, so a uniform quantizer would be wasteful for speech signal.

Nonuniform quantization, in which the step size increases as the separation from the origin of the input-

output amplitude increases, can provide fine quantization to the weak signals and coarse quantization of the

strong signals. In other words, the weak passages, which need more protection, are favored at the expense

of the loud passages. Thus in the case of nonuniform quantization, quantization noise can be made

proportional to signal size. The effect is to improve the overall SNR by reducing the noise for the

predominant weak signals, at the expense of an increase in noise for the rarely occurring signals.

The use of non-uniform quantizer is equivalent to passing the baseband signal through a compressor and

then applying the compressed signal to a uniform quantizer.

Quantization and Compression Quantization is sometimes used for compression. As an example, suppose we have a digital image

which is represented by 8 different gray levels: [0 31 63 95 159 191 223 255]. To directly store

each of the image values, we need at least 8-bits for each pixel since the values range from 0 to

255. However, since the image only takes on 8 different values, we can assign a different 3-bit

integer (a code) to represent each pixel: [000 001 ... 111]. Then, instead of storing the actual gray

levels, we can store the 3-bit code for each pixel. A look-up table, possibly stored at the beginning

of the ¯le, would be used to decode the image. This lowers the cost of an image considerably: less

hard drive space is needed, and less bandwidth is required to transmit the image (i.e. it downloads

quicker). In practice, there are much more sophisticated methods of quantizing images which rely

on quantization.

Pulse Code Modulation Pulse Code Modulation (hereinafter referred to as PCM) is a sampled modulation similar to Pulse

Amplitude Modulation. Since PCM encodes a message into bits of 1’s and 0’s, it is often referred

to as a source code. PCM does not yield waveforms that vary linearly with the message however.

Nyquist criteria apply to PCM since it is obtained through sampling. That means that the sampling

frequency must be at least twice the highest frequency in the message.

Page 15: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 15

PCM offers advantages over other modulation methods in its resistance to noise and its ability to

be processed digitally. PCM is particularly resistant to noise added once it has been modulated in

the communication channel. PCM can be processed entirely in the digital domain, allowing any

desired signal alterations to be performed that would otherwise be impossible in the analog

domain.

An Analog to Digital or A/D converter is used to convert the continuous message signal into a

series of digital numbers, with each of the numbers representing a level of the quantized message

signal. This stream of digital number is the PCM signal. Once the quantized signal is in the digital

domain, it is easy to perform any signal processing desired by simply performing the appropriate

mathematical operation.

A D/A converter performs an inverse operation to that of the A/D converter, changing digital

numbers to analog voltages. The A/D and D/A converters must match with respect to word size,

sampling rate, and mapping in order for the PCM signal to be properly demodulated.

Page 16: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 16

Laboratory Assignment

1. Image Quantization Download the file 'fountainbw.tif' from the W:\lab1utilities\statistics. Place it in the present

working directory or in a directory on the path. The image 'fountainbw.tif' is an 8-bit grayscale

image. We will investigate what happens when we quantize it to smaller numbers of bits/pixel.

a) Load it into Matlab and display it using the following sequence of commands.

y = imread('fountainbw.tif');

image(y);

colormap(gray(256));

axis('image');

b) The image array will initially be of type uint8, so you will need to convert the image matrix to

type double before performing any computation. Use the command

z=double(y)

c) Uniform quantizer implementation:

There is an easy way to uniformly quantize a signal. Let

where X is the signal to be quantized, and N is the number of quantization levels. To force

the data to have a uniform quantization step of ∆,

Subtract Min(X) from the data and divide the result by ∆.

Round the data to the nearest integer

Multiply the rounded data by ∆ and add Min(X) to convert the data back to its original scale.

d) Write a Matlab function Y = Uquant(X,N) which will uniformly quantize an input array X

(either a vector or a matrix) to N discrete levels.

e) Use this function to quantize the fountain image to 7 b/pel, 6, 5, 4, 3, 2, 1 b/pel, and observe

the output images. Print hard copies of only the 7, 4, 2, and 1 b/pel images, as well as the

original.

INLAB REPORT:

1. Describe the artifacts (errors) that appear in the image as the number of bits is lowered?

2. Note the number of b/pel at which the image quality noticeably deteriorates.

3. Hand in the printouts of the above four quantized images and the original.

4. Compare each of these four quantized images to the original.

Page 17: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 17

Laboratory Assignment

2. Audio Quantization If an audio signal is to be coded, either for compression or for digital transmission, it must undergo

some form of quantization. Most often, a general technique known as vector quantization is

employed for this task, but this technique must be tailored to the specific application so it will not

be addressed here. In this assignment, we will observe the effect of uniformly quantizing the

samples of two audio signals.

a) Download the file 'speech.au' and 'music.au' from the W:\lab1utilities\statistics. Place it in the

present working directory or in a directory on the path.

b) Use your Uquant function to quantize each of these signals to 7, 4, 2 and 1 bits/sample.

c) Listen to the original and quantized signals and answer the following questions:

For each signal, describe the change in quality as the number of b/sample is reduced?

For each signal, is there a point at which the signal quality deteriorates drastically?

At what point (if any) does it become incomprehensible?

Which signal's quality deteriorates faster as the number of levels decreases?

Do you think 4 b/sample is acceptable for telephone systems? ... 2 b/sample?

d) Use subplot to plot in the same figure, the four quantized speech signals over the index range

7201:7400.

e) Generate a similar figure for the music signal, using the same indices. Make sure to use orient

tall before printing these out.

INLAB REPORT:

Hand in answers to the above questions, and the two Matlab figures.

3. Error Analysis As we have clearly observed, quantization produces errors in a signal. The most effective methods

of the analysis of the error signal turn out to be probabilistic. In order to apply these methods,

however, one needs to have a clear understanding of the error signal's statistical properties. For

example, can we assume that the error signal is white noise? Can we assume that it is uncorrelated

with the quantized signal? As you will see in this exercise, both of these are good assumptions if

the quantization intervals are small compared with sample-to-sample variations in the signal.

If the original signal is X, and the quantized signal is Y, the error signal is defined by the

following:

E = Y – X

When the spacing, ∆, between quantization levels is sufficiently small, a common statistical model

for the error is a uniform distribution from -∆/2 to ∆/2 .

a) Compute the error signal for the quantized speech for 7, 4, 2 and 1 b/sample.

b) Use the command hist(E,20) to generate a 20-bin histogram for each of the four error signals.

Use subplot to place the four histograms in the same figure.

INLAB REPORT:

Page 18: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 18

1. Hand in the histogram figure.

2. How does the number of quantization levels seem to affect the shape of the distribution?

3. Explain why the error histograms you obtain might not be uniform?

4. Signal to Noise Ratio One way to measure the quality of a quantized signal is by the Power Signal-to-Noise Ratio

(PSNR). This is defined by the ratio of the power in the quantized speech to power in the noise.

In this expression, the noise is the error signal E. Generally, this means that a higher PSNR implies

a less noisy signal.

From previous labs we know the power of a sampled signal, x(n), is defined by

where L is the length of x(n). Compute the PSNR for the four quantized speech signals from the

previous section.

In evaluating quantization (or compression) algorithms, a graph called a "rate-distortion curve" is

often used. This curve plots signal distortion vs. bit rate. Here, we can measure the distortion by

PSNR1 , and determine the bit rate from the number of quantization levels and sampling rate. For

example, if the sampling rate is 8000 samples/sec, and we are using 7 bits/sample, the bit rate is 56

kilobits/sec (kbps).

Assuming that the speech is sampled at 8kHz:

Plot the rate distortion curve using PSNR

1 as the measure of distortion. Generate this curve by

computing the PSNR for 7, 6, 5,..., 1 bits/sample. Make sure the axes of the graph are in terms of

distortion and bit rate.

INLAB REPORT:

Hand in a list of the 4 PSNR values, and the rate-distortion curve.

Page 19: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 19

Laboratory Assignment

Design problem: We intend to build a complete PCM communication system that has the following design

specifications

Message signal(x(t)): sine wave Frequency of x(t) : 5HZ Sampling frequency: 100 Hz Amplitude of message signal: 2Vpp Number of bits/sample: 2 Quantizer type: Uniform

Building PCM encoder Model a) Copy the file 'PCM.mdl' from the W:\lab1utilities\statistics. Place it in the present working

directory or in a directory on the path.

b) Connect the blocks to get the following PCM model.

c) Set the parameter of each block to meet our design specifications in the above design problem.

d) Visualize the message signal throughout the different stages in the above system.

e) How can we reconstruct the original continuous time signal from the signal at the output of the

quantizer decoder?

f) What is the resulting SQNR of your 4 bit PCM system for the sine signal? How does your

result compare with your theoretical calculations? Explain why you think there are

differences.

g) Change the input of the quantizer into a speech signal which you have used in the previous

laboratory assignment.

h) Listen to the output wave file; do you think 2 b/sample is acceptable for speech signals?

Page 20: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 20

Simulation of μ-law Quantizer

Build a 4-bit non-uniform PCM system using a μ-law compressor and expander. Test your system

using the sine and audio waves from the previous section as inputs. Pick a value of μ which you

think will work best for the audio signal.

a. What value of μ did you choose and why?

b. What is the resulting SQNR for the sine and audio signals? Compare your results to the

previous exercise. Have you gained any performance? For which message signal do you get

the largest performance gain and why?

INLAB REPORT:

1. Include printouts of all SIMULINK block diagrams you designed.

2. Answer all questions and back them up with results, analysis, theory, and any computations.

3. Write a paragraph about questions and confusion you have experienced in this part of the lab.

Page 21: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 21

Lab 3- Detection of Binary Signals in Gaussian Noise

Introduction:

We will investigate matched filters, which play an important role in applications such as digital

communication, radar, sonar, ultrasound imaging, and many others. We will consider the digital

communication application, in which the objective is to transmit binary data (0's and 1's) from one

location to another. Matched filters are defined by their impulse response, so the filter output is

computed by a convolution operation.

We will see how the system performance is affected by type of degradation that occurs in every

real communication system: passage of the data stream is affected additive noise. The lab will

conclude with a design project in which you will diagnose the shortcomings of a given digital

communication system, and then improve the performance by designing proper matched filters.

Background:

Figure 3.1 Block diagram of basic elements of a digital communication system

Noise in Radio Communications Systems

The task of the demodulator or detector is to retrieve the bit stream from the received waveform, as

nearly error free as possible, notwithstanding the distortion to which the signal may have been

subjected. There are two primary causes for signal distortion. The first is filtering effects of the

transmitter, channel, and receiver distortion. A non ideal system transfer function causes symbol

"smearing", which can produce intersymbol interference.

The second cause for signal distortion is the noise that is produced by a variety of sources, such as

galaxy noise, terrestrial noise, amplifier noise, and unwanted signals from other sources. An

unavoidable cause of noise is the thermal motion of electrons in a conducting media. This motion

produces thermal noise in amplifiers and circuits which corrupts the signal in additive fashion; that

is, the received signal, r(t) is the sum of the transmitted signal, s(t) and the thermal noise, n(t). The

statistics of thermal noise have been developed using quantum mechanics and are well known.

The primary statistical characteristic of thermal noise is that the noise amplitudes are distributed

according to a normal or Gaussian distribution.

The primary spectral characteristic of thermal noise is that its two-sided power spectral density,

G(f)=N0/2, is flat for all frequencies of interest for radio communication systems. In other words,

Information Source &

Input transducer

Sampler & Quantizer

Source encoder

Digital modulation

Channel

Digital demodulation

Source decoder

Output transducer

m(t)

11010…

011001…

Page 22: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 22

thermal noise, on the average, has just as much power per hertz in low-frequency fluctuations as I

high-frequency fluctuations- up to a frequency of about 1210 hertz. The adjective "white" is used in

the sense that white light contains equal amount of all frequencies within the visible light band of

electromagnetic radiation.

Maximum Likehood Receiver Structure:

In a basic digital communication system, the optimum receiver for an AWGN channel is composed

of two parts; one is either a signal correlator or a matched filter and the other is a detector. This lab

considers a matched filter. The matched filter is assumed to be matched to the transmitted signal in

this lab.

Correlator

The signal correlator cross correlates the received signal with all possible transmitted signals. Let

us assume that a M-ary scheme is used in a baseband digital communication system. The outputs

of the signal correlator, 1,, Mo rr in Figure 3.2, are as follows

t

dsrtr0

00 )()()(

.

.

.

t

MM dsrtr0

11 )()()( .

where )(tr is the received signal at the receiver and the possible transmitted signals are

TtMitsi 0,1,..,0),(

After we sample the correlator outputs at time t=T, send them directly to the detector. For example,

let us consider that there are two possible transmitted signals in an AWGN channel. Two possible

transmitted signals are assumed to be orthogonal each other. )(tso is assumed to be transmitted

through an AWGN channel. The signal correlator computes two output signals as follows

)()()( tntstr o

o

T

o

T

oo nEdnsdsr 00

2)()()(

1

00

11 )()()()( ndnsdssr

T

o

T

o

where )(tr is the received signal at the receiver. or and 1r are the correlator outputs. on and 1n are

the noise components at the output of the correlator. E is the energy of the signal, )(tso .

Page 23: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 23

)(tr

)(0 ts

)(1 tsM

.

.

.

t

dt0

t

dt0

Detector

t=T

t=T

or

1Mr

Fig 3.2 Signal correlator ; cross correlating the received signal with M transmitted

signals

Matched Filter

The matched filter provides a method similar to the signal correlator to demodulate the received

signal )(tr . When a M-ary scheme is assumed to be used in a baseband digital communication

system, the block diagram of matched filter is shown in Figure 3.3. The impulse response of the

filter matched to the transmitted signal )(ts is represented by

TttTsth 0),()(

When we assume the signal )(ts is transmitted, the output of the matched filter is as follows

t

dtTssty0

)()()(

If we sample this output at t=T, it is given by

EdsTy

T

0

2 )()(

where E is the energy of the signal )(ts .

Thus, the output of the matched filter sampled at t=T is equal to the output of the signal correlator.

Figure 3.3 Matched Filter ; matched to the possible M received signals.

.

.

.

)(0 tTs

)(1 tTsM

)(tr

Detector

t=T

t=T

or

1Mr

Page 24: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 24

Simulation Procedure:

The simulation model for the system to be simulated is illustrated in Fig-3.4

Data Generation:

The first step is to simulate the digital source. The source produces digital messages that are

discrete in time, have either 0 or 1 as one sample value and have a finite number of possible

outputs. The messages are called a bit sequence having a sequence with either 0 or 1 value.

In the following code we will generate data consisting of a 1-by-N element in data consists of

either 0 or 1.

Txdata = rand(1,10)>0.5

Encoder

This block converts random input bits into symbols that are suitable for the type of modulation to

be used.

UpSampler and Transmit Filter.

This block converts the input binary symbols into a baseband waveform to be transmitted over the

channel. The shape of the filter will determine the shape of symbol that represents the binary data.

We will convolve the matching filter with the impulse train to get the data shaped; take a look to

the figure below:

Figure 3.5 Convolution with impulse train

Fig 3.4 Simulation Diagram model

Page 25: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 25

We need to reshape the encoded data into an impulse train; this can be done with the operation

called oversampling.

Look to the following examples:

X=[1 2 3 4 5 6] % length =6

2 (X)= [1 0 2 0 3 0 4 0 5 0 6 0] %length = 2*6=12 and inserts 2-1 =1 zeros

3 (X)= [1 0 0 2 0 0 3 0 0 4 0 0 5 0 0 6 0 0] %length=3*6=18 , inserts 3-1=2 zeros

In Matlab, to oversample the signal x by fs, we may use the following code:

Oversamp=zeros(1,fs*length(x))

Oversamp(1:fs:end)=x

Radio Communication Channel- AWGN

If we construct a mathematical model for the signal at the input of the receiver, the channel is

assumed to corrupt the signal by addition of noise.

r(t)=s(t)+n(t)

where s(t) is the transmitted signal, r(t) is the received signal and n(t) is a sample function of

AWGN process with probability density function (pdf) and power spectral density as follows:

where No is a constant and often called the noise power density. To simulate in Matlab, we simply

use the built-in function randn, which generates random numbers and matrices whose elements are

normally distributed with mean 0 and variance 1. Therefore, if we add AWGN noise with power 1

to the digital modulation signal (Txdata)

data_ch=Txdata+randn(1,length(Txdata))

However, in the simulation, we sometimes calculate the BER, performance by varying the noise

power, where we define the noise power as a variable, npower. Since data_ch is a voltage, not

power, we must change the notation npower from power to voltage. We define a variable attn as

the toot of npower as:

Attn = npower

And thus the new Gaussian noise will be generated as

Noise= Attn* randn(1,N)

Receive Filter and Sampler.

This block converts the received baseband waveform to a symbol stream, which can be used a

decision variable for decoding the received bits. In the first case, the receive filter coefficients are

those of an ideal integrator (i.e, same as the transmit filter coefficients). This block also samples

the received waveform. The sampling point is at t = nTb.

HzWNof /5.0)(

Page 26: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 26

The sampled output is then compared with a predetermined threshold to decide and thus guess the

input data stream.

Bit Error Rate:

We analyze the bit rate to evaluate the system performance. To calculate the number of errors, we

subtract the transmitted signal from the received data (after making a decision). If no error exists,

you obtain a zero vector with the length of data. Otherwise, you obtain a nonzero vector in which

"-1" or "1" data occurs at the error positions. The following code computes the number of errors

occurred.

Subdata=rxdata-txdata

NoE=sum(abs(Subdata))

Page 27: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 27

Laboratory assignment:

Write a simulation program to determine the error probability for a binary antipodal signaling

system using the following signaling pulse shape, assuming a signaling rate of one bit per second

(i.e. T = 1):

TtTtTEts 0,)/sin(/2)(

where E is the signal energy and 1=T is the bit-rate. For the purposes of simulation, assume (with

no loss of generality) a normalized signaling rate of 1 signal/second (T=1), and a sampling rate (for

programming purposes) of 20 samples/second (i.e., the transmitted pulse is represented by 20

uniformly spaced samples in the interval from 0 to 1.)

Plot the probability of error as a function of the SNR in the range from 0 to 8 dB in steps of 1 dB

under perfect time synchronization at the output of the matched filter. Then, modify your

simulation program to obtain the performance of the same system when there is a synchronization

error of 15% and 30%. Plot all three curves (0%, 15% and 230% synchronization error) in the

same graph. Include in the same graph a fourth plot for the analytical probability of error under

perfect synchronization. Present your results in the form of a short report and attach your Matlab

program in the and in an appendix. Include comments in your Matlab program.

Change the signaling shape into s(t)=1 for 0 ≤ t ≤T and answer the requirements above.

Hints:

1. A "matched filter" implementation may be simpler (use the filter command of Matlab).

2. To vary the SNR, it is best to fix the signal energy E to 1 and then vary the variance of the

additive noise. You can do this by generating unit-variance Gaussian variables and multiplying

them by the appropriate standard deviation. Note that the SNR is defined as:

22

ESNR

where E is the signal energy (assumed to be 1) and 2 is the variance of the additive noise.

3. You should note that the performance of the system depends strictly on Eb/N0 ratio so changing

the shape of signaling, with the same signal energy, does not change

Page 28: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 28

Real Time Implementation of the Shaping and Matched

Filter Using TIC6000 DSK

Objective:

In this Lab we will use the TIC600 DSK to shape a binary stream of data into a binary PSK with a

sine shape.

Experimental Procedure:

The first step is to find a suitable sampling frequency to represent the shaping filter with a finite

number of coefficients. Thus the first requirement is to estimate the BW of the continuous time

shaping filter.

TtTtTEth 0,)/.sin(/2)(

As the filter is finite in the time domain, theoretically the bandwidth is infinite. But due to practical

issues, we can approximate the BW as the band that contains the majority of the power of the

filter.

To estimate the bandwidth, we should look to the filter in the frequency domain. to find the Fourier

transform we may consider the filter as a product of a sine wave with a period 2*T and a rect

signal with a duration of 2*T. Approximately the B.W will be 3/T. (In your lab report, prove it).

As the sampling frequency of our DSK is constant and has a value of 8 KHz, we should have a

filter with a maximum BW of 4 KHz => T= ¾ msec => the maximum bit rate is 4/3 Kbit/sec using

our DSK.

To be in the safe side, take T=1/500 sec.

After determining the bite time (T), and knowing the sampling frequency fs=8 KHz (the same as

the DSK), it is easy know to find the coefficient of shaping filter using Matlab.

Write a code in Matlab to generate the coefficients of the shaping filter.

Use FIR_cof_gen , which we used in the DSP Lab, to write the coefficients in a file named

Shaping.coff. Keep in mind that the function FIR_cof_gen scales the coefficient such that

it prevents overriding at the DSP processor which is not the case in this application. So

modify the function such that it doesn’t scale the coefficients.

Using CCS write an Interrupt driven C code that do the following:

Store a stream of binary data (0’s and 1’s) in a matrix named data.

Include the file that contains the coefficients of the shaping filter

Read the stored binary data number by number and then shape each number with

the appreciate shape TtTt 0,)/.sin(

Connect the oscilloscope to the output of the D/A and investigate the output.

Try to implement the Matched filter in the same manner as above, but you should pay a

special attention to a suitable synchronization approach.

Page 29: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 29

Lab 4 - Performance of M-ary PAM and M-ary PSK

Modulation schemes

Objective In this part, our objective is to study digital modulation schemes in detail. We will consider different methods of digital modulations: a binary pulse amplitude modulation (PAM), a M-ary PAM, a binary phase shift keying (PSK), and a M-ary PSK.

PULSE AMLITUDE MODULATION (PAM) In a pulse amplitude modulation (PAM), the message bit sequences are modulated with carrier

signals having different amplitudes. When we try to transmit symbols having just two different

amplitude levels, it is called a binary PAM. When we transmit symbols having M different

amplitude levels, it is called a M-ary PAM.

BINARY PAM (PULSE AMLITUDE MODULATION) When we consider a binary PAM, we transmit symbols having two different amplitude levels. In a baseband binary PAM case, the symbols are represented as follows

)()(),()( 21 tgtstgts

where )(tg is a pulse shaping function that could be a rectangular or a raised cosine etc.

If )(tg is a rectangular;

In a binary PAM, each symbol is used to transmit 1 bit. If the symbol duration is T, the transmission rate is equal to 1/T bits/sec.

M-ary PAM (PULSE AMLITUDE MODULATION) When we consider a baseband M-ary PAM, M symbols that we want to transmit can be represented as follows

MmtgAts mm ,..,2,1),()(

where dMmAm )12( , 2d is the distance between adjacent symbol amplitudes, and )(tg is the pulse shaping function that can be a rectangular pulse or a raised cosine and so on.

Assumed that M is the number of different symbols that we can transmit, mA in the above equation may have the values as follows

)(1 ts t

t

)(2 ts

-A

A

Page 30: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 30

*

*

*

-(M-1)d

-(M-3)d

(M-1)d

dMA

dMA

dMA

dMA

M )1(

...

)5(

)3(

)1(

3

2

1

It has the constellation points as below

Figure 4.1.1 Constellation of a M-ary PAM in a signal space

Simply, when we consider the carrier modulated PAM, the modulated signal may be represented as follows

TttftgA

tfjtgAts

cm

cmm

0),2cos()(

)}2exp()(Re{)(

where T is a symbol duration.

When we assume that symbols having M different amplitude levels are transmitted, M is equal to k2 . It

means that each symbol is used to transmit k bits. If the symbol duration is T, the transmission rate is equal to k/T bits/sec.

PHASE SHIFT KEYING (PSK)

In a phase shift keying (PSK), the message bit sequences are modulated with carrier signals

having different phases. When we try to transmit symbols having just two different phases, it is

called a binary PSK. When we transmit symbols having M different phases, it is called a M-ary

PSK.

BINARY PSK (PHASE SHIFT KEYING) When we consider a binary PSK, we transmit symbols having two different phases. In carrier modulated systems,

)2exp()/)1(2exp()(Re)( tfjMmjtgts cm

M

mtftg c

)1(22cos)(

.

where Ttm 0,2,1

.

The message information is embedded in the phase of the carrier signal, M

mm

)1(2

and can be represented as follows

tfM

mtgtf

M

mtgts ccm

2sin

)1(2sin)(2cos

)1(2cos)()(

where m=1,2.

Page 31: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 31

On the right side of the above equation, the first term is an inphase component and the second term is

a quadrature component of the low-pass equivalent of )(tsm . The basis functions of this are given by

tftgtf

tftgtf

c

g

c

g

2sin)(2

)(

2cos)(2

)(

2

1

.

M

m

M

ms

gg

m

)1(2sin

2

)1(2cos

2

.

In a binary PSK, M is equal to 2. Thus, the possible carrier phases are 0 and . A binary PSK is equivalent to a binary PAM.

M-ary PSK (PHASE SHIFT KEYING)

When we consider a M-ary PSK, we transmit symbols having M different phases. In carrier modulated systems,

)2exp()/)1(2exp()(Re)( tfjMmjtgts cm

M

mtftg c

)1(22cos)(

.

where TtMm 0,,..,1

.

The message information is embedded in the phase of the carrier signal, M

mm

)1(2

and can be represented as follows

tfM

mtgtf

M

mtgts ccm

2sin

)1(2sin)(2cos

)1(2cos)()(

where m=1,…,M. On the right side of the above equation, the first term is an inphase component and the second term is

a quadrature component of the low-pass equivalent of )(tsm . The basis functions of this are given by

tftgtf

tftgtf

c

g

c

g

2sin)(2

)(

2cos)(2

)(

2

1

.

M

m

M

ms

gg

m

)1(2sin

2

)1(2cos

2

.

Page 32: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 32

2/g

2/g

2/g

When we assume that M is equal to 4, the possible carrier phases are 2/3,,2/,0 .

In 8 PSK, the possible carrier phases are 4/7,...,2/,4/,0 . The following figures show a signal space diagram for each M-ary PSK.

(a) M = 2 (b) M = 4

(c) M = 8 Figure 4.2.1 Constellations of several M-ary PSK in a signal space; (a) a binary PSK, (b) 4 PSK, and (c) 8 PSK

The minimum distance between adjacent constellation points is

))/2cos(1(min Md g

e .

OPTIMUM RECEIVER THROUGH AWGN CHANNEL

In a basic digital communication system, the optimum receiver for an AWGN channel is composed of two parts; one is either a signal correlator or a matched filter and the other is a detector. We will consider a signal correlator and a matched filter in the following two sections. A maximum likelihood decoding algorithm will be explained in the third section and the performance for different modulation schemes will be evaluated with regard to the averaged probability of error in the last section.

PERFORMANCE FOR AWGN CHANNEL

The probability of error can be a good measure for the performance of the modulation scheme for AWGN channel. Monte Carlo simulation is used to estimate and plot the probabilities of either bit or symbol error for the performance of a digital communication system.

Performance of a quadrature PSK

Let us generate the message bit sequences having a length of 10000 digit. A quadrature PSK digital communication system is assumed in an AWGN channel. Use Monte Carlo simulation to estimate and plot the performance of a quadrature PSK communication system reliably.

Page 33: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 33

a) Plot the bit error probability performance, theoretical and simulated, versus the SNR per bit (0 ~ 10 dB). What is the bit error probability at 5dB? b) Plot the symbol error probability performance, theoretical and simulated, versus the SNR per bit (0 ~ 10 dB). What is the symbol error probability at 5dB?

c) Plot the power spectral density for the PSK signal.

Performance of a 8-PSK digital Let us generate the message bit sequences having a length of 10000 digit. An 8-PSK digital communication system is assumed in an AWGN channel. Use Monte Carlo simulation to estimate and plot the performance of an 8-PSK communication system reliably.

a) Plot the bit error probability performance, theoretical and simulated, versus the SNR per bit (0 ~ 12 dB). What is the bit error probability at 5dB and 12dB? b) Plot the symbol error probability performance, theoretical and simulated, versus the SNR per bit (0 ~ 12 dB). What is the symbol error probability at 5dB and 12dB?

c) Plot the power spectral density for the PSK signal.

Performance of a 4-PAM Let us generate the message bit sequences having a length of 10000 digits. A 4-PAM digital communication system is assumed in an AWGN channel. Use Monte Carlo simulation to estimate and plot the performance of a 4-PAM communication system reliably.

a) Plot the bit error probability performance, theoretical and simulated, versus the SNR per bit (0 ~ 12 dB). What is the bit error probability at 5dB? b) Plot the symbol error probability performance, theoretical and simulated, versus the SNR per bit (0 ~ 12 dB). What is the symbol error probability at 5dB?

c) Plot the power spectral density for the PAM signal.

Performance of a 8-PAM Let us generate the message bit sequences having a length of 10000 digits. An 8-PAM digital communication system is assumed in an AWGN channel. Use Monte Carlo simulation to estimate and plot the performance of an 8-PAM communication system reliably.

a) Plot the bit error probability performance, theoretical and simulated, versus the SNR per bit (0 ~ 12 dB). What is the bit error probability at 12dB? b) Plot the symbol error probability performance, theoretical and simulated, versus the SNR per bit (0~12 dB).What is the symbol error probability at 12dB?

c) Plot the power spectral density for the PAM signal.

Page 34: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 34

Lab 5- Studying the Performance of Digital Communication

systems Using Simulink

Objective:

In this Lab we will introduce the simulink as powerful tool to simulating the performance of digital

modulation systems with time. Also we will take an easy example to study 16-Ary PSK using the

communication toolbox functions.

Part One: Passband Simulation

This section introduces a passband simulation model that shows the error rate of QPSK modulation

over an AWGN channel with a varying noise level.

What Is the Communications Blockset?

The Communications Blockset is a collection of Simulink® blocks for designing and simulating

communication systems. With the Communications Blockset, you can design models in the form

of block diagrams, using simple click-and-drag mouse operations. You can run simulations on a

model at the push of a button, and change parameters while the simulation is running. The

Communications Blockset contains ready-to-use blocks to model various processes within

communication systems, including Signal generation Source coding Error-correction Interleaving

Modulation/demodulation Transmission along a channel Synchronization In addition, you can

create specialized blocks, to implement your own algorithms.

All the power of MATLAB® is available to you when you use the Communications Blockset. You

can run simulations from the command line and invoke MATLAB expressions and M-files.

Speed of Baseband versus Passband Models

The passband and baseband models produce error rates that differ from each other by less than 1%.

However, the passband model takes a significantly longer time to process the same amount of data.

Although the actual speed depends on your system, the relative times in the tables below can serve

as a guide.

Notice these general trends:

Baseband simulation is considerably faster than passband simulation. The difference in speed

is especially dramatic when the carrier frequency in the passband simulation is high.

Baseband simulation using large frames is faster than baseband simulation that does not use

frames.

Page 35: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 35

Laboratory Assignment:

We intend to build a digital communication system that has the following design specifications

Modulation type: Passband PSK Carrier frequency: 320000Hz

Bit rate: 128K bits/sec Symbol rate: 32K symbols/sec.

Channel noise: AWGN

Shaping filter: rectangle, and take128 samples to represent it.

Delays in Digital Modulation

Digital modulation and demodulation blocks sometimes incur delays between their inputs and

outputs, depending on their configuration and on properties of their signals. The following table

lists sources of delay and the situations in which they occur.

As a result of delays, data that enters a modulation or demodulation block at time T appears in the

output at time T+delay. In particular, if your simulation computes error statistics or compares

transmitted with received data, then it must take the delay into account when performing such

computations or comparisons.

In constructing this model, to set the parameters for the Error Rate Calculation block and Delay

block correctly, you need to know the delay between the transmitted and received signals. You can

sometimes determine this delay from the parameters of the blocks between the transmitted and

received signals. But if you are unable to determine the delay in this way, you can do so with the

xcorr function, from the Signal Processing Toolbox, which finds the cross correlation between the

signal and shifts of its delayed version. To use the xcorr function, you must modify the model

slightly as follows:

Set the Es/No parameter of the AWGN Channel block to 100. This essentially removes all

noise from the model.

Drag a Signal To Workspace block, from the DSP Sinks library, into the model window.

Connect the line leading out of the random Integer Generator block to the Signal To

Workspace block.

Double-click the Signal To Workspace block to open its mask, and change the Variable

name parameter to Tx.

Drag another Signal To Workspace block, from the DSP Sinks library, into the model

window and connect it to the line leading out of the M-PSK Demodulator Passband block.

Page 36: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 36

Double-click the second Signal To Workspace block into the model window and change

the Variable name parameter to Rx.

Pull down the Simulation menu and select Simulation parameters. Set Stop time to 0.1.

Determining the Delay in the PSK Model

Running the model sends the transmitted and received signals to the workspace as vectors called

Tx and Rx, respectively. To find the delay between Tx and Rx, type the following commands at

the MATLAB prompt.

[m,index]=max(xcorr(Rx,Tx));

L=length(Tx);

delay=index-L

To check the model we will run the model at no noise or let us say the ES/N0 is 100 dB. See the

error vector.

Set the parameters of the error rate calculator as follow:

Receive delay: the value found above

Computational delay: 0.

Target number of errors: 100.

Maximum number of symbols: 10000.

Check the error vector ErrorVec at the workspace and you will find it of length 3; the first column

is the probability of error, the second is the total number of errors found, and the third is the total

number of data compared. What values will this vector have?

Generating Error Curves

To plot error rates as a function of noise level using the simulation, execute the following code in

MATLAB. The plot includes both the theoretical error rates and the error rates from running the

simulation.

Change the value of Es/N0 at AWGN block to a variable called noise.

We will link with the Simulink through the workspace, so our script will modify the value of

the variable noise which will subsequently change the Es/No in our model.

db=0:8; %Eb/N0, Bit energy in dB.

dBs=db+10*log10(2) % convert to symbol energy Es=log2(M)*Eb, take the logarithm…in dB

for i=1:length(db)

noise=dBs(i); % as we need to vary Es/N0 in our model not Eb/N0

sim('model name');

pe(i)=ErrorVec(1);

end

semilogy(db,pe) % plot the probability versus the Ebit/N0 . % Computing theoretical values.

linEbNoVec = 10 .^ (0.1 .* EbNoVec);

temp = 0.5.*erfc((sqrt(2.*linEbNoVec))./sqrt(2));

ser = temp.*(2 - temp); % Computes the theoretical symbol error

hold on;

semilogy(db,ser,'*') %plot the probability versus the Ebit/N0 .

Page 37: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 37

Using Communication toolbox

Simple Digital Modulation Example This example illustrates the basic format of the baseband

modulation and demodulation commands, dmodce and ddemodce. Although the example uses the

PSK method, most elements of this example apply to digital modulation techniques other than

PSK. The example generates a random digital signal, modulates it, and adds noise. Then it creates

a scatter plot, demodulates the noisy signal, and computes the symbol error rate. The ddemodce

function demodulates the analog signal y and then demaps to produce the digital signal z. Notice

that the scatter plot does not look exactly like a signal constellation. Whereas the signal

constellation would have 16 precisely located points, the noise causes the scatter plot to have a

small cluster of points approximately where each constellation point would be. However, the noise

is sufficiently small that the signal can be recovered perfectly. Note Because some options vary

by method, you should check the reference pages before adapting the code here for other uses.

Below are the code and the scatter plot. M = 16; % Use 16-ary modulation.

Fd = 1; % Assume the original message is sampled % at a rate of 1 sample per second.

Fs = 3; % The modulated signal will be sampled % at a rate of 3 samples per second.

% Use M-ary PSK modulation to produce y. x = randint(100,1,M); % Random digital message

y = dmodce(x,Fd,Fs,'psk',M); % Add some Gaussian noise.

% Create scatter plot from noisy data.

ynoisy = y + .04*randn(300,1) + .04*j*randn(300,1);

scatterplot(ynoisy,1,0,'b.'); % Demodulate y to recover the message.

z = ddemodce(ynoisy,Fd,Fs,'psk',M);

s = symerr(x,z) % Check symbol error rate.

Page 38: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 38

Lab 6- INTRODUCTION TO ERROR-CONTROL CODING

Introduction:

In digital electronic systems, information is carried by signals with discrete amplitudes so that the

individual message bits can be more easily distinguished from one another. But when this digital

information needs to be stored or transmitted over long distances or at very high speeds, noise

becomes an issue. Sources of such unwanted noise include the thermal motion of electrons, damage

to the storage media, or coupling from other energy sources.

In communications systems, one way to decrease the probability of bit errors is to increase the

power of the transmitted signal until it is much higher than the noise. But the amount by which the

signal power can be increased may be limited by the rating of the electronic circuits in the

transmitter and even at the receiving end. This power level may also be regulated, as in the case of

radio signals whose levels are specified by the Federal Communications Commission (FCC) in the

United States.

So clearly we need some other means of controlling the probability of error. Forward error

correction, or channel coding, provides this added dimension. By adding redundant symbols to the

transmitted or stored digital information, we can achieve not only a means of error detection, but

error correction as well.

In this lab, we will utilize one such error control code, known as the (7,4) Hamming block code.

(7,4) means that 4 message bits, represented by the vector m, are converted into a 7-bit code,

represented by the vector x, according to the following table:

This coding process can be conveniently represented in matrix notation (even though alternative

methods are often used in physical electronic implementations):

x = m G (modulo 2)

Page 39: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 39

Where G is the "generator matrix" given by:

(the G, H and E matrices used here are given by Simon Haykin, Digital Communications , Wiley,

1988, pp. 378f). After the message bits pass through a noisy medium that introduces unknown

errors, we can model the received vector y as follows:

y = x + e (modulo 2)

In modulo 2 addition we have 0+0 = 1+1 = 0; 0+1 = 1+0 = 1. Therefore we imagine the error

vector e as a binary vector; where a component of e is 1, the received y vector differs from the

originating x vector.

The receiver then needs to decode the data in an attempt to recover the original message bits. This

produces a "syndrome", s, which determines what the error vector was (if no errors or only a single

bit error has occurred). This is again conveniently represented in matrix notation, though physical

electronics may implement it differently:

s = y HT (modulo 2)

Where HT is the transpose of the "parity-check" matrix, H, given by:

The 3-bit syndrome uniquely determines what the error pattern was, for single bit errors. So since

we know what the error was, we can correct it and decrease the probability of a received bit error

for the system! The following table defines the syndrome to error pattern relationship:

Page 40: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 40

But if the syndrome is perceived as a binary number, it can be converted to decimal and used as an

index into the following error-pattern look-up matrix. The decimal value of the syndrome now

points to the row of E that contains the corresponding error pattern.

The (7,4) Hamming code is such that, when there is a single error in y, the row of E chosen with

the syndrome matches the e used above to model the relationship between x and y. Therefore,

given y, the decoding procedure is

y(corrected) = y + e (modulo 2) = x + e + e (modulo 2) = x

since addition modulo 2 of any binary vector to itself results in a vector of zeroes.

Page 41: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 41

IN Lab Procedure:

In this experiment, we will be using Matlab to simulate the following system:

This picture applies to digital communication systems, like computer modems.

Draw a similar block diagram for a CD player. What are the sources of noise in such a

system?

We have made available an m-file "coder.m" that is a skeleton version of the m-file you are to

write. The crucial statements, which you must fill in, are missing. The matrices G, H, and E as

defined above are set up for you in the leading statements. In the first simulation, you are to

proceed as follows in Matlab:

diary filename1

Avect=2;

bits=10000;

coder(Avect,bits)

This performs a simulation for a message stream of length bits, i.e. bits/4 messages, each 4 bits in

length. Avect is a vector of signal amplitudes A; in the first simulation we use only the single

value A = 2. Execution should take less than a minute.

In the final simulation we use

diary filename2

Avect=[0.5,1/sqrt(2),1,sqrt(2),2,2*sqrt(2),4];

bits=200000;

coder(Avect,bits)

which will take several minutes. Therefore in order to avoid wasting a lot of time you should be

sure the first simulation is right by showing the results to us before proceeding.

In the procedure outlined below, you are asked in several places to record 20 values. We

recommend that this be done only in the first simulation with bits=10000. What is asked can be

done e.g. with a simple Matlab statement such as

SRC_UNCODED(1:20)

Page 42: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 42

Step 1 : Generating the Uncoded Source Sequence

The Matlab "randn" function generates random numbers with zero mean and a Gaussian

distribution of unit variance. It can be used in conjunction with the "sign" function (which returns

+/-1 if a number is greater than or less than zero, respectively) to generate the sequence of '1's and

'0's that will make up the SRC_UNCODED row vector. Think of this sequence as a bit stream of

sampled music that will be recorded on a CD or sent to another computer via a modem.

=> Create the SRC_UNCODED row vector of length bits.

Verify your work by recording the first 20 bits of SRC_UNCODED.

Step 2 : Generating the Coded Source Sequence

Now we'll generate the coded sequence by applying the (7,4) Hamming code to the

SRC_UNCODED sequence.

We need to break up the SRC_UNCODED bit stream into 4-bit sequences that will be converted

into 7-bit sequences by the coding algorithm. This can be accomplished by a Matlab loop that

multiplies 4 bits of SRC_UNCODED (m) by the generator matrix, G, and concatenates or adds in

the results (x) to form SRC_CODED.

Verify your work by recording the coded versions of the first 20 bits of SRC_UNCODED

that you wrote down in Step 1 (this will be more than 20 bits). Do these agree with the code

table?

One might assume that, since we are encoding 4-bit sequences (the blocks, m), our original

data stream simulates a system that produces only nibbles (1 nibble = half of a byte) of data.

Would it make any difference if the data stream was originally created as bytes of

information? as 2-byte words? Explain

Step 3 : Modulation

At this point, we are ready to transmit the binary data (such as bytes on a computer) over a

physical medium (such as an ethernet cable). A discrete-time sequence must be converted into a

continuous-time signal for transmission. This is known as modulation. We will simulate a

modulation scheme known as BPSK, binary phase-shift keying. The phase-shift here is obviously

180° (although BPSK usually refers to shifting the phase of sinusoidal carrier, not DC pulses as we

are using here).

Page 43: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 43

In order to accomplish this in our simulation, we must convert our SRC sequences of '1's and '0's

into a sequence of '+1' and '-1', and then multiply by A.

=> Generate the TX_UNCODED and TX_CODED signals.

Verify your work by recording the modulated levels of the first 20 pulses in the

TX_UNCODED sequence.

Step 4 : Introducing Noise

At this point, our data has entered the physical medium and will be modified by additive white

Gaussian noise. Again, the Matlab "randn" function will be employed. As mentioned in Step 1,

the random numbers produced by this function have a "variance" of one. This tells us how much

the random numbers vary about the mean. Thus in the zero mean case, as we have here, the

variance is the mean square value of the noise.

=> Generate a noise sequence equal in length to the TX_UNCODED sequence. Plot a histogram

of the noise samples (Matlab "hist" function).

A histogram shows us how many samples occurred over a particular range of values.

Print out the histogram for your lab report. What percentage of the noise samples had

values between -1 and +1?

Also verify your work by recording the first 20 noise samples.

=> Generate the RX_UNCODED sequence by adding the noise samples to the TX_UNCODED

sequence.

Verify your work by recording the first 20 noise samples and the first 20 RX_UNCODED

samples. Compare them to the TX_UNCODED samples recorded in Step 3.

=> Now repeat the previous two operations to generate RX_CODED by adding noise to each bit of

TX_CODED (you will need a longer noise sequence here).

For a signal coming from a "random process" such as noise, we are interested in its power, rather

than energy because the energy of signals that persist for all time is infinite. Power,

Page 44: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 44

or energy per unit time, is the relevant measure here. For zero-mean additive noise, its power is

equal to its variance. For noise, it is also useful to define a positive-frequency power density, N0.

Mathematically, we admit negative frequency and consider power as distributed half in negative

frequencies, half in positive frequencies, and we integrate the power density or spectrum over

positive and negative frequencies to get the total power. In all other respects we think of frequency

as positive, since nothing can happen a negative number of times per second. Thus N0, since it

relates to only half the frequencies, must be twice the power density that we integrate to get total

power. So what is N0 for our experiment?

Another issue is the signal power or energy. Here we shall take two points of view. The energy of

every bit in the coded case is the same as the energy in the uncoded case, namely, A2. Therefore

the power in the coded case is the same as for the uncoded case, although the former takes 7/4 as

long to transmit. From this point of view the signal to noise ratio (SNR) for the coded case is the

same as for the uncoded case, namely, A2/N0.

An alternative viewpoint is that in the coded case we are using 7/4 times as much energy, i.e. the

energy per message bit is 7/4 what it is in the uncoded case, so the SNR is (7/4)A2/N0. This is

considered here the "adjusted" SNR.

Step 5 : Demodulation

At this point, our simulated data has made it through the noisy medium and has arrived at its

destination. The receiver must now convert the continuous time signal back into a discrete one

through an analog-to-digital conversion called demodulation or detection. We will use a simple

threshold detector referred to as a slicer. Its threshold is 0V, so any signal above 0 V will be

interpreted as a '1' and any signal below 0 V will be interpreted as a '0'.

=> Generate the demodulated bit sequences DEST_UNCODED and DEST_CODED.

Verify your work by recording the first 20 bits of the DEST_UNCODED row vector.

Compare these to the 20 original SRC_UNCODED samples from Step 1 and the noise

samples recorded in Step 4. Did any bit errors occur? What were the noise samples that

caused these receiver errors?

Page 45: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 45

Step 6 : Decoding

It's now time to decode the DEST_CODED sequence. We need to break up the DEST_CODED

bit stream into 7-bit sequences, y, that will be converted back into 4-bit message sequences by the

decoding algorithm. In a noise-free environment, the 4 message bits are just the last 4 bits of the

7-bit code word (this is easily seen from the (7,4) Hamming code table presented in the

Introduction). But in order to take advantage of the error correction feature of this code, we must

determine if an error occurred by using the parity check matrix and if so, to correct it by using the

syndrome that results.

The decoder loop needs to perform the following for every 7-bit code, y, in the whole

DEST_CODED sequence:

First, take the 7-bit sequence and multiply it by HT, modulo 2. This is similar to the coding

loop that was used in Step 2. This gives us the 3-bit syndrome, s.

Next, convert the 3-bit syndrome from a binary number into an integer. Thus [0,0,0] => 0;

[0,0,1] => 1; ... ; [1,1,1]=>7.

Use this integer + 1 as an index to extract the correct row, e, from the error-pattern look-up

matrix E. Thus a syndrome of [0,0,0], or integer 0, returns the 1st row of E. Since this row

is all '0's, none of the original 7 bits are in error. Similarly, a syndrome of [1,1,1], or

integer 7, returns the 8th

row of E. The '1' in the 6th column of this error vector indicates a

bit error in 6th column of the received 7-bit code, y.

Using the error vector, e, from the previous look-up we can correct the single bit error by

adding e to y, modulo 2.

Finally, concatenate or add in the last 4 bits (this is where the original message was

located) of the now corrected row vector to DEST_DECODED.

If you have trouble with the above loop, see your TA.

Verify your work by recording the first 20 bits of the DEST_DECODED sequence. These

should match fairly closely the original 20 data bits of SRC_UNCODED recorded in Step 1.

Why might some of the bits still be in error after coding and decoding with this (7,4)

Hamming code? Explain.

Step 7 : Calculate the Error Probability

Since this is a simulation, we have the original data sequence and can compare the two received

sequences to it to determine exactly how many errors occurred. This gives us an indication as to

the probability of error for the particular signal energy per bit to noise power density ratio we were

using.

Page 46: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 46

=> Determine the number of errors for the uncoded transmission and the encoded transmission by

comparing DEST_UNCODED and DEST_DECODED to SRC_UNCODED. The Matlab "xor"

and "sum" functions are very useful here.

For each value of A compute the SNR and the adjusted SNR (7/4 times the former), in dB.

Record and compare the number of bit errors for the uncoded and coded cases. Comment on

the effectiveness of the coding. Also, comment on its drawbacks. When might such a

forward error control technique be impractical?

For each value of A record, in a vector, the error probabilities (number of errors/bits) for

the uncoded and coded cases, and SNRs, unadjusted and adjusted.

Step 8 : Repeat the Above for Different Signal Energies per Bit

Repeat Steps 1-7 for different values of A, omitting all the questions and recordings except for step

7. You will need to record the error probabilities and signal to noise ratios (unadjusted and

adjusted) for the uncoded and coded cases each time.

Print out a copy of your diary, final -.m file and your plots, and attach both to your lab

report.

This is the heart of the experiment. The validity of the results depends on not only your choice of

A, but also your data stream length. Why? Think about why a simulation with a choice of

parameters that yield of no errors is not very useful (what is the error probability for those

parameters? Is it valid?). How many bits would you need to simulate with to detect a probability

of error of 10-7

? Choosing a very long data stream may become computationally prohibitive.

Step 9 : Plot your results

The skeleton m-file provided performs the plotting of the results, using Matlab's "semilogy"

plotting function. We plot

uncoded probability of message bit error vs. SNR

coded probability of message bit error vs. SNR

coded probability of message bit error vs. adjusted SNR

Comment on how closely your data matches the theoretical curves shown in the appendix

B (for the "Uncoded BPSK" and "(7,4) Hamming"). The former is essentially our uncoded

case and the latter is supposed to be our coded, adjusted SNR, case. Unfortunately this

widely reproduced curve for the (7,4) Hamming code seems to be wrong, the formula for it

being a good approximation only for higher SNRs.

In your conclusion, discuss how forward error control coding compares to simply raising

the signal to noise ratio for a digital communication system. Be sure to mention power

savings versus bandwidth

Page 47: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 47

Appendix A:

Instructions for the IN Lab Procedure:

The procedures outlined in the should be carried out as follows:

Download the m-file coder.m from the Lab account (H:\Channel_Coding). This is an

outline of the Matlab program you are to write. That is, you should proceed by filling in the

parts not given to you. These are roughly speaking the essential encoding and decoding

operations. Note that the E, G and H matrices are provided. Put this file in the working

directory.

Modulo 2 of a matrix M can be taken via mod(M,2).

In the figure on the last page of the general instructions the abscissa is actually 10log10

(SNR).

A binary row vector v of length 3 can be converted to an integer via vi=v*[4 2 1]';

When the problem has been done correctly, with L=10000 and A=2, both

DEST_UNCODED and DEST_DECODED will have a significant number of errors but

much less in the latter case. Show your results to the TA.

When you and the TA are satisfied you have done all correctly then do the problem with

bits=200000 and with A = 0.5, 1/sqrt(2), 1, sqrt(2), 2, 2*sqrt(2), 4 (specify Avect

appropriately) and any other values you think may be interesting. On a copy of the graph

on the last page, indicate the experimental values you have obtained in the various cases.

For each value of A you have three results; those for DEST_UNCODED, using the

unadjusted SNR, and those for DEST_DECODED, using both the unadjusted and adjusted

SNRs. You will also get graphs generated by the program.

Page 48: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 48

Appendix B :

We would like to compare our results to the alleged theoretical ones depicted on the following

graph:

Page 49: Communications II LABORATORY - الصفحات الشخصيةsite.iugaza.edu.ps/mabufoul/files/2010/02/lab_manual.pdf · Communications II LABORATORY : Lab1- Signal Statistics, an

Page 49

Laboratory / Pre-lab Report Guidelines.

This section describes how lab reports should be prepared.

1. Reports must be typewritten or neatly printed. Points will be subtracted for sloppy

appearance.

2. Each lab report should have a cover sheet. The cover sheet should include your names,

date, lab number and title, and especially your lab section number.

3. Each page of your lab report must contain the last names of all members in your lab

group. You must list group names in the following ways:

a) For Matlab plots - use the gtext('names') Matlab command.

b) For code listings - use a comment line %names

c) For other sections - write out names by hand or in type font.

Lab reports that do not conform to this policy will not be accepted.

4. Your report need only contain items requested in the exercises. All questions should be

answered in detail. You do not need to rephrase the lab procedure.

5. Make sure all plots are clearly titled and axes are labeled.

6. All Matlab code should be properly commented. Make sure all Matlab code printouts

indicate the purpose of the function or script.

7. You should write a conclusion paragraph.

8. On the front page of your report, please provide an estimate of the average amount of time

spent of lab by the group.

9. You are an engineer. You are expected to present data and calculations clearly and precisely.