Programs Comm Lab

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 78

Communication lab-II/21ECL55

1. FREQUENCY SHIFT KEY (FSK) GENERATION AND DETECTION

Aim:
To generate and demonstrate the FSK signal. Compare the similarity
of the original and reconstructed signal.

Objectives:
 To design and construct FSK modulation circuit.
 Test the circuit and record the readings.
 Plot the output waveforms.
 Design and construct FSK modulator.
 Integrate modulator with demodulator.
 Test the demodulator and record the readings.
 Plot the input and out put waveforms and compares the parameters.

FSK Modulation Circuit:


In the binary FSK the frequency of carrier is shifted according to the
binary symbol. However the phase of the carrier is unaffected.

Dept. of E C E, K I T, Tiptur
Page 1
Communication lab-II/21ECL55

Design:

Assume:
Ic (sat) = 2mA
hfe (min) = 30
VCE(sat) = 0.2V
VBE = 0.7V
Ιc 2 x 10−3
Ι B= = =66 .66 μA
β 30
V V V c−V cε ( sat )
R E= E = E =
IE IC Ιc
8−0 . 2
R E= =3 . 9 Κ Ω
2 x 10−3
.
Vin−Vbe −Ve
R B= =22 K Ω
ΙB
Choose R B =22 K Ω

Procedure:
1. Construct the circuit as shown bellow in fig-1 with the designed values.
2. Set m (t) at input=250 Hz, 10V (p-p) using pulse generator.
3. Set c (t) at collector circuit to 3 KHz, 5V (p-p) using function generator.
4. Connect CRO at CH1at input and CH2 at output terminals.
5. Adjust the CRO to clearing view of the input and output wave forms.
6. Align input and output waveforms to check if output exists while the
input at logic1
7. Measure the input and output waveforms (refer figure for typical
waveforms)
NOTE: Ensure that all grounds of the circuit are made common.

Dept. of E C E, K I T, Tiptur
Page 2
Communication lab-II/21ECL55

FSK Demodulator Circuit:

This receiver contains two BPFs, one with centre frequency f H another
with centre frequency fc. Since fH-fC=2fb, the out put filter does not overlap
with each other. The output of filter are applied to the envelop detectors.
The out put of detectors are compared by comparators. If unipolar
comparator is used then output of comparator is bit sequence b (t).

Circuit Diagram:

Design:

1
Let fc = 2 π RC
Let fm = 200 Hz
Choose fc= 800 Hz
Let c = 0.1mf
1 1
R= = =
2 π f c C 2 π x 800 x 0 . 1 x 10−6 12.4KΩ

Procedure:
1. Construct the circuit as shown below in figure with the designed values.

Dept. of E C E, K I T, Tiptur
Page 3
Communication lab-II/21ECL55

2. Feed the output of FSK signal to the input of the FSK demodulation
circuit.
3. Observe the demodulated output with the help of CRO.
4. The output of Demodulator is the recovered message which is compared
with the input message.
Expected Waveform:

m(t)
10Vp-p t

Message

FSK t
Output

ASK t
Output

Demod
t
Output

Result:

Dept. of E C E, K I T, Tiptur
Page 4
Communication lab-II/21ECL55

2. PHASE SHIFT KEY (PSK) GENERATION AND DETECTION

Aim:
To generate and demonstrate BPSK signal compare similarly of the
original and reconstruction signal.
Objectives:
 Design and constant the BPSK generator circuit.
 Test the circuit and record the readings.
 Design and construct the BPSK detection circuit.
 Test the circuit and record the readings.
 Plot the input and output waveforms and compare the parameters.

Generation Circuit:
Theory:
In a binary phase shift keying BPSK binary symbol ‘1’ and ‘0’
modulate the phase of the career. Let us assume that the carrier is given as
S (t) =A Cos 2Πfct. Here ‘A’ represents peak value of sinusoidal corner. The
BPSK signal may be generated by applying career signal to a balanced
modulator. Here the base band signal bit is applied as a modulating signal
to balanced modulator.
Circuit Diagram:

Dept. of E C E, K I T, Tiptur
Page 5
Communication lab-II/21ECL55

Design:
Assume: Ic (sat) = 2mA
hfe (min) = 30
VCE (sat) = 0.2v
VBE = 0.7 v
Ιc 2 x 10−3
Ι B= = =66 . 66 μA
hfe 30
VE VE V c−V cε ( sat )
R E= = =
IE IC Ιc
8 −0 . 2
R E= =3 . 9 Κ Ω
2 x 10−3
Choose R E =3 . 3 Κ Ω
V m −V Bε− V E 10−0 . 7 −7 . 8
R B= = . =22 K Ω
IB 66 . 66 x 10−6
Choose R B =22 K Ω
Procedure:
1. Construct the circuit as shown in figure with the designed values.
2. Set m (t) at e/p equal to 250 Hz 10V (p-p) using a pulse generator.
3. Set c (t) at collection circuit to 2 KHz 7V (p-p) using function generator.
4. Connect CRO out the input terminals CH2 at the output terminals.
5. Adjust CRO to clearly view of the input and output waveforms.
6. Alight the input and output waveforms to check the input and output
exists.

Dept. of E C E, K I T, Tiptur
Page 6
Communication lab-II/21ECL55

7. Measure p-p of input and output waveforms.


8. Record observation and table readings.
Detection Circuit:
Theory:
The transmitted BPSK signal is fed to square low device. This signal
under goes a phase change depending upon the time delay from transmitted
and to receiver end. This change is usually fixed phase shift in transmitted
signal. Then the signal fed to bit synchronizer and integrator. The integrator
integrates the signal over one bit period
Circuit Diagram:

Design:
1
Let fc = 2 π RC
Let fm = 200 Hz
Choose fc= 800 Hz
Let c = 0.1μF
1 1
R= = =
2 π f c C 2 π x 800 x 0 . 1 x 10−6 2KΩ

Procedure:

Dept. of E C E, K I T, Tiptur
Page 7
Communication lab-II/21ECL55

1. Design and construct the circuit as shown in the figure with the
designed values.
2. The generated BPSK signal is fed at the input of the adder.
3. The output of the envelop detector is fed to the comparator where it is
compared with respect to get the proper square wave.
4. The output of the comparator is required or receiver message which is
compare with the input message.

Expected Waveform:

m(t)
10Vp-p t

Message

c(t) t
5Vp-p
Carrier

PSK t
Output

ASK
Output t

Dept. of E C E, K I T, Tiptur
Demod Page 8
Output t
Communication lab-II/21ECL55

3. DIFFERENTIAL PHASE SHIFT KEYING (DPSK) MODULATION AND


DEMODULATION
Aim:
To study the various steps involved in generating differential phase shift
keyed signal at the modulator end and recovering the binary signal from the received
DPSK signal.
Apparatus:
1. Differential Phase Shift Keying Trainer
2. CRO
3. Connecting Wires

Theory:
DPSK may be viewed as the non-coherent version of PSK. It eliminates the
need for a coherent reference signal at the receiver by combining two basic
operations at the transmitter:
1. Differential encoding of the input binary wave and
2. Phase-Shift Keying hence, the name, differential phase shift keying (DPSK).

In effect to send symbol 0, we phase advance the current signal wave-form by 1800,
and to send symbol 1, we leave the phase of the current signal waveform unchanged.

Dept. of E C E, K I T, Tiptur
Page 9
Communication lab-II/21ECL55

The receiver is equipped with a storage capability, so that it can measure the relative
phase difference between the waveforms received during two successive bit intervals.
Provided that the unknown phase θ contained in the received wave varies slowly, the
phase difference between wave forms received in two successive bit intervals will be
independent of θ.
The block diagram of a DPSK transmitter is shown in fig.1 below. It consists, in part
of a logic network and a one-bit delay element interconnected so as to convert the
binary sequence {b k} into a differentially encoded sequence {d k}. This sequence is
amplitude level encoded and then used to modulate a carrier wave of frequency fc,
thereby producing the desired DPSK signal.
FIG (1)-BLOC DIAGRAM OF DPSK TRASMITTER

The optimum receiver for differentially coherent detection of binary DPSK is as shown in
fig.2 below. This implementation merely requires that sample values

be stored, thereby avoiding the need for delay lines that may be needed otherwise.
The equivalent receiver implementation that tests squared elements is more
complicated, but its use makes the analysis easier to handle in that the two signals to
be considered are orthogonal.

Dept. of E C E, K I T, Tiptur
Page 10
Communication lab-II/21ECL55

FIG(2) BLOCK DIAGRAM OF DPSK RECIVER


In DPSK modulation and demodulation, the IC8038 is a basic waveform generator
which generates sine, square, triangle waveforms. The sine wave generated by this
8038 IC is used as carrier signal to the system. The square wave generated by 8038
IC is at +/_ 12v level. So this is converted into a +5v
signal with the help of a tra sistor and diode. This square wave is used as a
clock input to a decade counter(IC 7490) which generates the modulating data outputs.

The differential signal to the modulating signal is generated using an exclusive- OR


gate and a 1-bit delay circuit.CD 4051 is an analog multiplexer to which carrier is
applied with and without 180 degrees phase shift(created by using an operational
amplifier connected in inverting amplifier mode) to the two inputs of the IC741.
Differential signal generated by EX-NOR gate (IC CD4077) is given to the
multiplexers control signal input. Depending upon the level of the control signal,
carrier signal applied with or without phase shift is steered to the output. One-bit
delay generation of differential signal to the input is created by using a D-flip-flop
(IC 7474).
During the demodulation, the DPSK signal is converted into a +5v square wave signal
using a transistor and is applied to one input of an EX-NOR gate. To the second input
of the gate, carrier signal is applied after conversion into a +5v signal. So the, EX-NOR
gate output is equivalent to the differential signal of the

Dept. of E C E, K I T, Tiptur
Page 11
Communication lab-II/21ECL55

modulating data. This differential data is applied to the one input of an Exclusive-
NOR gate and to the second input, after one-bit delay the same signal is given. So the
output of this EX-NOR gate is modulating signal.

Dept. of E C E, K I T, Tiptur
Page 12
Communication lab-II/21ECL55

Connection Diagram of DPSK Modulator and demodulator with EX-NOR


Differential encoder and decoder

Procedure:
1. Switch on MICRO LAB INSTRUMENTS PSK/DPSK Trainer kit.
2. Connect the carrier output of carrier SIN0 (TP3) and SIN180 (TP4) degree
to the PSK/DPSK modulator Block TP9 and TP7 respectively as show in
the connection diagram.
3. Connect the Data Bit output (TP14) to the Differential Encoder -1(EX-
NOR Logic) input at test point TP16.

4. Observe the Differential data output at the TP19 using CRO.


5. Connect the Differential Encoder -1 output (TP19) to the input of
PSK/DPSK modulator Block test point TP11.
6. Observe the DPSK signal at the test point TP13.
7. Connect the PSK/DPSK output (TP13) to the PSK/DPSK Demodulator
block test point TP24.

8. Observe the DPSK Demodulated output at Test point TP 27 using CRO.


9. The frequency of modulation data signal should be equal to the
demodulated O/P.

Dept. of E C E, K I T, Tiptur
Page 13
Communication lab-II/21ECL55

Expected Waveforms:

Dept. of E C E, K I T, Tiptur
Page 14
Communication lab-II/21ECL55

Result:
The operation of DPSK is observed and the output waveforms are verified.

Connection Diagram of DPSK Modulator and demodulator with EX-OR Differential


encoder and decoder

Procedure:
1. Switch on MICRO LAB INSTRUMENTS PSK/DPSK Trainer kit.
2. Connect the carrier output of carrier SIN0 (TP3) and SIN180 (TP4) degree to
the PSK/DPSK modulator Block TP9 and TP7 respectively as show in the
connection diagram.
3. Connect the Data Bit output (TP14) to the Differential Encoder -2(EX-OR
logic) input at test point TP20.
4. Observe the differential data with EX-OR logic at the output of the
Differential Encoder -2 at test point TP23.
5. Connect the Differential Encoder -2 output at Test point TP23 to Data
input (TP11) of PSK/DPSK Modulator block.
6. Observe the DPSK output at the test point TP13.
7. Connect the DPSK signal to PSK/DPSK Demodulator test point (TP23)
8. Observe DPSK demodulated data at the test point TP27.

Dept. of E C E, K I T, Tiptur
Page 15
Communication lab-II/21ECL55 II/21ECL55

Connection Diagram of PSK Modulator and demodulator

Procedure:
9. Switch on MICRO LAB INSTRUMENTS PSK/DPSK Trainer kit.
10. Connect the carrier output of carrier SIN0 (TP3) and SIN180 (TP4) degree to
the PSK/DPSK modulator Block TP9 and TP7 respectively as show in the
connection diagram.
11. Connect the serial data bit (TP14) to the Data input (TP11) of the
PSK/DPSK Modulator block.
12. Observe and sketch PSK output waveform at the test point TP13 using
CRO.
13. Connect the PSK modulated signal (TP13) to the PSK Demodulator/Phase
comparator test point TP24.
14. Observe the final PSK demodulated Output at the Test point TP27.

Dept. of E C E, K I T, Tiptur
Page 16
Communication lab-II/21ECL55 II/21ECL55

4 QUADRATURE PHASE SHIFT KEYING (QPSK)


MODULATIONAND DEMODULATION

Introduction
The purpose of analog modulation is to impress an information-bearing
analog waveform onto a carrier for transmission. The purpose of digital
modulation is to convert an information-bearing discrete-time symbol sequence
into a continuous-time waveform (perhaps impressed on a carrier).
Key concerns - bandwidth efficiency and implementation complexity.
These are affected by: baseband pulse shape
Phase transition characteristics envelope fluctuations (channel non-linearities)

Digital modulation is the process by which digital symbols are


transformed into waveforms that are compatible with the characteristics of the
channel.
Modulation can be used to minimize the effects of interference. Modulation can
also be used to place a signal in a frequency band where design requirements,
such as filtering and amplification, can be easily met. This is the case when
radio-frequency (RF) signals are converted to an intermediate frequency (IF) in
a receiver.

Theory
If we define four signals, each with a phase shift differing by 900 then we
have quadrature phase shift keying (QPSK).
The input binary bit stream {dk}, dk = 0,1,2, arrives at the modulator input at a rate
1/T bits/sec and is separated into two data streams dI(t) and dQ(t) containing
odd and even bits respectively.
dI(t) = d0, d2, d4 ,...
dQ(t) = d1, d3, d5 ,...

A convenient orthogonal realisation of a QPSK waveform , s(t) is achieved by

Dept. of E C E, K I T, Tiptur
Page 17
Communication lab-II/21ECL55 II/21ECL55
amplitude modulating the in-phase and quadrature data streams onto the square
carrier wave .
The pulse stream dI(t) modulates the carrier with an amplitude of  1.
This is equivalent to shifting the phase of the function by 0 or ;
consequently this
produces a BPSK waveform. Similarly the pulse stream dQ(t) modulates the 90 degree
shifted carrier function, yielding a BPSK waveform orthogonal to the first. The
summation of these two orthogonal waveforms is the QPSK waveform.
The values of (t) = 0, -(/2), /2,  represent the four possible combinations of
aI (t) and aQ (t).
Each of the four possible phases of carriers represents two bits of data.
Thus there are two bits per symbol. Since the symbol rate for QPSK is half the
bit rate, twice as much data can be carried in the same amount of channel
bandwidth as compared to BPSK. This is possible because the two signals I
and Q are orthogonal to each otherand can be transmitted without interfering
with each other.

In QPSK the carrier phase can change only once every 2T secs. If from
one T interval to the next one, neither bit stream changes sign, the carrier phase
remains unchanged. If one component aI(t) or aQ (t) changes sign, a phase
change of /2 occurs. However if both components change sign then a phase shift
of  occurs.
Figure below shows modulated wave

Constellation Diagram

Figure shows constellation diagram for QPSK with Gray coding. Each adjacent
symbol only differs by one bit.

Dept. of E C E, K I T, Tiptur
Page 18
Communication lab-II/21ECL55 II/21ECL55

Sometimes known as quaternary or quadriphase PSK or 4-PSK, QPSK


uses four points on the constellation diagram, equispaced around a circle. With
four phases, QPSK can encode two bits per symbol, shown in the diagram with
Gray coding to minimize the BER — twice the rate of BPSK. Analysis shows
that this may be used either to double the data rate compared to a BPSK system
while maintaining the bandwidth of the signal or to maintain the data-rate of
BPSK but halve the bandwidth needed.

Although QPSK can be viewed as a quaternary modulation, it is easier to


see it as two independently modulated quadrature carriers. With this
interpretation, the even (or odd) bits are used to modulate the in-phase
component of the carrier, while the odd (or even) bits are used to modulate the
quadrature-phase component of the carrier. BPSK is used on both carriers and

Dept. of E C E, K I T, Tiptur
Page 19
Communication lab-II/21ECL55 II/21ECL55

they can be independently demodulated.

As a result, the probability of bit-error for QPSK is the same as for BPSK:

However, with two bits per symbol, the symbol error rate is increased:

If the signal-to-noise ratio is high (as is necessary for practical QPSK systems) the
probability of symbol error may be approximated:

As with BPSK, there are phase ambiguity problems at the receiver and differentially
encoded QPSK is more normally used in practice.

Block Diagram of QPSK Systems.

Dept. of E C E, K I T, Tiptur
Page 20
Communication lab-II/21ECL55 II/21ECL55

Implementation:

QPSK Modulation
In QPSK modulation, the bit stream of the signal to be transmitted
(PCM signal) is previously sampled and decomposed into two binary waves
(dibits). Each pair of dibits is associated with one of four possible phases of
the QPSK modulation. The modulated signal is:
s(t) = Ikc(t) + Qk c(t- Where c(t) is Sine wave carrier

where I and Q are the in-phase and in-quadrature components of the


modulated signal. The signal's values (1 or −1) determine four points (or
symbols) in the QPSK signal space (or constellation). I and Q values are
assigned according to associated dibits combinations. The classical circuitry to
implement s(t) is based on the block diagram shown in Figure If I and Q take
their values from the set [1,−1], the constellation shows four points at phases

Dept. of E C E, K I T, Tiptur
Page 21
Communication lab-II/21ECL55 II/21ECL55
45º, 135º, 225º, and 315º. In this case, the QPSK also is called 4-QAM.

The realization of this circuit consists of rotating the angles of the


QPSK constellation 135º, by increasing the set of possible values of I and Q
components to [−1,0,1]. In this case, the table shows the modified phase
distribution.

MODIFIED CARRIER PHASES


Dibits PHASES
0 0 PHASE 0 Degree
0 1 PHASE 180 Degree
1 0 PHASE 90 Degree
1 1 PHASE 270 Degree

These phases are easily realizable with conventional logic circuitry


because the initial phase of 0º is the same as the carrier wave. The remaining
phases may be obtained from simple 90º consecutive phase shifts, avoiding the
mixers of Figure 1. This is shown in Figure2.

QPSK Demodulation

A demodulator that's suitable for the aforementioned QPSK modulator


generates four modified carrier phases (0°, 90°, 180°, and 270°) obtained in the
modulator by rotating the angles of the QPSK constellation. Then, a simple
XNOR operation between each phase and the modulated signal will produce a
logic "1" only if both coincide. If the received phase is 0° (related to dibit 00),
all XNORs produce a logic "0" .If the phase is 90° (dibit 10), only the upper
branch gives a "1". This situation is inverted for 270° (dibit 01). In this case,
the logic "1" is produced at the lower branch. But if the phase is 180° (dibit
11), a logic "1" is added to both branches. The result is the demodulated PCM
signal.

Dept. of E C E, K I T, Tiptur
Page 22
Communication lab-II/21ECL55 II/21ECL55

Connection Diagram of QPSK Modulation:

Connection Procedure:

1. Switch ON QPSK Trainer kit (DCT-006).


2. Observe the 8 bit Serial data out at (TP1 and TP2).
3. Connect the Serial Output Data (TP2) to Serial Data input (TP5).
4. Observe the carrier SIN0, SIN90, SIN180 and SIN270 in TP15,
TP13, TP17 and TP11 respectively.

Dept. of E C E, K I T, Tiptur
Page 23
Communication lab-II/21ECL55 II/21ECL55
5. Connect the SIN0 (TP15) to SIN0 of QPSK Modulator (TP18).
6. Connect the SIN90 (TP15) to SIN90 of QPSK Modulator (TP19).
7. Connect the SIN180 (TP15) to SIN180 of QPSK Modulator (TP20).
8. Connect the SIN270 (TP15) to SIN270 of QPSK Modulator (TP21).
9. Observe the Even and odd bits at the TP7 and TP9 respectively.
10. Connect the Even bit (TP7) to the EVEN (TP22) of QPSK Modulator.
11. Connect the Odd bit (TP9) to the Odd (TP23) of QPSK Modulator.
12. Observe and Sketch the QPSK Modulated output at test point
(TP25) using CRO.

Connection Diagram of QPSK Modulation:

Connection Procedure:

1. Connect the QPSK Modulated output (TP25) to the QPSK input (TP27).
2. Observe and sketch the SQUARRER-1 output at TP28.
3. Observe and sketch the SQUARRER-2 output at TP29.
4. Phase comparison using CD4033 phase comparator to get EVEN and
Odd Bit in TP30 and TP31 respectively.

Dept. of E C E, K I T, Tiptur
Page 24
Communication lab-II/21ECL55 II/21ECL55
5. To Combining the EVEN and Odd bits to get original Data bits at the
TP32

5 Write a program to encode binary data using Huffman code


and decode it. Using C
#include <stdio.h>
#include <string.h>
typedef struct node_t {
struct node_t *left, *right;
int freq;
char c;
} *node;

struct node_t pool[256] = {{0}};


node qqq[255], *q = qqq - 1;
int n_nodes = 0, qend = 1;
char *code[128] = {0}, buf[1024];

node new_node(int freq, char c, node a, node b)


{
node n = pool + n_nodes++;
if (freq) n->c = c, n->freq = freq;
else {
n->left = a, n->right = b;
n->freq = a->freq + b->freq;
}
return n;
}
/* priority queue */
void qinsert(node n)
{
int j, i = qend++;
while ((j = i / 2)) {

Dept. of E C E, K I T, Tiptur
Page 25
Communication lab-II/21ECL55 II/21ECL55
if (q[j]->freq <= n->freq) break;
q[i] = q[j], i = j;
}
q[i] = n;
}
node qremove()
{
int i, l;
node n = q[i = 1];
if (qend < 2) return 0;
qend--;
while ((l = i * 2) < qend) {
if (l + 1 < qend && q[l + 1]->freq < q[l]->freq) l++;
q[i] = q[l], i = l;
}
q[i] = q[qend];
return n;
}
/* walk the tree and put 0s and 1s */
void build_code(node n, char *s, int len)
{
static char *out = buf;
if (n->c) {
s[len] = 0;
strcpy(out, s);
code[n->c] = out;
out += len + 1;
return;
}
s[len] = '0'; build_code(n->left, s, len + 1);
s[len] = '1'; build_code(n->right, s, len + 1);
}
void init(const char *s)

Dept. of E C E, K I T, Tiptur
Page 26
Communication lab-II/21ECL55 II/21ECL55
{
int i, freq[128] = {0};
char c[16];
while (*s) freq[(int)*s++]++;
for (i = 0; i < 128; i++)
if (freq[i]) qinsert(new_node(freq[i], i, 0, 0));
while (qend > 2)
qinsert(new_node(0, 0, qremove(), qremove()));
build_code(q[1], c, 0);
}
void encode(const char *s, char *out)
{
while (*s) {
strcpy(out, code[*s]);
out += strlen(code[*s++]);
}
}
void decode(const char *s, node t)
{
node n = t;
while (*s) {
if (*s++ == '0') n = n->left;
else n = n->right;
if (n->c) putchar(n->c), n = t;
}
putchar('\n');
if (t != n) printf("garbage input\n");
}
int main(void)
{
int i;
const char *str = "this is an example for huffman encoding";
char buf[1024];

Dept. of E C E, K I T, Tiptur
Page 27
Communication lab-II/21ECL55 II/21ECL55
init(str);
for (i = 0; i < 128; i++)
if (code[i]) printf("'%c': %s\n", i, code[i]);
encode(str, buf);
printf("encoded: %s\n", buf);
printf("decoded: ");
decode(buf, q[1]);
return 0;
}
Output:
' ': 000
'a': 1000
'c': 01101
'd': 01100
'e': 0101
'f': 0010
'g': 010000
'h': 1101
'i': 0011
'l': 010001
'm': 1111
'n': 101
'o': 1110
'p': 10011
'r': 10010
's': 1100
't': 01111
'u': 01110
'x': 01001
encoded:
011111101001111000000011110000010001010000101010011000111110011010001010
100000101110100100001101011100010001011111000101000010110101101111001100
0011101010000

Dept. of E C E, K I T, Tiptur
Page 28
Communication lab-II/21ECL55 II/21ECL55
decoded: this is an example for huffman encoding

6. Write a program to encode binary data using a (7,4)


Hamming code and decode it
#include<stdio.h>
void main() {
int data[10];
int dataatrec[10],c,c1,c2,c3,i;
printf("Enter 4 bits of data one by one\n");
scanf("%d",&data[0]);
scanf("%d",&data[1]);
scanf("%d",&data[2]);
scanf("%d",&data[4]);
//Calculation of even parity
data[6]=data[0]^data[2]^data[4];
data[5]=data[0]^data[1]^data[4];
data[3]=data[0]^data[1]^data[2];
printf("\nEncoded data is\n");
for(i=0;i<7;i++)
printf("%d",data[i]);
printf("\n\nEnter received data bits one by one\n");
for(i=0;i<7;i++)
scanf("%d",&dataatrec[i]);
c1=dataatrec[6]^dataatrec[4]^dataatrec[2]^dataatrec[0];
c2=dataatrec[5]^dataatrec[4]^dataatrec[1]^dataatrec[0];
c3=dataatrec[3]^dataatrec[2]^dataatrec[1]^dataatrec[0];
c=c3*4+c2*2+c1 ;
if(c==0) {
printf("\nNo error while transmission of data\n");
}
else {

Dept. of E C E, K I T, Tiptur
Page 29
Communication lab-II/21ECL55 II/21ECL55
printf("\nError on position %d",c);

printf("\nData sent : ");


for(i=0;i<7;i++)
printf("%d",data[i]);
printf("\nData received : ");
for(i=0;i<7;i++)
printf("%d",dataatrec[i]);
printf("\nCorrect message is\n");
//if errorneous bit is 0 we complement it else vice versa
if(dataatrec[7-c]==0)
dataatrec[7-c]=1;
else
dataatrec[7-c]=0;
for (i=0;i<7;i++) {
printf("%d",dataatrec[i]);
}
}
}
Enter 4 bits of data one by one
1
0
1
0
Encoded data is
1010010
Enter received data bits one by one
1
0
1
0
0
1

Dept. of E C E, K I T, Tiptur
Page 30
Communication lab-II/21ECL55 II/21ECL55
0
No error while transmission of data

7. Write a program to encode binary data using a [(3, 1, 2)/suitably


designed) Convolution code and decode it.

#include <stdio.h>
// Function to perform convolutional encoding
void convolutionalEncode(int message[], int encoded[], int length) {
// Generator matrix for a (3, 1, 2) convolutional code
int generatorMatrix[2][3] = {
{1, 1, 0},
{1, 0, 1}
};

// Initialize encoded array


for (int i = 0; i < length * 2; i++) {
encoded[i] = 0;
}

// Perform convolutional encoding


for (int i = 0; i < length; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
encoded[i * 2 + j] ^= message[i + k] & generatorMatrix[j][k];
}
}
}
}

int main() {

Dept. of E C E, K I T, Tiptur
Page 31
Communication lab-II/21ECL55 II/21ECL55
// Input message (binary)
int message[] = {1, 0, 1, 0, 1, 1}; // Change this as needed
int length = sizeof(message) / sizeof(message[0]);

// Calculate the size of the encoded array


int encodedLength = length * 2;

// Array to store the encoded message


int encoded[encodedLength];

// Perform convolutional encoding


convolutionalEncode(message, encoded, length);

// Display the original message


printf("Original Message: ");
for (int i = 0; i < length; i++) {
printf("%d ", message[i]);
}
printf("\n");

// Display the encoded message


printf("Encoded Message: ");
for (int i = 0; i < encodedLength; i++) {
printf("%d ", encoded[i]);
}
printf("\n");

return 0;
}

Dept. of E C E, K I T, Tiptur
Page 32
Communication lab-II/21ECL55 II/21ECL55

8. For a given data, use CRC-CCITT polynomial to obtain the


CRC code. Verify the program for the
cases a) Without error b) With error
#include<stdio.h>
#include<conio.h>
void crc(int om, int og, int tm[50], int gp[50], int gc[50], int g[50])
{
int i,j,k;
for(i=0;i<=om+og;i++)
{
if(g[og]==1)
gc[og-1]=tm[i]^gp[0];
else
gc[og-1]=tm[i];
for(j=og-1;j>=0;j--)
{
if(g[j]==1)
gc[j-1]=gp[j]^gp[0];
else
gc[j-1]=gp[j];
}
printf("\n");
for(k=0;k<=og-1;k++)
{
gp[k]=gc[k];
printf("%d",gc[k]);
}
}
}

Dept. of E C E, K I T, Tiptur
Page 33
Communication lab-II/21ECL55 II/21ECL55
main()
{
int i, flag=0, m[50],om,g[50],og,tm[50],rm[50],gp[50],gc[50];
for(i=0;i<=50;i++)
{
tm[i]=0;
gp[i]=0;
}
clrscr();
printf("\n enter the order of generator");
scanf("%d",&og);
printf("enter the generator");
for(i=0;i<=og;i++)
scanf("%d",&g[i]);
printf("\n enter the order of the message");
scanf("%d",&om);
printf("\n enter the message sequences");
for(i=0;i<=om;i++)
scanf("%d",&tm[i]);
crc(om,og,tm,gp,gc,g);
printf("\n the crc code for given generator and message is");
for(i=0;i<=og-1;i++)
printf("%d",gc[i]);
for(i=1;i<=og;i++)
tm[om+i]=gc[i-1];
printf("\n the transmitted message sequence is :");
for(i=0;i<=om+og;i++)
{
printf("%d",tm[i]);
}
printf("\n\n enter the received message:");
for(i=0;i<=om+og;i++)
scanf("%d",&rm[i]);

Dept. of E C E, K I T, Tiptur
Page 34
Communication lab-II/21ECL55 II/21ECL55
for(i=0;i<=og;i++)
gp[i]=0;
crc(om,og,rm,gp,gc,g);
for(i=0;i<=og-1;i++)
{
if((gc[i])!=0)
flag=1;
}
if(flag==1)
printf("\n error in the received message");
else
printf("\n no error in the received message");
getch();
}

Dept. of E C E, K I T, Tiptur
Page 35
Communication lab-II/21ECL55 II/21ECL55

9 Write a program for congestion control using leaky bucket


algorithm.

#include<stdio.h>
#include<conio.h>
#include<time.h>
void main()
{
int a[5],buck_rem=0, buck_cap=0, rate=0,i,sent,recv;
clrscr();
printf("\n enter th bucket capacity\n");
scanf("%d",&buck_cap);
printf("enterthe rate of transmission\n");
scanf("%d",&rate);
srand(time(NULL));

Dept. of E C E, K I T, Tiptur
Page 36
Communication lab-II/21ECL55 II/21ECL55
for(i=0;i<5;i++)
a[i]=rand()%80+1;
printf("clock pkt_size received sent remaining\n");
for(i=0;i<5;i++)
{
if((buck_rem+a[i])>buck_cap)
recv=-1;
else
{
recv=a[i];
buck_rem=buck_rem+a[i];
}
if(buck_rem!=0)
{
sleep(1);
if(buck_rem<rate)
{
sent=buck_rem;
buck_rem=0;
}
else
{
sent=rate;
buck_rem=buck_rem-rate;
}
}
else
sent=0;
if(recv==1)
printf("\n%d\t%d\t%d\t%d\t%d\t\n",i,a[i],sent,buck_rem);
else
printf("\n%d\t%d\t%d\t%d\t%d\n",i,a[i],recv,sent,buck_rem);
}

Dept. of E C E, K I T, Tiptur
Page 37
Communication lab-II/21ECL55 II/21ECL55
getch();
}

10 Write a program for distance vector algorithm to find


suitable path for transmission
#include<stdio.h>
#include<conio.h>
void dij(int n, int cost[][30], int d[], int s1[])
{
int i,j,v,min,u;
for(i=1;i<=n-1;i++)
{
min=999;
for(j=1;j<=n;j++)
{
if(s1[j]==0)
{ if(d[j]<min)
min=d[j];
u=j;
}
}
}
s1[u]=1;
for(v=1;v<=n;v++)
{
if (s1[v]==0)
d[v]=MIN(d[v],d[u]+cost[u][v]);
}
}

void main()
{

Dept. of E C E, K I T, Tiptur
Page 38
Communication lab-II/21ECL55 II/21ECL55
int i,j,s,n,d[30],s1[30],cost[30][30];
clrscr();
printf("\n enter the no of nodes");
scanf("%d",&n);
printf("\n enter the cost of adj matrix");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i!=j)
{
printf("\n(%d,%d)",i,j);
scanf("%d",&cost[i][j]);
}
} }
printf("enter the source\n");
scanf("%d",&s);
for(i=1;i<=n;i++)
{
d[i]=cost[s][i];
s1[i]=0;
}
s1[s]=1;
dij(n,cost,d,s1);
printf("\n the dist from %d to all other nodes\n",s);
for(i=1;i<=n;i++)
{
if(i!=s)
printf("%d-->%d=%d\n",s,i,d[i]);
}
}
int MIN(int a,int b)
{

Dept. of E C E, K I T, Tiptur
Page 39
Communication lab-II/21ECL55 II/21ECL55
return(a<b)?a:b;
}

11 Write a program for flow control using sliding window


protocols.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int temp1, temp2, temp3, temp4, i, winsize=8, noframes=12, moreframes;
char c;
int receiver(int);
int simulate(int);
clrscr();
temp1=0,temp2=0,temp3=0, temp4=0;
printf("\n number of frames is %d\t",noframes);
getch();
moreframes=noframes;
while(moreframes>=0)
{
temp1=simulate(winsize);
winsize=temp1;
temp4+=temp1;
if(temp4>noframes)
temp4=noframes;
for(i=temp3+1;i<=temp4;i++)
printf("\n sending frame %d",i);
getch();
temp2=receiver(temp1);
temp3+=temp2;

Dept. of E C E, K I T, Tiptur
Page 40
Communication lab-II/21ECL55 II/21ECL55
if(temp3>noframes)
temp3=noframes;
printf("\n ack for the frames upto %d",temp3);
getch();
moreframes=temp2;
temp4=temp3;
if(winsize<=0)
winsize=8;
}
printf("\n end of sliding window protocol");
getch();
}
int receiver(int temp1)
{
int i;
for(i=1;i<100;i++)
rand();
i=rand()%temp1;
return i;
}
int simulate(int winsize)
{
int temp1,i;
for(i=1;i<50;i++)

temp1=rand();
if(temp1==0)
{
temp1=simulate(winsize);
i=temp1%winsize;
return winsize;
}
else

Dept. of E C E, K I T, Tiptur
Page 41
Communication lab-II/21ECL55 II/21ECL55
return temp1%winsize;
}

12 Configure a simple network (Bus/star) topology using


simulation software.

Creating a program to configure a simple network with bus/star topology in C requires


some basic knowledge of socket programming. In this example, a basic C program to
simulate a network with a central server (star topology) and multiple clients (bus
topology) that communicates with the server. This program uses sockets to establish
communication between clients and the server.

Please note that this is a simplified example for educational purposes and does not
represent a real-world network configuration. Also, you'll need to compile and run this
program on a Unix-like system.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define SERVER_PORT 12345


#define MAX_CLIENTS 10

void handle_client(int client_socket) {


char buffer[256];
ssize_t bytes_received;

while (1) {
memset(buffer, 0, sizeof(buffer));

Dept. of E C E, K I T, Tiptur
Page 42
Communication lab-II/21ECL55 II/21ECL55
bytes_received = recv(client_socket, buffer, sizeof(buffer), 0);
if (bytes_received <= 0) {
printf("Client disconnected.\n");
break;
}
printf("Received from client: %s", buffer);

// Echo back to the client


send(client_socket, buffer, strlen(buffer), 0);
}

close(client_socket);
}

int main() {
int server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_len = sizeof(client_addr);

// Create socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
perror("Error creating socket");
exit(1);
}

// Configure server address


server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;

Dept. of E C E, K I T, Tiptur
Page 43
Communication lab-II/21ECL55 II/21ECL55

// Bind socket to address


if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("Error binding socket");
exit(1);
}

// Listen for incoming connections


if (listen(server_socket, MAX_CLIENTS) == -1) {
perror("Error listening for connections");
exit(1);
}

printf("Server is listening on port %d...\n", SERVER_PORT);

while (1) {
// Accept incoming connection
client_socket = accept(server_socket, (struct sockaddr*)&client_addr,
&client_addr_len);
if (client_socket == -1) {
perror("Error accepting connection");
continue;
}

printf("Client connected from %s:%d\n", inet_ntoa(client_addr.sin_addr),


ntohs(client_addr.sin_port));

// Handle client communication in a separate thread or process (not shown in this


example)
handle_client(client_socket);
}
Dept. of E C E, K I T, Tiptur
Page 44
Communication lab-II/21ECL55 II/21ECL55

close(server_socket);

return 0;
}

This program creates a simple server that listens on a specified port (SERVER_PORT)
for incoming client connections. Clients can connect to the server, send messages, and
receive responses. The server uses a loop to accept multiple client connections.
Compile the program using a C compiler (e.g., gcc) and run it on your Unix-like system.
You can simulate the bus topology by running multiple client instances that connect to
the same server.
Result:

Dept. of E C E, K I T, Tiptur
Page 45
Communication lab-II/21ECL55 II/21ECL55

Demonstration Experiments [For CIE]

13 Configure and simulate wireless local area network

Introduction to ns2- Network Simulator


Network Simulator (Version 2), widely known as NS2, is simply an event-driven
simulation tool that has proved useful in studying the dynamic nature of
communication networks.

Simulation of wired as well as wireless network functions and protocols (e.g.,


routing algorithms, TCP, UDP) can be done using NS2.

In general, NS2 provides users with a way of specifying such network protocols
and simulating their corresponding behaviors.

Basic Architecture of NS2

NS2 provides users with an executable command “ns” which takes one input
argument, the name of a Tcl simulation scripting file. In most cases, a simulation
trace file is created and is used to plot graph and/or to create animation.

Dept. of E C E, K I T, Tiptur
Page 46
Communication lab-II/21ECL55 II/21ECL55
NS2 consists of two key languages: C++ and Object-oriented Tool Command
Language (OTcl). While the C++ defines the internal mechanism (i.e., a backend)
of the simulation.

The OTcl sets up simulation by assembling and configuring the objects as well as
scheduling discrete events (i.e., a frontend). The C++ and the OTcl are linked
together using TclCL.

After simulation, NS2 outputs either text-based simulation results. To interpret


these results graphically and interactively, tools such as NAM (Network
AniMator) and XGraph are used.

To analyze a particular behavior of the network, users can extract a relevant


subset of text-based data and transform it to a more conceivable presentation.

NS Simulator Preliminaries

⮚ Initialization and termination aspects of ns simulator.

⮚ Definition of network nodes, links, queues, and topology.

⮚ Definition of agents and applications.

⮚ The nam visualization tool

⮚ Tracing and random variable.

Initialization and termination of TCL script in Ns2

 As the first step, we create the simulator object.

# create a simulator object


Dept. of E C E, K I T, Tiptur
Page 47
Communication lab-II/21ECL55 II/21ECL55
set ns [new Simulator]

 Define the trace files, and place monitors at places in the topology to
collect information about packets flows. NS2 supports two primary
monitoring capabilities: traces and monitors. The traces enable recording
of packets whenever an event such as packet drop or arrival occurs in a
queue or a link. The monitors provide a means for collecting quantities,
such as number of packet drops or number of arrived packets in the queue.
The monitor can be used to collect these quantities for all packets or just
for a specified flow (a flow monitor).

# open the nam trace file


set nam_trace_fd [open tcp_tahoe.nam w]
$ns namtrace-all
$nam_trace_fd
set trace_fd
[open
tcp_tahoe.tr w]

"w" means write i.e the file


tcp_tahoe.tr is opened for writing. "r"
means reading and "a" means
appending

 Set up the network topology by creating node objects, and connecting the
nodes with link objects. If the output queue of a router is implemented as a
part of a link, we need to specify the queue type. In this project, DropTail
queue is used. In some cases, we may define the layout of the network
topology for better NAM display.

# create four nodes


set node1 [$ns node]
set node2 [$ns node]
set node3 [$ns node]
Dept. of E C E, K I T, Tiptur
Page 48
Communication lab-II/21ECL55 II/21ECL55
set node4 [$ns node]

# create links between the nodes


$ns duplex-link $node1 $node3 2Mb 20ms DropTail
$ns duplex-link $node2 $node3 2Mb 20ms DropTail
$ns duplex-link $node3 $node4 1Mb 20ms DropTail
$ns queue-limit $node3 $node4 1Mb 20ms DropTail

# set the display layout of nodes and links for nam


$ns duplex-link-op $node1 $node3 orient right down
$ns duplex-link-op $node2 $node3 orient right-up
$ns duplex-link-op $node3 $node4 orient right

# define different colors for nam data flows


$ns color 0 Green
$ns color 1 Blue
$ns color 2 Red
$ns color 3 Yellow

# monitor the queue for the link between node 2 and node 3
$ns duplex-link-op $node3 $node4 queuePos 0.5

Define traffic patterns by creating agents, applications and flows. In NS2, packets are
always sent from one agent to another agent or a group of agents. In addition, we need
to associate these agents with nodes.

# TCP traffic source


# create a TCP agent and attach it to node node1
set tcp [new Agent/TCP]
$ns attach-agent $node1 $tcp
$tcp set fid_ 1

Dept. of E C E, K I T, Tiptur
Page 49
Communication lab-II/21ECL55 II/21ECL55
$tcp set class_ 1

# window_ * (packetsize_ + 40) / RTT


$tcp set window_ 30
$tcp set packetSize_ $packetSize

# create a TCP sink agent and attach it to node node4


set sink [new Agent/TCPSink]
$ns attach-agent $node4 $sink

# connect both agents


$ns connect $tcp $sink

# create an FTP source "application"


set ftp [new Application/FTP]
$ftp attach-agent $tcp

# UDP traffic source


# create a UDP agent and attach it to node 2
set udp [new Agent/UDP]
$udp set fid_ 2 # red color
$ns attach-agent $node2 $udp

# create a CBR traffic source and attach it to udp


set cbr [new Application/Traffic/CBR]
$cbr set packetSize_ $packetSize
$cbr set rate_ 0.25Mb
$cbr set random_ false
$cbr attach-agent $udp

# creat a Null agent (a traffic sink) and attach it to node 4


set null [new Agent/Null]
$ns attach-agent $node4 $null

Dept. of E C E, K I T, Tiptur
Page 50
Communication lab-II/21ECL55 II/21ECL55
$ns connect $udp $null

# Define a 'finish' procedure


proc finish {} {
global ns nam_trace_fd trace_fd

# close the nam trace file


$ns flush-trace
close $nam_trace_fd

In here the trace data is flushed into the file by using command $ns flush-trace and
then file is closed.
# execute nam on the trace file
exec nam tcp_tahoe.nam & exit 0
}

 Schedule the simulation by defining the start and stop of the simulation, traffic flows,
tracing, and other events.

# schedule events for all the flows


$ns at 0.25 "$ftp start"
$ns at 0.25 "$cbr start"
$ns at 5.0 "$cbr stop"
$ns at 5.0 "$ftp stop"

# call the finish procedure after 6 seconds of simulation time


$ns at 6 "finish"
# run the simulation
$ns run

Finally we need to extract useful data from the traces, as you just did using Awk
commands, and feed it to plotting software to get human readable results. In the
individual tasks below, each task is prefaced with the name of the files you should

Dept. of E C E, K I T, Tiptur
Page 51
Communication lab-II/21ECL55 II/21ECL55
hand in with respect to that subtask.

Structure of Trace File:

● Events in Queues can be recorded in a trace file.

● Statistical information (such as throughput on a link/queue) can be computed


using the trace data.

Snap shot of a generated trace file for wired network:

There are 12 fields and we can explain it as;

1. EVENT OR TYPE IDENTIFIER: Each trace line starts with an event


(+, -, d, r) descriptor followed of that event

Dept. of E C E, K I T, Tiptur
Page 52
Communication lab-II/21ECL55 II/21ECL55
+: a packet enque event
- : a packet
deque event
r: a packet
reception
event
d: a packet drop (e.g., sent to
dropHead_) event c: a packet
collision at the MAC level

2. TIME: At which the packet tracing string is created, i.e., by the


simulation time (in seconds)

3-4. SOURCE AND DESTINATION NODE: source and destination ID's


of tracing objects. i.e., from and to node, this identifies the link on which the
event occurred.

5. ACKET NAME: Name of the packet type.

6. PACKET SIZE:
The next information in the line before flags (appeared as " " since no flag is
set) is
packet type and size (in Bytes). Currently, NS implements only the
Explicit Congestion Notification (ECN) bit and the remaining bits are
not used

7. FLAGS: 7 digit flag string. “-”:


disable
1st = “E”: ECN (Explicit Congestion Notification) echo is
enabled.
2nd = “P”: the priority in the IP header is enabled.
3rd: Not in use
4th = “A”: Congestion action

Dept. of E C E, K I T, Tiptur
Page 53
Communication lab-II/21ECL55 II/21ECL55
5th = “E”: Congestion has occurred.
6th = “F”: The TCP fast start is used.
7th = “N”: Explicit Congestion Notification (ECN) is on.
8. FLOW ID: This field is flow id (fid) of IPv6 that a user can
set for each flow at the input OTcl script. Even though fid field may not
use in a simulation, users can use this field for analysis purposes. The
fid field is also used when specifying stream color for the NAM
display.

9-10. SOURCE AND DESTINATION ADDRESS: The next two


fields are source and destination address in forms of "node.port".

11. SEQUENCE NUMBER: This field shows the network layer


protocol's packet sequence number. Note that even though UDP
implementations do not use sequence number, NS keeps track of UDP
packet sequence number for analysis purposes

12. PACKET UNIQUE ID: This field shows the unique id of the packet.

TRACE FILE DESCRIPTION


Following list shows the trace file variables and its
explanations; s – s-send packet
r - received packet
d - packet dropped
f - packet forwarded
c - collision of packet at MAC level
t - time at which
packet tracing started
Hs - ID of the hop
Hd - ID of the next hop
towards destination Ni -
Node ID
Nx,Ny,Nz - Co ordinates that the
Dept. of E C E, K I T, Tiptur
Page 54
Communication lab-II/21ECL55 II/21ECL55
nodes situated Ne - Node energy
level
Nl - Trace level
Nw - Reason of the
event
AGT - Agent
RTR -Routing
END - DROP End of Simulation

Dept. of E C E, K I T, Tiptur
Page 55
Communication lab-II/21ECL55 II/21ECL55

COL - DROP MAC


COLLISION DUP - DROP
MAC DUPLICATE
DERR - DROP MAC PACKET ERROR
RET - DROP MAC RETRY COUNT
EXCEED STA - DROP MAC INVALID
STATE
BSY - DROP MAC BUSY
NRTE - DROP RTR - NO
ROUTE LOOP - DROP RTR
ROUTE LOOP
TTL - DROP RTR TTL has reached
Zero TOUT - DROP-RTR-QTIME
OUT Expired
IS - SOURCE ADDRESS OF SOURCE PORT
ID - DESTINATION ADDRESS OF DESTINATION
PORT IL - PACKET SIZE
IF -
FLOW ID
II -
UNIQUE
ID
IV - TTL VALUE NEXT HOP INTO

MAC LAYER INFORMATION


Ma - MAC Layer duration
Md - Destination. Ethernet
Address Ms - Source Ethernet
Address
Mt - Ethernet Type

Dept. of E C E, K I T, Tiptur
Page 56
Communication lab-II/21ECL55 II/21ECL55

PACKET INFORMATION
-P arp - address resolution protocol-Po - ARP Request /
Reply Pm - Source MAC Address
Ps - Source Address
Pa - Destination MAC
Address Pd - Destination
Address
Pn - Nodes
Transversed Pq -
Flag
Pi - Route Request Sequence Number/ Sequence
Number Pp - Flag
Pl - Reply Length
Pe - src of source
routing Pw - Error
Report Flag Pc -
Report to whom
Pb - Link error from link a to link b
-P cbr - CBR data
Pf - How many level packet
leave Po - Optimal Number
of Forward
-P TCP - TCP flow
-Ps - seq. number
Pu - acknowledgement
Pf - Packet
Failure

XGRAPH:
The xgraph program draws a graph on an X display given data read from either data files

Dept. of E C E, K I T, Tiptur
Page 57
Communication lab-II/21ECL55 II/21ECL55
or from standard input if no files are specified. xgraph in ns2 is used to plot the network
parameter characteristics like throughput, delay, jitter, latency etc.

Syntax: xgraph [options] file-name


exec xgraph filename_pdr.tr -geometry 800x800 # for single parameter
exec xgraph filename_throughput.tr -geometry 800x800 &
exec xgraph filename_delay.tr -geometry 800x800 & # for more than one parameters

The following commands can be used to improve the appearance of xgraph .

 -geometry WxH+X+Y or /=WxH+X+Y (Geometry)

Specifies the initial size and location of the xgraph window.

 -bar (BarGraph)

Specifies that vertical bars should be drawn from the data points to a base point which can
be specified with -brb. Usually, the -nl flag is used with this option. The point itself is
located at the center of the bar.

Dept. of E C E, K I T, Tiptur
Page 58
Communication lab-II/21ECL55 II/21ECL55

 -fitx

Translate and scale the x data from all datasets to fit [0 . . . 1].

 -fity

Translate and scale the y data from all datasets to fit [0 . . . 1].

 -fmtx <printf-format> -fmty <printf-format>

Use the format specified to generate the legends for the x or y axis.

 -bd <color> (Border)

This specifies the border color of the xgraph window.

 -bg <color> (Background)

Background color of the xgraph window.

 -fg <color> (Foreground)

Foreground color. This color is used to draw all text and the normal grid lines in the
window.

 -t <string> (TitleText)

Title of the plot. This string is centered at the top of the graph.

 -tf <fontname> (TitleFont)

Dept. of E C E, K I T, Tiptur
Page 59
Communication lab-II/21ECL55 II/21ECL55
Title font. This is the name of the font to use for the graph title. A font name may be
specified exactly (e.g.”9x15” or”-*-courier-bold-r-normal-*-140-*”). The family is the
family name (like helvetica) and the size is the font size in points (like 12). The default for
this parameter is”helvetica-18”.

 -x <unitname> (XUnitText)

This is the unit name for the X axis. Its default is”X”.

 -y <unitname> (YUnitText)

This is the unit name for the Y axis. Its default is”Y”.

Syntax: exec xgraph filename.tr -geometry 800x400 & -bar -fitx -fity -bb -bg white

AWK- an advanced: AWK is a high level programming language which is used to


process text files, named after its three original author's name:

A: Alfred Aho
W:
Peter
Weinb
erger
K:
Brian
Kernig
han

 AWK is a programmable, pattern matching and processing tool.

 AWK is not just a command but a programming tool too.

Dept. of E C E, K I T, Tiptur
Page 60
Communication lab-II/21ECL55 II/21ECL55

 AWK Scripts are very good in processing the data from the log (trace files)

which we get from NS2.

AWK PROGRAM STRUCTURE


Awk program structure contains mainly three parts;
1. Begin
2. Content
3. End

BEGIN {<initialization>}
<pattern1> {<actionSet1>}
<pattern2> {<actionSet2>}
...
END {<final finalActionSet>}

BEGIN: Begin deals with what to be executed prior to text file processing,
normally which is used to initialize variable values or constants.

CONTENT: Script which process the text file. In this part, AWK moves lines by
lines (i.e., records by records) and executes the <actionSet> if the current line
matches with the pattern. The actions repeat until AWK reaches the end of the file.

END: This part explains what to be executed after the text file processing i.e.
What to print on the terminal or to show output in terminal.

EXECUTION
Awk has two types of execution;
1) Plain Execution.
2) Match and Execute.

Plain Execution: Simply AWK statements.

Dept. of E C E, K I T, Tiptur
Page 61
Communication lab-II/21ECL55 II/21ECL55
Match and execute: The second type of execution is “Match and Execute”, when
executes plain execution statements only if the current line (of the input text file)
matches with a predefined pattern.

The pattern can be either:

1. Logical Expression

2. Regular Expression.

TRACE FILE AND AWK SCRIPT


Here is a sample of trace file from NS2,
AWK Scripts are very good in processing the data column wise. For example the
first column in the above trace file represents r, s which indicates receive, sent
respectively. If we want to trace the entire r and s alone from this trace file we can
represent it as $1
So
$1: Action (r, s, d, f, +, -)
$2 Time
$3 Time value
$4 node id
$5 node id value
$6 id of next hop
$7 next hop id value
..
To run awk script, we have to use terminal window we have to run the awk script
using command;

awk -f <awk file name> <trace


file name> awk -f file
name.awk file name.tr
The ‘-f’ instructs the awk utility to get the awk program from the source file i.e. from
.awk file. After entering command you will get values.
Dept. of E C E, K I T, Tiptur
Page 62
Communication lab-II/21ECL55 II/21ECL55
Other Commands used in terminals:

 mkdir folder_name (To make directory)

 cd folder_name (To change to the specified directory)

 gedit file_name.tcl (To open the TCL file)

 gedit file_name.tr (To open the Trace file)

 ns file_name.tcl (To run the TCL file)

 gedit file_name.awk (To open the AWK file)

 awk –f file_name.awk file_name.tr (To run AWK file)

To run awk for Xgraph:

 awk –f file name.awk file1.tr>a1(give enter)

 awk –f file name.awk file2.tr>a2(give enter)

 xgraph a1 a2 (enter)

Program:
set ns [new Simulator]
set tf [open lab8.tr w]
$ns trace-all $tf
set topo [new Topography]
$topo load_flatgrid 1000 1000 set
nf [open lab8.nam w]
$ns namtrace-all-wireless $nf 1000 1000
$ns node-config -adhocRouting DSDV \
-llType LL \
-macType Mac/802_11 \

Dept. of E C E, K I T, Tiptur
Page 63
Communication lab-II/21ECL55 II/21ECL55
-ifqType Queue/DropTail \
-ifqLen 50 \
-phyType Phy/WirelessPhy \
-channelType Channel/WirelessChannel \
-propType Propagation/TwoRayGround \
-antType Antenna/OmniAntenna \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON
create-god 3
set n0 [$ns node] set
n1 [$ns node] set n2
[$ns node]

$n0 label "tcp0"


$n1 label "sink1/tcp1"
$n2 label "sink2"

$n0 set X_ 50
$n0 set Y_ 50
$n0 set Z_ 0
$n1 set X_ 100
$n1 set Y_ 100
$n1 set Z_ 0
$n2 set X_ 600
$n2 set Y_ 600
$n2 set Z_ 0

$ns at 0.1 "$n0 setdest 50 50 15"


$ns at 0.1 "$n1 setdest 100 100 25"

Dept. of E C E, K I T, Tiptur
Page 64
Communication lab-II/21ECL55 II/21ECL55
$ns at 0.1 "$n2 setdest 600 600 25" set tcp0
[new Agent/TCP]
$ns attach-agent $n0 $tcp0 set ftp0
[new Application/FTP]
$ftp0 attach-agent $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n1 $sink1
$ns connect $tcp0 $sink1 set
tcp1 [new Agent/TCP]
$ns attach-agent $n1 $tcp1 set ftp1
[new Application/FTP]
$ftp1 attach-agent $tcp1

set sink2 [new Agent/TCPSink]


$ns attach-agent $n2 $sink2
$ns connect $tcp1 $sink2
$ns at 5 "$ftp0 start"
$ns at 5 "$ftp1 start"
$ns at 100 "$n1 setdest 550 550 15"
$ns at 190 "$n1 setdest 70 70 15" proc
finish { } {
global ns nf tf
$ns flush-trace exec nam
lab8.nam & close $tf
exit 0
}
$ns at 250 "finish"
$ns run
Results:

Dept. of E C E, K I T, Tiptur
Page 65
Communication lab-II/21ECL55 II/21ECL55

14 Simulate the BER performance of (2, 1, 3) binary


convolutional code with generator sequences g(1) =(1 0 1 1) and
g(2) =(1 1 1 1) on AWGN channel. Use QPSK modulation
scheme. Channel decoding is to be performed through Viterbi
decoding. Plot the bit error rate versus SNR (dB), i.e. Pe,b
versus Eb/N0. Consider binary input vector of size 3 lakh bits.
Also find the coding gain.

// Parameters
SNR_dB_range = 0:10; // SNR values in dB
num_bits = 300000; // Number of bits to transmit
code_rate = 1/2; // Code rate (2, 1, 3) convolutional code

Dept. of E C E, K I T, Tiptur
Page 66
Communication lab-II/21ECL55 II/21ECL55
k = 2; // Number of bits per symbol in QPSK modulation
n = 2; // Constraint length of the convolutional code

// Generator sequences
g1 = [1 0 1 1];
g2 = [1 1 1 1];

// QPSK modulation
M = 4; // Number of constellation points
constellation = exp(%i * (%pi/4) * [1 3 5 7]);

// Eb/N0 in linear scale


SNR_linear = 10.^(SNR_dB_range / 10);

// Initialize BER array


BER = zeros(1, length(SNR_dB_range));

for i = 1:length(SNR_dB_range)
snr_linear = SNR_linear(i);

// Generate random binary data


input_bits = rand(1, num_bits, 'bin');

// Encode the data using the convolutional code


encoded_bits = [];
state = zeros(1, n); // Initialize the shift register
for bit = input_bits
u = [bit state(1)];
state = circshift(state, [0 -1]);
state(n) = mod(g1 * u', 2);

Dept. of E C E, K I T, Tiptur
Page 67
Communication lab-II/21ECL55 II/21ECL55
encoded_bits = [encoded_bits state(n) u(1)];
end

// Modulate the encoded bits using QPSK


modulated_symbols = constellation(encoded_bits * (2^(k-1)) + 1);

// Add AWGN noise


noise_real = grand(1, num_bits/k, "nor", 0, 1/sqrt(2*snr_linear));
noise_imag = grand(1, num_bits/k, "nor", 0, 1/sqrt(2*snr_linear));
received_symbols = modulated_symbols + noise_real + %i * noise_imag;

// Demodulate the received symbols


[~, demodulated_bits] = min(abs(received_symbols' - constellation), [], 2);
demodulated_bits = demodulated_bits - 1;

decoded_bits = [];

// Viterbi decoding
traceback_length = n - 1; // Length of traceback buffer for the Viterbi decoder
path_metrics = zeros(1, M^traceback_length);
survivor_paths = zeros(M^traceback_length, traceback_length);

for symbol = demodulated_bits


new_path_metrics = zeros(1, M^traceback_length);
new_survivor_paths = zeros(M^traceback_length, traceback_length);

for survivor_state = 0:M^traceback_length - 1


survivor_state_bits = dec2base(survivor_state, M, traceback_length) - '0';
for input_bit = 0:M - 1
new_state = circshift(survivor_state_bits, [0 -1]);

Dept. of E C E, K I T, Tiptur
Page 68
Communication lab-II/21ECL55 II/21ECL55
new_state(traceback_length) = input_bit;
transition = bin2dec(mat2str(new_state, 0)) + 1;
new_path_metrics(transition) = path_metrics(survivor_state + 1) +
abs(received_symbols(symbol + 1) - constellation(input_bit + 1))^2;
new_survivor_paths(transition, :) = new_state;
end
end

path_metrics = new_path_metrics;
survivor_paths = new_survivor_paths;
end
// Traceback to find the decoded bits
best_path = find(path_metrics == min(path_metrics));
best_path = best_path(1) - 1;
state_bits = dec2base(best_path, M, traceback_length) - '0';
for j = 1:traceback_length
input_bit = state_bits(traceback_length);
decoded_bits = [decoded_bits input_bit];
best_path = best_path >> 1;
state_bits = circshift(state_bits, [0 -1]);
state_bits(traceback_length) = input_bit;
end

// Calculate BER
bit_errors = sum(decoded_bits ~= input_bits);
BER(i) = bit_errors / num_bits;
end

// Calculate coding gain


SNR_dB_coding_gain = -10 * log10(BER);

Dept. of E C E, K I T, Tiptur
Page 69
Communication lab-II/21ECL55 II/21ECL55

// Plot BER vs. Eb/N0


clf;
semilogy(SNR_dB_range, BER, '*-');
xlabel('Eb/N0 (dB)');
ylabel('Bit Error Rate (BER)');
grid on;
title('(2, 1, 3) Convolutional Code BER Performance');
xtitle('SNR (dB)', 'BER');
show_window();

// Print coding gain


coding_gain = SNR_dB_coding_gain(1) - SNR_dB_range(1);
disp('Coding Gain (dB):');
disp(coding_gain);

Result:

15. To simulate the Bit Error Rate (BER) performance of a (7, 4)


Hamming code using QPSK modulation and maximum-likelihood
decoding on an AWGN channel in SCILAB, you can follow this
code. Make sure you have SCILAB installed on your system.

```scilab
// Parameters
SNR_dB_range = 0:10; // SNR values in dB
num_bits = 500000; // Number of bits to transmit
k = 4; // Number of information bits

Dept. of E C E, K I T, Tiptur
Page 70
Communication lab-II/21ECL55 II/21ECL55
n = 7; // Total number of bits (including parity bits)

// QPSK modulation
M = 4; // Number of constellation points
constellation = exp(%i * (%pi/4) * [1 3 5 7]);

// Eb/N0 in linear scale


SNR_linear = 10.^(SNR_dB_range / 10);

// Initialize BER array


BER = zeros(1, length(SNR_dB_range));

for i = 1:length(SNR_dB_range)
snr_linear = SNR_linear(i);

// Generate random binary data


input_bits = rand(1, num_bits, 'bin');

// Encode the data using (7, 4) Hamming code


encoded_bits = [];
for j = 1:k:num_bits
info_bits = input_bits(j:j+k-1);
parity_bits = mod(info_bits * [1 1 0 1; 1 0 1 1; 0 1 1 1], 2);
encoded_bits = [encoded_bits info_bits parity_bits];
end

// Modulate the encoded bits using QPSK


modulated_symbols = constellation(encoded_bits * (2^(k-1)) + 1);

Dept. of E C E, K I T, Tiptur
Page 71
Communication lab-II/21ECL55 II/21ECL55

// Add AWGN noise


noise_real = grand(1, num_bits, "nor", 0, 1/sqrt(2*snr_linear));
noise_imag = grand(1, num_bits, "nor", 0, 1/sqrt(2*snr_linear));
received_symbols = modulated_symbols + noise_real + %i * noise_imag;

// Demodulate the received symbols (maximum-likelihood decoding)


demodulated_bits = zeros(1, num_bits);
for j = 1:k:num_bits
received_symbol_block = received_symbols(j:j+n-1);
min_distance = realmax();
decoded_bits = [];
for symbol = 1:M
distance = norm(received_symbol_block - constellation(symbol));
if distance < min_distance
min_distance = distance;
decoded_bits = de2bi(symbol-1, k, 'left-msb');
end
end
demodulated_bits(j:j+k-1) = decoded_bits;
end

// Calculate BER
bit_errors = sum(demodulated_bits ~= input_bits);
BER(i) = bit_errors / num_bits;
end

// Calculate coding gain

Dept. of E C E, K I T, Tiptur
Page 72
Communication lab-II/21ECL55 II/21ECL55
SNR_dB_coding_gain = -10 * log10(BER);

// Plot BER vs. Eb/N0


clf;
semilogy(SNR_dB_range, BER, '*-');
xlabel('Eb/N0 (dB)');
ylabel('Bit Error Rate (BER)');
grid on;
title('(7, 4) Hamming Code BER Performance');
xtitle('SNR (dB)', 'BER');
show_window();

// Print coding gain


coding_gain = SNR_dB_coding_gain(1) - SNR_dB_range(1);
disp('Coding Gain (dB):');
disp(coding_gain);
```

Copy and paste this code into a SCILAB script file and run it. It will simulate the BER
performance of the (7, 4) Hamming code using QPSK modulation and maximum-likelihood
decoding on an AWGN channel, generate a plot of BER vs. Eb/N0, and display the coding
gain in dB.

Result:

Dept. of E C E, K I T, Tiptur
Page 73
Communication lab-II/21ECL55 II/21ECL55

16. Simulate the BER performance of rate 1/3 Turbo code.


Turbo encoder uses two recursive systematic encoders with (𝐷) =
[1, 1+𝐷 4 1+𝐷+𝐷2+𝐷3+𝐷4 ] and pseudo-random interleaver. Use
QPSK modulation scheme. Channel decoding is to be performed
through maximum a-posteriori (MAP) decoding algorithm. Plot
the bit error rate versus SNR (dB), i.e. Pe,b versus Eb/N0.
Consider binary input vector of size of around 3 lakh bits and
the block length as 10384 bits. Also find the coding gain.

// Parameters

Dept. of E C E, K I T, Tiptur
Page 74
Communication lab-II/21ECL55 II/21ECL55
SNR_dB_range = 0:1:10; // SNR values in dB
num_bits = 300000; // Number of bits to transmit
block_length = 10384; // Length of each code block
rate = 1/3; // Turbo code rate
k = rate * block_length; // Number of information bits per code block

% Define generator polynomials for the constituent convolutional codes


G1 = [1, 1 + %D^4, 1 + %D + %D^2 + %D^3 + %D^4];
G2 = G1;

% Create interleaver (pseudo-random interleaver)


interleaver = randperm(block_length);

% QPSK modulation
M = 4; // Number of constellation points
constellation = exp(%i * (%pi/4) * [1 3 5 7]);

% Eb/N0 in linear scale


SNR_linear = 10.^(SNR_dB_range / 10);

% Initialize BER array


BER = zeros(1, length(SNR_dB_range));

for i = 1:length(SNR_dB_range)
snr_linear = SNR_linear(i);

// Generate random binary data


input_bits = rand(1, num_bits, 'bin');

Dept. of E C E, K I T, Tiptur
Page 75
Communication lab-II/21ECL55 II/21ECL55

// Turbo encoding
encoded_bits = [];
for j = 1:block_length:num_bits
input_block = input_bits(j:j+block_length-1);

% Encode the data using the first encoder


encoded_block1 = encode(input_block, G1);

% Interleave the encoded bits


interleaved_block = encoded_block1(interleaver);

% Encode the interleaved bits using the second encoder


encoded_block2 = encode(interleaved_block, G2);

% Interleave the encoded bits again


interleaved_block2 = encoded_block2(interleaver);

encoded_bits = [encoded_bits input_block interleaved_block interleaved_block2];


end

// Modulate the encoded bits using QPSK


modulated_symbols = constellation(encoded_bits * (2^(k-1)) + 1);

// Add AWGN noise


noise_real = grand(1, length(modulated_symbols), "nor", 0, 1/sqrt(2*snr_linear));
noise_imag = grand(1, length(modulated_symbols), "nor", 0, 1/sqrt(2*snr_linear));
received_symbols = modulated_symbols + noise_real + %i * noise_imag;

Dept. of E C E, K I T, Tiptur
Page 76
Communication lab-II/21ECL55 II/21ECL55

// Demodulate the received symbols (MAP decoding)


decoded_bits = [];
for j = 1:block_length:num_bits
received_block = received_symbols(j:j+block_length-1);

% Perform MAP decoding for the first code


decoded_block1 = decode(received_block, G1);

% Deinterleave the decoded bits


deinterleaved_block = decoded_block1(interleaver);

% Perform MAP decoding for the second code


decoded_block2 = decode(deinterleaved_block, G2);

% Deinterleave the decoded bits again


deinterleaved_block2 = decoded_block2(interleaver);

decoded_bits = [decoded_bits deinterleaved_block2];


end

// Calculate BER
bit_errors = sum(decoded_bits ~= input_bits);
BER(i) = bit_errors / num_bits;
end

// Calculate coding gain


SNR_dB_coding_gain = -10 * log10(BER);

Dept. of E C E, K I T, Tiptur
Page 77
Communication lab-II/21ECL55 II/21ECL55

// Plot BER vs. Eb/N0


clf;
semilogy(SNR_dB_range, BER, '*-');
xlabel('Eb/N0 (dB)');
ylabel('Bit Error Rate (BER)');
grid on;
title('Rate 1/3 Turbo Code BER Performance');
xtitle('SNR (dB)', 'BER');
show_window();

// Print coding gain


coding_gain = SNR_dB_coding_gain(1) - SNR_dB_range(1);
disp('Coding Gain (dB):');
disp(coding_gain);

Code will simulate the BER performance of the rate 1/3 Turbo code using QPSK
modulation and MAP decoding, generate a plot of BER vs. Eb/N0, and display the coding
gain in dB.

Result:

Dept. of E C E, K I T, Tiptur
Page 78

You might also like