Professional Documents
Culture Documents
Chapter Wise Report
Chapter Wise Report
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.
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.
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
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.
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.
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.
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."
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.
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.
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
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
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.
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.
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.
1.5.7 Healthcare
BBDNIITPage 5
Smartphone Android Controlled Robot
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
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.
The circuit diagram for the project is shown on next page. It describes
different components and their interconnections
BBDNIITPage 7
Smartphone Android Controlled Robot
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.
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
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.
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
3.3 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
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
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
BBDNIITPage 15
Smartphone Android Controlled Robot
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
Fig. Gripper
BBDNIITPage 17
Smartphone Android Controlled Robot
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
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
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;
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;
}
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 );
UART1_Init(9600);
while(1)
{
PORTB0_bit = ~PORTB0_bit;
delay_ms(100);
}
BBDNIITPage 23
Smartphone Android Controlled Robot
INTRODUCTION OF ANDROID
7.1 INTRODUCTION
BBDNIITPage 24
Smartphone Android Controlled Robot
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
The Android SDK provides you the API libraries and developer tools
necessary to build, test, and debug apps for Android.
With a single download, the ADT Bundle includes everything you need to
begin developing apps:
BBDNIITPage 26
Smartphone Android Controlled Robot
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:
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
</manifest>
Setting Up Bluetooth
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
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
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).
The following sections describe how to find devices that have been paired, or
discover new devices using device discovery.
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());
}
}
BBDNIITPage 34
Smartphone Android Controlled Robot
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
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
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.
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.
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.
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:
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
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){}
}
}
Note that when accept() returns the BluetoothSocket, the socket is already
connected, so you should notcall connect() (as you do from the client-side).
BBDNIITPage 40
Smartphone Android Controlled Robot
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;
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;
}
BBDNIITPage 42
Smartphone Android Controlled Robot
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.
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()
/* Call this from the main activity to send data to the remote device */
publicvoid write(byte[] bytes){
try{
mmOutStream.write(bytes);
}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.
For a demonstration of using the Bluetooth APIs, see the Bluetooth Chat
sample app.
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:
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:
BluetoothHeadset mBluetoothHeadset;
BBDNIITPage 46
Smartphone Android Controlled Robot
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;
}
}
};
BBDNIITPage 47
Smartphone Android Controlled Robot
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.
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.
BBDNIITPage 51
Smartphone Android Controlled Robot
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.
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.
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.
<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>
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" />
</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" />
</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" />
</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" />
</selector>
BBDNIITPage 56
Smartphone Android Controlled Robot
Location: C:\Users\workspace\ACRobot\res\layout
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: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>
Source code:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
</menu>
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;
// Member fields
privatefinal BluetoothAdapter mAdapter;
privatefinal Handler mHandler;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
privateint mState;
/**
* 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
/**
* @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");
/**
* Start the ConnectThread to initiate a connection to a remote device.
BBDNIITPage 62
Smartphone Android Controlled Robot
/**
* 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 accept thread because we only want to connect to one device
if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
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
/**
* 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);
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
privatevoid connectionLost() {
setState(STATE_LISTEN);
/**
* 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;
publicvoid run() {
if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
setName("AcceptThread");
BluetoothSocket socket = null;
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;
publicvoid run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
BBDNIITPage 66
Smartphone Android Controlled Robot
synchronized (BluetoothService.this) {
mConnectThread = null;
}
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;
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
publicvoid run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = newbyte[1024];
int bytes;
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);
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;
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BBDNIITPage 69
Smartphone Android Controlled Robot
@Override
protectedvoid onDestroy() {
super.onDestroy();
/**
* Start device discover with the BluetoothAdapter
*/
privatevoid doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
BBDNIITPage 70
Smartphone Android Controlled Robot
// 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);
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;
/**
* 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);
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);
}
});
@Override
publicvoid onStart() {
super.onStart();
if (D)
Log.e(TAG, "++ ON START ++");
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
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;
publicint timer=0;
BBDNIITPage 74
Smartphone Android Controlled Robot
//sample booleans
privateboolean isOn =false;
BBDNIITPage 75
Smartphone Android Controlled Robot
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 ++");
BBDNIITPage 77
Smartphone Android Controlled Robot
@Override
publicsynchronizedvoid onResume() {
super.onResume();
if (D)
Log.e(TAG, "+ ON RESUME +");
privatevoid setupConnection() {
Log.d(TAG, "setupConnection()");
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
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;
}
}
}
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;
}
}
};
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
BBDNIITPage 82
Smartphone Android Controlled Robot
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
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:
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
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