OFDM SIMULATION in MATLAB PDF
OFDM SIMULATION in MATLAB PDF
OFDM SIMULATION in MATLAB PDF
A Senior Project
In Partial Fulfillment
By
June 2010
Table of Contents
ii
List of Figures and Tables
List of Figures
List of Tables
iii
Chapter 1 INTRODUCTION
greater than the delay time in order to avoid inter-symbol interference (ISI) [1]. Since
data rate is inversely proportional to symbol period, having long symbol periods
means low data rate and communication inefficiency. A multicarrier system, such as
FDM (aka: Frequency Division Multiplexing), divides the total available bandwidth
in the spectrum into sub-bands for multiple carriers to transmit in parallel [2]. An
overall high data rate can be achieved by placing carriers closely in the spectrum.
However, inter-carrier interference (ICI) will occur due to lack of spacing to separate
the carriers. To avoid inter-carrier interference, guard bands will need to be placed in
low data rate carriers to construct a composite high data rate communication system.
Orthogonality gives the carriers a valid reason to be closely spaced, even overlapped,
without inter-carrier interference. Low data rate of each carrier implies long symbol
Although the idea of OFDM started back in 1966 [4], it has never been widely
utilized until the last decade when it becomes the modem of choice in wireless
1
The objective of this project is to demonstrate the concept and feasibility of an
OFDM system, and investigate how its performance is changed by varying some of
simulate a basic OFDM system. From the process of this development, the
2
Chapter 2 BACKGROUND
term symbol refers to a collection, in various sizes, of bits [6]. OFDM data are
generated by taking symbols in the spectral space using M-PSK, QAM, etc, and
convert the spectra to time domain by taking the Inverse Discrete Fourier Transform
(IDFT). Since Inverse Fast Fourier Transform (IFFT) is more cost effective to
implement, it is usually used instead [3]. Once the OFDM data are modulated to time
signal, all carriers transmit in parallel to fully occupy the available frequency
bandwidth [7]. During modulation, OFDM symbols are typically divided into frames,
so that the data will be modulated frame by frame in order for the received signal be
in sync with the receiver. Long symbol periods diminish the probability of having
inter-symbol interference, but could not eliminate it. To make ISI nearly eliminated,
3
an uncertainty of up to the length of a cyclic extension and still obtain the correct
information for the entire symbol period. As shown in Figure 1 [8], a guard period,
another name for the cyclic extension, is the amount of uncertainty allowed for the
receiver to capture the starting point of a symbol period, such that the result of FFT
still has the correct information. In Figure 2 [9], a comparison between a precisely
detected symbol period and a delayed detection illustrates the effectiveness of the
cyclic extension.
available spectral bandwidth, but also by the IFFT size (the relationship is described
ifft _ size
by: number of carriers 2 ), which is determined by the complexity of the
2
system [10]. The more complex (also more costly) the OFDM system is, the higher
IFFT size it has; thus a higher number of carriers can be used, and higher data
4
transmission rate achieved. The choice of M-PSK modulation varies the data rate and
Bit Error Rate (BER). The higher order of PSK leads to larger symbol size, thus less
number of symbols needed to be transmitted, and higher data rate is achieved. But
this results in a higher BER since the range of 0-360 degrees of phases will be divided
into more sub-regions, and the smaller size of sub-regions is required, thereby
received phases have higher chances to be decoded incorrectly. OFDM signals have
high peak-to-average ratio, therefore it has a relatively high tolerance of peak power
Orthogonality
of the product of two signals is zero over a time period, then these two signals are
said to be orthogonal to each other. Two sinusoids with frequencies that are integer
is defined by:
T
0
cos(2 nf ot ) cos(2 mf ot )dt = 0 (n m)
where n and m are two unequal integers; fo is the fundamental frequency; T is the
period over which the integration is taken. For OFDM, T is one symbol period and fo
1
set to to for optimal effectiveness [11 and 12].
T
5
2.2 Overview of This OFDM Simulation Project
Since MATLAB has a built-in function ifft() which performs Inverse Fast
Fourier Transform, IFFT is opted for the development of this simulation. Six m-files
are written to develop this MATLAB program of OFDM simulation. One of them is
the main program script file, which is the only file that needs to be run, while other
source input. Another bitmap image file will be generated at the end of the
err_calc.mat is to archive the baseband data before the transmission, and be retrieved
simulation and reserve them for the receiver to use later. In the reality, the receiver
would always have these parameters; in this simulation, these parameters are
configured by the user at the beginning, so they are passed to the receiver by
signal after it travels through the channel, and lets the receiver to read it directly.
When the simulation proceeds through the OFDM transmitter and communication
channel, it pauses and waits for the user to trigger for proceeding to the receiver. The
reason for using the last two *mat files is that as soon as the OFDM receiver
proceeds, the program will clear all data/variables stored in MATLAB workspace.
This is to simulate the real situation in which OFDM receivers have no knowledge of
6
the data except for the received signal at the exit of the communication channel.
Simulation runtime for both the transmitter and receiver are measured and shown on
Appendix C contains all the MATLAB source codes for this project with detailed
7
Chapter 3 DESIGN and IMPLEMENTATION
3.1 Overview
Figure 3 shows a block diagram of a generic OFDM system. ADC, DAC, and
simulated in this project. This MATLAB simulation program consists of six files.
Source data for this simulation is taken from an 8-bit grayscale (256 gray
levels) bitmap image file (*.bmp) based on the users choice. The image data will
PSK from four variations provided by this simulation. The converted data will then
be separated into multiple frames by the OFDM transmitter. The OFDM modulator
modulates the data frame by frame. Before the exit of the transmitter, the modulated
frames of time signal are cascaded together along with frame guards inserted in
between as well as a pair of identical headers added to the beginning and end of the
data stream. The communication channel is modeled by adding Gaussian white noise
The receiver detects the start and end of each frame in the received signal by
an envelope detector. Each detected frame of time signal is then demodulated into
useful data. The modulated data is then converted back to 8-bit word size data used
8
9
source cascade
data frames;
from DPSK cyclic parallel
frames serial add frame RF
input modulation IFFT bins extension to DAC
divider to IFFT guards, front-end
bmp (1, 2, 4, allocation addition serial
parallel header
file or 8 bits)
and trailer
OFDM Transmitter
communication
channel
OFDM Receiver
OFDM Demodulator
received
data to DPSK extract cyclic serial
parallel frames RF
generate demodulation carriers extension to
cascade to FFT detection
ADC front-end
output (1, 2, 4, from removal parallel
frames serial
bmp file or 8 bits) FFT bins
3.2 System Configurations and Parameters
program variables to start the simulation. Some variables are entered by the user.
The rest are either fixed or derived from the user-input and fixed variables. The user-
1) Input file an 8-bit grayscale (256 gray levels) bitmap file (*.bmp);
The number of carriers needs to be no more than [(IFFT size)/2 2], because there
are as many conjugate carriers as the carriers, and one IFFT bin is reserved for DC
signal while
##########################################
#*********** OFDM Simulation ************#
another IFFT bin ##########################################
and conjugate carriers. All user-inputs are checked for validity and the program will
10
request the user to correct any incorrect fields with brief guidelines provided. An
example is shown in Table 1. This script also determines how the carriers and
number of carriers
Figure 4 shows an
example of 120
conjugate carriers
The program reads data from an input image file and obtains an h-by-w matrix
where h is the height of the image and w is the width (in pixels). This matrix is
rearranged into a serial data stream. Since the input image is an 8-bit grayscale
bitmap, its word size is always 8 bits/word. The source data will then be converted to
the symbol size corresponding to the order of PSK chosen by the user.
11
data stream to a binary matrix with each column representing a symbol in the symbol
size of the selected PSK order. This binary matrix will then be converted to the data
stream with such a symbol size, which is the baseband to enter the OFDM transmitter.
36 7 182
0 0 0 0 1 0
0 1 0 1 0 1
1 0 0 1 1 1
[36, 7, 182] [2, 4, 0, 7, 11, 6]
0 0 0 1 1 0
three 8-bit words binary matrix six 4-bit symbols
through the base conversion again to return to 8-bits/word. This time, since the PSK
symbol size might be less than 8 bits/symbol, ofdm_base_convert.m would trim the
data stream to a multiple of 8/symbol-size before the base conversion in order to let
each symbol conversion have sufficient bits. If the OFDM receiver does not detect
all the data frames at the exactly correct locations, demodulated data may not be in
the same length as the transmitted data stream. [2, 4, 0, 7, 11] may be the received
data stream instead of [2, 4, 0, 7, 11, 6]. For this instance, 11 is dropped and only
stream that is longer than the original transmitted data stream due to some
imprecision processing caused by channel noise. In such cases, the received data
12
stream is trimmed to the length of the original data stream in order to fit the
On the contrary, the received data would more likely have a length less than
the original. In these cases, the program would consider the number of the full
missing rows as the amount to trim h, the height of the original image. Some
treatment is processed for the partially missing row if it exists. When one or more
full missing rows occur, the program shows a warning message informing the user
that the output image is in a smaller size than the original image. For the partially
missing row of received pixel data, the program would fill a number of pixels to make
it in the same length as all other rows. Each of these padded pixels would have the
same grayscale level as the pixel right above it in the image (one less row, same
column). This would make the partial missing row of pixels nearly seamless.
The core of the OFDM transmitter is the modulator, which modulates the
input data stream frame by frame. Data is divided into frames based on the variable
symb_per_frame, which refers to the number of symbols per frame per carrier. It is
typically would not be much greater than 1000 in this simulation, thus the total
13
number of symbols per frame would typically be under 10,000. This is an
experimentally reasonable number of symbols that one frame should keep under for
transmitted is less than the total number of symbols per frame, the data would not be
divided into frames and would be modulated all at once. As shown in Figure 5, even
guards with all zero values and in a length of one symbol period are still added to
both ends of the modulated time signal. This is to assist the receiver to locate the
beginning of the substantial portion of the time signal. As shown in Figure 6, for
modulated signals with multiple frames, a frame guard is inserted in between any two
adjacent frames as well as both ends of the cascaded time signal. Finally, a pair of
headers is padded to both ends of the guarded series of frames. The headers are
It is normal that the total number of transmitting data is not a multiple of the
number of carriers. To convert the input data stream from serial to parallel, the
14
modulator must pad a number of zeros to the end of the data stream in order for the
data stream to fit into a 2-D matrix. Suppose a frame of data with 11,530 symbols is
carrier while each row represents one symbol period over all carriers.
within an interval defined by the symbol size (order of PSK chosen) and patches it on
the top of the matrix. Figure 8 shows a 31-by-400 resulted matrix. For each column,
starting from the second row (the first actual data symbol), the value is changed to the
remainder of the sum of its previous row and itself over the symbol size (power 2 of
the PSK order). An illustration below shows how this operation is carried out for a
2 2
0 0 2
3
with [2] added as the reference becomes 3 , which is then differentiated to 1
2
2 3
1 1 0
15
Every symbol in the differentiated matrix is translated to its corresponding phase
2 180
2
180
1 is translated to 90
3 270
0
0
The modulator generates a DPSK matrix filled with complex numbers whose phases
are those translated phases and magnitudes are all ones. These complex numbers are
DATA
Conjugate
Figure 9 shows that the matrix is widened to
DATA
31
IFFT size (for example: IFFT size = 1024) and becomes
400 400
a 31-by-1024 IFFT matrix. Since each column of the Figure 9 pre-IFFT matrix
DPSK matrix represents a carrier, their values are stored to the columns of the IFFT
matrix at the locations where their corresponding carriers should reside. Their
conjugate values are stored to the columns corresponding to the locations of the
conjugate carriers (refer to Figure 4). All other columns in the IFFT matrix are set to
zero. To obtain the transmitting time signal matrix, Inverse Fast Fourier Transform
(IFFT) of this matrix is taken. Only the real part of the IFFT result is useful, so the
16
Periodic Time Guard Insertion
1280
An exact copy of the last 25% portion of each
31
symbol period (row of the matrix) is inserted to the
further widened to a width of 1280. This is the periodic time guard that helps the
clipping in this MATLAB program is set by the user. Peak power clipping is
basically setting any data points with values over clipping below peak power to
clipping below peak power. The peak-to- RMS ratios of the transmitted signal
before and after the channel are shown for a comparison regarding this peak power
by:
variance of the modulated signal
of AWGN =
linear SNR
17
It has a mean of zero and a standard deviation equaling the square root of the quotient
of the variance of the signal over the linear Signal-to-Noise Ratio, the dB value of
For only the first frame, this selected portion is relatively larger for taking the header
into account. The selected portion of received signal is sampled to a shorter discrete
signal with a sampling rate defined by the system. A moving sum is taken over this
sampled signal. The index of the minimum of the sampled signal is approximately
the start of the frame guard while one symbol period further from this index is the
approximate location for the start of the useful signal frame. The frame detector will
then collect a moving sum of the input signal from about 10% of one symbol period
earlier than the approximate start of the frame guard to about one third of s symbol
period further than the approximate start of the useful signal frame. The first portion,
with a length of one less than a symbol period of this moving sum is discarded. The
first minimum of this moving sum is the detected start of the useful signal frame.
frame. The OFDM receiver shows the progress of frames being demodulated.
18
However, the total number of frames may vary by a wide range depending on the
total amount of information transmitted via the OFDM system. It is a neat idea to
keep the number of displays for this progress within a reasonable range, so that the
MATLAB command screen is not overwhelmed by these status messages, nor the
amount of messages shown is less than useful. To achieve this, the first and last
frames are designed to show for sure, the rest would have to meet a condition:
rem(k,max(floor(num_frame/10),1))==0
where k is the variable to indicate the k-th frame being modulated, and num_frame
is the total number of frames. It means that for a total number of frames being 20 or
more, it only displays the n-th frame when n is an integer multiple of the round-down
integer of a tenth of the total number of frames; and for a total number of frames
being 19 or less, it shows every frame that is being modulated. This would keep the
total number of displays within the range from 11 to 19, provided that the total
number of frames is more than 10; otherwise, it simply shows as many messages as
a reverse process of OFDM modulation. And like its modulator, the OFDM
demodulator demodulates the received data frame by frame unless the transmitted
data has length less than the designed total number of symbols per frame.
19
Periodic Time Guard Removal
continue to be used for illustration. Figure 11 shows that after converting a frame of
discrete time signal from serial to parallel, a length of 25% of a symbol period is
discarded from all rows. Thus the remaining is then a number of discrete signals with
1280 1024
31 31
Fast Fourier Transform (FFT) of the received time signal is taken. This
results the spectrum of the received signal. As shown in Figure 12, the columns in
the locations of carriers are extracted to retrieve the complex matrix of the received
data.
1024 400
Reference Row
DATA
Conjugate
DATA
31 31
DATA
400 400
Figure 12 Received Data Extracted from FFT bins
The phase of every element in the complex matrix is converted into 0-360
degrees range and translated to one of the values within the symbol size. The
20
translated values form a new matrix. The differential operation is performed in
parallel on this new matrix to retrieve the demodulated data. This differential
400 400
Reference Row
31 30 DATA
DATA
symbols in a column of the matrix. As shown in Figure 13, the reference row is
removed during this operation. Finally, a parallel to serial operation is performed and
the demodulated data stream for this frame is obtained. Note that a series of zeros
may have been padded to the original data before transmission in order to make each
carrier have the same number of data symbols. Therefore, the modulator may have to
remove the padded zeros from the last portion of the demodulated data stream before
the final version of the received data can be obtained. The number of padded zeros is
calculated by taking the remainder of total number of data symbols over the number
of carriers.
Data loss
As mentioned in section 3.3 Input and Output, one or more of full rows of
pixels may be missing at the output of the receiver. In such cases, this program
21
would show the number of missing data and the total number of data transmitted, as
well as the percentage of data loss, which is the quotient of the two.
Demodulated data is compared to the original baseband data to find the total
Phase Error
During the OFDM demodulation, before being translated into symbol values
the received phase matrix is archived for calculating the average phase error, which is
defined by the difference between the received phase and the translated phase for the
All aforementioned error calculations are based on the OFDM symbols. What
is more meaningful for the end-user of the OFDM communication system is the
actual percent error of pixels in the received image. This is done by comparing the
Program Display
A summary showing the above error calculations is displayed at the end of the
22
400 carriers using an IFFT size of 1024, through a channel with 5 dB peak power
3.8 Plotting
Since all magnitudes are ONE, what this plot really shows is how the
In this graph, its easy to see that the original data has a number of
4. Modulated time signal for one symbol period on multiple (limiting to six)
carriers;
constellations.
23
The first four plots are derived from OFDM modulation while the last three are from
demodulation. None of these plots include a complete OFDM data packet. The first
three plots represent only the first symbol period in the first frame of data, whereas
the fourth plot represents up to the first six symbol periods in the first frame. Since
the first and last portion of the received/modulated data have higher probability of
by the fifth, sixth, and seventh plots is from the approximate middle of a frame, which
is also approximately the middle one among all data frames. However, its still
possible that the sample taken for the demodulation plots is still erroneous on certain
trials of this MATLAB simulation. It is important to note that even if the fifth, sixth,
and seventh plots dont show reasonable information, the overall OFDM transmission
and reception would still likely be valid since these plots only represent one symbol
period among many. Appendix B provides a example of each of these seven plots.
24
Chapter 4 TEST RESULTS
Appendix B shows a trial of the OFDM Simulation with the configuration
shown in Table 4.
Parameters Values
Source Image Size 800 x 600
IFFT size 2048
Number of Carriers 1009
Modulation Method QPSK
Peak Power Clipping 9 dB
Signal-to-Noise Ratio 12 dB
As shown in Table 6 in appendix B, theres a BER of 0.68% while the percent error
in the output image pixels is 1.80%. This is expected when the OFDM symbol size is
not the same as word size of the source data. i.e. Modulation method is not 256-PSK.
The reason is that a set of four QPSK symbols is mapped to one 8-bit word, and when
one or more of the 4 QPSK symbols in a set is decoded incorrectly, the whole 8-bit
word is mistranslated, therefore, it counts as all 4 QPSK symbols are errors when
considering the pixels percent error. However, in BER calculation, the interest is the
accuracy of the Tx and Rx, thus it only counts any of the QPSK symbols that are
decoded incorrectly. Average phase error of 12.33 o means that theres still a certain
With 1.80% pixel percent error, the noise on the output image is still easily
observable, but the information content received is highly usable. This is due to the
use of QPSK, in which received phases have 45o of tolerance. A sign of successful
25
QPSK is shown in the third graph in Figure 26 with obvious four groups of
constellations.
First graph in Figure 25 shows that IFFT bins are almost fully utilized by
QPSK. This can also been seen on the second graph in Figure 26, and it makes sense
to have those values somewhat scattered. It also makes sense to see in the first graph
of Figure 26, that the amplitudes of the received data are not as flat as the original,
By dropping the number of carriers and IFFT size to about half while all other
parameters remain the same, the simulation runtime for both the transmitter and
receiver dont seem to vary much. This is because the simulation program monitors
the total number of symbols to form one frame of data, thus total number of frames
did not vary much. The runtime measured depends on the number of computer
modulated and
frame. Conclusively,
this runtime
26
varied numbers of carriers. However, its
same. A plot in Figure 14 shows that using 16-PSK and 256-PSK also verifies this
theory. However, as shown in Figure 15, BER increased massively by raising the
PSK mothods.
As expected,
requires a larger
SNR to minimize
BER.
27
Similarly,
as shown in
require a
relatively large
SNR to transmit
Figure 17 Pixel Error vs SNR
data with an acceptable percent error. Figures 18 to 22 show the original image and
28
BPSK; SNR = 0 dB BPSK; SNR = 5 dB
29
QPSK; SNR = 0 dB QPSK; SNR = 0 dB
30
16-PSK; SNR = 0 dB 16-PSK; SNR = 5 dB
31
256-PSK; SNR = 0 dB 256-PSK; SNR = 5 dB
32
Even some low SNR received images, especially 256-DPSK modulated
images, have rather high BER; most of the information in the received images is still
observable. For example, at 15 dB of SNR, even though the 256-PSK received image
has a BER of 93.63%, the image is still observable. This is because for grayscale
digital images, if the decoded value of a pixel is off by a small number of gray levels,
its not easily observed by human eye, but will be counted as a bit error. In fact,
when toggling between the original and received image in this case, its obvious that
the gray level on most of the pixels did change, but the relatively contents are still
somewhat intact. A balanced trade-off between BER-tolerance and desire of data rate
33
Chapter 5 CONCLUSION
All major components of an OFDM system are covered. This has demonstrated the
basic concept and feasibility of OFDM, which was thoroughly described and
demodulator, keeping track of data format and data size throughout all the processes
of the whole simulation, designing an appropriate frame detector for the receiver, and
characteristics of this simulated OFDM system. It was noted that for some
combinations of OFDM parameters, the simulation may fail for some trials but may
succeed for repeated trails with the same parameters. It is because the random noise
generated on every trial differs, and trouble may have been caused for the frame
detector in the OFDM receiver due to certain random noise. Future work is required
to debug this issue and make the frame detector free of error.
adding ability to accept input source data in a word size other than 8-bit, adding an
modulation method.
34
Bibliography
[1] Schulze, Henrik and Christian Luders. Theory and Applications of OFDM and
http://zone.ni.com/devzone/cda/ph/p/id/269
http://www.wimax.com/commentary/wimax_weekly/sidebar-1-1-a-brief-history-of-ofdm
[5] Lui, Hui and Li, Guoqing. OFDM-Based Broadband Wireless Networks Design and
[6] Litwin, Louis and Pugel, Michael. The Principles of OFDM 2001
[7] Heiskala, Juha and Terry, John. OFDM Wireless LANs: A Theoretical and Practical Guide
SAMS 2001
[8] Lawrey, Eric Adaptive Techniques for Multiuser OFDM Ph.D. Thesis, James Cook
University 2001
http://www.dsplog.com/2008/02/03/understanding-an-ofdm-transmission/
http://www.dsplog.com/2007/12/31/minimum-frequency-spacing-for-having-orthogonal-sinusoidals/
35
Appendix A Glossary and Acronyms
word size Essentially the same as symbol size, but its the symbol size
36
Appendix B A Trial of this OFDM MATLAB Simulation
>> OFDM_SIM
##########################################
#*********** OFDM Simulation ************#
##########################################
##########################################
#******** END of OFDM Simulation ********#
##########################################
>>
Table 6 OFDM Simulation Log
37
B.2 Input and Output Images
38
B.3 Transmitter Plots
39
B.4 Receiver Plots
40
Appendix C Complete Source Codes for this Project
% ####################################################### %
% ************* OFDM SYSTEM INITIALIZATION: ************* %
% **** setting up parameters & obtaining source data **** %
% ####################################################### %
fprintf('\n\n##########################################\n')
fprintf('#*********** OFDM Simulation ************#\n')
fprintf('##########################################\n\n')
41
% ####################################################### %
% ******************* OFDM TRANSMITTER ****************** %
% ####################################################### %
42
% ####################################################### %
% **************** COMMUNICATION CHANNEL **************** %
% ####################################################### %
% ####################################################### %
% ********************* OFDM RECEIVER ******************* %
% ####################################################### %
% receive data
load('received.mat');
time_wave_rx = time_wave_rx.';
end_x = length(time_wave_rx);
start_x = 1;
data = [];
phase = [];
last_frame = 0;
unpad = 0;
if rem(w*h, carrier_count)~=0
unpad = carrier_count - rem(w*h, carrier_count);
end
num_frame=ceil((h*w)*(word_size/symb_size)/(symb_per_frame*carrier_count));
fig = 0;
43
for k = 1:num_frame
if k==1 || k==num_frame || rem(k,max(floor(num_frame/10),1))==0
fprintf('Demodulating Frame #%d\n',k)
end
% pick appropriate trunks of time signal to detect data frame
if k==1
time_wave = time_wave_rx(start_x:min(end_x, ...
(head_len+symb_period*((symb_per_frame+1)/2+1))));
else
time_wave = time_wave_rx(start_x:min(end_x, ...
((start_x-1) + (symb_period*((symb_per_frame+1)/2+1)))));
end
% detect the data frame that only contains the useful information
frame_start = ...
ofdm_frame_detect(time_wave, symb_period, envelope, start_x);
if k==num_frame
last_frame = 1;
frame_end = min(end_x, (frame_start-1) + symb_period*...
(1+ceil(rem(w*h,carrier_count*symb_per_frame)/carrier_count)));
else
frame_end=min(frame_start-1+(symb_per_frame+1)*symb_period, end_x);
end
% take the time signal abstracted from this frame to demodulate
time_wave = time_wave_rx(frame_start:frame_end);
% update the label for leftover signal
start_x = frame_end - symb_period;
if k==ceil(num_frame/2)
fig = 1;
end
% demodulate the received time signal
[data_rx, phase_rx] = ofdm_demod...
(time_wave, ifft_size, carriers, conj_carriers, ...
guard_time, symb_size, word_size, last_frame, unpad, fig);
if fig==1
fig = 0; % indicate that ofdm_demod() has already generated plots
end
% ####################################################### %
% ********************** DATA OUTPUT ******************** %
% ####################################################### %
44
buff_h = h;
h = ceil(length(data_out)/w);
% if one or more rows of pixels are missing, show a message to indicate
if h~=buff_h
disp('WARNING: Output image smaller than original')
disp(' due to data loss in transmission.')
end
% to make the patch nearly seamless,
% make each patched pixel the same color as the one right above it
if length(data_out)~=(w*h)
for k=1:(w*h-length(data_out))
mend(k)=data_out(length(data_out)-w+k);
end
data_out = [data_out mend];
end
end
% ####################################################### %
% ****************** ERROR CALCULATIONS ***************** %
% ####################################################### %
% Let received and original data match size and calculate data loss rate
if length(data_rx)>length(baseband_tx)
data_rx = data_rx(1:length(baseband_tx));
phase_rx = phase_rx(1:length(baseband_tx));
elseif length(data_rx)<length(baseband_tx)
fprintf('Data loss in this communication = %f%% (%d out of %d)\n', ...
(length(baseband_tx)-length(data_rx))/length(baseband_tx)*100, ...
length(baseband_tx)-length(data_rx), length(baseband_tx))
end
% find errors
errors = find(baseband_tx(1:length(data_rx))~=data_rx);
fprintf('Total number of errors = %d (out of %d)\n', ...
length(errors), length(data_rx))
% Bit Error Rate
fprintf('Bit Error Rate (BER) = %f%%\n',length(errors)/length(data_rx)*100)
% Error pixels
45
x = ofdm_base_convert(baseband_tx, symb_size, word_size);
x = uint8(x);
x = x(1:(size(data_out,1)*size(data_out,2)));
y = reshape(data_out', 1, length(x));
err_pix = find(y~=x);
fprintf('Percent error of pixels of the received image = %f%%\n\n', ...
length(err_pix)/length(x)*100)
fprintf('##########################################\n')
fprintf('#******** END of OFDM Simulation ********#\n')
fprintf('##########################################\n\n')
46
C.2 System Configuration Script File (ofdm_parameters.m)
% number of carriers
carrier_count = ifft_size; % force into the while loop below
while (isempty(carrier_count) || ...
(carrier_count>(ifft_size/2-2)) || carrier_count<2)
carrier_count = input('Number of carriers: ');
if (isempty(carrier_count) || (carrier_count > (ifft_size/2-2)))
disp('Must NOT be greater than ("IFFT size"/2-2)')
end
end
47
if (isempty(symb_size) || ...
(symb_size~=1&&symb_size~=2&&symb_size~=4&&symb_size~=8))
disp('Only 1, 2, 4, or 8 can be choosen')
end
end
% channel clipping in dB
clipping = [];
while isempty(clipping)
clipping = input...
('Amplitude clipping introduced by communication channel (in dB):
');
end
48
C.3 Data Word/Symbol Size Conversion Function File (ofdm_base_convert.m)
% base to binary
for k=1:base
binary_matrix(k,:) = floor(data_in/2^(base-k));
data_in = rem(data_in,2^(base-k));
end
% binary to new_base
data_out = zeros(1, size(newbase_matrix,2));
for k=1:new_base
data_out = data_out + newbase_matrix(k,:)*(2^(new_base-k));
end
49
C.4 Modulation Function File (ofdm_modulate.m)
% --------------------------------- %
% ##### Differential Encoding ##### %
% --------------------------------- %
% an additional row and include reference point
carrier_symb_count = size(data_tx_matrix,1) + 1;
diff_ref = round(rand(1, carrier_count)*(2^symb_size)+0.5);
% ------------------------------------------ %
% ## PSK (Phase Shift Keying) modulation ### %
% ------------------------------------------ %
% convert data to complex numbers:
% Amplitudes: 1; Phaes: converted from data using constellation mapping
[X,Y] = pol2cart(data_tx_matrix*(2*pi/(2^symb_size)), ...
ones(size(data_tx_matrix)));
complex_matrix = X + i*Y;
% ------------------------------------------------------------ %
50
% ##### assign IFFT bins to carriers and imaged carriers ##### %
% ------------------------------------------------------------ %
spectrum_tx = zeros(carrier_symb_count, ifft_size);
spectrum_tx(:,carriers) = complex_matrix;
spectrum_tx(:,conj_carriers) = conj(complex_matrix);
% Figure(1) and Figure(2) can both shhow OFDM Carriers on IFFT bins
if fig==1
figure(1)
stem(1:ifft_size, abs(spectrum_tx(2,:)),'b*-')
grid on
axis ([0 ifft_size -0.5 1.5])
ylabel('Magnitude of PSK Data')
xlabel('IFFT Bin')
title('OFDM Carriers on designated IFFT bins')
figure(2)
plot(1:ifft_size, (180/pi)*angle(spectrum_tx(2,1:ifft_size)), 'go')
hold on
grid on
stem(carriers, (180/pi)*angle(spectrum_tx(2,carriers)),'b*-')
stem(conj_carriers, ...
(180/pi)*angle(spectrum_tx(2,conj_carriers)),'b*-')
axis ([0 ifft_size -200 +200])
ylabel('Phase (degree)')
xlabel('IFFT Bin')
title('Phases of the OFDM modulated Data')
end
% --------------------------------------------------------------- %
% ##### obtain time wave from spectrums waveform using IFFT ##### %
% --------------------------------------------------------------- %
signal_tx = real(ifft(spectrum_tx'))';
51
hold on
end
grid on
axis ([0 ifft_size -limt limt])
ylabel('Amplitude')
xlabel('Time')
title('Samples of OFDM Time Signals over one symbol period')
end
% ------------------------------------- %
% ##### add a periodic guard time ##### %
% ------------------------------------- %
end_symb = size(signal_tx, 2); % end of a symbol period without guard
signal_tx = [signal_tx(:,(end_symb-guard_time+1):end_symb) signal_tx];
% parellel to serial
signal_tx = signal_tx'; % MATLAB's reshape goes along with columns
signal_tx = reshape(signal_tx, 1, size(signal_tx,1)*size(signal_tx,2));
52
C.5 Frame Detection Function File (ofdm_frame_detect.m)
signal = abs(signal);
53
C.6 Demodulation Function File (ofdm_demod.m)
% ------------------------------------------ %
% ##### remove the periodic time guard ##### %
% ------------------------------------------ %
symb_rx_matrix = symb_rx_matrix(guard_time+1:symb_period,:);
% ------------------------------------------------------------------ %
% ### take FFT of the received time wave to obtain data spectrum ### %
% ------------------------------------------------------------------ %
rx_spectrum_matrix = fft(symb_rx_matrix)';
54
axis ([0 ifft_size -200 +200])
grid on
ylabel('Phase (degrees)')
xlabel('FFT Bin')
title('Phase of Receive OFDM Spectrum')
end
% ----------------------------------------------------------------- %
% ### extract columns of data on IFFT bins of all carriers only ### %
% ----------------------------------------------------------------- %
rx_spectrum_matrix = rx_spectrum_matrix(:,carriers);
% --------------------------------------------- %
% ### PSK (Phase Shift Keying) demodulation ### %
% --------------------------------------------- %
% calculate the corresponding phases from the complex spectrum
rx_phase = angle(rx_spectrum_matrix)*(180/pi);
% make negative phases positive
rx_phase = rem((rx_phase+360), 360);
% --------------------------------- %
% ##### Differential Decoding ##### %
% --------------------------------- %
% reverse the differential coding
decoded_phase = diff(rx_phase);
% make negative phases positive
decoded_phase = rem((decoded_phase+360), 360);
% phase-to-data classification
base_phase = 360/(2^symb_size);
% phase-to-data translation
decoded_symb = ...
floor(rem((decoded_phase/base_phase+0.5),(2^symb_size)));
55
if last==1
decoded_symb = decoded_symb(1:(length(decoded_symb)-unpad));
decoded_phase = decoded_phase(1:(length(decoded_phase)-unpad));
end
56