[go: up one dir, main page]

0% found this document useful (0 votes)
85 views57 pages

WC Lab Manual

I'm assuming you meant "ML" as in Machine Learning. Machine Learning is a subset of Artificial Intelligence that involves training algorithms to learn from data and make predictions or decisions without being explicitly programmed. 1. Types of Machine Learning (Supervised, Unsupervised, Reinforcement)? 2. Machine Learning applications (Image Recognition, Natural Language Processing, Predictive Analytics)? 3. Popular Machine Learning algorithms (Linear Regre

Uploaded by

hetvikela987
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views57 pages

WC Lab Manual

I'm assuming you meant "ML" as in Machine Learning. Machine Learning is a subset of Artificial Intelligence that involves training algorithms to learn from data and make predictions or decisions without being explicitly programmed. 1. Types of Machine Learning (Supervised, Unsupervised, Reinforcement)? 2. Machine Learning applications (Image Recognition, Natural Language Processing, Predictive Analytics)? 3. Popular Machine Learning algorithms (Linear Regre

Uploaded by

hetvikela987
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

SANJAYBHAI RAJGURU COLLEGE OF

ENGINEERING
RAJKOT

LAB MANUAL

Wireless Communication
(3171608)
SANJAYBHAI RAJGURU COLLEGE OF
ENGINEERING
CERTIFICATE

This is to certify that Shri / Kum.


…………………………..…………………………………………………. Enroll No.
……………………..of B.E. ……th Semester……………………branch has
satisfactorily completed the laboratory work in ……………………….

Date of Submission: …………………………

Staff Sign Head of department


INDEX
Sr.No. Date Experiment Description Faculty Sign
1 Prepare a wireless Ad-hoc network and its working.

2 Write a MATLAB Program based on Free space


Propagation Model Free Space Path Loss Support for
Modeling Propagation in Free Space

3 Write a MATLAB Program based on Ground Reflection


(Two-ray) Model Two Ray Channel

4 Write a MATLAB Program based on Diffraction


Model.
5 Write a program that identifies the Bluetooth devices in
the wireless range

6 Write a program that prints the signal strength of WiFi


connection of the given computer

7 Write a program to find hamming distance. For


example Hamming distance d(v1,v2)=3 if
v1=011011,v2=110001.
PRACTICAL - 1
AIM: Prepare a wireless Ad-hoc network and its working.
 While non-technical people do not typically know it, it is possible to connect Wi-Fi
computers together without the use of a wireless router or access point; this feature is called
Ad-Hoc networking.
 With Ad-Hoc networking, the multiple computers are connected directly to each other
through the same wireless cards used to connect to the more standard wireless router or
access point. In this article, we will review the process of setting up an Ad-Hoc network on
Windows 7.

 How to Create an Ad-Hoc Network on Windows 7:-

Fig:1Windows 7 Networking and Sharing Center

Now, from this point, there are two different ways to setup an Ad-Hoc network:

 one uses the Setup a connection or network wizard

 the other utilizes the Manage Wireless Networks control panel

The choice of which one to use depends on your preference. The setup of the Ad-Hoc network only
needs to be performed on the first computer being configured.
 Ad-Hoc Network Configuration using the Setup a Connection or Network Wizard:-

 When using the wizard method, the first task to perform requires the selection of 'Set up a
new connection or network' option from the main window; this is shown in Figure 1.

Figure 2: Setup a Connection or Network

 At the bottom of the list shown in the window is the option to Set up a wireless ad hoc
(computer-to-computer) network. Once this option is selected the window shown in Figure 3
is displayed.

Figure 3: Set up a wireless ad hoc network


 The window shown in Figure 3 describes the Ad Hoc network and describes the
requirements. Once you review the text on this window select next.

Figure 4: Give your network a name and choose security options

 The next window shown in Figure 4 lets the user select the Network name, Security type and
Security key which will be used between the computers. It is always recommended that a
strong security option is used even when only connecting together two computers as it is
always possible for a nearby person to exploit the lack of security.
 There is also an option to Save this network; when this box is selected, the Ad-Hoc wireless
network is saved in the list of available wireless networks to connect to.

Figure 5: The Ad-Hoc network is ready to use


 Once the Ad-Hoc network has been set up, the window shown in Figure 5 will be displayed;
this completes the process using the wizard method.

 Ad-Hoc Network Configuration using the Manage Wireless Network


Control Panel:-
 Using the Manage Wireless Networks control panel method, the first task is to select the
Manage wireless networks option from the top left of the main window; this is shown in
Figure 6.

Figure 6: Manage Wireless Networks

Figure 7: Manage Wireless Networks that use (Wireless Network Connection)


 Once the Manage wireless networks selection has been selected, the window shown in Figure
7 is shown. From this window, the next option is to select the Add selection to add a wireless
network.

Figure 8: How do you want to add a network?

 Once the Add selection is selected, the window shown in Figure 8 is displayed. From this
window the option to 'Create an ad hoc network' would be used to create an ad hoc network.

Figure 9: Setup a wireless Ad-Hoc network


 Once this option has been selected, a familiar window is shown that runs through the same
set up a wireless ad hoc network selection that are used in the previous method. This process
is shown in figures 9, 10 and 11.

Figure 10: Give your network a name and choose security options

Figure 11: The Ad-Hoc network is ready to use

 Now, if you selected the option to Save this network when creating the Ad-Hoc network, it
will show up under Manage wireless networks as shown in Figure 12.
Figure 12: Manage wireless networks that use (Wireless Network Connection)

 Regardless of whether the Save this network option was selected, the computer is going to
connect to the just created Ad-Hoc network. However, if the network was not saved, once the
computer is rebooted or if a connection is made to another wireless network then the Ad-Hoc
network will not be an available option without recreating it again.

Figure 13: Available Networks

 Connecting to an Already Created Ad-Hoc Network:-


 The configuration of the computers connecting to an already created Ad-Hoc wireless
network is the same as connecting to any other type of wireless network. Figure 14 shows the
available wireless networks as shown on the other computers. The different icon shown to the
right of each network name shows the type of wireless network.

Figure 14: Open Network and Sharing Center

 Simply select the network and choose connect. If no wireless security was selected, then the
network will be connected; if wireless security was configured then the window shown in
Figure 15 will be displayed to allow the entry of the security key.

figure 15: Wireless Security

 Once the network is connected, the network will show as connected as shown in Figure 16.
Figure 16: Connected to Wireless Ad-Hoc Network

 IP Addressing in Ad-Hoc Networks:-


 Now, another important thing to remember is that typically there is no DHCP server running
on computer hosts. What this means is that there will be no IP address automatically assigned
as is typically done when using a wireless router or access point.
 Two options are available: either to use APIPA addressing (169.254.0.0/16) which will
permit a connection between the two computers automatically when a DHCP server is unable
to be contacted or using static IP addressing.
 Figures 17 and 18 show the output from the ‘ipconfig' and ‘arp –a' commands on two
computers connected via an Ad-Hoc network using APIPA addressing. The two computers'
addresses can be seen in each other's ARP tables.
Figure 17: Windows IP Configuration
Figure 18: Windows IP Configuration

 The Ad-Hoc network is very useful when trying to connect computers together which have
wireless capabilities and no active wireless router or access point to connect them together. If
the need to network computers together in these situations happens, the Ad-Hoc option is
certainly an easy to setup option which enables these abilities.

1)Explain physical and logical architecture of the wireless network


2) How Mobile IP does works
PRACTICAL – 2
AIM: Write a MATLAB Program based on Free space Propagation Model

Free Space Path Loss


Support for Modeling Propagation in Free Space

Propagation environments have significant effects on the amplitude, phase, and shape of
propagating space-time wavefields. In some cases, you may want to simulate a system that
propagates narrowband signals through free space. If so, you can use the phased. Free
Space System object™ to model the range-dependent time delay, phase shift, Doppler shift, and
gain effects.
Consider this object as a point-to-point propagation channel. By setting object properties, you
can customize certain characteristics of the environment and the signals propagating through it,
including:
 Propagation speed and sampling rate of the signal you are propagating
 Signal carrier frequency
 Whether the object models one-way or two-way propagation
Each time you call step on a phased. Free Space object, you specify not only the signal to
propagate, but also the location and velocity of the signal origin and destination.
You can use fspl to determine the free space path loss, in decibels, for a given distance and
wavelength.

Free Space Path Loss in dB

Assume a transmitter is located at (1000,250,10) in the global coordinate system. Assume a


target is located at (3000,750,20). The transmitter operates at 1 GHz. Determine the free space
path loss in decibels for a narrowband signal propagating to and from the target.
[tgtrng,~] = rangeangle([3000; 750; 20],[1000; 250; 10]);

Determine the wavelength for 1 GHz.

lambda = physconst('LightSpeed')/1e9;

Solve for the two-way loss in dB using fspl. The two-way loss is twice the one-way loss.

L = 2*fspl(tgtrng,lambda)
L = 197.4635
The free space path loss in decibels is approximately 197.5 dB.
Alternatively, you can compute the loss directly from
Loss = 2*pow2db((4*pi*tgtrng/lambda)^2)

Loss = 197.4635

Propagate Linear FM Pulse Waveform to Target and Back

Construct a linear FM pulse waveform of 50 ms duration with a bandwidth of 100 kHz. Model
the range-dependent time delay and amplitude loss incurred during two-way propagation. The
pulse propagates between the transmitter located at (1000,250,10) and a target located
at (3000,750,20). The signals propagate at the speed of light.

waveform = phased.LinearFMWaveform('SweepBandwidth',1e5,...
'PulseWidth',5e-5,'OutputFormat','Pulses',...
'NumPulses',1,'SampleRate',1e6,'PRF',1e4);
signal = waveform();
channel = phased.FreeSpace('SampleRate',1e6,...
'TwoWayPropagation',true,'OperatingFrequency',1e9);
y = channel(signal,[1000; 250; 10],[3000; 750; 20],[0;0;0],[0;0;0]);

Plot the magnitude of the transmitted and received pulse to show the amplitude loss and time
delay.

t = unigrid(0,1/waveform.SampleRate,1/waveform.PRF,'[)');
subplot(2,1,1)
plot(t.*1e6,abs(signal))
title('Magnitude of Transmitted Pulse')
xlabel('Time (microseconds)')
ylabel('Magnitude')
subplot(2,1,2)
plot(t.*1e6,abs(y))
title('Magnitude of Received Pulse')
xlabel('Time (microseconds)')
ylabel('Magnitude')
The delay in the received pulse is approximately 14 μs, the expected value for a distance of 4.123
km.
1) What is Bluetooth? Explain concept of piconet and scatter net in Bluetooth.
PRACTICAL - 3
AIM: Write a MATLAB Program based on Ground Reflection (Two-ray)
Model

Two Ray Channel

The Two Ray Channel models a narrowband two-ray propagation channel. A two-ray
propagation channel is the simplest type of multipath channel. You can use a two-ray channel to
simulate propagation of signals in a homogeneous, isotropic medium with a single reflecting
boundary. This type of medium has two propagation paths: a line-of-sight (direct) propagation
path from one point to another and a ray path reflected from the boundary. You can use this
System object for short-range radar and mobile communications applications where the signals
propagate along straight paths and the earth is assumed to be flat. You can also use this object for
sonar and microphone applications. For acoustic applications, you can choose the fields to be
non-polarized and adjust the propagation speed to be the speed of sound in air or water. You can
use Two Ray Channel to model propagation from several points simultaneously.
While the System object works for all frequencies, the attenuation models for atmospheric gases
and rain are valid for electromagnetic signals in the frequency range 1–1000 GHz only. The
attenuation model for fog and clouds is valid for 10–1000 GHz. Outside these frequency ranges,
the System object uses the nearest valid value.
The Two Ray Channel System object applies range-dependent time delays to the signals, and as
well as gains or losses, phase shifts, and boundary reflection loss. The System object applies
Doppler shift when either the source or destination is moving.
Signals at the channel output can be kept separate or be combined — controlled by
the Combined Rays Output property. In the separate option, both fields arrive at the destination
separately and are not combined. For the combined option, the two signals at the source
propagate separately but are coherently summed at the destination into a single quantity. This
option is convenient when the difference between the sensor or array gains in the directions of
the two paths is not significant and need not be taken into account.
Unlike the phased. Free Space System object, the Two Ray Channel System object does not
support two-way propagation.
To perform two-ray channel propagation:
 Create the Two Ray Channel object and set its properties.
 Call the object with arguments, as if it were a function.
Syntax

prop_sig = channel(sig,origin_pos,dest_pos,origin_vel,dest_vel)

Description

prop_sig = channel (sig,origin_pos,dest_pos,origin_vel,dest_vel) returns the resulting


signal, prop_sig, when a narrowband signal, sig, propagates through a two-ray channel from
the origin_pos position to the dest_pos position. Either the origin_pos or dest_pos arguments can
have multiple points but you cannot specify both as having multiple points. The velocity of the
signal origin is specified in origin_vel and the velocity of the signal destination is specified
in dest_vel. The dimensions of origin_vel and dest_vel must agree with the dimensions
of origin_pos and dest_pos, respectively.

Electromagnetic fields propagated through a two-ray channel can be polarized or nonpolarized.


For, nonpolarized fields, such as an acoustic field, the propagating signal field, sig, is a vector or
matrix. When the fields are polarized, sig is an array of structures. Every structure element
represents an electric field vector in Cartesian form.

In the two-ray environment, there are two signal paths connecting every signal origin and
destination pair. For N signal origins (or N signal destinations), there are 2N number of paths.
The signals for each origin-destination pair do not have to be related. The signals along the two
paths for any single source-destination pair can also differ due to phase or amplitude differences.

You can keep the two signals at the destination separate or combined — controlled by
the Combined Rays Output property. Combined means that the signals at the source propagate
separately along the two paths but are coherently summed at the destination into a single
quantity. To use the separate option, set Combined Rays Output to false. To use
the combined option, set Combined Rays Output to true. This option is convenient when the
difference between the sensor or array gains in the directions of the two paths is not significant
and need not be taken into account.

Scalar Field Propagating in Two-Ray Channel


This example illustrates the two-ray propagation of a signal, showing how the signals from the
line-of-sight and reflected path arrive at the receiver at different times.

Create and Plot Propagating Signal


Create a nonpolarized electromagnetic field consisting of two rectangular waveform pulses at a
carrier frequency of 100 MHz. Assume the pulse width is 10 ms and the sampling rate is 1 MHz.
The bandwidth of the pulse is 0.1 MHz. Assume a 50% duty cycle in so that the pulse width is
one-half the pulse repetition interval. Create a two-pulse wave train. Set
the GroundReflectionCoefficient to 0.9 to model strong ground reflectivity. Propagate the field
from a stationary source to a stationary receiver. The vertical separation of the source and
receiver is approximately 10 km.

c = physconst('LightSpeed');
fs = 1e6;
pw = 10e-6;
pri = 2*pw;
PRF = 1/pri;
fc = 100e6;
lambda = c/fc;
waveform = phased.RectangularWaveform('SampleRate',fs,'PulseWidth',pw,...
'PRF',PRF,'OutputFormat','Pulses','NumPulses',2);
wav = waveform();
n = size(wav,1);
figure;
plot((0:(n-1)),real(wav),'b.-');
xlabel('Time (samples)')
ylabel('Waveform magnitude')
Specify the Location of Source and Receiver
Place the source and receiver about 1000 meters apart horizontally and approximately 10 km
apart vertically.
pos1 = [1000;0;10000];
pos2 = [0;100;100];
vel1 = [0;0;0];
vel2 = [0;0;0];

Compute the predicted signal delays in units of samples.


[rng,ang] = rangeangle(pos2,pos1,'two-ray');

Create a Two-Ray Channel System Object


Create a two-ray propagation channel System object™ and propagate the signal along both the
line-of-sight and reflected ray paths.
channel = twoRayChannel('SampleRate',fs,...
'GroundReflectionCoefficient',.9,'OperatingFrequency',fc,...
'CombinedRaysOutput',false);
prop_signal = channel([wav,wav],pos1,pos2,vel1,vel2);

Plot the Propagated Signals


 Plot the signal propagated along the line-of-sight.
 Then, overlay a plot of the signal propagated along the reflected path.
 Finally, overlay a plot of the coherent sum of the two signals.

n = size(prop_signal,1);
delay = 0:(n-1);
plot(delay,abs(prop_signal(:,1)),'g')
hold on
plot(delay,abs(prop_signal(:,2)),'r')
plot(delay,abs(prop_signal(:,1) + prop_signal(:,2)),'b')
hold off
legend('Line-of-sight','Reflected','Combined','Location','NorthWest')
xlabel('Delay (samples)')
ylabel('Signal Magnitude')
The plot shows that the delay of the reflected path signal agrees with the predicted delay. The
magnitude of the coherently combined signal is less than either of the propagated signals
indicating that there is some interference between the two signals.
1) what are HLR and VLR? Describe its functions in call routing and roaming
PRACTICAL - 4
AIM: Write a MATLAB Program based on Diffraction Model.
The amplitude of a diffracted scalar wave of frequency and wave vector magnitude can be
accurately represented by an integral over surface elements of contributions of the form
where is the value of the wavefront within the aperture, is the distance between this source point
and an observation point, and is the angle to the observation point from the normal to the
incident wave front. The term proportional to (the dominant part at large distances) is halved at
and vanishes in the backwards direction (). If application, we have and the far field result
expresses Huygens’s principle.
This script calculates the observed intensity distribution for a plane wave normally incident upon
a plane containing a rectangular aperture and observed striking a parallel viewing plane at some
distance. The integral for the amplitude is a harmonic function of time and we set t=0. The real
and imaginary parts differ only in phase. The intensity is proportional to the time average of the
square of either and hence to the square of the absolute value of the complex quantity.

Calculate the wave amplitude on the viewing screen.


Initialize array to hold amplitudes on the viewing screen.
Q=[];
Create a function to calculate the contribution to the total unnormalized amplitude at the viewing
point from a source point.

func = @(x,y,xp,yp,zp)(exp(i*k.*((x-xp).^2+(y-yp).^2+(z-zp).^2).^(1/2))...

./((x-xp).^2+(y-yp).^2+(z-zp).^2).^(1/2))...

.*(1*i*k+(zp./((x-xp).^2+(y-yp).^2+(z-zp).^2).^(1/2)).*(1*i*k+((x-xp).^2+(y-yp).^2+(z-
zp).^2).^(-1/2)));

Loop over y-positions on the viewing screen.

tic
for yp=yprange

Initialize a column vector to contain amplitude values for a column of screen position values.

q=[];
Loop over x positions on the viewing screen.
for xp=xprange
Create a function to calculate the total amplitude at the viewing position for the given field point.
%fun = @(x,y)exp(i*k.*((x-xp).^2+(y-yp).^2+(z-zp).^2).^(1/2))./((x-xp).^2+(y-yp).^2+(z-
zp).^2).^(1/2);
fun=@(x,y)func(x,y,xp,yp,zp);
Integrate the function over the slit and aggregate the values in the column vector.
q=[q ;integral2(fun,xmin,xmax,ymin,ymax,'Method','tiled','RelTol',RelTol)];
end
Aggregate column vectors.
Q=[Q q];
end
toc

Plot the intensity along the x-axis of the viewing screen.


Find the index corresponding to the x-axis on the viewing screen.
sizeQ=size(Q);
midindex=round(sizeQ(2)/2);
Extract the vector of amplitudes along the x-axis of the viewing screen.
q=Q(:,midindex);
Construct the corresponding intensity vector normalized to its maximum value.
I=abs(q);I=I/max(I);
Plot the intensity along the screen x-axis.
figure
mask=I>0;
semilogy(xprange(mask),I(mask),'.-')
title('Single slit diffraction pattern')
xlabel('x_{screen} (wavelengths)');ylabel('Relative intensity')
For an aperture narrow in x, at large distance, the intensity exhibits a standard diffraction pattern
along the x-direction.
Plot the intensity along the y-axis of the viewing screen.
sizeQ=size(Q);
midindex=round(sizeQ(1)/2);
Extract the vector of amplitudes along the y-axis of the viewing screen.
q=Q(midindex,:);
Construct the corresponding intensity vector normalized to its maximum value.
I=abs(q);I=I/max(I);

Plot the intensity along the screen y-axis.


figure
mask=I>0;
semilogy(yprange(mask),I(mask),'.-')
title('Single slit diffraction pattern')
xlabel('y_{screen} (wavelengths)');ylabel('Relative intensity')

For an aperture wide in y, at large distance, the intensity approximates the shape of the aperture
but is still modulated by diffraction fringes.

Make a 2D color map of the intensity on the viewing screen.


Scale the units to correspond to a nominal laser wavelength.
figure
lam=.65e-6;
xprange_meter=xprange*lam;
yprange_meter=yprange*lam;
[X,Y]=ndgrid(xprange_meter,yprange_meter);
pcolor(X,Y,log(abs(Q)));shading interp;
colorbar
%axis equal % Uncomment this line to equalize the x and y scales
title(['Intensity for \lambda=',num2str(lam),' m'])
subtitle(['Delta x =',num2str(2*xmax*lam*1e6),' \mu; Delta y =',num2str(2*ymax*lam*1e6),'
\mu'])
xlabel('x (m)');ylabel('y (m)')
1)Explain the functioning of cellular network. How the given set of frequencies are
used to increase the capacity of a network.
PRACTICAL - 5
AIM: Write a program that identifies the Bluetooth devices in the wireless
range

REMOTE CONTROL SERVER


Here is my RemoteBluetoothServer class:
package com.luugiathuy.apps.remotebluetooth;

public class RemoteBluetoothServer{

public static void main(String[] args) {


Thread waitThread = new Thread(new WaitThread());
waitThread.start();
}

The main method creates a thread to wait for connection from client and handle the signal.

package com.luugiathuy.apps.remotebluetooth;

import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class WaitThread implements Runnable {


/** Constructor */
public WaitThread() {
}
@Override

public void run() {


waitForConnection();
}

/** Waiting for connection from devices */


private void waitForConnection() {
// retrieve the local Bluetooth device object
LocalDevice local = null;

StreamConnectionNotifier notifier;
StreamConnection connection = null;

// setup the server to listen for connection


try {
local = LocalDevice.getLocalDevice();
local.setDiscoverable(DiscoveryAgent.GIAC);

UUID uuid = new UUID(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"


String url = "btspp://localhost:" + uuid.toString() + ";name=RemoteBluetooth";
notifier = (StreamConnectionNotifier)Connector.open(url);
} catch (Exception e) {
e.printStackTrace();
return;
}
// waiting for connection
while(true) {
try {
System.out.println("waiting for connection...");
connection = notifier.acceptAndOpen();

Thread processThread = new Thread(new ProcessConnectionThread(connection));


processThread.start();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
}
package com.luugiathuy.apps.remotebluetooth;

import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.InputStream;
import javax.microedition.io.StreamConnection;
public class ProcessConnectionThread implements Runnable {
private StreamConnection mConnection;

// Constant that indicate command from devices

private static final int EXIT_CMD = -1;


private static final int KEY_RIGHT = 1;
private static final int KEY_LEFT = 2;

public ProcessConnectionThread(StreamConnection connection)


{
mConnection = connection;
}
@Override
public void run() {
try {
// prepare to receive data
InputStream inputStream = mConnection.openInputStream();
System.out.println("waiting for input");
while (true) {
int command = inputStream.read();
if (command == EXIT_CMD) {
System.out.println("finish process");
break;
}
processCommand(command);
}

} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Process the command from client
* @param command the command code
*/

private void processCommand(int command) {


try {
Robot robot = new Robot();
switch (command) {

case KEY_RIGHT:

robot.keyPress(KeyEvent.VK_RIGHT);
System.out.println("Right");
break;
case KEY_LEFT:
robot.keyPress(KeyEvent.VK_LEFT);
System.out.println("Left");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
REMOTE CONTROL CLIENT (Android)

The RemoteBluetooth class is our main activity for this application:

protected void onStart() {


super.onStart();

// If BT is not on, request that it be enabled.


// setupCommand() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
// otherwise set up the command service
else {
if (mCommandService==null)
setupCommand();
}
}

private void setupCommand() {


// Initialize the BluetoothChatService to perform bluetooth connections
mCommandService = new BluetoothCommandService(this, mHandler);
}
The onStart() function to check whether the bluetooth on our phone is enabled or not. If not, it
creates an Intent to turn the bluetooth on.
The setupCommand() to create BluetoothCommandService object to send the command when
we push the Volume Up and Down buttons:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
mCommandService.write(BluetoothCommandService.VOL_UP);
return true;
}
else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
mCommandService.write(BluetoothCommandService.VOL_DOWN);
return true;
}

return super.onKeyDown(keyCode, event);


}
1) Explain Difference between 1G, 2G, 2.5G and 3G mobile communications.
```
PRACTICAL - 6
AIM: Write a program that prints the signal strength of WiFi connection of
the given computer

package com.example.sairamkrishna.myapplication;

import android.net.wifi.WifiManager
;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {


Button enableButton,disableButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

enableButton=(Button)findViewById(R.id.button1);
disableButton=(Button)findViewById(R.id.button2);

enableButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
});
disableButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="76dp"
android:text="Enable Wifi"
android:layout_centerVertical="true"
android:layout_alignEnd="@+id/imageView" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disable Wifi"
android:layout_marginBottom="93dp"
android:layout_alignParentBottom="true"
android:layout_alignStart="@+id/imageView" />

</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sairamkrishna.myapplication" >
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name=".MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>
</manifest>
1) Discuss Applications of mobile computing
PRACTICAL - 7
AIM: Write a program to find hamming distance. For example Hamming distance
d(v1,v2)=3 if v1=011011,v2=110001.

public class Hamming


{
private String compOne;
private String compTwo;

public Hamming(String one, String two)


{
compOne = one;
compTwo = two;
}

///
// Calculating the Hamming Distance for two strings requires the string to be of the same
length.
///
public int getHammingDistance()
{
if (compOne.length() != compTwo.length())
{
return -1;
}

int counter = 0;

for (int i = 0; i < compOne.length(); i++)


{
if (compOne.charAt(i) != compTwo.charAt(i)) counter++;
}

return counter;
}

///
// Hamming distance works best with binary comparisons, this function takes a string arrary
of binary
// values and returns the minimum distance value
///
public int minDistance(String[] numbers)
{
int minDistance = Integer.MAX_VALUE;

if (checkConstraints(numbers))
{
for (int i = 1; i < numbers.length; i++)
{
int counter = 0;
for (int j = 1; j <= numbers[i].length(); j++)
{
if (numbers[i-1].charAt(j-1) != numbers[i].charAt(j-1))
{
counter++;
}
}

if (counter == 0) return counter;


if (counter < minDistance) minDistance = counter;
}
}
else
{
return -1;
}

return minDistance;
}

private Boolean checkConstraints(String[] numbers)


{
if (numbers.length > 1 && numbers.length <=50)
{
int prevLength = -1;
for (int i = 0; i < numbers.length; i++)
{
if (numbers[i].length() > 0 && numbers[i].length() <= 50)
{
if (prevLength == -1)
{
prevLength = numbers[i].length();
}
else
{
if (prevLength != numbers[i].length())
{
return false;
}
}

for (int j = 0; j < numbers[i].length(); j++)


{
if (numbers[i].charAt(j) != '0' && numbers[i].charAt(j) != '1')
{
return false;
}
}
}
else
{
return false;
}
}
}
else
{
return false;
}

return true;
}
}
1)Explain functional architecture of GSM system. What are the possible handover
scenarios in GSM?
2) Explain RFID and WiMAX.

You might also like