You are on page 1of 121

INDEX

8051 MICROCONTROLLER ....................... 3


SWITCH CONTROLLED LED ..................................................................................... 4
INTERRUPT PROGRAMMING ..................................................................................... 5
STEPPER MOTOR INTERFACING ............................................................................... 7

PIC MICROCONTROLLER......................... 9
BIT PATTERN ON PORTC ........................................................................................ 10
Timer Operation........................................................................................................ 12
PWM SIGNAL GENERATION ..................................................................................... 14
ANALOG TO DIGITAL CONVERTER ......................................................................... 16

ARM ...................................................... 18
General Purpose Output Interface ................................................................................ 19
Interfacing with Switch ............................................................................................... 21
ADC Interfacing ........................................................................................................ 23
Timer Interface ......................................................................................................... 24
UART Interfacing ...................................................................................................... 26
LCD Interfacing ........................................................................................................ 28

PSPICE .................................................. 30
CMOS Inverter ......................................................................................................... 31
NAND Gate .............................................................................................................. 32
2:1 Multiplexer.......................................................................................................... 33
4:1 Multiplexer.......................................................................................................... 34
D Latch ................................................................................................................... 36
Full Adder ................................................................................................................ 37

Labview .................................................. 39
Binary to Decimal Conversion ..................................................................................... 40
Odd/Even Number Generation .................................................................................... 42
3 Bit Counter ........................................................................................................... 44
7-Segment Display .................................................................................................... 47
Band Pass IIR Filter ................................................................................................... 50
Rotation of an Array .................................................................................................. 52

MATLAB ................................................ 54
Linear Convolution .................................................................................................... 55
Circular Convolution .................................................................................................. 57
DFT using MATLAB .................................................................................................. 59

FFT Using MATLAB ................................................................................................. 61


FIR Low Pass Filter ................................................................................................... 63
FIR High Pass Filter .................................................................................................. 65

Micro Electro Mechanical Systems ............... 67


Cantilever Beam ........................................................................................................ 68
Thermal Bimorph ....................................................................................................... 69
Capacitive Pressure Sensor ......................................................................................... 70
Piezoelectric Shear Actuated Beam .............................................................................. 72

VXWORKS.............................................. 74
Communication through Pipe ....................................................................................... 75
Binary Semaphore ...................................................................................................... 77
Interprocess Communication ....................................................................................... 79
Measuring Of Execution Time ..................................................................................... 82
Pre emptive Scheduling .............................................................................................. 87

Network Simulator 2 ............................... 90


Familiarization of NS2 ................................................................................................ 91
Creation of a Network Topology .................................................................................. 93
Creation of TCP and UDP traffic ................................................................................. 95
Study of Congestion in a network ................................................................................. 98
Flow Control Mechanism in TCP ............................................................................... 100
Creation of Wireless Network .................................................................................... 104
Study of Routing logic in Ad-hoc Network ................................................................... 107

VHDL .................................................. 111


FULL ADDER ........................................................................................................ 112
MULTIPLEXER ...................................................................................................... 113
DECODER ............................................................................................................. 116
MAGNITUDE COMPARATOR .................................................................................. 118
DEMULTIPLEXER .................................................................................................. 119
ALU ...................................................................................................................... 120

8051 MICROCONTROLLER
(89v51RD2)
Pre-requisites :
Software required :
Operating System :
Tools
:
Supporting Software:
Hardware required
:
Development Board :
Interfacing circuits :

Windows
Keil
Flash magic
Philips 89V51RD2 kit
Nil

SWITCH CONTROLLED LED


Aim : To write a program to get value from port2 and to send to port0 connected to LED.

Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program

assembly program:
ORG 0000h
LJMP MAIN
ORG 0100H
MAIN: MOV P2, #0FFH
HERE: MOV P0, P2
SJMP HERE

; P2 as input
; read value from port2 and send to port0

c program:
#include<reg51.h>
#define SW P2
#define Led P0

//Define 8051 Registers


//Define Switch to Port2
//Define Led to Port0

// Main Function
void main()
{
P2=0xff;
//Port-2 as input to FFh
P0=0x00;
//Port-0 as output to 00h
while(1)
//Loop Forever
{
Led = ~SW; /*Assign the Switch value to Led .inverted value is
applied because led are connected as common anode
type*/
}
}

INTERRUPT PROGRAMMING
AIM: To write a program to make use of interrupts in 8051 in both assembly and c
language.

ASSEMBLY PROGRAM:
ORG 0000h
LJMP MAIN
ORG 0003H
MOV P0,#0FH
RETI

; external interrupt 0

ORG 000BH
CPL P1.1
RETI

; timer1 interrupt

ORG 0013H
MOV P0,#0F0H
RETI

; external interrupt 1

ORG 0100H
MAIN: MOV IE,#87H
MOV TMOD,#02H
MOV TH0,#0A4H

;enable global, timer, external interrupt


;timer0 in auto reload mode
;for 200us square wave

HERE: SJMP HERE

C PROGRAM:

#include <reg51.h>
sbit port1 = P1^1;
void ext0(void) interrupt 0
{
P0=0x0f;
}
void timer0(void) interrupt 1
{
port1 = ~port1;
}
5

void ext1(void) interrupt 2


{
P0=0xf0;
}
void main()
{
P0=0x00;
IE=0x87;
TMOD=0x02;
TH0=0x0A4;
TR0=1;
while(1);
}

STEPPER MOTOR INTERFACING


AIM: To write a program to rotate a stepper motor in clockwise and anticlockwise
direction in 8051 microcontroller.

C PROGRAM:
#include <reg51.h>
#include<stdio.h>
voidDelayMs(unsigned int);
void main (void)
{
P0 = 0;
port
while(1)
{
Clockwise ();
DelayMs (500);
P0
=
0;
AntiClockwise ();
DelayMs (500);
P0
=
0;
}
}
//

//Define 8051 registers

//Delay function

//Initialize Port0 as output


//Loop Forever

Clockwise Routine

void Clockwise (void)


{
unsignedint i;
for (i=0;i<50;i++)
direction*/
{
P0 = 0x01;DelayMs(200);
P0 = 0x02;DelayMs(200);
P0 = 0x04;DelayMs(200);
P0 = 0x08;DelayMs(200);
}
}

/*rotates 50 steps in clockwise

//

Anticlockwise Routine

voidAntiClockwise (void)
{
unsignedint i;
for (i=0;i<50;i++)

/*rotates 50 steps in anticlockwise


direction*/

{
P0 = 0x08;DelayMs(200);
P0 = 0x04;DelayMs(200);
P0 = 0x02;DelayMs(200);
P0 = 0x01;DelayMs(200);
}
}
//

Delay Function

voidDelayMs(unsigned int n)
{
unsignedinti,j;
for(j=0;j<n;j++)
{
for(i=0;i<800;i++);
}
}

PIC MICROCONTROLLER

Pre-requisites :
Software required
:
Operating System :
Tools
:
Supporting Software:

Windows
MPLAB
Flash magic

Hardware required :
Development Board :
Interfacing circuits :

PIC 16F877A
Pickit-2

BIT PATTERN ON PORTC


Aim : To write an ALP program to blink the LED connected to PORTC
Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program
#include "P16f877A.inc"
t1h equ 53
t1l equ 2
bank0ram equ h'20'
cblock bank0ram
c1h
c1l
d1l
endc
org 0000h
clrw
bcf STATUS,5
bcf STATUS,6
clrf PORTC
start
bsf STATUS,5
clrf TRISC
clrf TRISB
bcf STATUS,5
again
movlw 0x00
movwf PORTC
call delay1
movlw 0xff
movwf PORTC
call delay1
goto again
delay1 movlw t1h
movwf c1h
movlw t1l
movwf c1l
movwf d1l
ddelay1 decfsz c1l,f
goto ddelay1
decfsz c1h,f
goto ddelay1
decfsz d1l,f
10

goto ddelay1
return
END

Output :

11

Timer Operation
Aim : To write an ALP program for timer operation to generate square wave.
Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program
#INCLUDE "P16F877A.INC"
BSF STATUS,RP0
BCF STATUS,RP1
CLRF TRISB
MOVLW 0X25
MOVWF T1CON
HERE: MOVLW 0XFF
MOVWF TMR1H
MOVLW 0XF2
MOVWF TMR1L
BCF PIR1,TMR1IF
BCF STATUS,RP0
BCF STATUS,RP1
COMF PORTB,1
BSF PIE1,TMR1IE
AGAIN: BTFSS PIR1,TMR1IF
GOTO AGAIN
BCF T1CON,TMR1ON
GOTO HERE
END

12

Output :

13

PWM SIGNAL GENERATION


Aim : To perform PWM operation using assembly language in EDS 16f87X board.
Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program
INCLUDE"P16F877A.INC"
LIST P=16F877A
org 0x0100
bsf STATUS,5
;select bank0
bcf STATUS,6
bcf TRISC,2
;make C2 pin as output
movlw D'188'
;2khz period
movwf PR2
bcf STATUS,5
movlw B'00000001'
;timer2 in 4 bit prescalar
movwf T2CON
movlw D'47'
;25% duty cycle(188*0.25)
movwf CCPR1L
movlw 0X0C
;select pwm operation
movwf CCP1CON
AGAIN: bcf PIR1,TMR2IF
bsf T2CON,TMR2ON
;timer2 made run
L1:
btfss PIR1,TMR2IF
;until it matches with PR2 register
goto L1
goto AGAIN
OVER : goto OVER
END

14

C PROGRAM:
#include<16f877a.h>
#use delay(clock=6000000)
void main()
{
setup_ccp1(ccp_pwm);
while(1)
{
setup_timer_2(t2_div_by_4,188,1);
set_pwm1_duty(47);
}

//6MHZ clock

//select pwm from ccp module

//2khz period, timer2 in 4


//bit prescalar
//25% duty cycle

Output :

15

ANALOG TO DIGITAL CONVERTER


Aim : To perform analog to digital conversion and display the digital data serially.

Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program
void main()
{
unsigned int i,value,max;
int16 volt;
//defines 16 bit number
printf("sampling");
setup_adc_ports(ALL_ANALOG);
// All pins analog
setup_adc( ADC_CLOCK_INTERNAL );
setup_psp(PSP DISABLED);
setup_spi(FALSE);
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
setup_timer_1(T1_DISABLED);
setup_timer_2(T2_DISABLED,0,1);
setup_comparator(NC_NC_NC_NC);
setup_vref(FALSE);
set_adc_channel(0);
// channel 0 (AN0)
delay_us(100);
while(1)
{
value=read_adc();
/*start conversion put result
in value */
volt=(int16)value*20;
printf("the digital value is %4ld mv \r\n",volt);
delay_ms(1000);
}
}

Output :
Output viewed in Hyper terminal (Real term)

16

Note:
The analog input is given at pin RA0(i.e. Port A0 pin)
The output is viewed in HyperTerminal.(with Default settings)

17

ARM

Pre-requisites :
Software required :
Operating System
Tools
Supporting Software
Hardware required :

:
:
:

Windows
KeilUvision IDE
Flash Magic

Development Board

LPC2148

Interfacing circuits

NA

18

General Purpose Output Interface


Aim : To blink the LED connected to LPC2148 processor with a finite delay.

Components Required:
LPC2148 trainer kit
KeilUvision 4
RS232 cable
Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program:
/*

LED INTERFACE*/

#include<lpc21xx.H>
void delay()
{
int i,j;
for(i=0x00;i<=0xff;i++)
for(j=0x00;j<=0xFf;j++);
}
/* LED0
LED7 : P1.24 - P1.31 */
void main()
{
PINSEL2 = 0X00000000;
// P1.24 TO P1.31 as GPIO
IO1DIR = 0XFF000000;
// p1.24 TO P1.31 as Output Port
while(1)
{
IO1SET=0XFF000000;
// P1.24 TO P1.31 goes high
delay();
IO1CLR=0XFF000000;
// P1.24 TO P1.31 goes low
delay();
}
}

Output:

19

Result :
Thus the LEDs connected to the port P1.24 and port P1.31 are toggled over the
LPC2148 trainer kit.

20

Interfacing with Switch


Aim :
To blink the LED connected to LPC2148 processor depending on the values of the
input switch
Components Required:
LPC2148 trainer kit
KeilUvision 4
RS232 cable
Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program:
/*------------------SWITCH INTERFACE------------------------------------*/
#include <lpc21xx.h>
static void delay(void )

//
//

SW0 - SW7
LED0 - LED7

:
:

P0.16 - P0.23
P1.23 - P1.31

{
volatile int i,j;
for (i=0;i<0x3F;i++)
for (j=0;j<500;j++);
}
void main()
{
PINSEL1 = 0x00000000;
PINSEL2 = 0x00000000;
IO0DIR
IO1DIR

= 0X00000000;
= 0Xff000000;

// Configured as GPIO port


// Configured as GPIO port
// P0.16 TO P0.23 as input
// P1.23 TO P1.31 as output

while(1)
{
IO1PIN = ((IO0SET & 0x00FF0000)<<0x08);
delay();
}
}

21

Output:

Result:
Thus the LEDs connected to ports P1.24 to P1.31 are turned on using the switches
connected to P0.16 to P0.23 on LPC2148 trainer kit.

22

ADC Interfacing
Aim : To interface the on chip ADC module in LPC2148.
Components Required:
LPC2148 trainer kit
KeilUvision 4
RS232 cable
Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program:
/*
ON CHIP ADC INTERFACE
#include<lpc214x.h>

*/

void main()
{
PINSEL1 = 0X01000000;
// P.028 as Analog i/p
PINSEL2 = 0x00000000;
// P1 as GPIO
IO1DIR = 0xFF000000;
// P1.24 to P1.31 as o/p
AD0CR
= 0x00210302;
//enable AD0.1 SEL=2
while(1)
{
while((AD0DR1&0x80000000)!= 0x80000000); //wait until conversion done
IO1PIN = AD0DR1<<16;
}
}

Output:

Result:
Thus the ADC interface is implemented successfully using the LPC2148 trainer kit.
23

Timer Interface
Aim : To interface on chip timer using polling method on LPC2148 trainer kit.
Components Required:
LPC2148 trainer kit
KeilUvision 4
RS232 cable
Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program:
#include <LPC214x.h>
voidtimer_init()
{
T1IR = 0xFF;
// reset match and capture event interrupts
T1TC = 0;
// Clear timer counter
T1PR = 59;
// Timer Increments every 0.017 usec
T1MCR = 3;
// Reset Timer Counter & Interrupt on match
T1TCR = 1;
// Turn on the timer module
}
void main(void)
{
PINSEL2 = 0X00000000;
IO1DIR = 0XFF000000;
timer_init();
while(1)
{
while(T1IR!=0x01);
//wait for int on the match
IO1SET = 0XFF000000;
//Turn on the LEDs on port1
T1TC
= 0;
//reset timer count value
T1IR
= 0x0ff;
//clear the int flag
while(T1IR!=0x01);
IO1CLR = 0XFF000000
//Turn off the LEDs
T1TC
= 0;
T1IR
= 0XFF;
}
}

24

Output:

Result:
Thus the timer interface using polling mechanism was implemented successfully on
LPC2148 trainer kit

25

UART Interfacing
Aim : To interface the on chip UART module in LPC2148.
Components Required:
LPC2148 trainer kit
KeilUvision 4
RS232 cable
Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program:
#include <lpc214x.h>
#define DESIRED_BAUDRATE
19200
#define CRYSTAL_FREQUENCY_IN_HZ 12000000
#define PCLK
CRYSTAL_FREQUENCY_IN_HZ
// since VPBDIV=0x01
#define DIVISOR
(PCLK/(16*DESIRED_BAUDRATE))
Char arr[]=" \n\r Vimicro system Pvt ltd. Chennai - 96. " ;
char serial_tr(char ch)
{
if (ch=='\n')
{
while (!(U0LSR&0x20));
//wait until TxReg is empty
U0THR='\r';
// store to Tx Holding Reg
}
while (!(U0LSR&0x20)) {}
//wait until Tx Holding Reg empty
U0THR=ch;
//store to Tx Holding Register
return
ch;
}
void Arm_Uart0_Init(void)
{
PINSEL0 = 0x00000005;
U0LCR=0x83; //
U0LCR: UART0 Line Control Register.
VPBDIV=0x01;
//
VPBDIV: VPB bus clock divider
U0DLL = DIVISOR&0xFF;
// U0DLL: UART0 Divisor Latch (LSB).
U0DLM= DIVISOR>>8;
//
U0DLM: UART0 Divisor Latch (MSB).
U0LCR= 0x03 ;
// U0LCR: UART0 Line Control Register
U0FCR= 0x05 ;

//

U0FCR: UART0 FIFO Control Register

}
/*----------------------------------------------------------------------------------------------*/
//
BAUD RATE CALCULATION
//
DIVISOR
=
(PCLK/(16*DESIRED_BAUDRATE))
//
For Example
//
Peripheral Clock Frequency (PCLK) = 12 Mhz
//
Desired Baud Rate
= 19200 bps
//
Divisor
=
(12000000/(16*19200)) = 39
//------------------------------------------------------------------void main ()
{
int i;
Arm_Uart0_Init();
// Serial Port Intialisation.
while(1)
{

26

for(i=0;arr[i]!='\0';i++)
{
serial_tr(arr[i]);
}
}
}

// Serial transmission.

Output:

Result:
Thus the on chip UART was interfaced successfully using the LPC2148 trainer kit.

27

LCD Interfacing
Aim : To interface the on chip LCD module in LPC2148.
Components Required:
LPC2148 trainer kit
KeilUvision 4
RS232 cable
Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program:
#include <lpc214x.h>
#define LCD_EN
0X00000800
#define RS 0X00000100
#define DIOW
0X00000200
unsigned char arr1[30]="Anna University ";
unsigned char arr2[30]="
Chennai..
";
unsigned int i;
void delay_ms()
{
unsigned inti,j;
for(j=0;j<0xf;j++)
for(i=0;i<0xff;i++);
}
void busy_check()
{
delay_ms();
}
void command_write(int comm)
{
busy_check();
IO0CLR = RS;
IO0CLR = DIOW;
IO1PIN =comm<<16;
IO0SET = LCD_EN;
IO0CLR = LCD_EN;
}
void lcd_init()
{
command_write(0x38);
command_write(0x01);
command_write(0x0f);
command_write(0x86);
command_write(0x06);
}

//
//
//
//

5 * 7 Matrix
Clear Display
Display ON and Cursor Blinking
5 * 7 Matrix

void lcd_out(unsigned char z)


{
busy_check();
IO0SET = RS; //RS
= 1
IO0CLR = DIOW;
IO1PIN = (z<<16);
//data with Rs=1
IO0SET = LCD_EN;
IO0CLR = LCD_EN;

28

}
void main()
{
//--------------------Used Port Lines--------------------------//
//LCD0-LCD7 - P1.16 to P1.23
//
//RS - P0.8
//
//DIOW - P0.9
//
//LCDEN2 - P0.11
//
//-------------------------------------------------------------//
PINSEL2=0x00000000;
IO0DIR =0xffffffff;
// RS, DIOW & LCDEN - Output Pins
IO1DIR =0xFFFFFFFF;
// LCD0 to LCD7
- Output Pins
IO0DIR =0x5FFF7FFF;
IO1DIR = 0xFFFFFFFF;
IO0CLR =0X00000800;
IO1PIN =0X00000000;
IO0PIN = 0X00000000;
IO0CLR =RS;
IO0CLR =DIOW;
IO0CLR = LCD_EN;
lcd_init();
command_write(0x80);
for(i=0;i<16;i++)
lcd_out(arr1[i]);
command_write(0xC0);
for(i=0;i<16;i++)
lcd_out(arr2[i]);
while(1);
}

Output:

Result:
Thus the LCD module was interfaced successfully using the LPC2148 trainer kit.

29

PSPICE

Software required :
Operating System :
Tools
:
Supporting Software:

Windows 7/8/xp
Orcad 10.3
NA

Hardware required
:
Development Board :
Interfacing circuits :

NA
NA

30

CMOS Inverter
Aim : To draw a inverter circuit using cmos transistor s.
Procedure:
Circuit Diagram :

5Vdc
V1

MbreakP

M1

OFFTIME = 5us DSTM1


ONTIME = 5us CLK
DELAY =
STARTVAL = 0
OPPVAL = 1

Out
MbreakN

Output:

Result:
Thus the nand operation is performed using mos transistors.

31

NAND Gate
Aim : To draw a circuit using cmos transistor to perform nand operation with two
inputs.
Procedure:
Circuit Diagram :

5Vdc
Vdc

OFFTIME = 1uS DSTM1


ONTIME = 1uS CLK
DELAY =
STARTVAL = 0
OPPVAL = 1

MbreakP

MbreakP

M2

OUT
MbreakN

OFFTIME = .5uSDSTM2
ONTIME = .5uS CLK
DELAY =
STARTVAL = 0
OPPVAL = 1

B
MbreakN

Output :

Result:
Thus the nand operation is performed using mos transistors.
32

2:1 Multiplexer
Aim : To draw a 2:1 multiplexer circuit using Transmission Gates
Procedure:
Circuit Diagram :

Vdd

OFFTIME = .5uS Dig


ONTIME = .5uS CLK
DELAY =
STARTVAL = 0
OPPVAL = 1

MbreakP
I0

Vdd

M4
MbreakN
S
10Vdc

OFFTIME = .5uSdig1
ONTIME = .5uS CLK
DELAY =
STARTVAL = 1
OPPVAL = 0

MbreakP
I1
out
MbreakN

Vdd

Output:

Result:
Thus the 2:1 mux circuit using Transmission Gates is drawn

33

4:1 Multiplexer
Aim : To draw a 4:1 mux circuit using Transmission Gates.
Procedure:
Circuit Diagram :
MbreakP
5

s0
V

OFFTIME = .5uS
ONTIME = .5uS CLK
DELAY = 1us
STARTVAL = 0
OPPVAL = 1

v dd

M2

A
1

M8
MbreakN

s1

INV

MbreakP
1
MbreakP
M3
OFFTIME = .5uS
ONTIME = .5uS CLK
DELAY = 2u
STARTVAL = 0
OPPVAL = 1

INV

M14
M9
MbreakN

M12
MbreakN

MbreakP
MbreakP
M4
OFFTIME = .5uS
ONTIME = .5uS CLK
DELAY = 3us
STARTVAL = 0
OPPVAL = 1

INV
2

C
M15

M10
MbreakN

v out
MbreakN

MbreakP

OFFTIME = .5uS
ONTIME = .5uS CLK
DELAY = 4us
STARTVAL = 0
OPPVAL = 1

M5

M11
MbreakN

Output:

34

Result:
Thus the 4:1 mux circuit using Transmission Gates is drawn

35

D Latch
Aim :
To draw a D latch circuit using Transmission Gates.
Procedure:
Circuit Diagram :

OFFTIME = 1us Clk


ONTIME = 1us CLK
DELAY =
STARTVAL = 0
OPPVAL = 1

U1

MbreakP
M1

OFFTIME = .75usD
ONTIME = .5uS CLK
DELAY =
STARTVAL = 1
OPPVAL = 0

V1
5

INV
M3
MbreakN

1
U3
INV

2
MbreakP
M2

Q
MbreakN

INV
2

U2

Output:

Result:
Thus the D latch circuit using Transmission Gates is drawn

36

Full Adder
Aim :
To draw a Full Adder circuit using cmos transistors.
Procedure:
Circuit Diagram :

M1

M11

M13

M15

MbreakP

MbreakP

MbreakP

M6

MbreakP

Vdc
5

MbreakP
M12

Carry

M8
M2

M3

M16

M7

MbreakP

MbreakP

MbreakP
MbreakP

MbreakP

MbreakP

MbreakP

M4

M5

MbreakP

Sum

MbreakP

M10

MbreakP

M22

MbreakP

M23

MbreakN

MbreakN

B
0
M24

A
5

Abar

M17

M18

M20

MbreakN

MbreakN

MbreakN

M25

MbreakN

MbreakN

M27
C

M19

M21

M26

MbreakN

MbreakN

MbreakN

Cbar

MbreakN

0
5

0
M28

M29

M31

MbreakN

MbreakN

MbreakN

M30

M32

MbreakN

MbreakN

5
Bbar

37

Output:

Result:
Thus the Full Adder circuit using cmos transistors is drawn

38

Labview

Pre-requisites :
Software required :
Operating System :
Tools
:
Supporting Software:
Hardware required
:
Development Board :
Interfacing circuits :

Windows 7/8/xp
NI Labview
NA

NA
NA

39

Binary to Decimal Conversion


Aim :
To convert the given binary number to its corresponding decimal equivalent using
Labview system design software.
Procedure :
Create a VI and place the blocks needed such as Numeric, LED.
Connect the blocks based on the logic as shown in the screen shot below.In the
front panel click
Run Continuously button and simulate the result.
Diagrams :
Front panel:

Block diagram:

40

Output :

Result :
The given binary number is converted into its decimal equivalent using Labview
system design software.

41

Odd/Even Number Generation


Aim :
To check whether the given number is even or odd using Labview system design
software.
Procedure :
Create a VI and place the blocks needed such as Numeric, LED.
Connect the blocks based on the logic as shown in the screen shot below.In the
front panel click
Run Continuously button and simulate the result.
Diagrams :

Front panel:

Block diagram:

42

Output :

Result :
The given binary number is converted into its decimal equivalent using Labview
system design software.

43

3 Bit Counter
Aim :
To design a 3-bit counter in LABVIEW

Procedure :
In the front panel place 3 LEDs and a Numeric indicator and connect as in the front
panel diagram
In the block diagram place a while loop
Convert the tunnel into feedback node and connect as in the block diagram.

Diagrams : (Circuit/Block/Interfacing Diagrams)


FRONT PANEL

44

BLOCK DIAGRAM:

Program
Not applicable

45

Output :

Result :
Thus 3-bit counter was designed and executed

46

7-Segment Display
Aim :
To design a seven segment display using LABVIEW

Procedure :
In the front panel place a Numeric control and 7 LEDs and arrange as in the front
panel diagram
In the block diagram place a case structure and connect as in the block diagram
using Boolean constants (True and False) and local variables.

Diagrams : (Circuit/Block/Interfacing Diagrams)


FRONT PANEL

47

BLOCK DIAGRAM:

48

Program
Not applicable
Output :

Result :
Thus the seven segment led was designed and executed

49

Band Pass IIR Filter


Aim:
To design the Frequency Response of band-pass IIR Filter using Labview system
design software.
Procedure:
Create a VI and place the blocks needed such as Numeric, LED and Case structure
block.
Connect the blocks based on the logic as shown in the screen shot below.
In the front panel click Run Continuously button and simulate the result.

Diagrams:
Front Panel

50

Block Diagram:

Program:
Not Applicable
OUTPUT:

Result:
Thus the Frequency Response of Band-Pass IIR Filter is designed using NILABVIEW.
51

Rotation of an Array
Aim:
To design the rotation of an array and to express the Boolean value of the array.
Procedure:
Create a VI and place the blocks needed such as Numeric, LED and Case structure
block.
Connect the blocks based on the logic as shown in the screen shot below.
In the front panel click Run Continuously button and simulate the result.

Diagrams (circuit/block/Interfacing Diagrams):


Front Panel

52

Block diagram:

Programs:
Not Applicable.
Output:

Result:
Thus the rotation of an array is designed using NI-LABVIEW.

53

MATLAB

Pre-requisites :
Software required :
Operating System
Tools

:
:

Windows
MATLAB R2010a

Hardware required

Nil

Development Board

NA

Interfacing circuits

NA

54

Linear Convolution

AIM:
To implement linear convolution using MATLAB functions.

Procedure:
ALGORITHM:
1. Get

two signals x (m) and h(p)in matrix form


2. The convolved signal is denoted as y (n)
3. y(n)is given by the formula

Total sequence y (n) =N+M-1.


4. Stop
PROGRAM:
close all
clear all
x=input('Enter x: ')
\\Enter the input sequence
h=input('Enter h: ')
\\Enter the impulse sequence
m=length(x);
\\Enter the length of input sequence
n=length(h);
\\Enter the length of impulse sequence
X=[x,zeros(1,n)];
\\Adding Zeros to make m=n
H=[h,zeros(1,m)];
\\Adding Zeros to make m=n
for i=1:n+m-1
Y(i)=0;
\\Initializing convolution value
for j=1:m
\\ computing the logic using the for loop
if(i-j+1>0)
Y(i)=Y(i)+X(j)*H(i-j+1);
else
end
end
end
stem(Y);
\\ plots discrete sequence of data
ylabel('Y[n]');
\\ label Y axis
xlabel('----->n');
\\ label X axis
title('Convolution of two signals ');
\\ giving the title for the plot

55

OUTPUT:
Enter x: [1 2 3 4]
x=
1 2 3 4
Enter h: [1 1 1 2]
h=
1 1 1 2
Y=
1 3 6 11 11

10

Convolution of Two Signals


12

10

Y[n]

4
---n

RESULT:
Two sequence linear convolution is performed using Matlab functions.

56

Circular Convolution
AIM:
To implement Circular Convolution using MATLAB functions.
PROGRAM:
clear all
close all
g=input('enter the first sequence');
// enter the first sequence
h=input('enter the second sequence');
// enter the second sequence
N=input('enter the number of points in the output sequence');
N1=length(g);
//Enter the length of first sequence
N2=length(h);
//Enter the length of second sequence
for n=1:N
//Computation of circular convolved seq
y(n)=0;
for i=1:N;
// compute the logic inside for loop
j=n-i+1;
if(j<=0)
j=N+j
end
y(n)=y(n)+g(i)*h(j)
end
end
subplot(3,1,1);
// dividing current figure into rectangular panes
stem(g);
//plot discrete sequence data
xlabel('n');
//label x axis
ylabel('g(n)');
// label Y axis
title('first sequence');
// Add title
subplot(3,1,2);
stem(h);
xlabel('n');
ylabel('h(n)');
title('second sequence');
subplot(3,1,3);
stem(y);
xlabel('n');
ylabel('y(n)');
title('circular convolution');

OUTPUT:
Enter the first sequence [1 2 3 4]
Enter the second sequence [1 2 3 4]
Enter the number of points in the output sequence 4
57

first sequence
g(n)

4
2
0

1.5

2.5
n
second sequence

3.5

1.5

2.5
n
circular convolution

3.5

1.5

2.5
n

3.5

h(n)

4
2
0

y(n)

40
20
0

RESULT:
Circular convolution is implemented using Matlab functions.

58

DFT using MATLAB


AIM:
To design a DFT using MATLAB functions.

PROGRAM:
clear all;
close all;
x=input('enter the input sequence');
//Enter the input sequence
n=input('enter the length of FFT');
//Enter the length of FFT
X=fft(x,n);
//returns the n point DFT using FFT function
subplot(3,1,1);
// subplot divides the current figure into rectangular panes
stem(x);
xlabel('n');
ylabel('x(n)');
title('Input Sequence');
// enter the input sequence
subplot(3,1,2);
stem(X);
// plot the discrete sequence data
xlabel('k')
ylabel('imaginary axis');
display('the resultant signal is');X
//Display the graph in the same window
y=real(X);
// returns the real value of x
z=imag(X);
// returns the imaginary values of x
subplot(3,1,3);
stem(y,z);
xlabel('real axis');
//label X axis
ylabel('imaginary axis');
//label Y axis
title('DFT Sequence');
//specify the title

OUTPUT:
Enter the input sequence [1,2,3,4,4,3,2,1]
Enter the length of FFT 8
The resultant signal is
X=
20.0000
0

-5.8284 - 2.4142i
-0.1716 + 0.4142i

0
0

-0.1716 - 0.4142i
-5.8284 + 2.4142i

59

Input Sequence

x(n)

4
2
0

imaginary axis

imaginary axis

n
5
0
-5

k
DFT Sequence
5
0
-5
-10

-5

5
real axis

10

15

20

RESULT:
Discrete Fourier transform is implemented using Matlab functions.

60

FFT Using MATLAB


AIM:
To design a FFT using MATLAB functions.

PROCEDURE:
Algorithm:

1. Get the signal x(n) of length N in matrix form


2. Get the N value
3. The transformed signal is denoted as,
X(k) =

for 0

N-1

PROGRAM:
clear all;
close all;
fs = 1000;
//Sampling frequency
T = 1/fs;
//sample time
L = 1000;
//time vector
t= (0:L-1)*T;
% sum of a 50Hz sinusoid and a 120Hz sinusoid
x = 0.7 * sin(2*pi*50*t) + sin(2*pi*120*t);
figure
plot(fs * t(1:200), x(1:200));
//plot uncorrupted signal
title(sinusoid signal with 50Hz and 120Hz);
xlabel(time(milliseconds));
y = x+2 * randn(size(t));
//add noise with signal
figure
plot(fs * t(1:200), y(1:200));
//plot corrupted signal
title(signal corrupted with zero mean random noise);
xlabel(time(milliseconds));
NFFT = 2^ nextpow2(L);
//next power of 2 from length of y
y = fft (y,NFFT) /L;
f = fs/2 * linspace (0,1,NFFT/2);
figure
//plot single-sided amplitude spectrum using FFT
plot(f, 2 * abs(y(1:NFFT/2)));
title(single sided amplitude spectrum of y(t));
xlabel(frequency(Hz));
ylabel(|y(f)|);

61

OUTPUT:
sinusoid signal with 50Hz and 120Hz
2
1.5
1
0.5
0
-0.5
-1
-1.5
-2

20

40

60

80
100
120
time(milliseconds)

140

160

180

200

160

180

200

400

450

500

signal corrupted with zero mean random noise


8
6
4
2
0
-2
-4
-6
-8

20

40

60

80
100
120
time(milliseconds)

140

single sided amplitude spectrum of y(t)


1.4

1.2

|y(f)|

0.8

0.6

0.4

0.2

50

100

150

200
250
300
frequency(Hz)

350

RESULT:
Fast Fourier Transform is implemented using Matlab function

62

FIR Low Pass Filter


AIM: To design a FIR Low Pass Filter Using MATLAB function
PROCEDURE:
Algorithm:

1. Get the passband and stopband ripples


2. Get the passband and stopband edge frequencies
3. Get the sampling frequency
4. Calculate the order of the filter
5. Find the window coefficients using the required equation
6. Draw the magnitude and phase
PROGRAM:
clear all;
close all;
rp= input('Enter passband ripple in dB'); // give the passband ripple
rs=input('Enter stopband ripple in dB'); //give the stopband ripple
fp=input('Enter passband frequency in Hz'); //give the passband ripple
fs=input('Enter stopband frequency in Hz'); //give the stopband ripple
f=input('Enter sampling frequency in Hz'); //give the sampling frequency
wp=2*fp/f; // sample the passband frequency
ws=2*fs/f; //sample the stopband ripple
num=-20*log10(sqrt(rp*rs))-13; // calculation of magnitude for rectangular window
den=14.6*(fs-fp)/f;
n=ceil(num/den);
// round off the value of numerator/denominator
n1=n+1;
if (rem(n,2)~=0);
n1=n;
n=n-1;
end
y =boxcar(n1);
// Use the function for rectangular window
b=fir1(n,wp,y);
//finding the FIR of lowpass filter
[h,om]=freqz(b,1,256);
m=20*log10(abs(h));
// finding magnitude in decibel
an=angle(h);
// phase in radians.
subplot(2,1,1);
plot(om/pi,m);
//plot the graph frequency Vs gain
ylabel('Gain in dB');
xlabel('Normalised frequency');
subplot(2,1,2);
// divide the current figure into rectangular panes
plot(om/pi,an);
//plot the graph frequency Vs phase
ylabel('Phase in radians');
xlabel('Normalised frequency');

63

OUTPUT:
Enter passband ripple in dB 0.05
Enter stopband ripple in dB 0.04
Enter passband frequency in Hz 1500
Enter stopband frequency in Hz 2000
Enter sampling frequency in Hz 9000

Gain in dB

50

-50

-100

0.1

0.2

0.3

0.4
0.5
0.6
Normalised frequency

0.7

0.8

0.9

0.1

0.2

0.3

0.4
0.5
0.6
Normalised frequency

0.7

0.8

0.9

Phase in radians

4
2
0
-2
-4

RESULT:
FIR low pass filter using window method is implemented using Matlab functions.

64

FIR High Pass Filter


AIM:To design a FIR High Pass Filter Using MATLAB functions.
PROCEDURE:

Algorithm:

1. Get the passband and stopband ripples


2. Get the passband and stopband edge frequencies
3. Get the sampling frequency
4. Calculate the order of the filter
5. Find the window coefficients using the required equation
6. Draw the magnitude and phase
PROGRAM:
clear all
close all
rp= input('Enter passband ripple in dB'); // give the passband ripple
rs=input('Enter stopband ripple in dB'); // give the stop band ripple
fp=input('Enter passband frequency in Hz'); //give the passband frequency
fs=input('Enter stopband frequency in Hz'); // give the stopband frequency
f=input('enter sampling frequency in Hz'); // give the sampling frequency
wp=2*fp/f;
// sampling passband frequency
ws=2*fs/f;
// sampling stopband frequency
num= -20*log10(sqrt(rp*rs))-13; // calculation of magnitude using rectangular window
den=14.6*(fs-fp)/f;
n=ceil(num/den);
// round off the value of numerator/denominator
n1=n+1;
if (rem(n,2)~=0);
n1=n;
n=n-1;
end
y =boxcar(n1);
// use the function for rectangular window
b=fir1(n,wp,'high',y);
// finding the FIR of high pass filter
[h,om]=freqz(b,1,256);
m=20*log10(abs(h));
// finding magnitude in decibel.
an=angle(h);
// find the phase
subplot(2,1,1);
plot(om/pi,m);
//plot the graph frequency Vs gain
ylabel('Gain in dB');
xlabel('Normalised frequency');
subplot(2,1,2);
plot(om/pi,an);
//plot the graph frequency Vs phases
ylabel('Phase in radians');
xlabel('Normalised frequency');
65

OUTPUT:
Enter passband ripple in dB 0 .05
Enter stopband ripple in dB 0.04
Enter passband frequency in Hz 1500
Enter stopband frequency in Hz 2000
Enter sampling frequency in Hz 9000

Gain in dB

50

-50

-100

0.1

0.2

0.3

0.4
0.5
0.6
Normalised frequency

0.7

0.8

0.9

0.1

0.2

0.3

0.4
0.5
0.6
Normalised frequency

0.7

0.8

0.9

Phase in radians

4
2
0
-2
-4

RESULT:
FIR high pass filter using window method is implemented using Matlab functions.

66

Micro Electro Mechanical Systems

Pre-requisites :
Software required :
Operating System :
Tools
:
Supporting Software:
Hardware required
:
Development Board :
Interfacing circuits :

Windows 7/8/xp
Comsol4.2a
NA
Nil
NA
NA

67

Cantilever Beam
Aim : To model a cantilever beam using comsol and to study its displacement
characteristics.
Procedure :
.After opening comsol, the model wizard appears. Choose 2-D for two dimensional
objects in space dimensions. Click next.
The window changes to add physics. Choose solid mechanics under structural
mechanics and then click next.
The select study type window appears. Choose stationary in preset studies and
click finish.
On the left hand side the model builder pane appears. Right click on Geometry to
create one rectangle with the following dimension.
Rectangle :- Object Type - Solid
]
Size - 1.width - 10e-3m
2.Height - 1e-3m
Position - 1.Base - Corner
2. x: 0m
3.y:0m
Click Build all.
Right click materials and click open materials browser. Add silicon dioxide. Assign
silicon dioxide to rectangle.
Right click on solid mechanics and select fixed constraint. Fix one corner of the
blocks .
Right click solid mechanics and select boundary load. Choose the load type as
pressure and give the value as (10pa) and choose the side to which load has to be
applied.
Right click on study and give compute.
The result will appear on the window after some time.

Output :

Result :
A cantilever beam using comsol and its displacement characteristics is studied
68

Thermal Bimorph
Aim : To model a thermal bimorph using comsol and to study its displacement
characteristics.
.Procedure :
After opening comsol, the model wizard appears. Choose 2-D for two dimensional
objects in space dimensions. Click next.
The window changes to add physics. Choose thermal stress under structural
mechanics and then click next.
The select study type window appears. Choose stationary in preset studies and
click finish.
On the left hand side the model builder pane appears. Right click on Geometry to
create two rectangles one by one with the following dimensions.
Rectangle1 :- Object Type - Solid
Size - 1.width - 10e-3m
2.Height - 1e-3m
Position - 1.Base - Corner
2. x: 0m
3.y:0m

Rectangle2 :- Object Type - Solid


Size - 1.width - 10e-3m
2.Height - 1e-3m
Position - 1.Base - Corner
2. x: 0m
3.y:1e-3m
Click Build all.
Right click materials and click open materials browser. Add silicon dioxide and
aluminium material to the model builder. Assign silicon to the bottom block and
aluminium to the top block.
Under geometry, click form union and click build all.
Right click on thermal stress and select fixed constraint. Fix one corner of the
blocks (1,3).
Right click on thermal stress and select temperature. Give temperature value
(400K) and choose the side to which heat has to be applied(2).
Right click on study and give compute.
Output :

Result :
A thermal bimorph using comsol and its displacement characteristics is studied.
69

Capacitive Pressure Sensor


Aim : To model a capacitive pressure sensor using comsol and to study its displacement
and electric potential characteristics.
Procedure :
After opening comsol, the model wizard appears. Choose 3-D for three dimensional
objects in space dimensions. Click next.
The window changes to add physics. Choose electro-mechanics under structural
mechanics and then click next.
The select study type window appears. Choose stationary in preset studies and
click finish.
On the left hand side the model builder pane appears. Right click on Geometry to
create two blocks one by one with the following dimensions.

Block1 :- Object Type - Solid


Size - 1.width - 15e-6m 2.Depth - 10e-6m 3.Height - 2e-6m
Position - 1.Base - Corner
2. x: 0m
3.y:0m 4.z:0m
Block2 :- Object Type - Solid
Size - 1.width - 10e-6m 2.Depth - 5e-6m 3.Height - 0.5e-6m
Position - 1.Base - Corner
2. x: 2e-6m
3.y:3e-6m 4.z:0.3e-6m
Block3 :- Object Type - Solid
Size - 1.width - 10e-6m 2.Depth - 5e-6m 3.Height - 0.5e-6m
Position - 1.Base - Corner
2. x: 2e-6m
3.y:3e-6m 4.z:1.3e-6m
Click Build all.
Right click materials and click open materials browser. Add Si(c),air to the model
builder. Assign Si(c) to blocks 2and 3. Assign air to block 1 and change the relative
permittivity in the settings window to 1 epsilon.
Under geometry, click form union and click build all.
Right click on electro-mechanics and select terminal and choose the following
surfaces 10,11,12,13,15,17. In terminal type change it to voltage and Vo = 3 volts.
Right click on electro-mechanics and select ground and choose the following
surfaces 6,7,8,9,14, 16.
Right click on electro-mechanics ->structural , select fixed constraints and choose
the following surfaces 6,8,9,7,11,14,15,16.
Right click on electro-mechanics ->structural , select boundary load and choose the
surface 13.
Right click on study and give compute.
The result will appear on the window after some time.

70

Output :

Result :
A capacitive pressure sensor using comsol and its displacement and electric
potential characteristics are studied.

71

Piezoelectric Shear Actuated Beam


Aim : To model a Piezoelectric shear-actuated beam using comsol and to study its
displacement and electric potential characteristics.
Procedure :
After opening comsol, the model wizard appears. Choose 3-D for three dimensional
objects in space dimensions. Click next.
The window changes to add physics. Choose piezoelectric devices under
structural mechanics and then click next.
The select study type window appears. Choose stationary in preset studies and
click finish.
On the left hand side the model builder pane appears. Right click on Geometry to
create two blocks one by one with the following dimensions.

Block1 :- Object Type - Solid


Size - 1.width - 0.1m 2.Depth - 0.03m 3.Height - 0.018m
Position - 1.Base - Corner
2. x: 0m
3.y:0m 4.z:0m
Block2 :- Object Type - Solid
Size - 1.width - 0.1m 2.Depth - 0.03m 3.Height - 0.002m
Position - 1.Base - Corner
2. x: 0m
3.y:0m 4.z:0.008m
Block3 :- Object Type - Solid
Size - 1.width - 0.01m 2.Depth - 0.03m 3.Height - 0.002m
Position - 1.Base - Corner
2. x: 0.055m
3.y:0m 4.z:0.008m
Click Build all.
Right
click
materials
and
click
open
materials
browser.
Add
aluminium,material2,Lead zirconate titanate to the model builder. Assign aluminium
to domains 1 and 3. Assign material2 to domains 2 and 5 and change the following
settings for material2.
young's modulus : 35.3e6
poisson's ratio :0.383
density : 32
Assign lead zirconate to domain 4.
Right click on piezoelectric devices and select piezoelectric model. Change the the
co-ordinate system to base vector system 2.
Right click on piezoelectric devices and select linear elastic material model. Choose
domains 1,2,3,5.
Right click on piezoelectric devices ->structural and select fixed constraints.
Choose domains 1,4,7.
Right click on piezoelectric devices ->structural ->boundary conditions -> electrical
and select electric potential. Choose domain 16. In electric potential settings make
V0=20 volts.
Right click on piezoelectric devices ->structural ->boundary conditions -> electrical
and select ground. Choose domain 17.
In mesh choose free tetrahedron and select build all.
Right click on study and select compute.
The result will appear on the window after some time.

72

Output :

Result :
A Piezoelectric shear-actuated beam using comsol and its displacement and
electric potential characteristics are studied.

73

VXWORKS

Pre-requisites :
Software required :
Operating System :
Tools
:
Supporting Software:

Windows xp
Windriver workbench 3.1
NA

Hardware required
:
Development Board :
Interfacing circuits :

NA
NA

74

Communication through Pipe


AIM:
To create Pipe and communicate through it, which is one of the inter Process
communication.
ALGORITHM:
1.Initialialize pipedriver using pipeDrv() and create pipedevice pipe_dev using
pipeDevCreate()
2.open the file pipe_dev in read write mode and write the message into the file from
readbuf and close the file.
3.open the file pipedev in read write mode and read the message into writebuf
4.print the messages in writebuf
PROGRAM:
#include "VxWorks.h"
#include "pipeDrv.h"
#include "stdio.h"
#include "ioLib.h"
void pipe()
{
char *readbuf="embedded";
char *readbuf1="system";
char writebuf[20];
int fd;
pipeDrv();
/* The argument to it are pipe name ,Number of message, Maximum Bytes per Message*/
pipeDevCreate("pipe_dev",10,100);
fd=open("pipe_dev",O_CREAT | O_RDWR,0777);
write(fd,readbuf,10);
write(fd,readbuf1,7);
close(fd);
/* Reading From The Pipe */
fd=open("pipe_dev", O_RDWR,0777);
read(fd,writebuf,10);
printf("\nThe first message is %s\n",writebuf);
read(fd,writebuf1,10);
printf("\nThe Second message is%s\n",writebuf);
}

75

OUTPUT:
The output of the program can be viewed in the Target console of the Windriver
IDE as follows

76

Binary Semaphore
AIM :
This program is to demonstrate the use of the use of the Binary Semaphore for the
purpose of the synchronisation between the various function in the program
ALGORITHM:
1. Create two semaphores and get their SEM_ID using semBCreate() function
specifying options and initial state.
2. Use semTake() function to take semaphore before executing the critical section
of a function.
3. Use semGive() function with same SEM-ID to release semaphore after
executing the critical section of a function.

PROGRAM:
#include <vxWorks.h>
#include <semLib.h>
#include <stdio.h>
SEM_ID mysem1;
SEM_ID mysem2;
void func1(void);
void func2(void);
void semCreate()
{
mysem1=semBCreate(SEM_Q_PRIORITY,SEM_FULL);
mysem2=semBCreate(SEM_Q_PRIORITY,SEM_FULL);
semTake(mysem1, WAIT_FOREVER);
printf("semcreate Got First Binary semaphore \n");
func1();
semGive(mysem1);
printf("semcreate Released First Binary semaphore\n");
func2();
}
void func1(void)
{
semTake(mysem2, WAIT_FOREVER);
printf("func1 Got second Binary semaphore\n");
semGive(mysem2);
printf("func1 Releases Second Binary semaphore\n");
}
void func2(void)
{
semTake(mysem2, WAIT_FOREVER);
printf("Func2 Got second Binary semaphore \n");
semGive(mysem2);
printf("func2: Releases Second Binary semaphore\n");
}
77

OUTPUT:
The output of the program can be viewed in the Target console of the Windriver IDE
as follows.

78

Interprocess Communication
AIM:
To write a program to show interprocess communication by creating several tasks
and enabling communication among them by using Message queue technique.
ALGORITHM:
1.Create and initialize a message queue using msgQCreate( ) function specifying
maximum number of messages in the queue, maximum length of one message
(Bytes) and options .
2.Store the MSG_Q_ID returned by msgQCreate( ) function.
3. Create two tasks for sending messages and two tasks for receiving messages.
4. Send message using msgQSend( ) function specifying MSG_Q_ID, buffer_name,
number of Bytes, timeout, priority.
5. If no tasks are waiting for messages on the message queue, the message is
simply added to the buffer of messages for that queue.
6.If any tasks are already waiting to receive a message from the message queue,
the message is immediately delivered to the first waiting task.
7. . Send message using msgQReceive( ) function specifying MSG_Q_ID,
buffer_name, number of Bytes, timeout.
8.If any messages are already available in the message queue's buffer, the first
message is immediately dequeued and returned to the caller.
9. If no messages are available, the calling task will block and be added to a queue
of tasks waiting for messages.

PROGRAM:
#include "vxWorks.h"
#include "msgQLib.h"
#include "stdio.h"
#include "taskLibCommon.h"
void taskOne(void);
void taskTwo(void);
void taskthree(void);
void taskfour(void);
#define MAX_MESSAGES 100
#define MAX_MESSAGE_LENGTH 50
MSG_Q_ID mesgQueueId;
void message(void)
{
int taskIdOne, taskIdTwo, taskIdThree, taskIdfour;
if ((mesgQueueId
=msgQCreate(MAX_MESSAGES,MAX_MESSAGE_LENGTH,MSG_Q_FIFO))== NULL)
printf("msgQCreate in failed\n");
79

if((taskIdOne =taskSpawn("t1",90,0x100,2000,(FUNCPTR)taskOne,0,0,0,0,0,0,0,0,0,0)) ==
ERROR)
printf("taskSpawn taskOne failed\n");
if((taskIdTwo =taskSpawn("t2",90,0x100,2000,(FUNCPTR)taskTwo,0,0,0,0,0,0,0,0,0,0)) ==
ERROR)
printf("taskSpawn taskTwo failed\n");
if((taskIdThree =taskSpawn("t3",90,0x100,2000,(FUNCPTR)taskthree,0,0,0,0,0,0,0,0,0,0))
== ERROR)
printf("taskSpawn taskThree failed\n");
if((taskIdfour =taskSpawn("t4",90,0x100,2000,(FUNCPTR)taskfour,0,0,0,0,0,0,0,0,0,0)) ==
ERROR)
printf("taskSpawn taskfour failed\n");
}
void taskOne(void)
{
char message[] = "Received message from taskOne";
printf("Am in task 1 ....... Sending\n");
if((msgQSend(mesgQueueId,message,MAX_MESSAGE_LENGTH,
WAIT_FOREVER,MSG_PRI_NORMAL)) == ERROR)
printf("msgQSend in taskOne failed\n");
}
void taskTwo(void)
{
char message1[] = "Received message from tasktwo";
printf("Am in task 2 ....... Sending\n");
if((msgQSend(mesgQueueId,message1,MAX_MESSAGE_LENGTH,
WAIT_FOREVER,MSG_PRI_NORMAL)) == ERROR)
printf("msgQSend in tasktwo failed\n");
}
void taskthree(void)
{
char msgBuf[MAX_MESSAGE_LENGTH];
printf("Am in task 3 ....... Receiving\n");
if(msgQReceive(mesgQueueId,msgBuf,MAX_MESSAGE_LENGTH, WAIT_FOREVER)==
ERROR)
printf("msgQReceive in taskTwo failed\n");
else
printf("%s\n",msgBuf);
}
void taskfour(void)
{
char msgBuf[MAX_MESSAGE_LENGTH];
printf("Am in task 2 ....... Receiving\n");
80

if(msgQReceive(mesgQueueId,msgBuf,MAX_MESSAGE_LENGTH, WAIT_FOREVER)==
ERROR)
printf("msgQReceive in taskTwo failed\n");
else
printf("%s\n",msgBuf);
msgQDelete(mesgQueueId);
}

OUTPUT:
The output of the program can be viewed in the Target console of the Windriver IDE
as follows.

81

Measuring Of Execution Time


AIM : To write a VxWorks code to measure the time taken for a function to execute using
timex() and timexN().

ALGORITHM:
1.Point the function pointer FUNCPTR to the function for which execution time is to be
measured
2.Use timex function with the pointer and arguments to call function
PROGRAM :

#include "vxWorks.h"
#include "timexLib.h"
#include "taskLibCommon.h"
#include "stdio.h"
#define LOOP_CNT 25
int print(void);
void time(void)
{
FUNCPTR ptr=print;
timex(ptr,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
}
int print(void)
{
int i,j,k;
for(i=0;i<LOOP_CNT;i++)
{
for(j=0;j<LOOP_CNT;j++)
{
for(k=0;k<LOOP_CNT;k++)
{
printf("TASK\n");
}
}
}
}

82

OUTPUT:
The output of the program can be viewed in the Target console of the Windriver IDE
as follows.

83

Round Robin Scheduling Algorithm


AIM : To write a program to perform scheduling of 3 tasks by using Roundrobin scheduling
algorithm.

ALGORITHM:
1. Calculate the timeslice for the tasks using sysClkRateGet() function. If
kernelTimeSlice(TIMESLICE) function returns no error then proceed creating
tasks.
2. Create three tasks using taskSpawn() function specifying name of new task,
priority of new task, task option word, stackSize, FUNCPTR entryPt( entry point
of new task ), 10 task arguments to pass to function.
3. Store the TASK_ID returned by taskSpawn() function.
4. If there is any error in task spawning, print the error message.
5. If no error, then function pointer to the specified task will be called.

PROGRAM:
#include "vxWorks.h"
#include "stdio.h"
#include "taskLibCommon.h"
#include "kernelLib.h"
#include "sysLib.h"
void task1(void);
void task2(void);
void task3(void);
#define PRIORITY 100
#define TIMESLICE sysClkRateGet()/60
void sched(void)
{
int taskid1,taskid2,taskid3;
if(kernelTimeSlice(TIMESLICE)==OK)
printf("TIMESLICE=%d\n",TIMESLICE);
if((taskid1=taskSpawn("task1",PRIORITY,0x100,2000,(FUNCPTR)task1,0,0,0,0,0,0,0,0,0,0
))==ERROR)
printf("Task spawn TASK1 failed\n");
if((taskid2=taskSpawn("task2",PRIORITY,0x100,2000,(FUNCPTR)task2,0,0,0,0,0,0,0,0,0,0
))==ERROR)
printf("Task spawn TASK2 failed\n");
if((taskid3=taskSpawn("task3",PRIORITY,0x100,2000,(FUNCPTR)task3,0,0,0,0,0,0,0,0,0,0
))==ERROR)
84

printf("Task spawn TASK3 failed\n");


}
void task1()
{
int i,j,k,l;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
`
{
for(k=0;k<10;k++)
{
printf("TASK1\n");
}
}
}
}
void task2()
{
int i,j,k,l;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
for(k=0;k<10;k++)
{
printf("TASK2\n");
}
}
}
}
void task3()
{
int i,j,k,l;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
for(k=0;k<10;k++)
{
printf("TASK3\n");
}
}
}
}

85

OUTPUT:
The output of the program can be viewed in the Target console of the Windriver IDE
as follows.

86

Pre emptive Scheduling


AIM : To write a program to create 3 tasks with different priorities and schedule them
according to their priority using Preemptive scheduling algorithm.

ALGORITHM:
1.Create three tasks using taskSpawn() function specifying name of new task,
priority of new task, task option word, stackSize, FUNCPTR entryPt( entry point of
new task ), 10 task arguments to pass to function.
2. Create three tasks with different priorities.
3. Store the TASK_ID returned by taskSpawn() function.
4. If there is any error in task spawning, print the error message.
5. If no error, then function pointer to the specified task will be called.

PROGRAM:
#include "vxWorks.h"
#include "stdio.h"
#include "taskLibCommon.h"
#include "kernelLib.h"
#include "sysLib.h"
void task1(void);
void task2(void);
void task3(void);
#define HIGH 100
#define MED 101
#define LOW 102

void sched(void)
{
int taskid1,taskid2,taskid3;
if((taskid1=taskSpawn("task1",LOW,0x100,2000,(FUNCPTR)task1,0,0,0,0,0,0,0,0,0,0))==E
RROR)
printf("Task spawn TASK1 failed\n");
if((taskid2=taskSpawn("task2",MED,0x100,2000,(FUNCPTR)task2,0,0,0,0,0,0,0,0,0,0))==E
RROR)
printf("Task spawn TASK2 failed\n");
if((taskid3=taskSpawn("task3",HIGH,0x100,2000,(FUNCPTR)task3,0,0,0,0,0,0,0,0,0,0))==
ERROR)
printf("Task spawn TASK3 failed\n");
}
87

void task1()
{
int i,j,k,l;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
printf("TASK1\n");
}
}
}
}
void task2()
{
int i,j,k,l;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
printf("TASK2\n");
}
}
}
}
void task3()
{
int i,j,k,l;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
printf("TASK3\n");
}
}
}
}

88

OUTPUT:
The output of the program can be viewed in the Target console of the Windriver IDE
as follows.

89

Network Simulator 2

Pre-requisites :
Software required :
Operating System
Tools

:
:

Supporting Software:

Hardware required :

Ubuntu/Linux
NS2 ( Network Simulator software)
NAM ( Network Animator)
gedit ( or any other text editor)
Java runtime Environment( OpenJDK Java6
Runtime)

Nil

Development Board :

NA

Interfacing circuits :

NA

90

Familiarization of NS2
Aim : To familiarize NS2 programming environment and to develop a program to create 2
nodes and establish a link between them

Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program
# Create the Simulation environment
set ns [new Simulator]
#open a file in write mode to capture the simulation results
set nf [open out.nam w]
#initiate the trace process and write the trace information to the file
$ns namtrace-all $nf

#Closing procedure that will be called at the end of simulation


proc finish {} {
global ns nf
$ns flush-trace
close $nf
# run the network animator application with the data that has been collected
exec nam out.nam
exit 0
}

#Create 2 nodes
set n0 [$ns node]
set n1 [$ns node]
#Create a duplex link between the nodes
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
#call the closing procedure at the end of 5 ms of sim
$ns at 5.0 "finish"
#initiate the simulation process
$ns run

Enter and save the program in a file with the name as ns_exp1.tcl under a separate folder
under users home directory (eg: <user home>/ns2/lab_experiments ) using gedit.
To compile and run this program
1. Open Terminal window in Ubuntu from Dash Home
2. Go to <user home>/ns2/lab_experiments
3. From the command prompt, type ns ns_exp1.tcl
91

Output :

Result :
The program was compiled and executed and the plot of a network with 2 nodes
and a link was observed in the Network Animator window.

92

Creation of a Network Topology


Aim :
To Construct a network topology with 6 nodes

Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program

#Create Simulation Environment and open the required trace files


set ns [new Simulator]
set tr [open out.tr w]
$ns trace-all $tr
set namtr [open out.nam w]
#Initiate the trace
$ns namtrace-all $namtr
#create
#define
set n0
set n1
set n2
set n3
set n4
set n5

6 nodes
nodes
[$ns node]
[$ns node]
[$ns node]
[$ns node]
[$ns node]
[$ns node]

#define Links
$ns duplex-link
$ns duplex-link
$ns duplex-link
$ns duplex-link
$ns duplex-link
$ns duplex-link

$n0
$n1
$n2
$n3
$n4
$n5

$n1
$n2
$n3
$n4
$n5
$n0

1Mb
1Mb
1Mb
1Mb
1Mb
1Mb

10ms
10ms
10ms
10ms
10ms
10ms

#define the position of the links


$ns duplex-link-op $n0 $n1 orient
$ns duplex-link-op $n1 $n2 orient
$ns duplex-link-op $n2 $n3 orient
$ns duplex-link-op $n3 $n4 orient
$ns duplex-link-op $n5 $n4 orient
$ns duplex-link-op $n5 $n0 orient
proc

DropTail
DropTail
DropTail
DropTail
DropTail
DropTail
right
right-down
left-down
left
right-down
right-up

finish { } {
global tr namtr
close $tr
close $namtr
exec nam out.nam &
exit 0

}
$ns at 10.0
$ns run

"finish"

93

Enter and save the program in a file with the name as ns_exp2.tcl under a separate folder
under users home directory (eg: <user home>/ns2/lab_experiments ) using gedit.
To compile and run this program
1. Open Terminal window in Ubuntu from Dash Home
2. Go to <user home>/ns2/lab_experiments
3. From the command prompt, type ns ns_exp2.tcl
Output :

Result :
The program was compiled and executed and the plot of a network with 6 nodes
was observed. TCP and UCP traffics were also observed in the simulation

94

Creation of TCP and UDP traffic


Aim : Construct a topology with traffic parameters for TCP and UDP type of traffic.

Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program
#create a simulation environment and trace files
set ns [new Simulator]
set tr [open out.tr w]
$ns trace-all $tr
set namtr [open out.nam w]
$ns namtrace-all $namtr
#Define colours for different transmission
$ns color 1 Red
$ns color 2 Blue
#define
set n0
set n1
set n2
set n3
set n4
set n5

nodes
[$ns node]
[$ns node]
[$ns node]
[$ns node]
[$ns node]
[$ns node]

#define Links
$ns duplex-link
$ns duplex-link
$ns duplex-link
$ns duplex-link
$ns duplex-link

$n0
$n2
$n3
$n4
$n5

$n1
$n0
$n0
$n1
$n1

1Mb
1Mb
1Mb
1Mb
1Mb

10ms
10ms
10ms
10ms
10ms

#define the position of the links


$ns duplex-link-op $n0 $n1 orient
$ns duplex-link-op $n0 $n2 orient
$ns duplex-link-op $n0 $n3 orient
$ns duplex-link-op $n1 $n4 orient
$ns duplex-link-op $n1 $n5 orient

DropTail
DropTail
DropTail
DropTail
DropTail
right
left-up
left-down
right-up
right-down

#create UDP source


set udp0 [new Agent/UDP]
$ns attach-agent $n3 $udp0
$udp0 set class_ 1
#create UDP destination
set null0 [new Agent/Null]
$ns attach-agent $n5 $null0
#connecting UDP source &destination
$ns connect $udp0 $null0

95

#create the application generating the CBR traffic


set cbr0 [new Application/Traffic/CBR]
$cbr0 set rate 2Mb
#attach the application to agent
$cbr0 attach-agent $udp0
#create TCP source
set tcp0 [new Agent/TCP]
$ns attach-agent $n3 $tcp0
$tcp0 set class_ 2
#create TCP destination
set sink0 [new Agent/TCPSink]
$ns attach-agent $n4 $sink0
#connecting TCP source &destination
$ns connect $tcp0 $sink0
#create the application generating the FTP traffic
#and attach it to the agent
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns
$ns
$ns
$ns
proc

at
at
at
at

1.0
5.0
1.2
6.2

"$cbr0
"$cbr0
"$ftp0
"$ftp0

start"
stop"
start"
stop"

finish { } {
global tr namtr
close $tr
close $namtr
exec nam out.nam &
exit 0

}
$ns at 10.0
$ns run

"finish"

Enter and save the program in a file with the name as ns_exp3.tcl under a separate folder
under users home directory (eg: <user home>/ns2/lab_experiments ) using gedit
To compile and run this program
1. Open Terminal window in Ubuntu from Dash Home
2. Go to <user home>/ns2/lab_experiments
3. From the command prompt, type ns ns_exp3.tcl
4. Click the play button on the animator window and observe the TCP and UDP
traffic

96

Output :

Result :
CBR and FTP applications generated UDP and TCP data from node3 and it was
received by node 4 and node5 respectively. Traffic behavior for different link parameters
were traffic rates were also observed.

97

Study of Congestion in a network


Aim : To Construct a consisting of 3 links and to study the congestion of the intermediate
node

Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program
#Create Simulation Environment and open the required trace files
set ns [new Simulator]
set nf [open twoflows.nam w]
$ns namtrace-all $nf
$ns color 1 Blue
$ns color 2 Red
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam twoflows.nam &
exit 0
}
set
set
set
set

n0
n1
n2
n3

[$ns
[$ns
[$ns
[$ns

node]
node]
node]
node]

$ns duplex-link $n0 $n2 1Mb 10ms DropTail


$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n3 $n2 1Mb 10ms SFQ
$ns duplex-link-op $n2 $n0 orient left-up
$ns duplex-link-op $n2 $n1 orient left-down
$ns duplex-link-op $n2 $n3 orient right
set udp0 [new Agent/UDP]
$udp0 set class_ 2
$ns attach-agent $n0 $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set udp1 [new Agent/UDP]
$udp1 set class_ 1
$ns attach-agent $n1 $udp1

98

set cbr1 [new Application/Traffic/CBR]


$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n3 $null0
$ns connect $udp0 $null0
$ns connect $udp1 $null0
$ns
$ns
$ns
$ns
$ns
$ns

at 0.5
at 1.0
at 4.0
at 4.5
at 5.0
run

"$cbr0 start"
"$cbr1 start"
"$cbr1 stop"
"$cbr0 stop"
"finish"

Enter and save the program in a file with the name as ns_exp4.tcl under a separate
folder under users home directory (eg: <user home>/ns2/lab_experiments ) using gedit.
To compile and run this program
1. Open Terminal window in Ubuntu from Dash Home
2. Go to <user home>/ns2/lab_experiments
3. From the command prompt, type ns ns_exp4.tcl
4. Click on the play button on the animator window and observe that drop of
packets after the transmission has progressed for some time by setting the
speed of simulation to a very low value (10ms)
Output :

Result :
Topology with 3 Links were created and packet drop was observed at the
intermediate nodes.
99

Flow Control Mechanism in TCP


Aim : To study the window mechanism in TCP/IP

Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program
# This script is created by NSG2 beta1
#===================================
#
Simulation parameters setup
#===================================
set val(stop)
1

;# time of simulation end

#===================================
#
Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#Open the NS trace file
set tracefile [open out1.tr w]
$ns trace-all $tracefile
#Open the NAM trace file
set namfile [open out1.nam w]
$ns namtrace-all $namfile
$ns color 1 Red
$ns color 2 Blue
#===================================
#
Nodes Definition
#===================================
#Create 4 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#===================================
#
Links Definition
#===================================
#Createlinks between nodes
$ns duplex-link $n0 $n1 20.0Mb 1ms DropTail
$ns queue-limit $n0 $n1 50
$ns duplex-link $n1 $n2 20.0Mb 1ms DropTail
$ns queue-limit $n1 $n2 50
$ns duplex-link $n1 $n3 20.0Mb 1ms DropTail
$ns queue-limit $n1 $n3 50
#Give node position (for NAM)
$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n1 $n3 orient right-down

100

#===================================
#
Agents Definition
#===================================
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
$tcp0 set class_ 1
set sink2 [new Agent/TCPSink]
$ns attach-agent $n2 $sink2
$ns connect $tcp0 $sink2
$tcp0 set packetSize_ 100
$tcp0 set window_ 500
$tcp0 set maxcwnd_ 100
$tcp0 set windowInit_ 1
#Setup a TCP connection
set tcp1 [new Agent/TCP]
$ns attach-agent $n0 $tcp1
$tcp1 set class_ 2
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
$ns connect $tcp1 $sink3
$tcp1 set packetSize_ 100
$tcp1 set window_ 500
$tcp1 set maxcwnd_ 100
$tcp1 set windowInit_ 1
#===================================
#
Applications Definition
#===================================
#Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 0.1 "$ftp0 start"
$ns at 1.0 "$ftp0 stop"
#Setup a FTP Application over TCP connection
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
$ns at 0.4 "$ftp1 start"
$ns at 1.0 "$ftp1 stop"
#===================================
#
Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam out1.nam &
exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Enter and save the program in a file with the name as ns_exp5.tcl under a separate
101

folder under users home directory (eg: <user home>/ns2/lab_experiments ) using gedit.
To compile and run this program
1. Open Terminal window in Ubuntu from Dash Home
2. Go to <user home>/ns2/lab_experiments
3. From the command prompt, type ns ns_exp5.tcl
4. Click on the play button on the animator window and observe the change in
the number of packets being sent during the start of transmission
5. Also observe the change in the number of packets being sent after the
occurrence of a packet drop
Output :
Flow is starting with low value for the initial number or packets

Number of packets doubles for every cycle

One more new traffic created to introduce congestion


102

Number of packets for both the flows has reached the maximum

Due to the packet drops, the window size of second flow was reset to initial value

Result :
Topology with 3 Links were created and packet drop was observed at the
intermediate nodes.
103

Creation of Wireless Network


Aim : To create a wireless network and simulate the data traffic as one of the nodes move
around

Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program
# This script is created by NSG2 beta1
#===================================
#
Simulation parameters setup
#===================================
set val(chan)
Channel/WirelessChannel
;# channel type
set val(prop)
Propagation/TwoRayGround
;# radio-propagation model
set val(netif) Phy/WirelessPhy
;# network interface type
set val(mac)
Mac/802_11
;# MAC type
set val(ifq)
Queue/DropTail/PriQueue
;# interface queue type
set val(ll)
LL
;# link layer type
set val(ant)
Antenna/OmniAntenna
;# antenna model
set val(ifqlen) 50
;# max packet in ifq
set val(nn)
2
;# number of mobilenodes
set val(rp)
DSDV
;# routing protocol
set val(x)
1100
;# X dimension of topography
set val(y)
900
;# Y dimension of topography
set val(stop)
50.0
;# time of simulation end
#===================================
#
Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#Setup topography object
set topo
[new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)
#Open the NS trace file
set tracefile [open out.tr w]
$ns trace-all $tracefile
#Open the NAM trace file
set namfile [open out.nam w]
$ns namtrace-all $namfile
$ns namtrace-all-wireless $namfile $val(x) $val(y)
set chan [new $val(chan)];#Create wireless channel
#===================================
#
Mobile node parameter setup
#===================================
$ns node-config -adhocRouting $val(rp) \
-llType
$val(ll) \
-macType
$val(mac) \

104

-ifqType
-ifqLen
-antType
-propType
-phyType
-channel
-topoInstance
-agentTrace
-routerTrace
-macTrace
-movementTrace

$val(ifq) \
$val(ifqlen) \
$val(ant) \
$val(prop) \
$val(netif) \
$chan \
$topo \
ON \
ON \
ON \
ON

#===================================
#
Nodes Definition
#===================================
#Create 2 nodes
set n0 [$ns node]
$n0 set X_ 102
$n0 set Y_ 298
$n0 set Z_ 0.0
$ns initial_node_pos $n0 20
set n1 [$ns node]
$n1 set X_ 103
$n1 set Y_ 496
$n1 set Z_ 0.0
set
$n2
$n2
$n2

n2 [$ns node]
set X_ 500
set Y_ 800
set Z_ 0.0

$ns initial_node_pos $n1 20


#===================================
#
Generate movement
#===================================
$ns at 0.5 " $n0 setdest 1000 800 10 "
#===================================
#
Agents Definition
#===================================
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n1 $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n0 $sink1
$ns connect $tcp0 $sink1
$tcp0 set packetSize_ 100
#===================================
#
Applications Definition
#===================================
#Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 50.0 "$ftp0 stop"
#===================================
#
Termination
#===================================

105

#Define a 'finish' procedure


proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam out.nam &
exit 0
}
for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "\$n$i reset"
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Enter and save the program in a file with the name as ns_exp6.tcl under a separate
folder under users home directory (eg: <user home>/ns2/lab_experiments ) using gedit
To compile and run this program
1. Open Terminal window in Ubuntu from Dash Home
2. Go to <user home>/ns2/lab_experiments
3. From the command prompt, type ns ns_exp6.tcl
4. Click on the play button on the animator window and observe the data
transmission as the node1 moves away from the range of node0
Output :

Result :
A simple 2 node wireless network was set up and the data transmission was
observed as one node move away from the other.

106

Study of Routing logic in Ad-hoc Network


Aim : To create an network of multiple nodes and initiate a data transfer between 2 nodes
through and an intermediate node. Also to study the change in the routing as the second
node moves around

Procedure :
Diagrams : (Circuit/Block/Interfacing Diagrams)
Not Applicable
Program
# This script is created by NSG2 beta1
# <http://wushoupong.googlepages.com/nsg>
#===================================
#
Simulation parameters setup
#===================================
set val(chan)
Channel/WirelessChannel
;# channel type
set val(prop)
Propagation/TwoRayGround
;# radio-propagation model
set val(netif) Phy/WirelessPhy
;# network interface type
set val(mac)
Mac/802_11
;# MAC type
set val(ifq)
Queue/DropTail/PriQueue
;# interface queue type
set val(ll)
LL
;# link layer type
set val(ant)
Antenna/OmniAntenna
;# antenna model
set val(ifqlen) 50
;# max packet in ifq
set val(nn)
5
;# number of mobilenodes
set val(rp)
AODV
;# routing protocol
set val(x)
750
;# X dimension of topography
set val(y)
603
;# Y dimension of topography
set val(stop)
50.0
;# time of simulation end
#===================================
#
Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#Setup topography object
set topo
[new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)
#Open the NS trace file
set tracefile [open out2.tr w]
$ns trace-all $tracefile
#Open the NAM trace file
set namfile [open out2.nam w]
$ns namtrace-all $namfile
$ns namtrace-all-wireless $namfile $val(x) $val(y)
set chan [new $val(chan)];#Create wireless channel
#===================================
#
Mobile node parameter setup
#===================================
$ns node-config -adhocRouting $val(rp) \
-llType
$val(ll) \

107

-macType
-ifqType
-ifqLen
-antType
-propType
-phyType
-channel
-topoInstance
-agentTrace
-routerTrace
-macTrace
-movementTrace

$val(mac) \
$val(ifq) \
$val(ifqlen) \
$val(ant) \
$val(prop) \
$val(netif) \
$chan \
$topo \
ON \
ON \
ON \
ON

#===================================
#
Nodes Definition
#===================================
#Create 5 nodes
set n0 [$ns node]
$n0 set X_ 205
$n0 set Y_ 301
$n0 set Z_ 0.0
$ns initial_node_pos $n0 20
set n1 [$ns node]
$n1 set X_ 399
$n1 set Y_ 404
$n1 set Z_ 0.0
$ns initial_node_pos $n1 20
set n2 [$ns node]
$n2 set X_ 601
$n2 set Y_ 503
$n2 set Z_ 0.0
$ns initial_node_pos $n2 20
set n3 [$ns node]
$n3 set X_ 355
$n3 set Y_ 115
$n3 set Z_ 0.0
$ns initial_node_pos $n3 20
set n4 [$ns node]
$n4 set X_ 599
$n4 set Y_ 98
$n4 set Z_ 0.0
$ns initial_node_pos $n4 20
#===================================
#
Generate movement
#===================================
$ns at 0.5 " $n2 setdest 650 90 10 "
#===================================
#
Agents Definition
#===================================
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n2 $sink1
$ns connect $tcp0 $sink1
$tcp0 set packetSize_ 100
#===================================
#
Applications Definition
#===================================
#Setup a FTP Application over TCP connection

108

set ftp0 [new Application/FTP]


$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 50.0 "$ftp0 stop"
#===================================
#
Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam out2.nam &
exit 0
}
for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "\$n$i reset"
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Enter and save the program in a file with the name as ns_exp7.tcl under a separate
folder under users home directory (eg: <user home>/ns2/lab_experiments ) using gedit.
To compile and run this program
1. Open Terminal window in Ubuntu from Dash Home
2. Go to <user home>/ns2/lab_experiments
3. From the command prompt, type ns ns_exp7.tcl
4. Click on the play button on the animator window and observe the data
transmission as the node1 moves away from the range of node0
Output :
Initial route from Node0 to Node 3

Initial route from Node0 to Node 3 after node 3 moved to a different location
109

Result :
A network with multiple nodes were created and transmission was initiated with one
of the node moving. Change in the routing path was observed as the node moved around.

110

VHDL

Pre-requisites :
Software required :
Operating System

Windows

Tools

Xilinx

Supporting Software:
Hardware required :

N/A

Nil

Development Board :

NA

Interfacing circuits :

NA

111

FULL ADDER
AIM:
To verify the operation of full adder using dataflow and behavioral modelling in
VHDL

PROGRAM:
DATA FLOW MODELLING:
entity fulladder is
Port ( a : in STD_LOGIC;
b : in STD_LOGIC;
cin : in STD_LOGIC;
s : out STD_LOGIC;
ca : out STD_LOGIC);
end fulladder;
architecture dataflow of fulladder is
begin
s<=a xor b xor cin;
ca<=(a and b) or (b and cin) or (cin and a);
end dataflow;

BEHAVIORAL MODELLING:
entity fulladder is
Port ( a : in STD_LOGIC;
b : in STD_LOGIC;
cin : in STD_LOGIC;
sum : out STD_LOGIC;
carry : out STD_LOGIC);
end fulladder;
architecture Behavioral of fulladder is
begin
process(a,b,cin)
begin
sum<=a xor b xor cin;
carry<=(a and b) or (b and cin) or (cin and a);
end process;
end Behavioral;

OUTPUT:

112

MULTIPLEXER
AIM:
To verify the operation of 16:1 multiplexer using structural, dataflow and behavioral
modelling in VHDL.

PROGRAM:
STRUCTURAL MODELLING:
entity mux is
Port ( a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p:in bit;
s0 : in bit;
s1 : in bit;
s2 : in bit;
s3 : in bit;
q : out bit);
end mux;
architecture structural of mux is
component and2 is
port(a,b,c,d,e:in bit;
z:out bit);
end component;
component inv is
port(a:in bit;
b:out bit);
end component;
component or2 is
port(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p:in bit;
z:out bit);
end component;
signal
m1,m2,m3,m4,m5,m6,m7,m8,m9,m10,m11,m12,m13,m14,m15,m16,s0bar,s1bar,s2bar,s3
bar:bit;
begin
v1:inv port map(s0,s0bar);
v2:inv port map(s1,s1bar);
v3:inv port map(s2,s2bar);
v4:inv port map(s3,s3bar);
v5:and2 port map(a,s0bar,s1bar,s2bar,s3bar,m1);
v6:and2 port map(b,s0bar,s1bar,s2bar,s3,m2);
v7:and2 port map(c,s0bar,s1bar,s2,s3bar,m3);
v8:and2 port map(d,s0bar,s1bar,s2,s3,m4);
v9:and2 port map(e,s0bar,s1,s2bar,s3bar,m5);
v10:and2 port map(f,s0bar,s1,s2bar,s3,m6);
v11:and2 port map(g,s0bar,s1,s2,s3bar,m7);
v12:and2 port map(h,s0bar,s1,s2,s3,m8);
v13:and2 port map(i,s0,s1bar,s2bar,s3bar,m9);
v14:and2 port map(j,s0,s1bar,s2bar,s3,m10);
v15:and2 port map(k,s0,s1bar,s2,s3bar,m11);
v16:and2 port map(l,s0,s1bar,s2,s3,m12);
v17:and2 port map(m,s0,s1,s2bar,s3bar,m13);
113

v18:and2 port map(n,s0,s1,s2bar,s3,m14);


v19:and2 port map(o,s0,s1,s2,s3bar,m15);
v20:and2 port map(p,s0,s1,s2,s3,m16);
v21:or2 port map(m1,m2,m3,m4,m5,m6,m7,m8,m9,m10,m11,m12,m13,m14,m15,m16,q);
end structural;
entity and2 is
port(a,b,c,d,e:in bit;
z:out bit);
end and2;
architecture structural of and2 is
begin
z<=a and b and c and d and e;
end structural;
entity inv is
port(a:in bit;
b:out bit);
end inv;
architecture structural of inv is
begin
b<=not a;
end structural;
entity or2 is
port(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p:in bit;
z:out bit);
end or2;
architecture structural of or2 is
begin
z<=a or b or c or d or e or f or g or h or i or j or k or l or m or n or p;
end structural;

OUTPUT:

DATAFLOW MODELLING:
entity mux is
Port ( a : in STD_LOGIC_vector(15 downto 0);
sel : in STD_LOGIC_vector(3 downto 0);
114

cout : out STD_LOGIC);


end mux;
architecture dataflow of mux is
begin
cout<=a(0) when sel(0)='0' and sel(1)='0' and sel(2)='0' and sel(3)='0' else
a(1) when sel(0)='0' and sel(1)='0' and sel(2)='0' and sel(3)='1' else
a(2) when sel(0)='0' and sel(1)='0' and sel(2)='1' and sel(3)='0' else
a(3) when sel(0)='0' and sel(1)='0' and sel(2)='1' and sel(3)='1' else
a(4) when sel(0)='0' and sel(1)='1' and sel(2)='0' and sel(3)='0' else
a(5) when sel(0)='0' and sel(1)='1' and sel(2)='0' and sel(3)='1' else
a(6) when sel(0)='0' and sel(1)='1' and sel(2)='1' and sel(3)='0' else
a(7) when sel(0)='0' and sel(1)='1' and sel(2)='1' and sel(3)='1' else
a(8) when sel(0)='1' and sel(1)='0' and sel(2)='0' and sel(3)='0' else
a(9) when sel(0)='1' and sel(1)='0' and sel(2)='0' and sel(3)='1' else
a(10) when sel(0)='1' and sel(1)='0' and sel(2)='1' and sel(3)='0' else
a(11) when sel(0)='1' and sel(1)='0' and sel(2)='1' and sel(3)='1' else
a(12) when sel(0)='1' and sel(1)='1' and sel(2)='0' and sel(3)='0' else
a(13) when sel(0)='1' and sel(1)='1' and sel(2)='0' and sel(3)='1' else
a(14) when sel(0)='1' and sel(1)='1' and sel(2)='1' and sel(3)='0' else
a(15) when sel(0)='1' and sel(1)='1' and sel(2)='1' and sel(3)='1';
end dataflow;

BEHAVIORAL MODELLING:
entity mux is
Port ( a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p : in STD_LOGIC;
sel : in STD_LOGIC_vector(3 downto 0);
dout : out STD_LOGIC);
end mux;
architecture Behavioral of mux is
begin
process(sel)
begin
case sel is
when "0000"=>dout<=a;
when "0001"=>dout<=b;
when "0010"=>dout<=c;
when "0011"=>dout<=d;
when "0100"=>dout<=e;
when "0101"=>dout<=f;
when "0110"=>dout<=g;
when "0111"=>dout<=h;
when "1000"=>dout<=i;
when "1001"=>dout<=j;
when "1010"=>dout<=k;
when "1011"=>dout<=l;
when "1100"=>dout<=m;
when "1101"=>dout<=n;
when "1110"=>dout<=o;
when others=>dout<=p;
end case;
end process;
end Behavioral;
115

DECODER
AIM:
To verify the operation of decoder using behavioural, dataflow and structural
modelling in VHDL.

PROGRAM:
BEHAVIORAL MODELLING:
entity decoder is
Port ( a : in bit;
b : in bit;
en : in bit;
y : out bit_vector(3 downto 0));
end decoder;
architecture Behavioral of decoder is
begin
process(en)
begin
if(en<='0')then
y<="0000";
elsif(en<='1')then
if(a='0' and b='0')then y<="0001";
elsif(a='0' and b='1')then y<="0010";
elsif(a='1' and b='0')then y<="0100";
elsif(a='1' and b='1')then y<="1000";
end if;
end if;
end process;
end Behavioral;

DATAFLOW MODELLING:
entity decoder is
Port ( a : in bit;
b : in bit;
en : in bit;
y : out bit_vector(3 downto 0));
end decoder;
architecture dataflow of decoder is
signal abar,bbar:bit;
begin
abar<=not a;
bbar<=not b;
y(0)<=abar and bbar and en;
y(1)<=abar and b and en;
y(2)<=a and bbar and en;
y(3)<=a and b and en;
end dataflow;

STRUCTURAL MODELLING:
entity decoder is
Port ( a : in bit;
b : in bit;
en : in bit;
y : out bit_vector(3 downto 0));
end decoder;
116

architecture dataflow of decoder is


component and2 is
Port ( a : in bit;
b : in bit;
c:in bit;
y : out bit);
end component;
component inv is
Port ( a : in bit;
y : out bit);
end component;
signal abar,bbar:bit;
begin
v1:inv port map(a,abar);
v2:inv port map(b,bbar);
v3:and2 port map(abar,bbar,en,y(0));
v4:and2 port map(abar,b,en,y(1));
v5:and2 port map(a,bbar,en,y(2));
v6:and2 port map(a,b,en,y(3));
end dataflow;
entity and2 is
Port ( a : in bit;
b : in bit;
c:in bit;
y : out bit);
end and2;
architecture dataflow of and2 is
begin
y<=a and b and c;
end dataflow;
entity inv is
Port ( a : in bit;
y : out bit);
end inv;
architecture dataflow of inv is
begin
y<=not a;
end dataflow;

OUTPUT:

117

MAGNITUDE COMPARATOR
AIM:
To verify the operation of magnitude comparator using behavioral modelling in
VHDL

PROGRAM:
BEHAVIORAL MODELLING:
entity MAGCOMPARATOR is
Port ( a : in STD_LOGIC_VECTOR(3 downto 0);
b : in STD_LOGIC_VECTOR(3 downto 0);
gr : out STD_LOGIC;
le : out STD_LOGIC;
eq : out STD_LOGIC);
end MAGCOMPARATOR;
architecture Behavioral of MAGCOMPARATOR is
begin
process(a,b)
begin
if(a=b)then
gr <= '0';
le <= '0';
eq <= '1';
elsif(a<b)then
gr <= '0';
le <= '1';
eq <= '0';
elsif(a>b)then
gr <= '1';
le <= '0';
eq <= '0';
end if;
end process;
end Behavioral;

OUTPUT:

118

DEMULTIPLEXER
AIM:
To verify the operation of demultiplexer using behavioral modelling in VHDL

PROGRAM:
BEHAVIORAL MODELLING:
entity demux is
port(i:in std_logic;
s0,s1,s2: in std_logic;
y:out std_logic_vector(7 downto 0));
end demux;
architecture Dataflow of demux is
begin
y<="00000000" when i='0' else
"00000001" when s0='0' and s1='0' and s2='0' else
"00000010" when s0='0' and s1='0' and s2='1' else
"00000100" when s0='0' and s1='1' and s2='0' else
"00001000" when s0='0' and s1='1' and s2='1' else
"00010000" when s0='1' and s1='0' and s2='0' else
"00100000" when s0='1' and s1='0' and s2='1' else
"01000000" when s0='1' and s1='1' and s2='0' else
"10000000" when s0='1' and s1='1' and s2='1' ;
end Dataflow;

OUTPUT:

119

ALU
AIM:
To verify the operation of ALU using behavioral modelling in VHDL

PROGRAM:
BEHAVIORAL MODELLING:
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;
entity alu is
port( Clk : in std_logic;
A,B : in signed(7 downto 0);
Op : in unsigned(2 downto 0);
R : out signed(7 downto 0)
);
end alu;
architecture Behavioral of alu is
signal Reg1,Reg2,Reg3 : signed(7 downto 0) := (others => '0');
begin
Reg1 <= A;
Reg2 <= B;
R <= Reg3;
process(Clk)
begin
if(rising_edge(Clk)) then
case Op is
when "000" =>
Reg3 <= Reg1 + Reg2;
when "001" =>
Reg3 <= Reg1 - Reg2;
when "010" =>
Reg3 <= not Reg1;
when "011" =>
Reg3 <= Reg1 nand Reg2;
when "100" =>
Reg3 <= Reg1 nor Reg2;
when "101" =>
Reg3 <= Reg1 and Reg2;
when "110" =>
Reg3 <= Reg1 or Reg2;
when "111" =>
Reg3 <= Reg1 xor Reg2;
when others =>
NULL;
end case;
end if;
120

end process;
end Behavioral;

OUTPUT:

121

You might also like