You are on page 1of 85

Smartphone Android Controlled Robot

INTRODUCTION TO ROBOTICS
1.1 ROBOTICS

Robotics is the branch of technology that deals with the design, construction,
operation, and application of robots, as well as computer systems for their
control, sensory feedback, and information processing. These technologies
deal with automated machines that can take the place of humans in
dangerous environments or manufacturing processes, or resemble humans in
appearance, behaviour, and/or cognition.

The concept of creating machines that can operate autonomously dates back
to classical times, but research into the functionality and potential uses of
robots did not grow substantially until the 20th century. Throughout history,
robotics has been often seen to mimic human behaviour, and often manage
tasks in a similar fashion. Today, robotics is a rapidly growing field, as
technological advances continue; research, design, and building new robots
serve various practical purposes, whether domestically, commercially, or
militarily. Many robots do jobs that are hazardous to people such as defusing
bombs, mines and exploring shipwrecks.

1.2 INTRODUCTION TO ROBOTS

A robot is a mechanical or virtual artificial agent, usually an electro-


mechanical machine that is guided by a computer program or electronic
circuitry.By mimicking a lifelike appearance or automating movements, a robot
may convey a sense of intelligence or thought of its own.

Robots have replaced humans in the assistance of performing those repetitive


and dangerous tasks which humans prefer not to do, or are unable to do due
to size limitations, or even those such as in outer space or at the bottom of the
sea where humans could not survive the extreme environments.

1.3 HISTORY OF ROBOTS

The history of robots has its origins in the ancient world. The modern concept
began to be developed with the onset of the Industrial Revolution which
allowed for the use of complex mechanics and the subsequent introduction of
electricity. This made it possible to power machines with small compact
motors. In the early 20th century, the modern formulation of a humanoid
machine was developed. Today, it is now possible to envisage human sized
robots with the capacity for near human thoughts and movement.

Following points briefly describe the history of robots:

1.3.1 The Indian Lokapannatti (11th/12th century) tells the story of King
Ajatasatru of Magadha who gathered the Buddhas relics and hid them in an

BBDNIITPage 1
Smartphone Android Controlled Robot

underground stupa. The Buddhas relics were protected by mechanical robots


(bhuta vahana yanta), from the kingdom of Roma visaya; until they were
disarmed by King Ashoka.

1.3.2 Inancient China, an account on automata is found in the Lie Zi text,


written in the 3rd century BC, in which King Mu of Zhou (1023–957 BC) is
presented with a life-size, human-shaped mechanical figure by Yan Shi, an
"artificer".

1.3.3 One of the first recorded designs of a humanoid robot was made by
Leonardo da Vinci (1452–1519) in around 1495. Da Vinci's notebooks,
rediscovered in the 1950s, contain detailed drawings of a mechanical knight in
armour which was able to sit up, wave its arms and move its head and jaw.

1.3.4 The first electronic autonomous robots with complex behaviour were
created by William Grey Walter of the Burden Neurological Institute at Bristol,
England in 1948 and 1949. He wanted to prove that rich connections between
a small number of brain cells could give rise to very complex behaviours -
essentially that the secret of how the brain worked lay in how it was wired up.
His first robots, named Elmer and Elsie, were constructed between 1948 and
1949 and were often described as tortoises due to their shape and slow rate
of movement. The three-wheeled tortoise robots were capable of phototaxis,
by which they could find their way to a recharging station when they ran low
on battery power.

1.3.5 Further progress on robots was possible only after the 1950s with the
invention of transistors and integrated circuits. The first digitally operated and
programmable robot was invented by George Devol in 1954 and was
ultimately called the Unimate. This ultimately laid the foundations of the
modern robotics industry.

1.4 TYPES OF ROBOTS

Following points illustrate different types of robots:

1.4.1 Mobile robots

Mobile robots have the capability to move around in their environment and are
not fixed to one physical location. An example of a mobile robot that is in
common use today is the automated guided vehicle or automatic guided
vehicle (AGV). An AGV is a mobile robot that follows markers or wires in the
floor, or uses vision or lasers.

1.4.2 Industrial robots

Industrial robots usually consist of a jointed arm (multi-linked manipulator) and

BBDNIITPage 2
Smartphone Android Controlled Robot

anend effector that is attached to a fixed surface. One of the most common
type of end effector is a gripper assembly.

1.4.3 Service robot

Most commonly industrial robots are fixed robotic arms and manipulators
used primarily for production and distribution of goods. The term "service
robot" is less well-defined. The International Federation of Robotics has
proposed a tentative definition, "A service robot is a robot which operates
semi- or fully autonomously to perform services useful to the well-being of
humans and equipment, excluding manufacturing operations."

Fig. A pick and place robot in a factory (Service Robot)

1.4.4 Educational robot

Robots are used as educational assistants to teachers. From the 1980s,


robots such as turtles were used in schools and programmed using several
languages.

1.4.5 Modular robot

Modular robots are a new breed of robots that are designed to increase the
utilization of robots by modularizing their architecture. The functionality and
effectiveness of a modular robot is easier to increase compared to
conventional robots. These robots are composed of a single type of identical,
several different identical module types, or similarly shaped modules, which
vary in size. Their architectural structure allows hyper-redundancy for modular
robots, as they can be designed with more than 8 degrees of freedom (DOF).
Creating the programming, inverse kinematics and dynamics for modular
robots is more complex than with traditional robots.

1.4.6 Collaborative robot

BBDNIITPage 3
Smartphone Android Controlled Robot

A collaborative robot or cobot is a robot that can safely and effectively interact
with human workers while performing simple industrial tasks. However, end-
effectors and other environmental conditions may create hazards, and as
such risk assessments should be done before using any industrial motion-
control application.

1.5 CONTEMPORARY USES OF ROBOTS

1.5.1 General-purpose autonomous robots

General-purpose autonomous robots can perform a variety of functions


independently. General-purpose autonomous robots typically can navigate
independently in known spaces, handle their own re-charging needs, interface
with electronic doors and elevators and perform other basic tasks.

1.5.2 Factory robots

Car production

Over the last three decades, automobile factories have become dominated by
robots. A typical factory contains hundreds of industrial robots working on fully
automated production lines, with one robot for every ten human workers. On
an automated production line, a vehicle chassis on a conveyor is welded,
glued, painted and finally assembled at a sequence of robot stations.

Packaging

Industrial robots are also used extensively for palletizing and packaging of
manufactured goods, for example for rapidly taking drink cartons from the end
of a conveyor belt and placing them into boxes, or for loading and unloading
machining centers.

Electronics

Mass-produced printed circuit boards (PCBs) are almost exclusively


manufactured by pick-and-place robots, typically with SCARA manipulators,
which remove tiny electronic components from strips or trays, and place them
on to PCBs with great accuracy. Such robots can place hundreds of
thousands of components per hour, far out-performing a human in speed,
accuracy, and reliability.

Dirty, dangerous, dull or inaccessible tasks

There are many jobs which humans would rather leave to robots. The job may
be boring, such as domestic cleaning, or dangerous, such as exploring inside
a volcano.

BBDNIITPage 4
Smartphone Android Controlled Robot

1.5.3 Space Probes robots

Almost every unmanned space probe ever launched was a robot. Some were
launched in the 1960s with very limited abilities, but their ability to fly and land
is an indication of their status as a robot.

1.5.4 Domestic robots

Domestic robots are simple robots dedicated to a single task work in home
use. They are used in simple but unwanted jobs, such as vacuum cleaning
and floor washing, and lawn mowing.

1.5.5 Military robots

Military robots are currently used in ground-based combat. They can use a
variety of weapons and there is some discussion of giving it some degree of
autonomy in battleground situations.

Unmanned combat air vehicles (UCAVs), which are an upgraded form of


UAVs, can do a wide variety of missions, including combat.

Fig. A military robot used in the US Army.

1.5.6 Mining robots

Mining robots are designed to help counteract a number of challenges


currently facing the mining industry, including skills shortages, improving
productivity from declining ore grades, and achieving environmental targets.
Due to the hazardous nature of mining, in particular underground mining, the
prevalence of autonomous, semi-autonomous, and tele-operated robots has
greatly increased in recent times

1.5.7 Healthcare

Robots in healthcare have two main functions. Those which assist an


individual, such as a sufferer of a disease like Multiple Sclerosis, and those
which aid in the overall systems such as pharmacies and hospitals.

BBDNIITPage 5
Smartphone Android Controlled Robot

Fig. A robotic leg powered by the air muscles used in healthcare

1.5.8 Research robots

While most robots today are installed in factories or homes, performing labour
or life saving jobs, many new types of robot are being developed in
laboratories around the world. Much of the research in robotics focuses not on
specific industrial tasks, but on investigations into new types of robot,
alternative ways to think about or design robots, and new ways to
manufacture them. It is expected that these new types of robot will be able to
solve real world problems when they are finally realized.

BBDNIITPage 6
Smartphone Android Controlled Robot

INTRODUCTION ABOUT PROJECT

2.1 INTRODUCTION

This project is about smart phone android operated robot. Here, we will create
a robot which will be controlled by a smart phone having android software in
it. The robot will be programmed according to the instructions from the smart
phone. The robot will act exactly as per the instructions from the smart phone.
It can move in any direction and can pick up object.

Smart phone is used because of its easy availability and current use. The
robot is well suited for different industrial purposes.

Fig. Block diagram of the project

2.2 CIRCUIT DIAGRAM

The circuit diagram for the project is shown on next page. It describes
different components and their interconnections

BBDNIITPage 7
Smartphone Android Controlled Robot

Here, a Bluetooth module is used to control the robot via 2 BO motors at


100RPM appox. The robot is control by an android phone application.

Microcontroller used is AT89S52 form 8051 family to work in a serial


communication UART mode the communication is configured on 9800bps to
communicate it with the Bluetooth module.
The Bluetooth module used is a HC-05 in smd package which works on a
3.3v and have a serial communication with any device connected to it the
communication speed can be configured on various speed via AT Command.
The BT module is a SPP supported profile so it can be connected easily to
any module or phone. In this profile the data can be sent and receive to
module. The BT module is connected to the RX pin of microcontroller.
The L293D is a motor driver IC to operate the motors in any direction required
dependent on the logic applied to the logic pins.
A readymade compact size chassis have been used to avoid the chassis
assembly. The chassis contains 2 decks the lower is used for BO motors
fitting the upper is used as a battery stack .on top the plate the board is
mounted by screw fitting.

Fig. Circuit Diagram

BBDNIITPage 8
Smartphone Android Controlled Robot

PROJECT COMPONENTS

For implementing any project, many components are required. This section
names such components and their brief description.

3.1 ATMEGA8L-8PU MICROCONTROLLER

The AVR is a modified Harvard architecture 8-bit RISC single


chip microcontroller which was developed by Atmel in 1996. The AVR was
one of the first microcontroller families to use on-chip flash memory for
program storage, as opposed to one-time programmable ROM, EPROM,
or EEPROM used by other microcontrollers at the time.
The AVR is a modified Harvard architecture machine where program and data
are stored in separate physical memory systems that appear in different
address spaces, but having the ability to read data items from program
memory using special instructions.

Fig.Pin diagram of ATMEGA8L-8PU microcontroller

BBDNIITPage 9
Smartphone Android Controlled Robot

SPECIFICATIONS-
High-performance, Low-power AVR 8-bit Microcontroller
- 130 Powerful Instructions - Most Single Clock Cycle Execution
- 32 x 8 General Purpose Working Registers
- Up to 6 MIPS Throughput at 16MHz
- Fully Static Operation
- On-chip 2-cycle Multiplier
Nonvolatile Program and Data Memories
- 8k Bytes of In-System Self-Programmable Flash
- Optional Boot Code Section with Independent Lock Bits
- 512K Bytes EEPROM
- Programming Lock for Software Security
- 1K Byte Internal SRAM
Peripheral Features
- On-chip Analog Comparator
- Programmable Watchdog Timer with Separate On-chip Oscillator
- Master/Slave SPI Serial Interface
- Two 8-bit Timer/Counters with Separate Prescaler, Compare
- One 16-bit Timer/Counter with Separate Prescaler, Compare and Capture
mode
- Real Time Counter with Separate Oscillator
- Three PWM Channels
- 8-channel ADC in TQFP and MLF package
- 6-channel ADC in PDIP package
- Byte-oriented Two-wire Serial Interface
- Programmable Serial USART
Special Microcontroller Features
- Power-on Reset and Programmable Brown-out Detection
- Internal Calibrated RC Oscillator
- External and Internal Interrupt Sources
- Five Sleep Modes: Idle, ADCNoise Reduction, Power-save, Power-down
and Standby
I/O and Packages
- 23 Programmable I/O Lines
- 28-lead PDIP, 32-lead TQFP, 32-pad MLF
Operating Voltages
- 4.5-5.5V for ATmega8L
Speed Grades
- 0-16 MHz for ATmega8L
Power Consumption
- Active: 3.6mA

BBDNIITPage 10
Smartphone Android Controlled Robot

- Idle Mode: 10mA


- Power-down Mode: 0.5 µA

3.2 HC-05 MODULE (BLUETOOTH)

The HC-05 small size Bluetooth TTL transceiver module are designed for
serial communication (SPP - serial port profile). It allows your target device to
both send or receive TTL data via Bluetooth technology without connecting a
serial cable to your computer.

Fig.HC-05 module (bluetooth)

Hardware details:
Built-in CSR company Bluetooth chip BC417143
Bluetooth® Technology v2.0 + EDR
TTL data transparent transfer between a host Bluetooth device
Compatible with all Bluetooth adapters that support SPP
Coverage up to 30 ft / 10 m
Built in antenna
Power input: +3.3VDC (bluetooth module)
Can set the module control parameters and control commands via AT
commands
The maximum serial baud rate: 1382400 bps, support for hardware flow
control transfer
Provide seven input and output ports
Connection/non-connection status indicators

BBDNIITPage 11
Smartphone Android Controlled Robot

Basic AT commands
Command Return Parameter Description

AT OK None Test

AT+VERSION? +VERSION:<Param> OK Param: Version number Get the soft


version

AT+ORGL OK None Restore default


status

AT+ADDR? +ADDR: <Param> OK Param: Bluetooth Get module


address Bluetooth
address

AT+NAME=<Param> OK Param: Bluetooth Set device’s


device name name

AT+NAME? +NAME:<Param> OK Param: Bluetooth Inquire device’s


device name name

AT+ROLE=<Param> OK Param:0=Slave role; Set module


1=Master role; 2=Slave- role
Loop role

AT+ ROLE? + ROLE:<Param> Param:0=Slave role; Inquire module


1=Master role; 2=Slave- role
Loop role

AT+UART=<Param>,<Param2>,<Param3> OK Param1: baud rate( Set serial


bits/s); Param2: stop parameter
bit; Param3: parity bit

AT+ UART? +UART=<Param>,<Param2>,<Param3> Param1: baud rate( Inquire serial


OK bits/s); Param2: stop parameter
bit; Param3: parity bit

3.3 LM317T IC

The LM317 is a popular adjustable linear voltage regulator. It was invented


by Robert C. Dobkin and Robert J. Widlar in 1970while they worked
at National Semiconductor.
The LM337, a negative complement to the LM317, regulates voltages below,
rather than above, the reference.

Fig Pin diagram of LM317T IC

BBDNIITPage 12
Smartphone Android Controlled Robot

Specifications

Attribute Value
Vout range 1.25 V – 37 V
Vin – Vout difference 3 V – 40 V
Operation ambient temperature 0 °C – 125 °C
Output Imax 1.5 A (with proper heat sinking)
Minimum Load Current 3.5 mA typical, 12 mA maximum[2]

Operation
As linear regulators, the LM317 and LM337 are used in DC to DC
converter applications.
Linear regulators inherently draw as much current as they supply. When this
current is multiplied by the voltage difference between input and output, a
significant amount of power is wasted as heat. This is not just inefficient, but a
significant design consideration; a heat sink is commonly required. For large
voltage differences, the wasted power can be more than the power supplied.
This trade-off must be accepted when using linear regulators, which are a
simple way to provide a stable voltage with few additional components. The
alternative is to use a switching voltage regulator, which is usually more
efficient, but tends to take up more space and require a higher component
count.
In packages with a heat-dissipating mounting tab, such as TO-220, the tab is
connected internally to the output pin, which may make it necessary to
electrically isolate the tab or the heat sink from other parts of the application
circuit.

3.4 L7805CV IC
The 78xx (sometimes L78xx, LM78xx, MC78xx...) is a family of self-contained
fixed linear voltage regulator integrated circuits. The 78xx family is commonly
used in electronic circuits requiring a regulated power supply due to their
ease-of-use and low cost. For ICs within the family, the xx is replaced with two
digits, indicating the output voltage (for example, the 7805 has a 5 volt output,
while the 7812 produces 12 Volts). The 78xx line are positive voltage
regulators: they produce a voltage that is positive relative to a common
ground. There is a related line of 79xx devices which are complementary
negative voltage regulators. 78xx and 79xx ICs can be used in combination to
provide positive and negative supply voltages in the same circuit.
78xx ICs have three terminals and are commonly found in the TO220 form
factor, although smaller surface-mount and larger TO3packages are available.

BBDNIITPage 13
Smartphone Android Controlled Robot

These devices support an input voltage anywhere from a few Volts over the
intended output voltage, up to a maximum of 35 to 40 Volts depending on the
make, and typically provide 1 or 1.5 amperes of current (though smaller or
larger packages may have a lower or higher current rating).

Advantages

78xx series ICs do not require additional components to provide a constant,


regulated source of power, making them easy to use, as well as economical
and efficient uses of space. Other voltage regulators may require additional
components to set the output voltage level, or to assist in the regulation
process. Some other designs (such as a switched-mode power supply) may
need substantial engineering expertise to implement.
78xx series ICs have built-in protection against a circuit drawing too much
power. They have protection against overheating and short-circuits, making
them quite robust in most applications. In some cases, the current-limiting
features of the 78xx devices can provide protection not only for the 78xx itself,
but also for other parts of the circuit.

Disadvantages

The input voltage must always be higher than the output voltage by some
minimum amount (typically 2.5 Volts). This can make these devices
unsuitable for powering some devices from certain types of power sources
(for example, powering a circuit that requires 5 Volts using 6-Volt batteries will
not work using a 7805).
As they are based on a linear regulator design, the input current required is
always the same as the output current. As the input voltage must always be
higher than the output voltage, this means that the total power (voltage
multiplied by current) going into the 78xx will be more than the output power
provided. The extra input power is dissipated as heat. This means both that
for some applications an adequate heatsink must be provided, and also that a
(often substantial) portion of the input power is wasted during the process,
rendering them less efficient than some other types of power supplies. When
the input voltage is significantly higher than the regulated output voltage (for
example, powering a 7805 using a 24 volt power source), this inefficiency can
be a significant issue.

BBDNIITPage 14
Smartphone Android Controlled Robot

3.5 L293D / L293DNE IC

The L293 and L293D are quadruple high-current half-H drivers. The L293 is
designed to provide bidirectional drive currents of up to 1 A at voltages from
4.5 V to 36 V. The L293D is designed to provide bidirectional drive currents of
up to 600-mA at voltages from 4.5 V to 36 V. Both devices are designed to
drive inductive loads such as relays, solenoids, dc and bipolar stepping
motors, as well as other high-current/high-voltage loads in positive-supply
applications.
All inputs are TTL compatible. Each output is a complete totem-pole drive
circuit, with a Darlington transistor sink and a pseudo-Darlington source.
Drivers are enabled in pairs, with drivers 1 and 2 enabled by 1,2EN and
drivers 3 and 4 enabled by 3,4EN. When an enable input is high, the
associated drivers are enabled and their outputs are active and in phase with
their inputs. When the enable input is low, those drivers are disabled and their
outputs are off and in the high-impedance state. With the proper data inputs,
each pair of drivers forms a full-H (or bridge) reversible drive suitable for
solenoid or motor applications.
On the L293, external high-speed output clamp diodes should be used for
inductive transient suppression.
A VCC1 terminal, separate from VCC2, is provided for the logic inputs to
minimize device power dissipation.
The L293and L293D are characterized for operation from 0°C to 70°C.

Features

Wide Supply-Voltage Range: 4.5 V to 36 V


Separate Input-Logic Supply
Internal ESD Protection
Thermal Shutdown
High-Noise-Immunity Inputs
Functional Replacements for SGS L293 and SGS L293D
Output Current 1 A Per Channel (600 mA for L293D)

BBDNIITPage 15
Smartphone Android Controlled Robot

Peak Output Current 2 A Per Channel (1.2 A for L293D)


Output Clamp Diodes for Inductive Transient Suppression (L293D)

Pin No Function Name


1 Enable pin for Motor 1; active high Enable 1,2
2 Input 1 for Motor 1 Input 1
3 Output 1 for Motor 1 Output 1
4 Ground (0V) Ground
5 Ground (0V) Ground
6 Output 2 for Motor 1 Output 2
7 Input 2 for Motor 1 Input 2
8 Supply voltage for Motors; 9-12V (up to 36V) Vcc 2
9 Enable pin for Motor 2; active high Enable 3,4
10 Input 1 for Motor 1 Input 3
11 Output 1 for Motor 1 Output 3
12 Ground (0V) Ground
13 Ground (0V) Ground
14 Output 2 for Motor 1 Output 4
15 Input2 for Motor 1 Input 4
16 Supply voltage; 5V (up to 36V) Vcc 1

Fig. Pin diagram of L293D / L293DNE IC

BBDNIITPage 16
Smartphone Android Controlled Robot

OTHER COMPONENTS

4.1 WHEELS
A wheel is a circular component that is intended to rotate on an axial bearing.
The wheel is one of the main components of thewheel and axle which is one
of the six simple machines. Wheels, in conjunction with axles, allow heavy
objects to be moved easily facilitating movement or transportation while
supporting a load, or performing labor in machines. Wheels are also used for
other purposes, such as a ship's wheel, steering wheel, potter's
wheel and flywheel.

Fig. Wheel

4.2 GRIPPER

In robotics, an end effector is the device at the end of a robotic arm,


designed to interact with the environment. The exact nature of this device
depends on the application of the robot.
Generally, the gripping mechanism is done by the grippers or mechanical
fingers. Generally only two-finger grippers are used for industrial robots as
they tend to be built for specific tasks and can therefore be less complex

Fig. Gripper

BBDNIITPage 17
Smartphone Android Controlled Robot

4.3 TOY MOTOR


The motor being dissected here is a simple electric motor that you would
typically find in a toy.
You can see that this is a small motor, about as big around as a dime. From
the outside you can see the steel can that forms the body of the motor, an
axle, a nylon end cap and two battery leads. If you hook the battery leads of
the motor up to a flashlight battery, the axle will spin. If you reverse the leads,
it will spin in the opposite direction. Here are two other views of the same
motor. (Note the two slots in the side of the steel can in the second shot --
their purpose will become more evident in a moment.)
The nylon end cap is held in place by two tabs that are part of the steel can.
By bending the tabs back, you can free the end cap and remove it. Inside the
end cap are the motor's brushes. These brushes transfer power from the
battery to the commutator as the motor spins:

Fig. Toy Motor

4.4 MICRO-SWITCH
This is small switch for interconnection. It has 4 terminals with 2 in pair
already connected .when you press the switch all four get connected.

Fig. Micro-switch
4.5 LED
A light-emitting diode (LED) is a two-lead semiconductor light source that
resembles a basic pn-junction diode, except that an LED also emits
light. When an LED's anode lead has a voltage that is more positive than its
cathode lead by at least the LED's forward voltage drop, current
flows. Electrons are able to recombine with holeswithin the device, releasing

BBDNIITPage 18
Smartphone Android Controlled Robot

energy in the form of photons. This effect is called electroluminescence, and


the color of the light (corresponding to the energy of the photon) is determined
by the energy band gap of the semiconductor.
An LED is often small in area (less than 1 mm2), and integrated optical
components may be used to shape its radiation pattern.

Fig. LED

4.6 RESISTANCE
The electrical resistance of an electrical conductor is the opposition to the
passage of an electric current through that conductor. The inverse quantity
is electrical conductance, the ease with which an electric current passes.
Electrical resistance shares some conceptual parallels with the mechanical
notion of friction. The SI unit of electrical resistance is theohm (Ω), while
electrical conductance is measured in siemens (S).
An object of uniform cross section has a resistance proportional to
its resistivity and length and inversely proportional to its cross-sectional area.
All materials show some resistance, except for superconductors, which have
a resistance of zero.
The resistance (R) of an object is defined as the ratio of voltage across it (V)
to current through it (I), while the conductance (G) is the inverse:

Fig. Resistance

BBDNIITPage 19
Smartphone Android Controlled Robot

HARDWARE INSTALLATIONS

Fig. Hardware Installations


Following steps are followed for making hardware installation of the project:
5.1 Take a cardboard mica of size 7 X 5 inches.

5.2 Attach the wheels by screws.

5.3 Mount the Printed Circuit Board(PCB) on the cardboard.

5.4 Install all the components and wires on the PCB according to their
working.

5.5 Also install two gear motors and connect them with the rest of the circuit to
make the circuit work.

5.6 Install the required Android app on the smartphone to control the robot.

5.7 Now give instructions from the smartphone to make the robot move in all
the four directions.

BBDNIITPage 20
Smartphone Android Controlled Robot

PROGRAM IN MICROCONTROLLER
Code used:

void UP(void)
{
PORTC5_bit = 1; //left motors
PORTC4_bit = 0;

PORTC3_bit = 1; //F //right motors


PORTC2_bit = 0;
}

void DOWN(void)
{
PORTC5_bit = 0;
PORTC4_bit = 1;

PORTC3_bit = 0; //B
PORTC2_bit = 1;
}

void LEFT(void)
{
PORTC5_bit = 0;
PORTC4_bit = 1;

PORTC3_bit = 1;
PORTC2_bit = 0;
}

void RIGHT(void)
{
PORTC5_bit = 1;
PORTC4_bit = 0;

PORTC3_bit = 0;
PORTC2_bit = 1;
}

void OK(void)
{
PORTC5_bit = 0;
PORTC4_bit = 0;
PORTC3_bit = 0;
PORTC2_bit = 0;
PORTC1_bit = 0;

BBDNIITPage 21
Smartphone Android Controlled Robot

PORTC0_bit = 0;
}

void OPEN(void)
{
PORTC1_bit = 1;
PORTC0_bit = 0;
}

void CLOSE(void)
{
PORTC1_bit = 0;
PORTC0_bit = 1;
}

void TASK() iv 0x00B


{
RXC0_bit = 0;
switch(UART_Read())
{
case 'U' :
UART1_Write('U');
UP();
break;

case 'D' :
UART1_Write('D');
DOWN();
break;

case 'R' :
UART1_Write('R');
LEFT();
break;

case 'L' :
UART1_Write('L');
RIGHT();
break;

case 'C' :
UART1_Write('C');
OK();
break;

BBDNIITPage 22
Smartphone Android Controlled Robot

case 'a' :
UART1_Write('a');
CLOSE();
break;

case 'e' :
UART1_Write('e');
OPEN();
break;
}
}

void main()
{

PWM16bit_Init(_PWM16_PHASE_CORRECT_MODE_8BIT,
_PWM16_PRESCALER_16bit_8, _PWM16_NON_INVERTED, 128, 1);
PWM16bit_Start(_TIMER1 );
delay_ms(5000);
PWM16bit_Change_Duty(10, _TIMER1_CH_B );

delay_ms(5000);
PWM16bit_Change_Duty(50, _TIMER1_CH_B );

delay_ms(5000);
PWM16bit_Change_Duty(254, _TIMER1_CH_B );

PORTB0_bit = ~PORTB0_bit; //PORTC = 0x55;


delay_ms(1000);
PORTB0_bit = ~PORTB0_bit; //PORTC = 0xAA;
delay_ms(1000);
PORTB0_bit = ~PORTB0_bit; //PORTC = 0x55;
delay_ms(1000);
PORTB0_bit = ~PORTB0_bit; //PORTC = 0xAA;
delay_ms(1000);
RXCIE_bit = 1;
SREG_I_bit = 1;

UART1_Init(9600);
while(1)
{
PORTB0_bit = ~PORTB0_bit;
delay_ms(100);
}

BBDNIITPage 23
Smartphone Android Controlled Robot

INTRODUCTION OF ANDROID

7.1 INTRODUCTION

Android is an operating system based on the Linux kernel, and designed


primarily for touchscreen mobile devices such as smartphones and tablet
computers. Initially developed by Android, Inc., which Google backed
financially and later bought in 2005, Android was unveiled in 2007 along with
the founding of the Open Handset Alliance—a consortium of hardware,
software, and telecommunication companies devoted to advancing open
standards for mobile devices. The first publicly available smartphone running
Android, the HTC Dream, was released on October 22, 2008.

The user interface of Android is based on direct manipulation, using touch


inputs that loosely correspond to real-world actions, like swiping, tapping,
pinching, and reverse pinching to manipulate on-screen objects. Internal
hardware—such as accelerometers, gyroscopes, and proximity sensors—is
used by some applications to respond to additional user actions, for example
adjusting the screen from portrait to landscape depending on how the device
is oriented. Android allows users to customize their home screens with
shortcuts to applications and widgets, which allow users to display live
content, such as emails and weather information, directly on the home screen.
Applications can further send notifications to the user to inform them of
relevant information, such as new emails and text messages.

Android's source code is released by Google under the Apache


License;[17] this permissive licensing allows the software to be freely modified
and distributed by device manufacturers, wireless carriers and enthusiast
developers. Most Android devices ship with a combination of open source and
proprietary software. As of July 2013, Android has the largest number of
applications ("apps"), available for download in Google Play store which has
had over 1 million apps published, and over 50 billion downloads. A developer
survey conducted in April–May 2013 found that Android is the most used

BBDNIITPage 24
Smartphone Android Controlled Robot

platform among developers: it is used by 71% of the mobile developers


population.

Android is popular with technology companies which require a ready-made,


low-cost and customizable operating system for high-tech devices. Despite
being primarily designed for phones and tablets, it also has been used in
televisions, games consoles, digital cameras, and other electronics. Android's
open nature has encouraged a large community of developers and
enthusiasts to use the open-source code as a foundation for community-
driven projects, which add new features for advanced users or bring Android
to devices which were officially released running other operating systems.

As of May 2012, Android became the most popular mobile OS, having the
largest installed base, and is a market leader in most countries including the
United States; there it has had the highest installed base of mobile phones for
years. In the third quarter of 2013, Android's share of the global smartphone
shipment market—led by Samsung products—was 81.3%, the highest
ever. In most markets Android-powered phones are the most popular
comprising more than half of the overall smartphone sales, including the
United States market starting with the September–November 2013
period. The operating system's success has made it a target for patent
litigation as part of the so-called "smartphone wars" between technology
companies. As of September 2013, one billion Android devices have been
activated.

BBDNIITPage 25
Smartphone Android Controlled Robot

Fig. Basic android symbol with android smartphone

7.2 ABOUT ANDOIRD SDK

The Android SDK provides you the API libraries and developer tools
necessary to build, test, and debug apps for Android.

If you're a new Android developer, we recommend you download the ADT


Bundle to quickly start developing apps. It includes the essential Android SDK
components and a version of the Eclipse IDE with built-in ADT (Android
Developer Tools) to streamline your Android app development.

With a single download, the ADT Bundle includes everything you need to
begin developing apps:

 Eclipse + ADT plugin


 Android SDK Tools
 Android Platform-tools
 The latest Android platform
 The latest Android system image for the emulator

BBDNIITPage 26
Smartphone Android Controlled Robot

Fig. Basic android development tool screen

BBDNIITPage 27
Smartphone Android Controlled Robot

BLUETOOTH API

8.1 INTRODUCTION

The Android platform includes support for the Bluetooth network stack, which
allows a device to wirelessly exchange data with other Bluetooth devices. The
application framework provides access to the Bluetooth functionality through
the Android Bluetooth APIs. These APIs let applications wirelessly connect to
other Bluetooth devices, enabling point-to-point and multipoint wireless
features.

Using the Bluetooth APIs, an Android application can perform the following:

 Scan for other Bluetooth devices


 Query the local Bluetooth adapter for paired Bluetooth devices
 Establish RFCOMM channels
 Connect to other devices through service discovery
 Transfer data to and from other devices
 Manage multiple connections
This document describes how to use Classic Bluetooth. Classic Bluetooth is
the right choice for more battery-intensive operations such as streaming and
communicating between Android devices.

This document describes how to use the Android Bluetooth APIs to


accomplish the four major tasks necessary to communicate using Bluetooth:
setting up Bluetooth, finding devices that are either paired or available in the
local area, connecting devices, and transferring data between devices.

All of the Bluetooth APIs are available in the android.bluetoothpackage.


Here's a summary of the classes and interfaces you will need to create
Bluetooth connections:

BluetoothAdapter
Represents the local Bluetooth adapter (Bluetooth radio).
The BluetoothAdapter is the entry-point for all Bluetooth interaction. Using

BBDNIITPage 28
Smartphone Android Controlled Robot

this, you can discover other Bluetooth devices, query a list of bonded (paired)
devices, instantiate a BluetoothDevice using a known MAC address, and
create aBluetoothServerSocket to listen for communications from other
devices.

BluetoothDevice
Represents a remote Bluetooth device. Use this to request a connection with
a remote device through aBluetoothSocket or query information about the
device such as its name, address, class, and bonding state.

BluetoothSocket
Represents the interface for a Bluetooth socket (similar to a TCP Socket).
This is the connection point that allows an application to exchange data with
another Bluetooth device via InputStream and OutputStream.

BluetoothServerSocket
Represents an open server socket that listens for incoming requests (similar
to a TCP ServerSocket). In order to connect two Android devices, one device
must open a server socket with this class. When a remote Bluetooth device
makes a connection request to the this device, the BluetoothServerSocketwill
return a connected BluetoothSocket when the connection is accepted.

BluetoothClass
Describes the general characteristics and capabilities of a Bluetooth device.
This is a read-only set of properties that define the device's major and minor
device classes and its services. However, this does not reliably describe all
Bluetooth profiles and services supported by the device, but is useful as a hint
to the device type.

Bluetooth Permissions
In order to use Bluetooth features in your application, you must declare the
Bluetooth permission BLUETOOTH. You need this permission to perform any
Bluetooth communication, such as requesting a connection, accepting a
connection, and transferring data.

BBDNIITPage 29
Smartphone Android Controlled Robot

If you want your app to initiate device discovery or manipulate Bluetooth


settings, you must also declare theBLUETOOTH_ADMIN permission. Most
applications need this permission solely for the ability to discover local
Bluetooth devices. The other abilities granted by this permission should not be
used, unless the application is a "power manager" that will modify Bluetooth
settings upon user request. Note: If you
useBLUETOOTH_ADMIN permission, then you must also have
the BLUETOOTH permission.

Declare the Bluetooth permission(s) in your application manifest file. For


example:

<manifest ... >


<uses-permissionandroid:name="android.permission.BLUETOOTH"/>
...

</manifest>

Setting Up Bluetooth

Fig. The enabling Bluetooth dialog


Before your application can communicate over Bluetooth, you need to verify
that Bluetooth is supported on the device, and if so, ensure that it is enabled.

If Bluetooth is not supported, then you should gracefully disable any Bluetooth
features. If Bluetooth is supported, but disabled, then you can request that the
user enable Bluetooth without leaving your application. This setup is
accomplished in two steps, using the BluetoothAdapter.

BBDNIITPage 30
Smartphone Android Controlled Robot

Get the BluetoothAdapter


The BluetoothAdapter is required for any and all Bluetooth activity. To get
the BluetoothAdapter, call the static getDefaultAdapter()method. This returns
a BluetoothAdapter that represents the device's own Bluetooth adapter (the
Bluetooth radio). There's one Bluetooth adapter for the entire system, and
your application can interact with it using this object.
If getDefaultAdapter() returns null, then the device does not support Bluetooth
and your story ends here. For example:

BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();


if(mBluetoothAdapter ==null){
// Device does not support Bluetooth
}

Enable Bluetooth
Next, you need to ensure that Bluetooth is enabled. Call isEnabled() to check
whether Bluetooth is currently enable. If this method returns false, then
Bluetooth is disabled. To request that Bluetooth be enabled,
call startActivityForResult() with the ACTION_REQUEST_ENABLE action
Intent. This will issue a request to enable Bluetooth through the system
settings (without stopping your application). For example:

if(!mBluetoothAdapter.isEnabled()){
Intent enableBtIntent
=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
A dialog will appear requesting user permission to enable Bluetooth, as
shown in Figure 1. If the user responds "Yes," the system will begin to enable
Bluetooth and focus will return to your application once the process completes
(or fails).
The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a
locally defined integer (which must be greater than 0), that the system passes
back to you in your onActivityResult()implementation as
the requestCode parameter.

BBDNIITPage 31
Smartphone Android Controlled Robot

If enabling Bluetooth succeeds, your activity receives the RESULT_OK result


code in theonActivityResult() callback. If Bluetooth was not enabled due to an
error (or the user responded "No") then the result code
is RESULT_CANCELED.
Optionally, your application can also listen for
the ACTION_STATE_CHANGED broadcast Intent, which the system will
broadcast whenever the Bluetooth state has changed. This broadcast
contains the extra fieldsEXTRA_STATE and EXTRA_PREVIOUS_STATE,
containing the new and old Bluetooth states, respectively. Possible values for
these extra fields
are STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF,
andSTATE_OFF. Listening for this broadcast can be useful to detect changes
made to the Bluetooth state while your app is running.

Tip: Enabling discoverability will automatically enable Bluetooth. If you plan to


consistently enable device discoverability before performing Bluetooth activity,
you can skip step 2 above. Read about enabling discoverability, below.

8.2 FINDING DEVICES


Using the BluetoothAdapter, you can find remote Bluetooth devices either
through device discovery or by querying the list of paired (bonded) devices.

Device discovery is a scanning procedure that searches the local area for
Bluetooth enabled devices and then requesting some information about each
one (this is sometimes referred to as "discovering," "inquiring" or "scanning").
However, a Bluetooth device within the local area will respond to a discovery
request only if it is currently enabled to be discoverable. If a device is
discoverable, it will respond to the discovery request by sharing some
information, such as the device name, class, and its unique MAC address.
Using this information, the device performing discovery can then choose to
initiate a connection to the discovered device.

Once a connection is made with a remote device for the first time, a pairing
request is automatically presented to the user. When a device is paired, the

BBDNIITPage 32
Smartphone Android Controlled Robot

basic information about that device (such as the device name, class, and
MAC address) is saved and can be read using the Bluetooth APIs. Using the
known MAC address for a remote device, a connection can be initiated with it
at any time without performing discovery (assuming the device is within
range).

Remember there is a difference between being paired and being connected.


To be paired means that two devices are aware of each other's existence,
have a shared link-key that can be used for authentication, and are capable of
establishing an encrypted connection with each other. To be connected
means that the devices currently share an RFCOMM channel and are able to
transmit data with each other. The current Android Bluetooth API's require
devices to be paired before an RFCOMM connection can be established.
(Pairing is automatically performed when you initiate an encrypted connection
with the Bluetooth APIs.)

The following sections describe how to find devices that have been paired, or
discover new devices using device discovery.

Note: Android-powered devices are not discoverable by default. A user can


make the device discoverable for a limited time through the system settings,
or an application can request that the user enable discoverability without
leaving the application. How to enable discoverability is discussed below.

8.3 QUERYING PAIRED DEVICES


Before performing device discovery, its worth querying the set of paired
devices to see if the desired device is already known. To do so,
call getBondedDevices(). This will return a Set of BluetoothDevices
representing paired devices. For example, you can query all paired devices
and then show the name of each device to the user, using an ArrayAdapter:

Set<BluetoothDevice> pairedDevices =
mBluetoothAdapter.getBondedDevices();
// If there are paired devices

BBDNIITPage 33
Smartphone Android Controlled Robot

if(pairedDevices.size()>0){
// Loop through paired devices
for(BluetoothDevice device : pairedDevices){
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName()+"\n"+ device.getAddress());
}
}

All that's needed from the BluetoothDevice object in order to initiate a


connection is the MAC address. In this example, it's saved as a part of an
ArrayAdapter that's shown to the user. The MAC address can later be
extracted in order to initiate the connection. You can learn more about
creating a connection in the section about Connecting Devices.

8.4 DISCOVERING DEVICES


To start discovering devices, simply call startDiscovery(). The process is
asynchronous and the method will immediately return with a boolean
indicating whether discovery has successfully started. The discovery process
usually involves an inquiry scan of about 12 seconds, followed by a page scan
of each found device to retrieve its Bluetooth name.

Your application must register a BroadcastReceiver for


the ACTION_FOUND Intent in order to receive information about each device
discovered. For each device, the system will broadcast
the ACTION_FOUNDIntent. This Intent carries the extra
fields EXTRA_DEVICE and EXTRA_CLASS, containing
a BluetoothDeviceand a BluetoothClass, respectively. For example, here's
how you can register to handle the broadcast when devices are discovered:

// Create a BroadcastReceiver for ACTION_FOUND


privatefinalBroadcastReceiver mReceiver =newBroadcastReceiver(){
publicvoid onReceive(Context context,Intent intent){
String action = intent.getAction();

BBDNIITPage 34
Smartphone Android Controlled Robot

// When discovery finds a device


if(BluetoothDevice.ACTION_FOUND.equals(action)){
// Get the BluetoothDevice object from the Intent
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName()+"\n"+ device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter =newIntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);// Don't forget to unregister during
onDestroy

All that's needed from the BluetoothDevice object in order to initiate a


connection is the MAC address. In this example, it's saved as a part of an
ArrayAdapter that's shown to the user. The MAC address can later be
extracted in order to initiate the connection. You can learn more about
creating a connection in the section about Connecting Devices.

8.5 ENABLING DISCOVERABILITY

If you would like to make the local device discoverable to other devices,
callstartActivityForResult(Intent, int) with
the ACTION_REQUEST_DISCOVERABLE action Intent. This will issue a
request to enable discoverable mode through the system settings (without
stopping your application). By default, the device will become discoverable for
120 seconds. You can define a different duration by adding
the EXTRA_DISCOVERABLE_DURATION Intent extra. The maximum
duration an app can set is 3600 seconds, and a value of 0 means the device
is always discoverable. Any value below 0 or above 3600 is automatically set
to 120 secs). For example, this snippet sets the duration to 300:

BBDNIITPage 35
Smartphone Android Controlled Robot

Intent discoverableIntent =new


Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DU
RATION,300);
startActivity(discoverableIntent);

Fig.The enabling discoverability dialog


A dialog will be displayed, requesting user permission to make the device
discoverable, as shown in Figure 2. If the user responds "Yes," then the
device will become discoverable for the specified amount of time. Your activity
will then receive a call to the onActivityResult()) callback, with the result code
equal to the duration that the device is discoverable. If the user responded
"No" or if an error occurred, the result code will beRESULT_CANCELED.

Note: If Bluetooth has not been enabled on the device, then enabling device
discoverability will automatically enable Bluetooth.

The device will silently remain in discoverable mode for the allotted time. If
you would like to be notified when the discoverable mode has changed, you
can register a BroadcastReceiver for
theACTION_SCAN_MODE_CHANGED Intent. This will contain the extra
fieldsEXTRA_SCAN_MODE and EXTRA_PREVIOUS_SCAN_MODE, which
tell you the new and old scan mode, respectively. Possible values for each
are SCAN_MODE_CONNECTABLE_DISCOVERABLE,SCAN_MODE_CONN
ECTABLE,or SCAN_MODE_NONE, which indicate that the device is either in
discoverable mode, not in discoverable mode but still able to receive

BBDNIITPage 36
Smartphone Android Controlled Robot

connections, or not in discoverable mode and unable to receive connections,


respectively.

You do not need to enable device discoverability if you will be initiating the
connection to a remote device. Enabling discoverability is only necessary
when you want your application to host a server socket that will accept
incoming connections, because the remote devices must be able to discover
the device before it can initiate the connection.

8.6 CONNECTING DEVICES


In order to create a connection between your application on two devices, you
must implement both the server-side and client-side mechanisms, because
one device must open a server socket and the other one must initiate the
connection (using the server device's MAC address to initiate a connection).
The server and client are considered connected to each other when they each
have a connected BluetoothSocket on the same RFCOMM channel. At this
point, each device can obtain input and output streams and data transfer can
begin, which is discussed in the section about Managing a Connection. This
section describes how to initiate the connection between two devices.

The server device and the client device each obtain the
required BluetoothSocket in different ways. The server will receive it when an
incoming connection is accepted. The client will receive it when it opens an
RFCOMM channel to the server.

Fig. The Bluetooth pairing dialog.


One implementation technique is to automatically prepare each device as a
server, so that each one has a server socket open and listening for
connections. Then either device can initiate a connection with the other and
become the client. Alternatively, one device can explicitly "host" the

BBDNIITPage 37
Smartphone Android Controlled Robot

connection and open a server socket on demand and the other device can
simply initiate the connection.

Note: If the two devices have not been previously paired, then the Android
framework will automatically show a pairing request notification or dialog to
the user during the connection procedure, as shown in Figure 3. So when
attempting to connect devices, your application does not need to be
concerned about whether or not the devices are paired. Your RFCOMM
connection attempt will block until the user has successfully paired, or will fail
if the user rejects pairing, or if pairing fails or times out.

8.7 CONNECTING AS A SERVER


When you want to connect two devices, one must act as a server by holding
an openBluetoothServerSocket. The purpose of the server socket is to listen
for incoming connection requests and when one is accepted, provide a
connected BluetoothSocket. When the BluetoothSocket is acquired from
the BluetoothServerSocket, the BluetoothServerSocket can (and should) be
discarded, unless you want to accept more connections.

About UUID
A Universally Unique Identifier (UUID) is a standardized 128-bit format for a
string ID used to uniquely identify information. The point of a UUID is that it's
big enough that you can select any random and it won't clash. In this case, it's
used to uniquely identify your application's Bluetooth service. To get a UUID
to use with your application, you can use one of the many random UUID
generators on the web, then initialize a UUID withfromString(String).
Here's the basic procedure to set up a server socket and accept a connection:

1. Get a BluetoothServerSocket by calling


thelistenUsingRfcommWithServiceRecord(String, UUID).
The string is an identifiable name of your service, which the system will
automatically write to a new Service Discovery Protocol (SDP) database
entry on the device (the name is arbitrary and can simply be your application
name). The UUID is also included in the SDP entry and will be the basis for

BBDNIITPage 38
Smartphone Android Controlled Robot

the connection agreement with the client device. That is, when the client
attempts to connect with this device, it will carry a UUID that uniquely
identifies the service with which it wants to connect. These UUIDs must
match in order for the connection to be accepted (in the next step).
2. Start listening for connection requests by calling accept().
This is a blocking call. It will return when either a connection has been
accepted or an exception has occurred. A connection is accepted only when
a remote device has sent a connection request with a UUID matching the
one registered with this listening server socket. When
successful, accept() will return a connected BluetoothSocket.
3. Unless you want to accept additional connections, call close().
This releases the server socket and all its resources, but does not close the
connected BluetoothSocketthat's been returned by accept(). Unlike TCP/IP,
RFCOMM only allows one connected client per channel at a time, so in most
cases it makes sense to call close() on
the BluetoothServerSocket immediately after accepting a connected socket.
The accept() call should not be executed in the main activity UI thread
because it is a blocking call and will prevent any other interaction with the
application. It usually makes sense to do all work with
aBluetoothServerSocket or BluetoothSocket in a new thread managed by
your application. To abort a blocked call such as accept(), call close() on
the BluetoothServerSocket (or BluetoothSocket) from another thread and the
blocked call will immediately return. Note that all methods on
aBluetoothServerSocket or BluetoothSocket are thread-safe.

Example
Here's a simplified thread for the server component that accepts incoming
connections:

privateclassAcceptThreadextendsThread{
privatefinalBluetoothServerSocket mmServerSocket;

publicAcceptThread(){
// Use a temporary object that is later assigned to mmServerSocket,

BBDNIITPage 39
Smartphone Android Controlled Robot

// because mmServerSocket is final


BluetoothServerSocket tmp =null;
try{
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
}catch(IOException e){}
mmServerSocket = tmp;
}

publicvoid run(){
BluetoothSocket socket =null;
// Keep listening until exception occurs or a socket is returned
while(true){
try{
socket = mmServerSocket.accept();
}catch(IOException e){
break;
}
// If a connection was accepted
if(socket !=null){
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(socket);
mmServerSocket.close();
break;
}
}
}

/** Will cancel the listening socket, and cause the thread to finish */
publicvoid cancel(){
try{
mmServerSocket.close();
}catch(IOException e){}
}
}

In this example, only one incoming connection is desired, so as soon as a


connection is accepted and theBluetoothSocket is acquired, the application
sends the acquired BluetoothSocket to a separate thread, closes
the BluetoothServerSocket and breaks the loop.

Note that when accept() returns the BluetoothSocket, the socket is already
connected, so you should notcall connect() (as you do from the client-side).

manageConnectedSocket() is a fictional method in the application that will


initiate the thread for transferring data, which is discussed in the section
about Managing a Connection.

You should usually close your BluetoothServerSocket as soon as you are


done listening for incoming connections. In this example, close() is called as

BBDNIITPage 40
Smartphone Android Controlled Robot

soon as the BluetoothSocket is acquired. You may also want to provide a


public method in your thread that can close the private BluetoothSocket in the
event that you need to stop listening on the server socket.

8.8 CONNECTING AS A CLIENT


In order to initiate a connection with a remote device (a device holding an
open server socket), you must first obtain a BluetoothDevice object that
represents the remote device. (Getting a BluetoothDevice is covered in the
above section about Finding Devices.) You must then use
the BluetoothDevice to acquire aBluetoothSocket and initiate the connection.

Here's the basic procedure:

1. Usingthe BluetoothDevice, get a BluetoothSocket by


callingcreateRfcommSocketToServiceRecord(UUID).
This initializes a BluetoothSocket that will connect to the BluetoothDevice.
The UUID passed here must match the UUID used by the server device
when it opened
its BluetoothServerSocket (withlistenUsingRfcommWithServiceRecord(Strin
g, UUID)). Using the same UUID is simply a matter of hard-coding the UUID
string into your application and then referencing it from both the server and
client code.
2. Initiate the connection by calling connect().
Upon this call, the system will perform an SDP lookup on the remote device
in order to match theUUID. If the lookup is successful and the remote device
accepts the connection, it will share the RFCOMM channel to use during the
connection and connect() will return. This method is a blocking call. If, for
any reason, the connection fails or the connect() method times out (after
about 12 seconds), then it will throw an exception.
Because connect() is a blocking call, this connection procedure should
always be performed in a thread separate from the main activity thread.

BBDNIITPage 41
Smartphone Android Controlled Robot

Note: You should always ensure that the device is not performing device
discovery when you callconnect(). If discovery is in progress, then the
connection attempt will be significantly slowed and is more likely to fail.

Example
Here is a basic example of a thread that initiates a Bluetooth connection:

privateclassConnectThreadextendsThread{
privatefinalBluetoothSocket mmSocket;
privatefinalBluetoothDevice mmDevice;

publicConnectThread(BluetoothDevice device){
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp =null;
mmDevice = device;

// Get a BluetoothSocket to connect with the given BluetoothDevice


try{
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
}catch(IOException e){}
mmSocket = tmp;
}

publicvoid run(){
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();

try{
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
}catch(IOException connectException){
// Unable to connect; close the socket and get out
try{
mmSocket.close();
}catch(IOException closeException){}
return;
}

// Do work to manage the connection (in a separate thread)


manageConnectedSocket(mmSocket);
}

/** Will cancel an in-progress connection, and close the socket */


publicvoid cancel(){
try{
mmSocket.close();
}catch(IOException e){}
}
}

BBDNIITPage 42
Smartphone Android Controlled Robot

Notice that cancelDiscovery() is called before the connection is made. You


should always do this before connecting and it is safe to call without actually
checking whether it is running or not (but if you do want to check,
call isDiscovering()).

manageConnectedSocket() is a fictional method in the application that will


initiate the thread for transferring data, which is discussed in the section
about Managing a Connection.

When you're done with your BluetoothSocket, always call close() to clean up.
Doing so will immediately close the connected socket and clean up all internal
resources.

8.9 MANAGING A CONNECTION


When you have successfully connected two (or more) devices, each one will
have a connectedBluetoothSocket. This is where the fun begins because you
can share data between devices. Using theBluetoothSocket, the general
procedure to transfer arbitrary data is simple:

1. Get the InputStream and OutputStream that handle transmissions through


the socket, viagetInputStream() and getOutputStream(), respectively.
2. Read and write data to the streams with read(byte[]) and write(byte[]).
That's it.

There are, of course, implementation details to consider. First and foremost,


you should use a dedicated thread for all stream reading and writing. This is
important because both read(byte[]) and write(byte[])methods are blocking
calls. read(byte[]) will block until there is something to read from the
stream.write(byte[]) does not usually block, but can block for flow control if the
remote device is not callingread(byte[]) quickly enough and the intermediate
buffers are full. So, your main loop in the thread should be dedicated to
reading from the InputStream. A separate public method in the thread can be
used to initiate writes to the OutputStream.

BBDNIITPage 43
Smartphone Android Controlled Robot

Example
Here's an example of how this might look:

privateclassConnectedThreadextendsThread{
privatefinalBluetoothSocket mmSocket;
privatefinalInputStream mmInStream;
privatefinalOutputStream mmOutStream;

publicConnectedThread(BluetoothSocket socket){
mmSocket = socket;
InputStream tmpIn =null;
OutputStream tmpOut =null;

// Get the input and output streams, using temp objects because
// member streams are final
try{
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}catch(IOException e){}

mmInStream = tmpIn;
mmOutStream = tmpOut;
}

publicvoid run(){
byte[] buffer =newbyte[1024]; // buffer store for the stream
int bytes;// bytes returned from read()

// Keep listening to the InputStream until an exception occurs


while(true){
try{
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes,-1, buffer)
.sendToTarget();
}catch(IOException e){
break;
}
}
}

/* Call this from the main activity to send data to the remote device */
publicvoid write(byte[] bytes){
try{
mmOutStream.write(bytes);
}catch(IOException e){}
}

/* Call this from the main activity to shutdown the connection */


publicvoid cancel(){
try{
mmSocket.close();
}catch(IOException e){}

BBDNIITPage 44
Smartphone Android Controlled Robot

}
}

The constructor acquires the necessary streams and once executed, the
thread will wait for data to come through the InputStream.
When read(byte[]) returns with bytes from the stream, the data is sent to the
main activity using a member Handler from the parent class. Then it goes
back and waits for more bytes from the stream.

Sending outgoing data is as simple as calling the thread's write() method from
the main activity and passing in the bytes to be sent. This method then simply
calls write(byte[]) to send the data to the remote device.

The thread's cancel() method is important so that the connection can be


terminated at any time by closing the BluetoothSocket. This should always be
called when you're done using the Bluetooth connection.

For a demonstration of using the Bluetooth APIs, see the Bluetooth Chat
sample app.

8.10 WORKING WITH PROFILES


Starting in Android 3.0, the Bluetooth API includes support for working with
Bluetooth profiles. A Bluetooth profile is a wireless interface specification for
Bluetooth-based communication between devices. An example is the Hands-
Free profile. For a mobile phone to connect to a wireless headset, both
devices must support the Hands-Free profile.

You can implement the interface BluetoothProfile to write your own classes to
support a particular Bluetooth profile. The Android Bluetooth API provides
implementations for the following Bluetooth profiles:

 Headset. The Headset profile provides support for Bluetooth headsets to be


used with mobile phones. Android provides the BluetoothHeadset class,
which is a proxy for controlling the Bluetooth Headset Service via
interprocess communication (IPC). This includes both Bluetooth Headset
and Hands-Free (v1.5) profiles. The BluetoothHeadset class includes

BBDNIITPage 45
Smartphone Android Controlled Robot

support for AT commands. For more discussion of this topic, see Vendor-
specific AT commands
 A2DP. The Advanced Audio Distribution Profile (A2DP) profile defines how
high quality audio can be streamed from one device to another over a
Bluetooth connection. Android provides the BluetoothA2dpclass, which is a
proxy for controlling the Bluetooth A2DP Service via IPC.
 Health Device. Android 4.0 (API level 14) introduces support for the
Bluetooth Health Device Profile (HDP). This lets you create applications that
use Bluetooth to communicate with health devices that support Bluetooth,
such as heart-rate monitors, blood meters, thermometers, scales, and so on.
For a list of supported devices and their corresponding device data
specialization codes, refer to Bluetooth Assigned
Numbers at www.bluetooth.org. Note that these values are also referenced
in the ISO/IEEE 11073-20601 [7] specification as
MDC_DEV_SPEC_PROFILE_* in the Nomenclature Codes Annex. For
more discussion of HDP, see Health Device Profile.
Here are the basic steps for working with a profile:

1. Get the default adapter, as described in Setting Up Bluetooth.


2. Use getProfileProxy() to establish a connection to the profile proxy object
associated with the profile. In the example below, the profile proxy object is
an instance of BluetoothHeadset.
3. Set up a BluetoothProfile.ServiceListener. This listener
notifies BluetoothProfile IPC clients when they have been connected to or
disconnected from the service.
4. In onServiceConnected(), get a handle to the profile proxy object.
5. Once you have the profile proxy object, you can use it to monitor the state of
the connection and perform other operations that are relevant to that profile.
For example, this code snippet shows how to connect to
a BluetoothHeadset proxy object so that you can control the Headset profile:

BluetoothHeadset mBluetoothHeadset;

BBDNIITPage 46
Smartphone Android Controlled Robot

// Get the default adapter


BluetoothAdapter mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();

// Establish connection to the proxy.


mBluetoothAdapter.getProfileProxy(context, mProfileListener,BluetoothProfile.HEADSET);

privateBluetoothProfile.ServiceListener mProfileListener
=newBluetoothProfile.ServiceListener(){
publicvoid onServiceConnected(int profile,BluetoothProfile proxy){
if(profile ==BluetoothProfile.HEADSET){
mBluetoothHeadset =(BluetoothHeadset) proxy;
}
}
publicvoid onServiceDisconnected(int profile){
if(profile ==BluetoothProfile.HEADSET){
mBluetoothHeadset =null;
}
}
};

// ... call functions on mBluetoothHeadset

// Close proxy connection after use.


mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset);

BBDNIITPage 47
Smartphone Android Controlled Robot

DEVELOPMENT OF “AC Robot” APP

9.1 INTRODUCTION
“AC Robot” is a basic universal Remote Controlfor Blue-Tooth enabled serial
devices suchas Blue Tooth modules connected to a micro-controller.For each
button pressed the correspondingASCII code for the label will be sent. For
example pressing buttons PICK and RELEASE will sendthe character "a" and
"e".The UP, DOWN, LEFT, RIGHT, and STOP buttons
willsend "U","D","L","R", and "C" characters.

9.2 BASICS OF ANDROID APP DEVELOPMENT

For creating new project click on the File -> New -> Project.

It opens the new wizard window where you can select application template
and set the name of the project and package name.

BBDNIITPage 48
Smartphone Android Controlled Robot

On the click on Next Button, it moves to the next step. Here provide the
“Application Name”, “Project Name” and “Package Name”. “Package Name” is
a same as “Name Space” in .Net and it must be unique. The project name is
only used by Eclipse and it must be unique in the workspace.

You also need to select “Minimum Required SDK” from dropdown. It is the
lowest version of Android that your application will support. Then select
“Target SDK” which is the Highest API that the application is known to work
with. Then select the installed SDK for “Compile With” option to compile your
code for selected targeted SDK.

In the next steps of the wizard, you need to select icons, some other
information and on the last step provide the name of your activity and it's
Navigation Type.

BBDNIITPage 49
Smartphone Android Controlled Robot

We will provide the detail of activity and layout later, for now we can say it is
window’s form as desktop application or as a Web page in web application.
Provide the name of Activity and Layout. Leave Navigation type “None” for
now. Press finish button. Eclipse will automatically generate start up activity
for you.

Within the Eclipse, you can see your project in the “Package Explorer” pane of
the left-hand side of the screen. The “HelloWorld” application contains several
auto generated folders and file. Let’s discuss it one by one.

BBDNIITPage 50
Smartphone Android Controlled Robot

/Src: It contains the all java source files those are associated to the project.
For example the MainActivity.java file generated by Eclipse is stored in this
directory under the package name “com.MyFirst.helloworld” you specified in
the wizard. You can add more packages for your application e.g.
com.MyFirst.Fragments, CommonClasses etc.
/gen: It contains the java source files and other code files generated by
Eclipse. We will use R.java file code later in our project. This file is generated
to link your resource files for use in your java
files in /src folder.

Android Directories (/Android 4.2 and /Android Dependencies): The


Android 4.2 directory is generated against your selected Android SDK and
Dependencies folder the support file is generated for the backward
compatibility with previous versions of Android SDK.
/assests: By default this is empty folder, but you can put your raw assets in it
and these files include in your projects as-is. For Example it is good location
for textures and game data.
/bin: It is the output directory for build. You can find the final .apk file and
other compiled resources in this folder.
/libs: It contains the private libraries (jar) those you might want to use in your
application.
/res: It contains all the resources files those are associated to your
application. All the graphical element, string and layout of application exists
one of the sub folder of the res. We will add some resource later in this
project. The auto generated layout file “activity_main.xml” by Eclipse exists in
layout sub folder.

BBDNIITPage 51
Smartphone Android Controlled Robot

Project.properties: This file is generated by android project wizard and it is


used for Eclipse settings. It is very rare to change this file directly. Instead
Right click on the project in Eclipse and click on properties and make any
change which is required for your application.

9.3 ACTIVITY
It is a most important concept of Android development. An activity represents
the screen in an application. You can use it in different ways as floating
window or embedded inside of another activity etc. The class must be
inherited from Activity class for your activity. extends keyword is used for
inheritance in java.
onCreate method is used to initialize your activity. We usually
call setContentView() method to define the layout for the activity and also get
UI controls using findViewByid() that are required to interact programmatically.
super.onCreate() means call the onCreate method of base class. Super is
used to access the base class in java. The layout that is associated with this
activity is in activity_main.xml. You can get the id of that resource
using R.layout.activity_main. R is the auto generated class that maintains the
resources and we use it to access to resources in
code. setContentView(R.layout.activity_main) sets the layout for activity.
onCreateOptionsMenu() method is used to handle the menu for that activity.

Access Control/View in Activity

After setting the content view of the activity, you can get control
using findViewById(viewId) method. It takes the view/control id as a
parameter and returns the view that is found. View is the base class for
widgets, which are used to create interactive UI components (buttons, text
fields, etc.). We need to cast the view into the original widgets.
There are three ways to implement listeners in java and they have their own
advantages and disadvantages. These three ways are
1. Inline implementation
2. Using the implements keyword
3. By using variables

BBDNIITPage 52
Smartphone Android Controlled Robot

You can study about these different ways on the internet. In the above
example I register listener for button using Inline implementation.
Call setOnClickListener() method of button and pass OnClickListener as an
parameter. In OnClickListener handler override the onClick event. When
user will click on button, it will callonClick event. You can write your code
inside onClick.

9.4 INTENT
Intent is the asynchronous message which allows android components to
request functionality from the other component of the Android System. It
represents an app’s ‘Intent to do something’. We can use intents for different
tasks e.g. making call, open map, open activity etc. But most often they are
used to start another activity.

How to Start another Activity


Till here, you have learnt about activity, layout resources and intent. Create
another activity name “LifeCycleActivity” and create its layout
“activity_life_cycle.xml” in layout folder. It is better to use Eclipse to add
activity in your application that automatically generates layout for that activity
and automatically put necessary information of activity in
“AndroidManifest.xml” file. Otherwise you need to do it manually. Right click
on your application in “Package Explorer” pane in left-hand side and click
on New > Other. It will open a popup window where you need to select
“AndroidActivity” and after completing the wizard, it will create a Activity and
default layout for you.

Lifecycle of the Activity


For proper understanding of the activities, it is necessary to understand the
life cycle of the activity. Activities are managed in the system as an activity
stack. When new activity started it is placed on the top of the stack and
becomes the running activity. The previous activities always remain below it in
the stack and will not come to the front until the new activity exists. Following
is the list of method which calls on each state of the activity.

BBDNIITPage 53
Smartphone Android Controlled Robot

onCreate() method called when activity is first created. onStart() called when
activity is visible to user andonResume() called when application starts
interaction with the user. At this point your activity comes at the top of activity
stack.
onPause() method called when system is about to start resuming of previous
activity. It is typically used to save the unsaved data to persist it, stop
animation or other work that can consume CPU.
onStop() method called when the activity is no longer visible to the user,
because another activity has been resumed and is covering this one.
onRestart() called after your activity has been stopped. It called prior to being
started again.
onDestroy() called before your activity is destroyed.

9.5 SETTING UP PATH FOR “AC Robot”


The envoirment for “AC Robot” set as follows:
Path:/ACRobot
Type: Project
Location: C:\Users\workspace\ACRobot
9.6 SETTING UP OF “AndroidManifest.xml” FILE
Path:/ACRobot/AndroidManifest.xml
Type: File (XML)
Location: C:\Users\workspace\ACRobot\AndroidManifest.xml
Source code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.acrobot"
android:versionCode="1"
android:versionName="1.0">

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-
permission>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"

BBDNIITPage 54
Smartphone Android Controlled Robot

android:theme="@style/AppTheme">
<activity
android:name="com.example.acrobot.FirstScreen"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DeviceListActivity"
android:theme="@android:style/Theme.Dialog"></activity>
<activity android:name=".Sample"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"
android:screenOrientation="landscape"></activity>
<activity android:name=".SampleTwo"></activity>
</application>

</manifest>

9.7 ICONS AND XML FILE PLACED IN “drawable” Folder


Path: /ACRobot/res/drawable

Type: Folder

Location: C:\Users\workspace\ACRobot\res\drawable

Fig. Icons of the android application tool designed for the project
File:graphic_up.xml
Source code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="false"
android:drawable="@drawable/blue_up_arrow" />
<item
android:state_pressed="true"
android:drawable="@drawable/blue_up_arrow_pressed" />

<item android:state_focused="true" android:state_pressed="false"


android:drawable="@drawable/blue_up_arrow_pressed" />

</selector>

BBDNIITPage 55
Smartphone Android Controlled Robot

File: graphic_down.xml
Source code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="false"
android:drawable="@drawable/blue_down_arrow" />
<item
android:state_pressed="true"
android:drawable="@drawable/blue_down_arrow_pressed" />

<item android:state_focused="true" android:state_pressed="false"


android:drawable="@drawable/blue_down_arrow_pressed" />

</selector>
File: graphic_left.xml
Source code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="false"
android:drawable="@drawable/blue_left_arrow" />
<item
android:state_pressed="true"
android:drawable="@drawable/blue_left_arrow_pressed" />

<item android:state_focused="true" android:state_pressed="false"


android:drawable="@drawable/blue_left_arrow_pressed" />

</selector>
File: graphic_right.xml
Source code:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="false"
android:drawable="@drawable/blue_right_arrow" />
<item
android:state_pressed="true"
android:drawable="@drawable/blue_right_arrow_pressed" />

<item android:state_focused="true" android:state_pressed="false"


android:drawable="@drawable/blue_right_arrow_pressed" />

</selector>

9.8 DESIGNING OF LAYOUT SCREENS


Path:/ACRobot/res/layout
Type: Folder

BBDNIITPage 56
Smartphone Android Controlled Robot

Location: C:\Users\workspace\ACRobot\res\layout

Fig. Various screens of the android application tool


File: device_list.xml
Source code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/title_paired_devices"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Paired Devices"
android:visibility="gone"
android:background="#666"
android:textColor="#fff"
android:paddingLeft="5dp"
/>
<ListView android:id="@+id/paired_devices"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stackFromBottom="true"
android:layout_weight="1"
/>
<TextView android:id="@+id/title_new_devices"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Other Devices"
android:visibility="gone"
android:background="#666"
android:textColor="#fff"
android:paddingLeft="5dp"
/>
<ListView android:id="@+id/new_devices"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stackFromBottom="true"
android:layout_weight="2"
/>

BBDNIITPage 57
Smartphone Android Controlled Robot

<Button android:id="@+id/button_scan"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Scan"
/>
</LinearLayout>
File: device_name.xml
Source code:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="5dp"
/>
File: first.xml
Source code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center_horizontal"
android:background="@drawable/background2">

<Button
android:id="@+id/host"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_marginTop="120dip"
android:text="Host" />

<Button
android:id="@+id/join"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:layout_marginTop="30dip"
android:text="Join" />

</RelativeLayout>
File: main.xml
Source code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background"
>

BBDNIITPage 58
Smartphone Android Controlled Robot

<Button android:layout_width="wrap_content" android:layout_height="wrap_content"


android:id="@+id/up"
android:layout_centerHorizontal="true" android:layout_above="@+id/right"
android:layout_marginBottom="20dip"
android:background="@drawable/graphic_up"></Button>

<Button android:layout_width="wrap_content" android:layout_height="wrap_content"


android:id="@+id/left"
android:layout_toLeftOf="@+id/up" android:layout_centerVertical="true"
android:layout_marginRight="20dip"
android:background="@drawable/graphic_left"></Button>

<Button android:layout_width="wrap_content" android:layout_height="wrap_content"


android:id="@+id/right"
android:layout_toRightOf="@+id/up" android:layout_centerVertical="true"
android:layout_marginLeft="20dip"
android:background="@drawable/graphic_right"></Button>

<Button android:layout_width="wrap_content" android:layout_height="wrap_content"


android:id="@+id/down"
android:layout_centerHorizontal="true" android:layout_below="@+id/right"
android:layout_marginTop="20dip"
android:background="@drawable/graphic_down"></Button>

<Button
android:id="@+id/stop"
android:layout_width="100dip"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/graphic_green"
android:text="STOP">
</Button>

<Button
android:id="@+id/drop"
android:layout_width="150dip"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="RELEASE" />

<Button
android:id="@+id/pick"
android:layout_width="150dip"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="PICK" />

</RelativeLayout>
File: maintwo.xml
Source code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"

BBDNIITPage 59
Smartphone Android Controlled Robot

android:orientation="horizontal"
android:background="@drawable/background2">

<TextView
android:id="@+id/title_two"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:gravity="center_horizontal"
android:text="Developed By:"
android:textSize="25sp">
</TextView>

<TextView
android:id="@+id/msg_status_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/title_two"
android:text="1. Satyendra Gupta 2. Pankaj Verma 3. Shubhendu Sharma 4. Suraj Rai"
android:textSize="20sp" />

</RelativeLayout>

9.9 DESIGNING OF MENU SCREENS


Path: /ACRobot/res/menu/first_screen.xml
Type: File (XML)
Location:C:\Users \workspace\ACRobot\res\menu\first_screen.xml

Source code:
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/scan" android:icon="@android:drawable/ic_menu_search"


android:title="Connect" />
<item android:id="@+id/discoverable"
android:icon="@android:drawable/ic_menu_mylocation"
android:title="Make Discoverable" />
<item android:id="@+id/aboutus" android:title="About Us"
android:icon="@android:drawable/ic_menu_myplaces"></item>

</menu>

9.10 VARIOUS ACTIVITIES USED IN “AC Robot”


The AC Robot uses the 2 google provided sample chat files which was
imported into the project.
1. BluetoothService.java
2. DeviceListActivity.java
The AC Robot has the 3 different activity named as:
1. FirstScreen.java
2. Sample.java
3. SampleTwo.java

BBDNIITPage 60
Smartphone Android Controlled Robot

File: BluetoothService.java
Source code:
package com.example.acrobot;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
* This class does all the work for setting up and managing Bluetooth
* connections with other devices. It has a thread that listens for
* incoming connections, a thread for connecting with a device, and a
* thread for performing data transmissions when connected.
*/
publicclass BluetoothService {
// Debugging
privatestaticfinal String TAG = "BluetoothService";
privatestaticfinalbooleanD = true;

// Name for the SDP record when creating server socket


privatestaticfinal String NAME = "BluetoothApp";

// Unique UUID for this application


// private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-
0800200c9a66");
privatestaticfinal UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-
00805F9B34FB");

// Member fields
privatefinal BluetoothAdapter mAdapter;
privatefinal Handler mHandler;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
privateint mState;

// Constants that indicate the current connection state


publicstaticfinalintSTATE_NONE = 0; // we're doing nothing
publicstaticfinalintSTATE_LISTEN = 1; // now listening for incoming connections
publicstaticfinalintSTATE_CONNECTING = 2; // now initiating an outgoing connection
publicstaticfinalintSTATE_CONNECTED = 3; // now connected to a remote device

/**
* Constructor. Prepares a new Bluetooth session.
* @param context The UI Activity Context
* @param handler A Handler to send messages back to the UI Activity
*/

BBDNIITPage 61
Smartphone Android Controlled Robot

public BluetoothService(Context context, Handler handler) {


mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
}

/**
* @return The Handler instance of the Bluetooth Service
*/
public Handler getHandler(){
return mHandler;
}
/**
* Set the current state of the connection
* @param state An integer defining the current connection state
*/
privatesynchronizedvoid setState(int state) {
if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;

// Give the new state to the Handler so the UI Activity can update
/*mHandler.obtainMessage(Sample.MESSAGE_STATE_CHANGE, state, -
1).sendToTarget();*/
Message msg = mHandler.obtainMessage(Sample.MESSAGE_STATE_CHANGE,
state, -1);
mHandler.sendMessage(msg);

/**
* Return the current connection state. */
publicsynchronizedint getState() {
return mState;
}

/**
* Start the Bluetooth service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
publicsynchronizedvoid start() {
if (D) Log.d(TAG, "start");

// Cancel any thread attempting to make a connection


if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

// Cancel any thread currently running a connection


if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

// Start the thread to listen on a BluetoothServerSocket


if (mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
setState(STATE_LISTEN);
}

/**
* Start the ConnectThread to initiate a connection to a remote device.

BBDNIITPage 62
Smartphone Android Controlled Robot

* @param device The BluetoothDevice to connect


*/
publicsynchronizedvoid connect(BluetoothDevice device) {
if (D) Log.d(TAG, "connect to: " + device);

// Cancel any thread attempting to make a connection


if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
}

// Cancel any thread currently running a connection


if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

// Start the thread to connect with the given device


mConnectThread = new ConnectThread(device);
mConnectThread.start();
setState(STATE_CONNECTING);
}

/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket The BluetoothSocket on which the connection was made
* @param device The BluetoothDevice that has been connected
*/
publicsynchronizedvoid connected(BluetoothSocket socket, BluetoothDevice device) {
if (D) Log.d(TAG, "connected");

// Cancel the thread that completed the connection


if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

// Cancel any thread currently running a connection


if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

// Cancel the accept thread because we only want to connect to one device
if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}

// Start the thread to manage the connection and perform transmissions


mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();

// Send the name of the connected device back to the UI Activity


Message msg = mHandler.obtainMessage(Sample.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(Sample.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);

setState(STATE_CONNECTED);
}

/**
* Stop all threads
*/
publicsynchronizedvoid stop() {
if (D) Log.d(TAG, "stop");
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

BBDNIITPage 63
Smartphone Android Controlled Robot

if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}


setState(STATE_NONE);
}

/**
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
publicvoid write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}

/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
privatevoid connectionFailed() {
setState(STATE_LISTEN);

// Send a failure message back to the Activity


Message msg = mHandler.obtainMessage(Sample.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Sample.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
}

/**
* Indicate that the connection was lost and notify the UI Activity.
*/
privatevoid connectionLost() {
setState(STATE_LISTEN);

// Send a failure message back to the Activity


Message msg = mHandler.obtainMessage(Sample.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Sample.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
}

/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
privateclass AcceptThread extends Thread {
// The local server socket
privatefinal BluetoothServerSocket mmServerSocket;

BBDNIITPage 64
Smartphone Android Controlled Robot

public AcceptThread() {
BluetoothServerSocket tmp = null;

// Create a new listening server socket


try {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
Log.e(TAG, "listen() failed", e);
}
mmServerSocket = tmp;
}

publicvoid run() {
if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
setName("AcceptThread");
BluetoothSocket socket = null;

// Listen to the server socket if we're not connected


while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "accept() failed", e);
break;
}

// If a connection was accepted


if (socket != null) {
synchronized (BluetoothService.this) {
switch (mState) {
caseSTATE_LISTEN:
caseSTATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
caseSTATE_NONE:
caseSTATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
if (D) Log.i(TAG, "END mAcceptThread");
}

publicvoid cancel() {
if (D) Log.d(TAG, "cancel " + this);
try {

BBDNIITPage 65
Smartphone Android Controlled Robot

mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of server failed", e);
}
}
}

/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
privateclass ConnectThread extends Thread {
privatefinal BluetoothSocket mmSocket;
privatefinal BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device) {


mmDevice = device;
BluetoothSocket tmp = null;

// Get a BluetoothSocket for a connection with the


// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;
}

publicvoid run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");

// Always cancel discovery because it will slow down a connection


mAdapter.cancelDiscovery();

// Make a connection to the BluetoothSocket


try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
// Start the service over to restart listening mode
BluetoothService.this.start();
return;
}

// Reset the ConnectThread because we're done

BBDNIITPage 66
Smartphone Android Controlled Robot

synchronized (BluetoothService.this) {
mConnectThread = null;
}

// Start the connected thread


connected(mmSocket, mmDevice);
}

publicvoid cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}

/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
privateclass ConnectedThread extends Thread {
privatefinal BluetoothSocket mmSocket;
privatefinal InputStream mmInStream;
privatefinal OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {


Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;

// Get the BluetoothSocket input and output streams


try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}

mmInStream = tmpIn;
mmOutStream = tmpOut;
}

publicvoid run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = newbyte[1024];
int bytes;

// Keep listening to the InputStream while connected


while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);

// Send the obtained bytes to the UI Activity


/*mHandler.obtainMessage(Sample.MESSAGE_READ, bytes, -1, buffer)

BBDNIITPage 67
Smartphone Android Controlled Robot

.sendToTarget();*/
Message msg = mHandler.obtainMessage(Sample.MESSAGE_READ, bytes, -1,
buffer);
mHandler.sendMessage(msg);
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}

/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
publicvoid write(byte[] buffer) {
try {
mmOutStream.write(buffer);

// Share the sent message back to the UI Activity


/*mHandler.obtainMessage(Sample.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();*/
Message msg = mHandler.obtainMessage(Sample.MESSAGE_WRITE, -1, -1,
buffer);
mHandler.sendMessage(msg);
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}

publicvoid cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}

File: DeviceListActivity.java
Source code:
package com.example.acrobot;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;

BBDNIITPage 68
Smartphone Android Controlled Robot

import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
* This Activity appears as a dialog. It lists any paired devices and
* devices detected in the area after discovery. When a device is chosen
* by the user, the MAC address of the device is sent back to the parent
* Activity in the result Intent.
*/
publicclass DeviceListActivity extends Activity {
// Debugging
privatestaticfinal String TAG = "DeviceListActivity";
privatestaticfinalbooleanD = true;

// Return Intent extra


publicstatic String EXTRA_DEVICE_ADDRESS = "device_address";

// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;

@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Setup the window


requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);

// Set result CANCELED incase the user backs out


setResult(Activity.RESULT_CANCELED);

// Initialize the button to perform device discovery


Button scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
publicvoid onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});

// Initialize array adapters. One for already paired devices and


// one for newly discovered devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

// Find and set up the ListView for paired devices


ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);

BBDNIITPage 69
Smartphone Android Controlled Robot

// Find and set up the ListView for newly discovered devices


ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);

// Register for broadcasts when a device is discovered


IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);

// Register for broadcasts when discovery has finished


filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);

// Get the local Bluetooth adapter


mBtAdapter = BluetoothAdapter.getDefaultAdapter();

// Get a set of currently paired devices


Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

// If there are paired devices, add each one to the ArrayAdapter


if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = "No Devices";
mPairedDevicesArrayAdapter.add(noDevices);
}
}

@Override
protectedvoid onDestroy() {
super.onDestroy();

// Make sure we're not doing discovery anymore


if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}

// Unregister broadcast listeners


this.unregisterReceiver(mReceiver);
}

/**
* Start device discover with the BluetoothAdapter
*/
privatevoid doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");

// Indicate scanning in the title


setProgressBarIndeterminateVisibility(true);
setTitle("Scanning...");

// Turn on sub-title for new devices


findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

BBDNIITPage 70
Smartphone Android Controlled Robot

// If we're already discovering, stop it


if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}

// Request discover from BluetoothAdapter


mBtAdapter.startDiscovery();
}

// The on-click listener for all devices in the ListViews


private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
publicvoid onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();

// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);

// Create the result Intent and include the MAC address


Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

// Set result and finish this Activity


setResult(Activity.RESULT_OK, intent);
finish();
}
};

// The BroadcastReceiver that listens for discovered devices and


// changes the title when discovery is finished
privatefinal BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
publicvoid onReceive(Context context, Intent intent) {
String action = intent.getAction();

// When discovery finds a device


if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} elseif (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle("Select a Device");
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = "No Devices Found";
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};

BBDNIITPage 71
Smartphone Android Controlled Robot

File: FirstScreen.java
Source code:
package com.example.acrobot;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

publicclass FirstScreen extends Activity {

privatestaticfinal String HOST_DEVICE_ADDRESS =


"HOST_DEVICE_ADDRESS";
privatestaticfinal String HOSTING = "HOSTING";
privatestaticfinal String TAG = "FirstScreen";
privatestaticfinalintREQUEST_CONNECT_DEVICE = 1;
privatestaticfinalintREQUEST_ENABLE_BT = 2;
private BluetoothAdapter mBluetoothAdapter;
private Context mContext = this;

/**
* For Debugging
*/
privateboolean D=true;

/**
* Stores the MAC address of the selected device from the DeviceListActivity
*/
private String selected_device_address;

@Override
protectedvoid onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first);

Button host_btn = (Button) findViewById(R.id.host);


Button join_btn = (Button) findViewById(R.id.join);

host_btn.setOnClickListener(new OnClickListener() {

@Override
publicvoid onClick(View v) {
// TODO Ensure this device is discoverable by others
Intent hostIntent = new Intent(mContext,Sample.class);
hostIntent.putExtra(HOSTING, true);
startActivity(hostIntent);

BBDNIITPage 72
Smartphone Android Controlled Robot

}
});

join_btn.setOnClickListener(new OnClickListener() {

@Override
publicvoid onClick(View v) {
// TODO Launch the DeviceListActivity to see devices and do
scan
Intent serverIntent = new Intent(mContext,
DeviceListActivity.class);
startActivityForResult(serverIntent,
REQUEST_CONNECT_DEVICE);
}
});

// Get local Bluetooth adapter


mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// If the adapter is null, then Bluetooth is not supported


if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available",
Toast.LENGTH_LONG).show();
finish();//TODO remove finish if unwanted
return;
}
}

@Override
publicvoid onStart() {
super.onStart();
if (D)
Log.e(TAG, "++ ON START ++");

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


// setupConnection() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
}

publicvoid onActivityResult(int requestCode, int resultCode, Intent data) {


if (D)
Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
caseREQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
selected_device_address = data.getExtras().getString(

DeviceListActivity.EXTRA_DEVICE_ADDRESS);
if(D){
Log.d(TAG,"Select device address stored:
"+selected_device_address+". Launching new Intent");

BBDNIITPage 73
Smartphone Android Controlled Robot

//Launch next activity and pass device address


Intent i = new Intent(this, Sample.class);
i.putExtra(HOST_DEVICE_ADDRESS,
selected_device_address);
startActivity(i);
}
break;
caseREQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
//TODO might need initialize here, BT is now enabled
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, "Bluetooth not enabled, Leaving...",
Toast.LENGTH_SHORT).show();
finish();//TODO Can remove if unwanted
}
}
}

File: Sample.java
Source code:
package com.example.acrobot;

import com.example.acrobot.R;
import com.example.acrobot.SampleTwo;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

publicclass Sample extends Activity {

publicint timer=0;

BBDNIITPage 74
Smartphone Android Controlled Robot

privatestaticfinal String HOSTING = "HOSTING";


// Debugging
privatestaticfinal String TAG = "BluetoothApp";
privatestaticfinalbooleanD = true;

// Message types sent from the BluetoothService Handler


publicstaticfinalintMESSAGE_STATE_CHANGE = 1;
publicstaticfinalintMESSAGE_READ = 2;
publicstaticfinalintMESSAGE_WRITE = 3;
publicstaticfinalintMESSAGE_DEVICE_NAME = 4;
publicstaticfinalintMESSAGE_TOAST = 5;

// Key names received from the BluetoothService Handler


publicstaticfinal String DEVICE_NAME = "device_name";
publicstaticfinal String TOAST = "toast";

// Intent request codes


privatestaticfinalintREQUEST_CONNECT_DEVICE = 1;
privatestaticfinalintREQUEST_ENABLE_BT = 2;

// Name of the connected device


private String mConnectedDeviceName = null;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothService mService = null;

// TODO Sample specific variables/fields/members


privateint robot_speed = 1;
//private TextView msg_status;
privatestaticfinal String HOST_DEVICE_ADDRESS =
"HOST_DEVICE_ADDRESS";

//sample booleans
privateboolean isOn =false;

/** Called when the activity is first created. */


@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (D)
Log.e(TAG, "+++ ON CREATE +++");

// Get local Bluetooth adapter


mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// If the adapter is null, then Bluetooth is not supported


if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available",
Toast.LENGTH_LONG).show();
finish();
return;
}

// TODO Sample specific operations

BBDNIITPage 75
Smartphone Android Controlled Robot

// Get a handle to the message status TextView located in our layout


// msg_status = (TextView) findViewById(R.id.message_status);

// Define a button called yourButtonName in your xml layout file


Button up = (Button) findViewById(R.id.up);
Button left = (Button) findViewById(R.id.left);
Button right = (Button) findViewById(R.id.right);
Button down = (Button) findViewById(R.id.down);
Button pick = (Button) findViewById(R.id.pick);
Button drop = (Button) findViewById(R.id.drop);
final Button stop = (Button) findViewById(R.id.stop);

up.setOnClickListener(new View.OnClickListener() {
@Override
publicvoid onClick(View v) {
// TODO Auto-generated method stub
if (mService.getState() ==
BluetoothService.STATE_CONNECTED)
{
sendMessage(String.valueOf('U'));
}
}
});

left.setOnClickListener(new View.OnClickListener() {
@Override
publicvoid onClick(View v) {
// TODO Auto-generated method stub
if (mService.getState() ==
BluetoothService.STATE_CONNECTED)
{
sendMessage(String.valueOf('L'));
}
}
});

right.setOnClickListener(new View.OnClickListener() {
@Override
publicvoid onClick(View v) {
// TODO Auto-generated method stub
if (mService.getState() ==
BluetoothService.STATE_CONNECTED)
{
sendMessage(String.valueOf('R'));
}
}
});

down.setOnClickListener(new View.OnClickListener() {
@Override
publicvoid onClick(View v) {
// TODO Auto-generated method stub
if (mService.getState() ==
BluetoothService.STATE_CONNECTED)
{
sendMessage(String.valueOf('D'));

BBDNIITPage 76
Smartphone Android Controlled Robot

}
}
});

pick.setOnTouchListener(new View.OnTouchListener() {
publicboolean onTouch(View v,MotionEvent event) {
timer++;
if ((mService.getState() ==
BluetoothService.STATE_CONNECTED)&&(timer%10==0))
sendMessage(String.valueOf('e'));
returnfalse;
}
});

drop.setOnTouchListener(new View.OnTouchListener() {
publicboolean onTouch(View v,MotionEvent event) {
timer++;
if ((mService.getState() ==
BluetoothService.STATE_CONNECTED)&&(timer%10==0))
sendMessage(String.valueOf('a'));
returnfalse;
}
});

stop.setOnClickListener(new View.OnClickListener() {
publicvoid onClick(View v) {
if (mService.getState() ==
BluetoothService.STATE_CONNECTED)
{
sendMessage(String.valueOf('C'));
}
}
});
}

@Override
publicvoid onStart() {
super.onStart();
if (D)
Log.e(TAG, "++ ON START ++");

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


// setupConnection() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the Bluetooth session
} else {
if (mService == null)
setupConnection();
}
if(getIntent().getBooleanExtra(HOSTING, false)==true){
ensureDiscoverable();
}
}

BBDNIITPage 77
Smartphone Android Controlled Robot

@Override
publicsynchronizedvoid onResume() {
super.onResume();
if (D)
Log.e(TAG, "+ ON RESUME +");

// Performing this check in onResume() covers the case in which BT was


// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity
// returns.
if (mService != null) {
// Only if the state is STATE_NONE, do we know that we haven't
// started already
if (mService.getState() == BluetoothService.STATE_NONE) {
// Start the Bluetooth services
mService.start();
}
}
}

privatevoid setupConnection() {
Log.d(TAG, "setupConnection()");

// Initialize the BluetoothService to perform bluetooth connections


mService = new BluetoothService(this, mHandler);

if (getIntent().getStringExtra(HOST_DEVICE_ADDRESS) != null) {
BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(getIntent().getStringExtra(
HOST_DEVICE_ADDRESS));
// Attempt to connect to the device
mService.connect(device);
}

@Override
publicsynchronizedvoid onPause() {
super.onPause();
if (D)
Log.e(TAG, "- ON PAUSE -");
}

@Override
publicvoid onStop() {
super.onStop();
if (D)
Log.e(TAG, "-- ON STOP --");
}

@Override
publicvoid onDestroy() {
super.onDestroy();
// Stop the Bluetooth services
if (mService != null)
mService.stop();
if (D)

BBDNIITPage 78
Smartphone Android Controlled Robot

Log.e(TAG, "--- ON DESTROY ---");


}

privatevoid ensureDiscoverable() {
if (D)
Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(

BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(

BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}

/**
* Sends a message.
*
* @param message
* A string of text to send.
*/
privatevoid sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mService.getState() != BluetoothService.STATE_CONNECTED) {
Toast.makeText(this, "Not Connected",
Toast.LENGTH_SHORT).show();
return;
}

// Check that there's actually something to send


if (message.length() > 0) {
// Get the message bytes and tell the BluetoothService to write
byte[] send = message.getBytes();
mService.write(send);

}
}

// The Handler that gets information back from the BluetoothService


privatefinal Handler mHandler = new Handler() {
@Override
publicvoid handleMessage(Message msg) {
switch (msg.what) {
caseMESSAGE_STATE_CHANGE:
if (D)
Log.i(TAG, "MESSAGE_STATE_CHANGE: " +
msg.arg1);
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
// TODO You are now connected, do some
initialization here
break;
case BluetoothService.STATE_CONNECTING:
// TODO Let the user know he is connecting

BBDNIITPage 79
Smartphone Android Controlled Robot

break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
// TODO When not connected tell the user he is not
connected
break;
}
break;
caseMESSAGE_WRITE:
// TODO byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
// TODO String writeMessage = new String(writeBuf);
// TODO Do something here if needed for the user sending a
// message
break;
caseMESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
// TODO Read the constructed msg from the readMessage
String
// When message is received change the message status
// msg_status.setText("Message Recieved: " + readMessage);
// msg_status.setTextColor(Color.GREEN);

break;
caseMESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName =
msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(),
"Connected to " + mConnectedDeviceName,
Toast.LENGTH_SHORT).show();
break;
caseMESSAGE_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(TOAST),
Toast.LENGTH_SHORT)
.show();
break;
}
}
};

publicvoid onActivityResult(int requestCode, int resultCode, Intent data) {


if (D)
Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
caseREQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras().getString(

DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter

BBDNIITPage 80
Smartphone Android Controlled Robot

.getRemoteDevice(address);
// Attempt to connect to the device
mService.connect(device);
}
break;
caseREQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupConnection();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
Toast.makeText(this, "Bluetooth not enabled, Leaving...",
Toast.LENGTH_SHORT).show();
finish();
}
}
}

@Override
publicboolean onCreateOptionsMenu(Menu menu) {// TODO make single item for
// discoverable
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.first_screen, menu);
returntrue;
}

@Override
publicboolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent,
REQUEST_CONNECT_DEVICE);
returntrue;
case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
returntrue;
case R.id.aboutus:
// TODO Go to next screen/activity
Intent i = new Intent(this, SampleTwo.class);
startActivity(i);
returntrue;
}
returnfalse;
}
}
File: SampleTwo.java
Sorce code:
package com.example.acrobot;
import android.app.Activity;
import android.os.Bundle;
publicclass SampleTwo extends Activity {
@Override

BBDNIITPage 81
Smartphone Android Controlled Robot

protectedvoid onCreate(Bundle savedInstanceState) {


// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.maintwo);
}
}

BBDNIITPage 82
Smartphone Android Controlled Robot

WORKING OF “SMARTPHONE ANDROID


CONTROLLED ROBOT”
The “AC Robot” full project and app is open source and can be downloaded
by the following link or scanning the QR code.
http://tinyurl.com/kh7zgex
http://tinyurl.com/opkqpem

Step to connect:
1. Connect the wiring, connect the batteries ,power up the robot
2. While the device is not connected, the bluetooth module board has a
red LED flashing
3. Download and install the “AC Robot.apk” in your android phone
4. At Smartphone, in AC Robot app search for bluetooth device.
5. Found name called "HC-05" device
6. Connect it, and passcode is "1234"
7. While connection is ok, you can see the Green LED become alwayson.

BBDNIITPage 83
Smartphone Android Controlled Robot

APPLICATIONS AND FUTURE SCOPE

This project has many applications and a very good future scope. It also
allows for modification of its components and parameters to get desired
output. Some of the notable applications are illustrated with future scope:

1. It can be used in various industries for picking various objects where


human intervention is not desired.
2. On a large scale, it can be used to develop robots with military applications.
It can be used to target enemy without any human being crossing the territory.
3. It provides for more development of applications based on android
operating system. Such as , Application based on sensors (accelerometer ,
gyroscope) etc.
This opens door for wide range of possible similar applications
3.1 Remote starter for car
3.2 Automation of household tasks
4. It is robust, sensitive and fast moving, hence can be applied in rescue
operations.
5. By varying its components and its values, it is easy to get different desired
outputs from the project.

Hence, we can say that it is a very useful project with many more applications
destined to come up in future.

BBDNIITPage 84
Smartphone Android Controlled Robot

REFERENCES AND BIBLIOGRAPHY


Following websites were accessed in the preparation of this project and its
report:

http://tinyurl.com/kh7zgex
http://www.codeproject.com/Articles/628894/Learn-How-to-Develop-Android-
Application
http://en.wikipedia.org/wiki/LM317
http://en.wikipedia.org/wiki/78xx
http://www.ti.com/product/l293D
http://www.engineersgarage.com/electronic-components/l293d-motor-driver-ic
https://www.futurlec.com/Atmel/ATMEGA8L.shtml
https://mbed.org/users/edodm85/notebook/HC-05-bluetooth/

BBDNIITPage 85

You might also like