Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO

Transmitter/Receiver Code Description


Introduction to Digital Communication Receiver Design
Introduction
A transmitter and sampled-IF receiver have been implemented in Matlab, and this document describes the corresponding code. This operation of the receiver, including its chosen
parameters, are described in the latter half of the lecture notes for DAY 4 under the heading of Putting It All Together: Receiver Design. This receiver system will be used in
the lab assignments for Days 2-4 by focusing only on the specific segment described in the
associated lectures, while allowing us to judge the impact on overall system performance.
The block diagram in Fig. 1 shows the steps of generation of the transmitted signal, its
propagation through the channel, and the operations performed by the receiver. While
Binary
message
sequence b

we{23, 21, 1, 3}
Analog
upconversion
Carrier
specification

P(f)

Coding

Pulse
shaping

Transmitted
signal
Channel

Other FDM
Noise
users
1

Antenna

Analog
received
signal

Analog
conversion
to IF

Digital downconversion
to baseband

Pulse
matched
filter

Ts
Carrier
Input to the
synchronization
software
receiver
m

T
Downsampling

Timing
synchronization

Equalizer

Q(m)e{23, 21, 1, 3}
Decision

^
b

Decoding

Source and Reconstructed


error coding
message
frame synchronization

Figure 1: System Block Diagram


the blocks in this figure are quite general, design choices were made in the development
of this particular transmitter/receiver implementation. These design choices (i.e. which
algorithms have been selected) and the code to implement them will be described in the
following sections.

Matlab Files
A brief description of each of the functions used in the complete system is provided here.
You can find all of the files in the /system code directory. For a more detailed description

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO

of the inputs and outputs for each of these functions, you can using the help command at
the Matlab prompt (e.g. by typing help Tx).

Main Files
Listings at the end of this code description document.
main.m This script is merely an example which shows how to set up the system
parameters, run the transmitter, run the receiver, and calculate the bit-error-rate.
Tx.m This function contains the transmitter, and introduces the impairments (e.g.
the channel, imperfect receiver frontend, etc.)
Rx.m This function decodes the received signal, and outputs the message.
globalParams.m This function contains the parameters for the system (e.g. sampling period, IF frequency, marker sequence, etc.)

Subroutine Files
These files are from Telecommunication Breakdown.
letters2pam.m This function converts an ASCII text sequence into 4-PAM symbols. Used by Tx.m.
pam2letters.m This function converts a sequence of 4-PAM symbols into an
ASCII text string. Used by Rx.m.
quantalph.m This function is effectively a minimum Euclidean distance detector,
or decision device. It accepts soft PAM symbols, and quantizes the input to the
nearest PAM symbol. Used by Rx.m.
srrc.m This function generates the impulse response for the square-root raisedcosing pulse shape. Used by both Tx.m and Rx.m.
interpsinc.m The function performs sinc interpolation, and is used for the baudtiming and downsampling in the receiver. Used by Rx.m.

Transmitter Details (Tx.m)


This section briefly describes each of the main components of the transmitter, and points
to their corresponding line numbers in the code. The components can also be found in the
block diagram in Fig. 1. Note that, in addition to the transmitter, Tx.m also includes the
channel and receiver frontend blocks.

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO

Calculate Intermediate Variables (lines 19-29) This part calculates intermediate variables which are used in the transmitter, including the upsampling/downsampling
ratios and the phase noise random process.
Generation of 4-PAM sequence (lines 30-32) This part encodes the ASCII test
message into 4-PAM signals (using letters2pam), and inserts the header and marker
sequences. The result is a serial stream of 4-PAM symbols stored in the variable
called s.
Pulse Shaping (lines 33-35) This part performs upsampling of the 4-PAM signal
and then filters the signal with the pulse shape obtained from srrc. The result is
stored in the variable x.
Analog Upconversion (lines 36-39) This part modulates the signal up to the
carrier frequency, and includes the effect of phase noise. The result is stored in x rf.
Channel (lines 40-42) This part convolves the upconverted signal with the channel, storing the result in the variable x2.
Noise (lines 43-47) This part adds the additive white Gaussian noise of specified
SNR.
Analog Conversion from RF to IF (lines 48-52) This part acts as the frontend
of the receiver, and performs analog conversion of the RF signal down to IF. While
the RF signal in reality would be analog, our computer simulation uses a digital
representation throughout; thus, the sampled-IF receiver is obtained from the RF
signal by simple downsampling. The result is the digital signal which gets passed
into Rx.m.

Receiver Details (Rx.m)


Similar to the previous section, this section briefly describes each of the main components
of the receiver, and points to their corresponding line numbers in the code. Most of the
components can also be found in the block diagram in Fig. 1.
Calculate Intermediate Variables (lines 18-25, 52-72) This part calculates intermediate variables which are used in the receiver. This includes calculation of the
effective carrier frequency and image frequency, memory allocation, variable allocation, and size determination.
Digital Downconversion via PLL (lines 26-34, 74-82) This part implements
the downconversion which is accomplished in the current receiver with a PLL. The
procedure consists of several sub-steps:
Parameter Initialization and Bandpass Filter Design (lines 26-34)
PLL Pre-processing (lines 74-76)
PLL Adaptation (lines 77-79)

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO

Mixing (lines 80-82)


Recall that the equation for PLL adaptation has the form
[k + 1] = [k] x(kTs ) sin (4f0 kTs + [k] + )
which appears in line 78. The carrier phase estimate is stored in the variable theta
while the downconverted signal is stored in the variable x down.
Pulse Matched Filter (lines 48-51, 83-85) This part performs filtering of the
signal with the square-root raised-cosine filter. The filtered signal is stored in the
variable x bb.
Downsampling/Timing Sync via Output Power (OP) Method (lines 35-38,
89-96) This part performs the downsampling and timing synchronization using
the method of output power maximization. The procedure makes several calls to the
interpsinc function, and consists of several sub-steps:
Parameter Initialization (lines 35-38)
Get current interpolated value (line 90)
Calculate approximate derivative (lines 91-93)
Algorithm Adaptation (line 94)
Recall the equation for the output-power-maximizing baud-timing adaptation algorithm has the form
"

kT
kT
[k + 1] = [k] + x[k] x
+ [k] + x
+ [k]
M
M

!#

which is seen in lines 91-94. The Matlab variable tau stores the timing offset, tnow
stores the current position, and x sampled stores the downsampled signal after timing
recovery.
Correlation (lines 97-102) Always running, this part calculates the correlation of
the downsampled signal with the known header sequence.
Header Search (lines 39-41, 104-110) This part searches for the header, by
comparing the correlation value with a threshold.
Equalization with Adaptation via LMS (lines 111-124) This part performs
equalization of the signal, which includes adaptation of the equalizer coefficient during
training periods (see paragraph below about different operating modes of receiver).
Equalization consists of two sub-steps
Adapt equalizer using LMS (lines 111-121)
Generate equalizer output (lines 121-124)

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO

Recall the equation for the LMS algorithm which has the form
fi [k + 1] = fi [k] + (s[k ] y[k]) r[k i]
and is seen in lines 114-115. The Matlab variable f stores the equalizer coefficients,
and eqOut stores the output of the equalizer.
Decision Device, Frame Sync, and Message Decoding (lines 125-129) This
part quantizes the equalizer output using quantalph, resulting in a stream of 4-PAM
symbol estimates stored in the variable dec. With knowledge of the start of the
header sequence from the previous stage, frame synchronization is performed, after
which the decisions pass into the decoder (i.e. pam2letters), the output of which is
stored in the variable decoded msg.
There are some other details of the receiver which are worth noting. The receiver consists
of two main loops and their corresponding counters
1. IFsampleIdx Each time this loop counter is incremented, the receiver has received
a new IF sample at the receiver frontend.
2. BBsampleIdx This loop counter is incremented every time a new baseband sample
is output from the baud-timing device.
Also, the receiver operates in 3 distinct modes:
1. HEADER SEARCH MODE In this mode, the receiver is running its correlator to search
for the header sequence.
2. TRAINING MODE In this mode, the receiver thinks that it is receiving training data,
and so it is training the equalizer using the LMS algorithm.
3. DATA MODE In this mode, the receiver has completed training, and believes that it
is receiving data.
The receiver starts in HEADER SEARCH MODE. Once the header is found, it switches to
TRAINING MODE, and when the training is complete it switches to DATA MODE. Once the
data transmission is complete (based on the length of the data sequence specified in the
system parameters), the receiver then returns to HEADER SEARCH MODE and repeats.

Listings
main.m
1
2
3

% Example script that demonstrates how to call transmitter and rece


iver
% code.

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

% written by A. Klein 26-Oct-2005


% call script to get global simulation parameters (i.e. carrier fre
q, baud rate, training data, etc)
globalParams
% initialize random seed for repeatability (helps for debugging) -randn(state,0);
rand(state,0);
% set channel, SNR, phase noise,
c = [1 -0.4 0.2];
%
SNR = 18;
%
er) sampled signal
phase_noise_variance = 1e-6;
%
process
%
%
%
%

and message to be sent ----------channel (T-spaced)


signal-to-noise ratio (dB) of (und
variance of underlying phase noise

(uncomment the following lines for the most benign conditions)


c = [1 0 0];
% no ISI
SNR = Inf;
% no noise
phase_noise_variance = 0;
% perfect oscillators

m=[This is the first frame which you probably shouldnt able to d


ecode perfectly unless you "cheat" and
give your receiver the initial points. Now were into the second
frame. You might be able to decod
e this one, and now the third, error-free. . . But if you didnt,
then dont worry yet. The only fr
ames you are required to decode during the actual testing are thos
e past the fifth frame. So youre
still okay. Were getting close to the end of the 5th frame, so
your receiver better start working.
Congratulations! If you can see this then youre receiver has su
ccessfully decoded the fifth frame.
You might want to re-test your receiver by using different initial
parameters, and different stepsiz
es to see what the effect is. Its probably help to plot the tim
e history of the adaptive parameter
elements, too, so you can see if theyre taking too long to conve
rge, if they seem unstable, etc. A
nd now some more Nirvana lyrics: With the lights out its less da
ngerous Here we are now Entertain u
s I feel stupid and contagious Here we are now Entertain us A mula
tto An albino A mosquito My Libido
And I forget Just what it takes And yet I guess it makes me smile

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO

35
36
37
38
39
40
41
42
43
44
45
46

I found it hard Its hard to find.


Well, if your receiver has made it this far with no errors, and pe
rforms error-free even when you ch
ange the initial parameter values, then its time to move on to t
he "medium" test vector. Good luck];
% call transmitter -----------------------------------------------[r, s]=Tx(m, c, SNR, phase_noise_variance);
m=m; m=m(:);
% call receiver --------------------------------------------------[decoded_msg y]=Rx(r);
% call code to calculate BER ----------------------------------BERcalc

Tx.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

function [r, s]=Tx(m, c, SNR, phase_noise_variance)


% function [r, s]=Tx(m, c, SNR, phase_noise_variance)
%
% Inputs:
%
m -- text message to be sent
%
c -- channel (T-spaced)
%
SNR -- signal to noise ratio
% phase_noise_variance -- variance of phase noise added to signal
%
% Outputs:
%
r -- received signal (at IF)
%
s -- transmitted symbols (for calculating SER)
% written by A. Klein 26-Oct-2005
global srrcLength marker training f_s T_t f_if rolloff dataLength
% determine suitable oversampling/downsampling factor
[M N]=rat(f_s*T_t);
M_scale=ceil((2*T_t*f_if+1+rolloff)/M);
M=M*M_scale;
N=N*M_scale;
% get dimensions
lines_of_text=size(m,1);
frame_length=(dataLength+(length([marker; training])));

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO


28
29
30
31

32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

char_str_length=frame_length*lines_of_text;
% insert training & header, and generate 4-PAM source vector
s=reshape([repmat([marker; training],lines_of_text,1) reshape(lett
ers2pam(reshape(m,lines_of_text*dataLength/4,1)),dataLength,lines_
of_text)],lines_of_text*(dataLength+(length([marker; training])))
,1);
% generate pulse-shaped signal
x=conv(srrc(srrcLength,rolloff,M,0),upsample(s,M));
% mix signal to RF (analog upconversion)
p_noise=cumsum(randn(size(x))*sqrt(phase_noise_variance/N)); % gene
rate phase noise process
x_rf=x.*cos(2*pi*f_if*[1:length(x)]*T_t/M+p_noise);
% pass through BP channel
x2=conv(x_rf,upsample(c,M));
% add channel noise of appropriate SNR
x2_size=size(x2);
x2_nrm=sqrt(x2(srrcLength*M+1:x2_size(1)-srrcLength*M)*x2(srrcLeng
th*M+1:x2_size(1)-srrcLength*M)/x2_size(1));
x_r=x2+randn(size(x2))*10^(-SNR/20)*x2_nrm;
% perform analog conversion to IF, and do AGC
r=x_r(N:N:end);
r_nrm=r*r/length(r);
r=r/sqrt(r_nrm);
% add some zeros to front and back
r=[zeros(floor(rand*10*M),1); r; zeros(10*M,1)];

Rx.m
1
2
3
4
5
6
7
8
9
10

function [decoded_msg, eqOut]=Rx(r)


% function [decoded_msg, eqOut]=Rx(r)
%
% Inputs:
%
r -- received signal (at IF)
%
% Outputs:
%
decoded_msg -- received signal (at IF)
%
eqOut
-- output of equalizer

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

% written by A. Klein 26-Oct-2005


global srrcLength marker training f_s T_t f_if rolloff dataLength
globalParams
% calculate new effective carrier frequency, and the image which wi
ll appear at 2f_c (and may get aliased)
f_c=f_if-fix(f_if/f_s)*f_s;
f_image=abs(mod(2*f_c+f_s/2,f_s)-f_s/2);
% calculate sizes ----------------------------markerLength=length(marker);
trainingLength=length(training);
% PLL parameters & BPF filter design -----------------------------bpf_ctr=f_image/f_s*2;
% set center frequency of BPF to 2f
BPFfilterOrder=500;
% should be an even number
ff=[0 bpf_ctr+[-0.006 -0.003 0.003 0.006] 1]; % BPF trans. band
fa=[0 0 1 1 0 0];
% values at transition regions
h=remez(BPFfilterOrder,ff,fa);
% design filter
phaseBPF=angle(exp(-1j*[0:length(h)-1]*pi*bpf_ctr)*h); % calculate
phase introduced by BPF
mu_PLL=0.001;
% stepsize for first PLL loop
% baud timing (OP) parameters -----------------------mu_timing=0.1;
% algorithm stepsize
delta=0.1;
% time for derivative
% correlation (i.e. header search) parameters --------correlThresh=6500;
% threshold for
determining whether weve received the header sequence
% equalizer parameters --------------------------eqLength=8;
% equalizer length
mu_eq_lms=0.005;
% trained LMS stepsize
eqDelay=3;
% desired delay (for LMS)
f=zeros(eqLength,1); f(eqDelay+1)=1; % equalizer initialization (m
ust have correct length)
% design SRRC (matched) filter --------------------------srrcFlt=srrc(srrcLength,rolloff,f_s*T_t,0);
srrcFltLength=length(srrcFlt);

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

% setup constants for each of the three operating modes-----------HEADER_SEARCH_MODE=1;


TRAINING_MODE=2;
DATA_MODE=3;
operationMode=HEADER_SEARCH_MODE; % we start in HEADER_SEARCH_MODE
% allocate memory and initialize variables --------------theta=zeros(length(r),1);
% stores outputs of PLL
x_down=zeros(length(r),1);
% stores downconverted signal (prematched filter)
x_bb=zeros(length(r),1);
% stores baseband signal (post-matc
hed filter)
x_sampled=zeros(ceil(length(r)/T_t/f_s),1); % stores sampled signa
l (post timing recovery)
Corr=zeros(ceil(length(r)/T_t/f_s),1);
% stores correlation v
alues (for header search)
tau=zeros(ceil(length(r)/T_t/f_s),1);
% stores timing recovery (
only used for plotting)
eqOut=zeros(ceil(length(r)/T_t/f_s),1); % stores output of equalizr
e_lms=zeros(ceil(length(r)/T_t/f_s),1);
% stores LMS error
dec=zeros(ceil(length(r)/T_t/f_s),1);
% stores PAM-4 decisions
packetIndex=0;
% packet counter
tnow=2*(srrcLength-2)*T_t*f_s;
% starting location for timing
BBsampleIdx=0;
% intialize baseband sample counter
start=BPFfilterOrder+1;
% outer loop starting point
for IFsampleIdx=start:length(r);
% pre-process signal for PLL
r2(IFsampleIdx)=h*r(IFsampleIdx:-1:IFsampleIdx-BPFfilterOrder)
.^2;
% adapt PLL
theta(IFsampleIdx+1)=theta(IFsampleIdx)-mu_PLL*r2(IFsampleIdx)*
sin(4*pi*f_c*IFsampleIdx/f_s+2*theta(IFsampleIdx)+phaseBPF);
% perform downconversion
x_down(IFsampleIdx)=r(IFsampleIdx)*cos(2*pi*f_c*IFsampleIdx/f_s
+theta(IFsampleIdx));
% perform matched filtering
x_bb(IFsampleIdx)=srrcFlt*x_down(IFsampleIdx:-1:IFsampleIdx-sr
rcFltLength+1);
while tnow<IFsampleIdx-2*srrcLength*T_t*f_s+2
% do we have a new baseband sample?

10

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO


87
88
89
90
91
92
93
94
95
96
97
98
99

100
101
102
103
104
105
106
107
108
109
111

BBsampleIdx=BBsampleIdx+1;
% ok, were at next baseband sample, so increment
% perform timing recovery (OP)
x_sampled(BBsampleIdx)=interpsinc(x_bb,tnow+tau(BBsampleIdx
),srrcLength);
% interpolated value at tnow+tau
x_deltap=interpsinc(x_bb,tnow+tau(BBsampleIdx)+delta,srrcLe
ngth);
% get value to the right
x_deltam=interpsinc(x_bb,tnow+tau(BBsampleIdx)-delta,srrcLe
ngth);
% get value to the left
dx=x_deltap-x_deltam;
% calculate numerical derivative
tau(BBsampleIdx+1)=tau(BBsampleIdx)+mu_timing*dx*x_sampled(
BBsampleIdx);
% alg update: OP
tnow=tnow+T_t*f_s;
% update current position
% run correlator, matched to marker sequence
if (BBsampleIdx>eqDelay+markerLength-1)
% need to skip t
he first few sample until we have enough to fill correlator
corInputSignal=x_sampled(BBsampleIdx-markerLength+1-eqD
elay:BBsampleIdx-eqDelay);
% extract portion of signal used f
or correlation
Corr(BBsampleIdx)=(marker*corInputSignal)^2;
% calculate correlation
end
switch operationMode
case HEADER_SEARCH_MODE
% if we havent already fou
nd marker, look for it...
if Corr(BBsampleIdx)>correlThresh
% has cor
relation exceeded threshold?
operationMode=TRAINING_MODE;
% yep, so switch to training mode
trainingIndex=1;
% reset to trainingIndex to first sample of training data
packetIndex=packetIndex+1;
% increment packet counter
end 110
case TRAINING_MODE % if were in equalizer training mod
e, train the LMS equalizer

112
rr=x_sampled(BBsampleIdx:-1:BBsampleIdx-eqLength+1)
;
% extract "regressor" vector of receive
d signal

11

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO


113

eqOut(BBsampleIdx)=f*rr;
% equalizer output

114
e_lms(BBsampleIdx)=training(trainingIndex)-eqOut(BB
sampleIdx);
% calculate LMS error term
115
f=f+mu_eq_lms*e_lms(BBsampleIdx)*rr;
% update equalizer coefficients
116
trainingIndex=trainingIndex+1;
% increment training index location
117
if trainingIndex>trainingLength
% are we done training?
118
operationMode=DATA_MODE;
% yep, switch to data mode
119
symbolIndex=1;
% and re-init symbol counter to 1
120
end
121
122
case DATA_MODE
% were into data portion of the pack
et -- equalizer, and save data
123
rr=x_sampled(BBsampleIdx:-1:BBsampleIdx-eqLength+1)
;
% extract "regressor" vector of receive
d signal
124
eqOut(BBsampleIdx)=f*rr;
% equalizer output
125
dec(symbolIndex)=quantalph(eqOut(BBsampleIdx),[-3 1 1 3]);
% make decisions
126
127
if mod(symbolIndex,4)==0
% if weve completed a w
hole letter (i.e. 4 PAM symbols), convert PAM symbols to letters
128
decoded_msg(packetIndex,symbolIndex/4)=pam2lett
ers(dec(symbolIndex-3:symbolIndex)); % re-assemble text message
129
end
130
symbolIndex=symbolIndex+1;
% increment training index location
131
if symbolIndex>dataLength % are we done with data
yet?
132
operationMode=HEADER_SEARCH_MODE; % yep, switc
h back to header search mode
133
end
134
end
135
end

12

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169

end
% plot results ---------------------------------------------------figure(1);
plot(theta)
title(carrier phase estimate)
ylabel(theta)
xlabel(time)
figure(2)
plot(tau)
title(timing offset estimates)
ylabel(tau)
xlabel(time)
figure(3)
plot(Corr)
hold on
plot([1 length(Corr)],[correlThresh correlThresh],:) % plot thre
shold
title(correlator output (for finding start of training))
xlabel(time)
ylabel(correlation value)
figure(4)
plot(eqOut,b.)
% plot constellation diagram
title(constellation diagram (equalizer output));
ylabel(estimated symbol values)
xlabel(time)
figure(5)
plot(e_lms)
title(error at equalizer output (during training))
ylabel(e_lms)
xlabel(time)

globalParams.m
1
2
3
4
5
6

global srrcLength marker training f_s T_t f_if rolloff dataLength


srrcLength=4;
% truncated srrc length (divided by 2)
marker=letters2pam(0); % marker sequence
training=letters2pam(Oh well whatever Nevermind); % training se
quence
f_s=850e3;
% sampling frequency (Hz)

13

Johnson/Introducing Receiver Design/Apr-May 05: KLEINS RADIO


7
8
9
10

T_t=6.4e-6;
f_if=2e6;
rolloff=0.3;
dataLength=400;

%
%
%
%

symbol period (seconds)


intermediate frequency (Hz)
srrc rolloff factor
number of PAM symbols per data frame

14

You might also like