0% found this document useful (0 votes)
12 views

android robot

project report

Uploaded by

Rakesh pal
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

android robot

project report

Uploaded by

Rakesh pal
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 69

TABLE OF CONTENTS

I. Project Description and Overview


1. Bluetooth Robot 2-3
2. Android Phones 3-4
II. A Brief overview of Bluetooth 6-8
III. Block Diagram 9-10
IV. Schematic Diagram & PCB Layout 11-13
V. Circuit Description 14-15
VI. Component Description
1. Register 18-21
2. Capacitor 22-24
3. Semi conductor 25-27
4. Opto coupler 27-28
5. Micro controller 28-31

1
VII. Hardware Development
1. Car Chassis/Motor
2. Bluetooth Module 28-35
3. PIC Microcontroller
4. H-Bridge
VIII. Software Development 36-41
IX. Coding 43-50
X. Conclusion 61-64
XI. References 66

2
Chapter I

Project description
and overview

1
I. PROJECT DESCRIPTION AND OVERVIEW

1.1 How it works ?

The core of our project (and also the component required for completion by the end
of the semester) was a Bluetooth car. The requirements for the Bluetooth car were that it
must connect wirelessly to a host via Bluetooth and that the host must be able to control the
car’s movements: forward, backward, left turn, right turn and stop. Abstract

This project is concerned with the designing and construction of a Bluetooth


enabled mobile robot and collaborative mobile robot devices. Software is to be developed
to illustrate the capabilities of the robots to complete their designated collaborative tasks..
Machines are a big part of the world’s production, transportation and exploration. Most of
the people today are unaware of how much work is done by robots everyday for example in
car manufacturing facilities and military operations. Mobile robots shall probably be the
most important machines in the future. Already, mobile robots are being used to explore
distant planets as well as for just simple house hold work such as mowing the lawn or
vacuuming. This report focuses on a Bluetooth Communication which was established
between the Robot and a Smartphone. This specific design and implementation would work
with most two-wheel differential robots that have a serial port available on their main
boards and can run Java Virtual Machine.

This project is concerned with the design and construction of a battery powered
robot swarm and the development of an application to illustrate the practical use of a
collaborative robot swarm. This project involved configuring hardware and developing
software to run the system. The main purpose of this project is to develop a remote user
interface to control a robot via a wireless technology. There is a need to communicate with
the robot remotely in order to control the robot movements and pass critical data both ways.
The current IR controls are not good enough because the robot does not have an IR

2
transmitter but only a receiver, meaning that the communication is one way. The IR
communication works only in line of direct sight and any objects in the way will obstruct
the communication. Bluetooth communication will enable us to control the robot up to 100
meters without the need for direct sight which means that the robot could be located behind
a wall or some other object and the communication would not be lost. This system will deal
with the basic robot movement functions, as well as user interface, Bluetooth
communication, serial RS232 communication between the robot and the Bluetooth module,
and RS232 communication between the Smartphone and the Bluetooth module. Full
implementation of the code both for the robot and the computer shall be developed in this
project.

1.2. Cell Phone Interface

As mobile phone handsets attain increasing capabilities, there are many more
opportunities for novel applications development. While it is important to respect these
resource constraints, some of the unique features of mobile phones also want to highlight,
such as high quality audio, constant connectivity and comfortable form factor for use as
device to interact with the physical world.

Mobile phones are the most pervasive portable computers currently available having
the capabilities to alter and manipulate our perceptions. They contain various sensors, such
as accelerometers and microphones, as well as actuators in the form of vibro-tactile
feedback. Visual feedback may be provided through mobile screens or video eye wear. To
ensure a fast adoption rate of gesture recognition as an Ubiquitous input mechanism,
technologies already available in mobile phones should be utilized. Features like
accelerometer sensing and vibro-tactile feedback are readily available in high-end mobile
phones, and this should filter through to most mobile phones in the future. Gesture
recognition allows users to perceive their mobile phone as an input mechanism. Dynamic
input systems in the form of gesture recognition are proving popular with users. This
application helps in controlling the wheel chair or the robot or a toy car with less physical
efforts thus improving overall well-being and quality of life. Robotics is concerned with the
study of machines that can displace human beings in implementing processes, in physical

3
activity and decision making. Smartphone or podcasts are considered these days a very
important device in our life. The addictiveness has been to such an extent that normal day-
to-day activities cannot happen without mobiles. Mobiles are developed every day, every
day there is a new model that include new features catering to increased demands with
changing lifestyle.

In this project, there is exploration of the opportunities available with the usage of
Smartphone OS coupled with Bluetooth technology in developing an environment for
current mobile phones and demonstrate applications and simultaneously exploiting the
unique features of these commercially available devices.

We desired to control the car from a second Bluetooth device such as laptop, and a
cell phone. Many cell phones currently on the market are equipped with Bluetooth
technology and some provide access to their Bluetooth hardware via J2ME: a small java
virtual machine distributed with mobile devices. As an extra flashy feature of our car, and
to further demonstrate the interoperability of Bluetooth, we wanted to write a J2ME MIDlet
(mobile application) to replace the PC from Part I. With the emergence of Web 2.0, and
Android, IPhone, Blackberry platforms more and more Bluetooth connector prototype
libraries exist and the controller software interface is left as a design challenge for anyone
whom wishes to take it. The main aim of the paper is to design and develop a Smartphone
OS coupled with Bluetooth technology based wireless remote control to control motions of
robot in the real time applications with four degrees of freedom.

4
Chapter II

A BRIEF OVERVIEW
OF BLUETOOTH

5
II. A BRIEF OVERVIEW OF BLUETOOTH

Bluetooth wireless technology is a relatively new technology for networking low power
devices over short ranges. As of today, it is available in four major versions and three
power classes.

Version Specified Maximum Transfer


1.0-1.2 700 kbps
2 3 Mbps
3 24 Mbps
4 ----

Power Class Range


Class 1 100 meters
Class 2 10 meters
Class 3 1 meter

6
Version 1.0 to 1.2 is the most prevalent in Bluetooth devices at the time of writing
—the differences between 1.0 and 1.2 were a series of small improvements and changes in
implementation. The bandwidth of Bluetooth 1.0/1.2 was severely limited, but for current
applications (transmitting mouse coordinates, keyboard inputs, cell phone contacts, images
< 100kb, etc.) it is not a problem. For our implementation, we use Bluetooth 1.2 in order to
cut down hardware costs, but as more and more devices begin to adopt Bluetooth the
version 2.0 hardware will almost most certainly support some level of encoded video
transmission.

For anyone interested in designing a device which uses Bluetooth, one of the most
important concepts to understand is how the Bluetooth protocol is structured. When a
software or hardware architect chooses Bluetooth, they are deciding to use one or more
Bluetooth profiles of communication. For example, one could decide to use the Bluetooth
Serial Port Profile (BSPP) which takes standard RS232 communication to the wireless
world, Bluetooth Stereo Audio Profile (A2DP) to transmit stereo music, OBEX File
Transfer to browse directory structures and copy files, or OBEX object push to send
somebody a file or electronic business card.

Bluetooth currently defines these different profiles and the Bluetooth SIG (the
group responsible for the Bluetooth standard) continues to define many more. It is
important to realize that although the Bluetooth protocol defines these profiles, none are
mandatory for any Bluetooth implementation. The advantage is that product architects can
ignore profiles that are not relevant to their design, and The Catch, of course, is that any
two devices that wish to communicate must implement the same profile.

When designing a Bluetooth device, hardware engineers find or build the analog
wireless components which process the complicated frequency hopping algorithms at
2.4GHz and software engineers find or develop the Bluetooth stack. The stack implements
and abstracts all the Bluetooth network profiles necessary for the device’s operation so they
can be used easily by the firmware writers. This is of course standard programming
paradigm for device drivers and interfacing with hardware. The data stack structure is
shown in Figure

7
Host Software
Communication Profiles
Hardware Control Interface
(Firmware/Software)
Radio/Baseband Hardware

TCP/IP Protocol

The TCP/IP model is a description framework for computer network protocols created in
the 1970s by DARPA, an agency of the United States Department of Defence. It evolved
from ARPANET, which was the world's first wide area network and a predecessor of
the Internet. The TCP/IP Model is sometimes called the Internet Model

The TCP/IP model, or Internet Protocol Suite, describes a set of general design
guidelines and implementations of specific networking protocols to enable computers to
communicate over a network. TCP/IP provides end-to-end connectivity specifying how
data should be formatted, addressed, transmitted, routed and received at the destination.
Protocols exist for a variety of different types of communication services between
computers.

TCP/IP, sometimes referred to as the Internet model, has four abstraction layers as
defined in RFC 1122. This layer architecture is often compared with the seven-layer OSI
Reference Model; using terms such as Internet reference model, incorrectly, however,
because it is descriptive while the OSI Reference Model was intended to be prescriptive,
hence being a reference model.

The TCP/IP model and related protocols are maintained by the Internet Engineering
Task Force (IETF).

8
We can also link our project to TCP IP Protocol and simplify things. Almost all
homes are equipped with telephone and internet facilities these days. By linking our system
with TCP IP, the Electric Meter readings can be directly obtained by people sitting in one
central office by using the communication lines. By employing this method, the use of
manpower will be reduced to a great extent.

Chapter III

BLOCK DIAGRAM

9
III. Block Diagram

M
1

Bluetooth
Motor
PIC Driver
Module
16F887
HC-05 L298
MOBILE

M2

Power Supply

10
Chapter IV

SCHEMATIC DIAGRAM
& PCB LAYOUT
11
IV. Schematic Diagram

12
PCB Layout

13
14
Chapter IV

CIRCUIT
DESCRIPTION

14
IV. CIRCUIT DESCRIPTION

HARDWARE DEVELOPMENT

This portion of the project turned out to be far more difficult than we originally imagined.
Since neither of us had much experience with Bluetooth or prior knowledge of motors nor
power systems--several aspects of the hardware provided weeks worth of engineering
challenges.
Before exploring the depths of individual hardware components we’ll touch briefly
on the parts used in our final implementation.

MOBILE

Bluetooth PIC FET


Module 18F4320 Drivers

H-Bridge
Figure 3.1: Operational Block Diagram

15
Chapter V

Description
Of
Components

16
Hardware Requirements

S.No. Component Specification Quantity Cost

1. Diode (1N4007) 12 6.00

2. IC (16F877A) 1 220.00

3. Resistance (4k7) 2 2.00

4. Resistance (1k) 8 2.00

5. Resistance (10k) 5 2.00

8. Capacitor (1000mfd/25v) 2 10.00

9. Capacitor (100mfd/25v) 2 9.00

10. Capacitor (0.1mfd/25v) 1 9.00

11. IC (MAX232) 1 40.00

12. IC (L298) 1 15.00

14. Opt coupler 2 55.00

13. Pcb (6X4Inch) 1 65.00

14. Led (3mm) 8 24.00

16. BATTERY 1 600.00

17. IC 7805 1 10.00

18. IC 7812 1 10.00

19. DB9 1 20.00

17
20 PRINTING 2 250.00

21 BLUETOOTH MODULE 2 2000.00

22. DC MOTOR 2 300.00

24. OTHERS ~ 1000.00

V. Component Description

5.1. Resistor
A resistor is a two-terminal electronic component that produces a voltage across its
terminals that is proportional to the electric current passing through it in accordance
with Ohm's law
V=IR

Resistors are elements of electrical networks and electronic circuits and are
ubiquitous in most electronic equipment. Practical resistors can be made of various
compounds and films, as well as resistance wire (wire made of a high-resistivity alloy, such
as nickel/chrome).

The primary characteristics of a resistor are the resistance, the tolerance, maximum
working voltage and the power rating. Other characteristics include temperature
coefficient, noise, and inductance. Less well-known is critical resistance, the value below
which power dissipation limits the maximum permitted current flow, and above which the
limit is applied voltage. Critical resistance is determined by the design, materials and
dimensions of the resistor.

Resistors can be integrated into hybrid and printed circuits, as well as integrated
circuits. Size, and position of leads (or terminals) are relevant to equipment designers;
resistors must be physically large enough not to overheat when dissipating their power.

Types of Resistors Used

18
1. Carbon composition

Carbon composition resistors consist of a solid cylindrical resistive element with embedded
wire leads or metal end caps to which the lead wires are attached. The body of the resistor
is protected with paint or plastic. Early 20th-century carbon composition resistors had
uninsulated bodies; the lead wires were wrapped around the ends of the resistance element
rod and soldered. The completed resistor was painted for color coding of its value.

The resistive element is made from a mixture of finely ground (powdered) carbon and an
insulating material (usually ceramic). A resin holds the mixture together. The resistance is
determined by the ratio of the fill material (the powdered ceramic) to the carbon. Higher
concentrations of carbon, a weak conductor, result in lower resistance. Carbon composition
resistors were commonly used in the 1960s and earlier, but are not so popular for general
use now as other types have better specifications, such as tolerance, voltage dependence,
and stress (carbon composition resistors will change value when stressed with over-
voltages). Moreover, if internal moisture content (from exposure for some length of time to
a humid environment) is significant, soldering heat will create a non-reversible change in
resistance value. These resistors, however, if never subjected to overvoltage nor
overheating were remarkably reliable considering the components size

They are still available, but comparatively quite costly. Values ranged from fractions of
an ohm to 22 mega ohms. Because of the expense these resistors tend to be used in power
supplies and welding controls

2. Carbon film

A carbon film is deposited on an insulating substrate, and a helix cut in it to create a


long, narrow resistive path. Varying shapes, coupled with the resistivity of carbon, (ranging
from 90 to 400 nΩm) can provide a variety of resistances.[2] Carbon film resistors feature a
power rating range of 0.125 W to 5 W at 70 °C. Resistances available range from 1 ohm to
10 megohm. The carbon film resistor has an operating temperature range of -55 °C to 155
°C. It has 200 to 600 volts maximum working voltage range.[3]. Special carbon film
resistors are used in applications requiring high pulse stability[1].

19
Fig.4.1

Resistor Marking

Most axial resistors use a pattern of colored stripes to indicate resistance. Surface-
mount resistors are marked numerically, if they are big enough to permit marking; more-
recent small sizes are impractical to mark. Cases are usually tan, brown, blue, or green,
though other colors are occasionally found such as dark red or dark gray.

Early 20th century resistors, essentially un-insulated, were dipped in paint to cover
their entire body for color coding. A second color of paint was applied to one end of the
element, and a color dot (or band) in the middle provided the third digit. The rule was
"body, tip, dot", providing two significant digits for value and the decimal multiplier, in
that sequence. Default tolerance was ±20%. Closer-tolerance resistors had silver (±10%) or
gold-colored (±5%) paint on the other end.

Four-band identification is the most commonly used color-coding scheme on


resistors. It consists of four colored bands that are painted around the body of the resistor.
The first two bands encode the first two significant digits of the resistance value, the third is
a power-of-ten multiplier or number-of-zeroes, and the fourth is the tolerance accuracy, or
acceptable error, of the value.

The first three bands are equally spaced along the resistor; the spacing to the fourth
band is wider. Sometimes a fifth band identifies the thermal coefficient, but this must be
distinguished from the true 5-color system, with 3 significant digits.

For example, green-blue-yellow-red is 56×10 4 Ω = 560 kΩ ± 2%. An easier


description can be as followed: the first band, green, has a value of 5 and the second band,
blue, has a value of 6, and is counted as 56. The third band, yellow, has a value of 10 4,

20
which adds four 0's to the end, creating 560,000 Ω at ±2% tolerance accuracy. 560,000 Ω
changes to 560 kΩ ±2% (as a kilo- is 103).

Each color corresponds to a certain digit, progressing from darker to lighter colors,
as shown in the chart below.

Fig.4.2

Trimmer Potentiometer

A trimmer or preset is a miniature adjustable electrical component. It is meant to be set


correctly when installed in some device, and never seen or adjusted by the device's user.
Trimmers can be variable resistors (potentiometers) or variable capacitors (trim
able inductors exist but are very uncommon). They are common in precision circuitry
like A/V components, and may need to be adjusted when the equipment is serviced. Unlike
many other variable controls, trimmers are mounted directly on circuit boards, turned with
a small screwdriver and rated for many fewer adjustments over their lifetime.

21
Trimmers come in a variety of sizes and levels of precision; for example, multi-turn
trim potentiometers exist, in which it takes several turns of the adjustment screw to reach
the end value, allowing for very high degrees of accuracy.

In 1952, Marlin Bourns patented the world's first trimming potentiometer, trademarked
"Trim pot", a name now commonly used to refer to any trimming potentiometer.

5.2.Capacitors

A capacitor (formerly known as condenser) is a device for storing electric charge. The
forms of practical capacitors vary widely, but all contain at least two conductors separated
by a non-conductor. Capacitors used as parts of electrical systems, for example, consist of
metal foils separated by a layer of insulating film.

A capacitor is a passive electronic component consisting of a pair of conductors separated


by a dielectric (insulator). When there is a potential difference (voltage) across the
conductors, a static electric field develops across the dielectric, causing positive charge to
collect on one plate and negative charge on the other plate. Energy is stored in the
electrostatic field. An ideal capacitor is characterized by a single constant value,
capacitance, measured in farads. This is the ratio of the electric charge on each conductor to
the potential difference between them.

22
Capacitors are widely used in electronic circuits for blocking direct current while allowing
alternating current to pass, in filter networks, for smoothing the output of power supplies, in
the resonant circuits that tune radios to particular frequencies and for many other purposes.

The capacitance is greatest when there is a narrow separation between large areas of
conductor; hence capacitor conductors are often called "plates", referring to an early means
of construction. In practice the dielectric between the plates passes a small amount of
leakage current and also has an electric field strength limit, resulting in a breakdown
voltage, while the conductors and leads introduce an undesired inductance and resistance.

Fig.4.5

Operation

A capacitor consists of two conductors separated by a non-conductive region. The non-


conductive region is called the dielectric or sometimes the dielectric medium. In simpler
terms, the dielectric is just an electrical insulator. Examples of dielectric mediums are glass,
air, paper, vacuum, and even a semiconductor depletion region chemically identical to the
conductors.

A capacitor is assumed to be self-contained and isolated, with no net electric


charge and no influence from any external electric field. The conductors thus hold equal
and opposite charges on their facing surfaces, and the dielectric develops an electric field.
In SI units, a capacitance of one farad means that one coulomb of charge on each conductor
causes a voltage of one volt across the device.

23
The capacitor is a reasonably general model for electric fields within electric
circuits. An ideal capacitor is wholly characterized by a constant capacitance C, defined as
the ratio of charge ±Q on each conductor to the voltage V between them

Sometimes charge build-up affects the capacitor mechanically, causing its capacitance to
vary. In this case, capacitance is defined in terms of incremental changes:

Capacitor types

Practical capacitors are available commercially in many different forms. The type of
internal dielectric, the structure of the plates and the device packaging all strongly affect the
characteristics of the capacitor, and its applications.
Values available range from very low (picofarad range; while arbitrarily low values
are in principle possible, stray (parasitic) capacitance in any circuit is the limiting factor) to
about 5 kF super capacitors.
Above approximately 1 microfarad electrolytic capacitors are usually used because
of their small size and low cost compared with other technologies, unless their relatively
poor stability, life and polarised nature make them unsuitable. Very high capacity
supercapacitors use a porous carbon-based electrode material.

Capacitor markings

24
Most capacitors have numbers printed on their bodies to indicate their electrical
characteristics. Larger capacitors like electrolytics usually display the actual capacitance
together with the unit (for example, 220 μF). Smaller capacitors like ceramics, however,
use a shorthand consisting of three numbers and a letter, where the numbers show the
capacitance in pF (calculated as XY x 10Z for the numbers XYZ) and the letter indicates
the tolerance (J, K or M for ±5%, ±10% and ±20% respectively).

5.3.Semiconductor Diode

A semiconductor diode’s behavior in a circuit is given by its current–voltage characteristic


or I–V graph (see graph at right). The shape of the curve is determined by the transport of
charge carriers through the so-called depletion layer or depletion region that exists at the p-
n junction between differing semiconductors. When a p-n junction is first created,
conduction band (mobile) electrons from the N-doped region diffuse into the P-
doped region where there is a large population of holes (vacant places for electrons) with
which the electrons “recombine”. When a mobile electron recombines with a hole, both
hole and electron vanish, leaving behind an immobile positively charged donor (dopant) on
the N-side and negatively charged acceptor (dopant) on the P-side. The region around the
p-n junction becomes depleted of charge carriers and thus behaves as an insulator.

However, the width of the depletion region (called the depletion width) cannot grow
without limit. For each electron-hole pair that recombines, a positively-charged dopant ion
is left behind in the N-doped region, and a negatively charged dopant ion is left behind in
the P-doped region. As recombination proceeds more ions are created, an increasing
electric field develops through the depletion zone which acts to slow and then finally stop
recombination. At this point, there is a “built-in” potential across the depletion zone.

25
Fig.4.6

If an external voltage is placed across the diode with the same polarity as the built-in
potential, the depletion zone continues to act as an insulator, preventing any significant
electric current flow (unless electron/hole pairs are actively being created in the junction
by, for instance, light. see photodiode). This is the reverse bias phenomenon. However, if
the polarity of the external voltage opposes the built-in potential, recombination can once
again proceed, resulting in substantial electric current through the p-n junction (i.e.
substantial numbers of electrons and holes recombine at the junction). For silicon diodes,
the built-in potential is approximately 0.7 V. Thus, if an external current is passed through
the diode, about 0.7 V will be developed across the diode such that the P-doped region is
positive with respect to the N-doped region and the diode is said to be “turned on” as it has
a forward bias.

At very large reverse bias, beyond the peak inverse voltage or PIV, a process called
reverse breakdown occurs which causes a large increase in current (i.e. a large number of
electrons and holes are created at, and move away from the pn junction) that usually
damages the device permanently. The avalanche diode is deliberately designed for use in
the avalanche region. In the zener diode, the concept of PIV is not applicable. A zener
diode contains a heavily doped p-n junction allowing electrons to tunnel from the valence
band of the p-type material to the conduction band of the n-type material, such that the
reverse voltage is “clamped” to a known value (called the zener voltage), and avalanche

26
does not occur. Both devices, however, do have a limit to the maximum current and power
in the clamped reverse voltage region. Also, following the end of forward conduction in
any diode, there is reverse current for a short time. The device does not attain its full
blocking capability until the reverse current ceases.

The second region, at reverse biases more positive than the PIV, has only a very
small reverse saturation current. In the reverse bias region for a normal P-N rectifier diode,
the current through the device is very low (in the µA range). However, this is temperature
dependent, and at sufficiently high temperatures, a substantial amount of reverse current
can be observed (mA or more).

The third region is forward but small bias, where only a small forward current is
conducted.

As the potential difference is increased above an arbitrarily defined “cut-in voltage” or “on-
voltage” or “diode forward voltage drop (V d)”, the diode current becomes appreciable (the
level of current considered “appreciable” and the value of cut-in voltage depends on the
application), and the diode presents a very low resistance.

The current–voltage curve is exponential. In a normal silicon diode at rated currents,


the arbitrary “cut-in” voltage is defined as 0.6 to 0.7 volts. The value is different for other
diode types — Schottky diodes can be rated as low as 0.2 V and red or blue light-emitting
diodes (LEDs) can have values of 1.4 V and 4.0 V respectively.

At higher currents the forward voltage drop of the diode increases. A drop of 1 V to
1.5 V is typical at full rated current for power diodes.

In our project we use diodes IN4007.

5.5. Optocoupler

There are many situations where signals and data need to be transferred from one
subsystem to another within a piece of electronics equipment, or from one piece of
equipment to another, without making a direct ohmic electrical connection. Often this is
because the source and destination are (or may be at times) at very different voltage levels,
like a microprocessor which is operating from 5V DC but being used to control a triac

27
which is switching 240V AC. In such situations the link between the two must be an
isolated one, to protect the microprocessor from over voltage damage .Relays can of course
provide this kind of isolation, but even small relays tend to be fairly bulky compared with
ICs and many of today other miniature circuit components. Because they are electro-
mechanical, relays are also not as reliable — and only capable of relatively low speed
operation. Where small size, higher speed and greater reliability are important, a much
better alternative is to use an opto coupler.

These use a beam of light to transmit the signals or data across an electrical barrier, and
achieve excellent isolation. Optocouplers typically come in a small 6 pin or 8-pin IC
package, but are essentially a combination of two distinct devices: an optical transmitter,
typically a gallium arsenide LED (light-emitting diode) and an optical receiver such as a
photo transistor or light-triggered diac. The two are separated by a transparent barrier
which blocks any electrical current flow between the two, but does allow the passage of
light.
The basic idea is shown in Figure, along with the usual circuit symbol for an
optocoupler. Usually the electrical connections to the LED section are brought out to the
pins on one side of the package and those for the phototransistor or diac to the other side, to
physically separate them as much as possible. This usually allows opto couplers to
withstand voltages of any where between 500V and 7500V between input and output.
Optocouplers are essentially digital or switching devices, so they are best for transferring

28
either on-off control signals or digital data. Analog signals can be transferred by means of
frequency or pulse-width modulation.

5.6.Microcontroller

In our initial foray into remote control car development we learned that most cars use a two
motor system, one in the back to push the car forward and one in the front to turn the
wheels left and right. We also discovered that the front motor is usually a servo motor
which requires a pulse width modulator (PWM) for control. Since we had thought about
controlling the rear wheel with a PWM as well, we needed a PIC capable of driving two
PWMs independently and without software control, if such a PIC existed. We also wanted
to have hardware UART to communicate with the Bluetooth module. This led us to find the
PIC 16F877A.

PIC16F876A Microcontroller made by Microchip Inc. It is a 40 pin microcontroller


and we predominantly use the B0/ INT (Interrupt Pin) to trigger the counter in our project.
A brief detail about the PIC Microcontrollers is given below.

PIC is a family of Harvard architecture microcontrollers made by Microchip Technology,


derived from the PIC1640 originally developed by General Instrument's Microelectronics
Division. The name PIC initially referred to "Peripheral Interface Controller".

PIC are popular with both industrial developers and hobbyists alike due to their low cost,
wide availability, large user base, extensive collection of application notes, availability of
low cost or free development tools, and serial programming (and re-programming with
flash memory) capability

1. Core architecture

The PIC architecture is characterized by its multiple attributes:

29
 Separate code and data spaces (Harvard architecture) for devices other than
PIC32, which has a Von Neumann architecture.
 A small number of fixed length instructions
 Most instructions are single cycle execution (2 clock cycles), with one delay cycle
on branches and skips
 One accumulator (W0), the use of which (as source operand) is implied (i.e. is not
encoded in the op code )
 All RAM locations function as registers as both source and/or destination of math
and other functions.
 A hardware stack for storing return addresses
 A fairly small amount of addressable data space (typically 256 bytes), extended
through banking
 Data space mapped CPU, port, and peripheral registers
 The program counter is also mapped into the data space and writable (this is used to
implement indirect jumps).

There is no distinction between memory space and register space because the RAM serves
the job of both memory and registers, and the RAM is usually just referred to as the register
file or simply as the registers

2. Performance

The architectural decisions are directed at the maximization of speed-to-cost ratio. The PIC
architecture was among the first scalar CPU designs and is still among the simplest and
cheapest. The Harvard architecture—in which instructions and data come from separate
sources—simplifies timing and microcircuit design greatly, and this benefits clock speed,
price, and power consumption.

The PIC instruction set is suited to implementation of fast lookup tables in the
program space. Such lookups take one instruction and two instruction cycles. Many
functions can be modeled in this way. Optimization is facilitated by the relatively large
program space of the PIC (e.g. 4096 x 14-bit words on the 16F690) and by the design of the
instruction set, which allows for embedded constants. For example, a branch instruction's

30
target may be indexed by W, and execute a "RETLW" which does as it is named - return
with literal in W.

Microchip PIC16F877A Microcontroller Features

High-Performance RISC CPU


 Lead-free; RoHS-compliant
 Operating speed: 20 MHz, 200 ns instruction cycle
 Operating voltage: 4.0-5.5V
 Industrial temperature range (-40° to +85°C)
 15 Interrupt Sources
 35 single-word instructions
 All single-cycle instructions except for program branches (two-cycle)

Special Microcontroller Features


 Flash Memory: 14.3 Kbytes (8192
words)
 Data SRAM: 368 bytes
 Data EEPROM: 256 bytes
 Self-reprogrammable under
software control
 In-Circuit Serial Programming via
two pins (5V)
 Watchdog Timer with on-chip RC
oscillator
 Programmable code protection
 Power-saving Sleep mode
 Selectable oscillator options
 In-Circuit Debug via two pins

Peripheral Features
 33 I/O pins; 5 I/O ports
 Timer0: 8-bit timer/counter with 8-bit prescaler
 Timer1: 16-bit timer/counter with prescaler
o Can be incremented during Sleep via external crystal/clock
 Timer2: 8-bit timer/counter with 8-bit period register, prescaler and postscaler
 Two Capture, Compare, PWM modules
o 16-bit Capture input; max resolution 12.5 ns
o 16-bit Compare; max resolution 200 ns
o 10-bit PWM

31
 Synchronous Serial Port with two modes:
o SPI Master
o I2C Master and Slave
 USART/SCI with 9-bit address detection
 Parallel Slave Port (PSP)
o 8 bits wide with external RD, WR and CS controls
 Brown-out detection circuitry for Brown-Out Reset

Analog Features
 10-bit, 8-channel A/D Converter
 Brown-Out Reset
 Analog Comparator module

5.7.CAR CHASIS & MOTORS


Due to time constraints and the fact we are electronic and communication engineers (not
mechanical engineers), we choose to purchase a cheap RC car from Toys R’ Us and use it
for the existing motors and chassis. An identical car is not necessary to reconstruct our
design, however when shopping for a car we tried to insure that both motors are brushed
DC motors. Specifically, ensure that the front motor is NOT a servo. A servo motor would
require motor control design modifications that are not discussed here within.

5.8.Bluetooth Module (HC-05)

We began the hardware design process by searching for and finding a suitable Bluetooth
module. Initially, our only requirement was that the module would need to handle the
wireless portion of the protocol by converting the raw Bluetooth data to/from a 2.4GHz
wave allowing us to simply deal with digital bits. Had we settled with this solution
however, we would have also needed to implement the entire Bluetooth Serial Port Profile
(BSPP) in software on the PIC microcontroller. After further research we found the HC-05
This HC-05 module satisfied the original requirement, implements a Bluetooth
stack and also provides the BSPP. The module is a dual inline package with an integrated
antenna convenient for breadboard development. The hardware interface consists of power,
ground, reset, factory reset, connection status, operation status, and a 3.3V RS232 interface.
Needless to say, we opted to use this module as our Bluetooth solution over any other.

32
In order to isolate issues in debugging, we worked with the UART interface on our
PIC microcontroller by using a logic level converter and a serial cable connected to the PC.
Once the UART interface was working, we then replaced the level converter with the HC-
05 module. At this point, we could say with certainty that any issues with connectivity and
data transfer were confined to the Bluetooth HC-05 module. This approach resulted in an
test driven development style with agility and no major complications.
.

Description
This Bluetooth with Blue2.0, Modify master & slave mode at any time, master and slave
mode is the same as the hardware to support the AT command set to support the baud
rate 2400 to 1382400.

The current firmware has been modified for the new version: The default setting for
serial port 【9600, N, 8,1】, password: 1234.

Support the AT command to modify the baud rate, device name, passkey, master or
slave mode (master and slave mode can be modified by AT commands), require
additional baud rate or the principal mode of an order, please indicate the support of the
baud rate 2400---1382400.

Note: HC-03, HC-05 are the Master and Slave integrated Bluetooth serial module,
Modify master & slave mode at any time HC-03 are industrial grade products, HC-05
are commercial grade products;

Features:

 Build-in CSR company Bluetooth chip BC417143


 Bluetooth specification v2.0 + EDR
 High-board antennas Paired with various Bluetooth adapter, Bluetooth phone
use, master-slave can also be used in double

33
 Can be set for the module control parameters and control commands issued via
AT commands
 The maximum serial baud rate: 1382400bps, support for hardware flow control
transfer
 Provide seven input and output ports, scalable user IO resources
 Used for embedded wireless serial transmission alternatives Size: 26.9mm x
13mm x 2.2 m

Specifications:

 Bluetooth protocol: Bluetooth Specification v2.0+EDR


 USB protocol: USB v1.1/2.0
 Frequency: 2.4GHz ISM band
 Modulation: GFSK(Gaussian Frequency Shift Keying)
 Transmit power: ≤4dBm, Class 2
 Sensitivity: ≤-84dBm at 0.1% BER
 Rate: Asynchronous: 2.1Mbps(Max) / 160 kbps
 Synchronous: 1Mbps/1Mbps
 Security features: Authentication and encryption
 Support profiles: Bluetooth serial port (master & slave)
 Power Supply: +3.3VDC 50mA
 Working temperature: –5 ~ +45 Centigrade

Applications:

 Mouse, keyboard, joystick


 Computers and peripherals
 GPS Receiver
 Instrument

 Industrial control
5.9. MOTOR DRIVER (L298)

Most brushed DC motors (which are the type


found in typical RC cars) are controlled by an
H-Bridge. The following image shows the
theory of operation of an H-bridge.
Essentially, there are 4 switches used
to create a path for current flow resulting in
the desired direction: forward, reverse and
34
halt. It is important to avoid turning the switches on in a way which would short power to
ground. Most H-bridges are constructed using 4 mosfets since a mosfet functions well as a
switch with minimal current loss.

The L298 chip is the bigger brother to the L293 chip (a popular small-motor driver IC), but
the L298 handles more current, and more voltage - just what you need for those robots that
need more power!
One of the first realizations in robotics is that making something move isn’t an easy
task. You simply can’t take a “brain” circuit and connect it to a motor and expect anything
to happen. The motor will simply say “HAH!” at the puny output signal from the brains,
and stay still. What the brain needs is an enforcer Muscle. Something to convince the motor
to do things the way the brains want it to be done. There are many ways to strengthen
(”buffer”) a signal so it’s strong enough to drive a large load like a motor. Transistor H-
bridge circuits, buffer chips, and dedicated motor driving chips are all suitable candidates,
with their own benefits and limitations.
We’re using the well-proven L298 for this design, as it has practically all the features
you’d need in a good motor driver, including thermal-shutdown, meaning that it will slow
down and stop if overloaded (rather than melting down in a catastrophic manner!).
Adding a low-drop out regulator lets you tap off 5V for any other circuitry you may want to
drive, and the indicator LEDs are always very useful when monitoring the behaviours of
your circuit.

35
Maximum current rating per channel: 2A
Maximum Supply voltage for Motors: 50V
Maximum Logic Voltage: 7V

Chapter VI

SOFTWARE
DEVELOPMENT

36
VI. SOFTWARE DEVELOPMENT

There were no specific difficulties in the development of our PC-based control software.
Any curiosities could easily be satisfied by looking through the provided source code.
However we would like to stress the importance of choosing appropriate tools for the job.
In our case, the C# was chosen as our implementation language because it allows for easy
development of graphical user interfaces. Additionally, C# (via the .NET 2.0 frameworks)
provides a strong library base for COM. By harnessing the already existing serial port
interface libraries we were able to spend more time focusing on the car hardware and less
time learning how to reinvent the wheel.

MPLAB
The MPASM assembler, the MPLINK object linker and the MPLIB object librarian are
typically used together under MPLAB IDE to provide GUI development of application
code for PIC1X MCU devices (PIC10/12/16/18 MCUs). The operation of these PIC
language tools with MPLAB IDE is discussed here.

MPLAB IDE and Tools Installation

In order to use the PIC language tools with MPLAB IDE, you must first install MPLAB
IDE. The latest version of this free software is available at our website
(http://www.microchip.com) or from any sales office. When you install MPLAB IDE, you

37
will be installing the MPASM assembler, the MPLINK object linker and the MPLIB object
librarian as well.
The language tools will be installed, by default, in the directory:
C:\Program Files\Microchip\MPASM Suite
The executables for each tool will be:
MPASM Assembler - mpasmwin.exe
MPLINK Object Linker - mplink.exe
MPLIB Object Librarian - mplib.exe
Other Utilities
All device include (header) files are also in this directory. For more on these files, see
MPASM assembler documentation.
All device linker script files are in the LKR subdirectory. For more on these files, see
MPLINK object linker documentation.
Code examples and template files are also included in subdirectories for your use. Template
files are provided for absolute code (Code) and relocatable code (Object) development.

MPLAB IDE Projects

A project in MPLAB IDE is a group of files needed to build an application, along with their
associations to various build tools. Below is a generic MPLAB IDE project.
In this MPLAB IDE project, an assembly source file (prog.asm) is shown with its
associated assembler (MPASM assembler). MPLAB IDE will use this information to
generate the object file prog.o for input into the MPLINK object linker. For more
information on the assembler, see the MPASM assembler documentation.
The C source file main.c is also shown with its associated MPLAB C18 C compiler.
MPLAB IDE will use this information to generate an object file (main.o) for input into the
MPLINK object linker. For more information on the compiler, see the MPLAB C18 C
compiler documentation listed in Recommended Reading.
In addition, precompiled object files (precomp.o) may be included in a project, with no
associated tool required. MPLAB C18 requires the inclusion of a precompiled standard

38
code module c018i.o, for example. For more information on available Microchip
precompiled object files, see the MPLAB C18 C compiler documentation.
Some library files (math.lib) are available with the compiler. Others may be built using the
librarian tool (MPLIB object librarian). For more information on the librarian, see the
MPLIB librarian documentation. For more information on available Microchip libraries,
see the MPLAB C18 C compiler documentation.
The object files, along with library files, are used to generate the project output files via the
linker (MPLINK object linker). Depending on your project, you may or may not need to
add a linker script file (device.lkr). For more information on using linker script files and the
linker, see the MPLINK linker documenation.
The main output file generated by the MPLINK linker is the COF file (prog.cof). The linker
then uses the utility MP2HEX to generate the Hex file (prog.hex), used by simulators,
emulators, debuggers and programmers. For more information on linker output files, see
the MPLINK linker documentation. For more information on utilities, see the related
documentation.

MPASM Assembler

The MPASM assembler (the assembler) is a command-line or Windows-based PC


application that provides a platform for developing assembly language code for Microchip's
PIC1X microcontroller (MCU) families.
The executable version of the assembler is mpasmwin.exe. Use this version with MPLAB
IDE, in a stand-alone Windows application, or on the command line. This version is
available with MPLAB IDE or with the regular and demo version of the MPLAB C18 C
compiler.
The MPASM assembler supports all PIC1X MCU devices, as well as memory and KeeLoq
secure data products from Microchip Technology Inc. (Some memory and KeeLoq devices
were not supported in MPLAB IDE after v5.70.40.)

How MPASM Assembler Helps You

39
The MPASM assembler provides a universal solution for developing assembly code for all
of Microchip's PIC1X MCUs. Notable features include:
 MPLAB IDE Compatibility
 Windows/Command Line Interfaces
 Rich Directive Language
 Flexible Macro Language
 Assembler Migration Path

Since the MPASM assembler is a universal assembler for all PIC1X MCU devices,
application code developed for the PIC16F877A can be translated into a program for the
PIC18F452. This may require changing the instruction mnemonics that are not the same
between the devices (assuming that register and peripheral usage were similar.) The rest of
the directive and macro language will be the same.

Assembler Compatibility Issues

The MPASM assembler is compatible with the MPLAB IDE integrated development
environment and all Microchip PIC1X MCU development systems currently in production.
The MPASM assembler supports a clean and consistent method of specifying radix (see
Numeric Constants and Radix.) You are encouraged to develop using the radix and other
directive methods described within this document, even though certain older syntaxes may
be supported for compatibility reasons.

Assembler Operation

The MPASM assembler can be used in two ways:


To generate absolute code that can be executed directly by a microcontroller.
To generate reloadable code that can be linked with other separately assembled or compiled
modules.

Generating Absolute Code

40
Absolute code is the default output from the MPASM assembler.
When a source file is assembled in this manner, all variables and routines used in the source
file must be defined within that source file, or in files that have been explicitly included by
that source file. If assembly proceeds without errors, a hex file will be generated,
containing the executable machine code for the target device. This file can then be used
with a debugger to test code execution or with a device programmer to program the
microcontroller.

Generating Reloadable Code

The MPASM assembler also has the ability to generate a reloadable object module that can
be linked with other modules using Microchip's MPLINK linker to form the final
executable code. This method is very useful for creating reusable modules.
Related modules can be grouped and stored together in a library using Microchip's MPLIB
librarian. Required libraries can be specified at link time, and only the routines that are
needed will be included in the final executable.

41
Chapter VII

CODING

42
VII. PIC Coding

#define _XTAL_FREQ 16000000


#include<htc.h>
const baud_constant=103;
__CONFIG(FOSC_HS & WDTE_OFF & PWRTE_ON & BOREN_ON &
LVP_OFF & CPD_OFF & WRT_OFF & CP_OFF);
const char message01[]= " RFID BASE ";
const char message02[]= " ACESS SYSTEM ";
const char message03[]= "Please Show card";
const char message04[]= "C.NO.=";
const char message05[]= " ACCESS DENIED ";
const char message06[]= " ACCESS GRANTED ";
const char message07[]= " Enter Password ";
const char cardno[]= "4100A35B84";
const char password[]= "1982";

unsigned char rs232buffer[10],pass_enter[4];


unsigned char rx_count=0,data;
unsigned int card_counter=0;
unsigned char lsb0,lsb1,lsb2,lsb3,lsb4;
unsigned int fre_count=0,time_count=0;
unsigned int refresh_count,fre_count_final=0;
void rs232_intialization();
void timer_intialization();
void initialization();

43
void card_dispalay();
void card_no_dispalay();
void switches();
void home_screen();
unsigned int time;
void bcd(int temp);
void Password_screen();
char ascii(char temp);
void password_acceptance();
unsigned char refresh,RS232_DATA,cnt,cursor_counter;
bit swf1;
bit swf2;
bit swf3;
bit swf4;
bit swf5;
bit swf6;
bit swf7;
bit swf8;
bit swf9;
bit swf10;
bit swf11;
bit swf12;
bit swf13;
bit swf14;
bit swf15;
bit swf16;
bit cursor;

bit card_accept,change,RX,pa;
#define m1r RE2
#define m1f RC0
#define m2f RC1
#define m2r RC2
#define headlight RA0

char temp;

void main()
{
44
change=1;
initialization();

///////////////////////////////main
loop/////////////////////////////////////////////////////////////////////////////////////////////////////

while(1)

{
//headlight on motor stop
if(RS232_DATA==0x80)
{
headlight=1;
m1f=0;
m1r=0;
m2f=0;
m2r=0;
}
//headlight off motor stop
if(RS232_DATA==0x00)
{
headlight=0;
m1f=0;
m1r=0;
m2f=0;
m2r=0;
}

//headlight on motor for


if(RS232_DATA==0x90)
{
headlight=1;
m1f=1;
m1r=0;
m2f=1;
m2r=0;
}

//headlight off motor for


45
if(RS232_DATA==0x10)
{
headlight=0;
m1f=1;
m1r=0;
m2f=1;
m2r=0;
}

//headlight on motor rev


if(RS232_DATA==0xa0)
{
headlight=1;
m1f=0;
m1r=1;
m2f=0;
m2r=1;
}
//headlight off motor rev
if(RS232_DATA==0x20)
{
headlight=0;
m1f=0;
m1r=1;
m2f=0;
m2r=1;
}

//headlight on motor left


if(RS232_DATA==0x84)
{
headlight=1;
m1f=1;
m1r=0;
m2f=0;
m2r=0;
}

//headlight off motor left


if(RS232_DATA==0x04)
46
{
headlight=0;
m1f=1;
m1r=0;
m2f=0;
m2r=0;
}

//headlight on motor right


if(RS232_DATA==0x88)
{
headlight=1;
m1f=0;
m1r=0;
m2f=1;
m2r=0;
}

//headlight off motor right


if(RS232_DATA==0x08)
{
headlight=0;
m1f=0;
m1r=0;
m2f=1;
m2r=0;
}

//////////////////////////////interrupt
sou/////////////////////////////////////////////////////////////////////////////////////////////////////
void interrupt sou()
{ char temp;
if(OERR==1)
{
CREN=0;
temp=RCREG;
CREN=1;
47
}

if(FERR==1)
{
CREN=0;
temp=RCREG;
CREN=1;
}

{
RCIF=0;
RS232_DATA=RCREG;
}

////////////////////////////////////////////
if(TMR0IF==1)
{
TMR0IF=0;
time_count++;

if(time_count==50)
{
time_count=0;
change=1;
}
TMR0=132;
}
if((cnt==1)|(cnt==3))
{
card_counter++;
if(card_counter==10000)
{
cnt=0;
change=1;
}
}
}

/////////////////////////////////
48
char ascii(char temp)
{
if(temp>=0x0a)
{
temp=temp+0x37;
}
if(temp<0x0a)
{
temp=temp+0x30;
}
return(temp);

}
/////////////////////////////////
void bcd(int temp)
{
int temp1;
lsb0=temp%10;
temp=temp/10;
lsb1=temp%10;
temp=temp/10;
lsb2=temp%10;
temp=temp/10;
lsb3=temp%10;
temp=temp/10;
lsb4=temp%10;
}

//////////////////////////////////
timer_intialization////////////////////////////////////////////////////////////////////////////////////
void rs232_intialization()
{
SPBRG=baud_constant;
TXSTA=0xa4;
RCIE=1;
RCSTA=0X90;
GIE=1;
PEIE=1;
}

49
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
void initialization()
{
ADCON1 = 0X07;
TRISA = 0X30;//PORTA OUTPUT
TRISB = 0X00;//PORTB OUTPUT
TRISC = 0b10100000;//PORTC OUTPUT
TRISD = 0X00;//PORTC OUTPUT
TRISE = 0X00;//PORTC OUTPUT
PORTA=PORTB=PORTC=PORTD=PORTE=0X00;

Android Application Coding

/*
* Copyright (C) 2011 Eirik Taylor
*
* This work is licensed under a Creative Commons Attribution-Noncommercial-Share
Alike 3.0 Unported License.
* See the following website for more information:
* http://creativecommons.org/licenses/by-nc-sa/3.0/
*
*/

package com.uzzors2k.blu_car;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;

50
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class blu_car extends Activity {

// Intent request codes


private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;

// Program variables
private byte AttinyOut;
private boolean ledStat;
private boolean connectStat = false;
private Button led_button;
private Button forward_button;
private Button reverse_button;
private Button connect_button;
private TextView xAccel;
protected static final int MOVE_TIME = 80;
private long lastWrite = 0;
private AlertDialog aboutAlert;
private View aboutView;
private View controlView;
OnClickListener myClickListener;
ProgressDialog myProgressDialog;
private Toast failToast;
private Handler mHandler;

// Sensor object used to handle accelerometer


private SensorManager mySensorManager;
private List<Sensor> sensors;

51
private Sensor accSensor;

// Bluetooth Stuff
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private ConnectThread mConnectThread = null;
private String deviceAddress = null;
// Well known SPP UUID (will *probably* map to RFCOMM channel 1 (default) if not
in use);
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-
00805F9B34FB");

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


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Create main button view


LayoutInflater inflater =
(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
aboutView = inflater.inflate(R.layout.aboutview, null);
controlView = inflater.inflate(R.layout.main, null);
controlView.setKeepScreenOn(true);
setContentView(controlView);

// Finds buttons in .xml layout file


led_button = (Button) findViewById(R.id.led_button);
forward_button = (Button) findViewById(R.id.forward_button);
reverse_button = (Button) findViewById(R.id.reverse_button);
connect_button = (Button) findViewById(R.id.connect_button);
xAccel = (TextView) findViewById(R.id.accText);

// Set Sensor
mySensorManager =
(SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensors = mySensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(sensors.size() > 0) accSensor = sensors.get(0);

// Handle click events from help and info dialogs


myClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
dialog.dismiss();

52
break;
case DialogInterface.BUTTON_NEUTRAL:
// Display website
Intent browserIntent = new
Intent("android.intent.action.VIEW",
Uri.parse(getResources().getString(R.string.website_url)));
startActivity(browserIntent);
break;
default: dialog.dismiss();
}
}
};

myProgressDialog = new ProgressDialog(this);


failToast = Toast.makeText(this, R.string.failedToConnect,
Toast.LENGTH_SHORT);

mHandler = new Handler() {


@Override
public void handleMessage(Message msg) {
if (myProgressDialog.isShowing()) {
myProgressDialog.dismiss();
}

// Check if bluetooth connection was made to selected device


if (msg.what == 1) {
// Set button to display current status
connectStat = true;
connect_button.setText(R.string.connected);

// Reset the BluCar


AttinyOut = 0;
ledStat = false;
write(AttinyOut);
}else {
// Connection failed
failToast.show();
}
}
};

// Create about dialog


AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setView(aboutView).setCancelable(true).setTitle(getResources().getString(R.string.
app_name) + " " +

53
getResources().getString(R.string.appVersion)).setIcon(R.drawable.blu_car_icon).setPositi
veButton(getResources().getString(R.string.okButton),
myClickListener).setNeutralButton(getResources().getString(R.string.websiteButton),
myClickListener);
aboutAlert = builder.create();

// Check whether bluetooth adapter exists


mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.no_bt_device, Toast.LENGTH_LONG).show();
finish();
return;
}

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


if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}

/**********************************************************************
* Buttons for controlling BluCar
*/

// Connect to Bluetooth Module


connect_button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
if (connectStat) {
// Attempt to disconnect from the device
disconnect();
}else{
// Attempt to connect to the device
connect();
}
}
});

// Toggle Headlights
led_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ledStat) {

54
AttinyOut = (byte) (AttinyOut & 124);
led_button.setText(R.string.ledON);
ledStat = false;
}else{
AttinyOut = (byte) (AttinyOut | 128);
led_button.setText(R.string.ledOFF);
ledStat = true;
}
write(AttinyOut);
}
});

// Drive forward
forward_button.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_DOWN) |
(event.getAction() == MotionEvent.ACTION_MOVE)) {
forward_button.setPressed(true);
AttinyOut = (byte) (AttinyOut | 16);
write(AttinyOut);
return true;

}else if (event.getAction() == MotionEvent.ACTION_UP) {


forward_button.setPressed(false);
AttinyOut = (byte) (AttinyOut & 236);
write(AttinyOut);
return true;
}
forward_button.setPressed(false);
return false;
}
});

// Back up
reverse_button.setOnTouchListener(new View.OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_DOWN) |
(event.getAction() == MotionEvent.ACTION_MOVE)) {
reverse_button.setPressed(true);
AttinyOut = (byte) (AttinyOut | 32);
write(AttinyOut);
return true;

55
}else if (event.getAction() == MotionEvent.ACTION_UP) {
reverse_button.setPressed(false);
AttinyOut = (byte) (AttinyOut & 220);
write(AttinyOut);
return true;
}
reverse_button.setPressed(false);
return false;
}
});

/** Thread used to connect to a specified Bluetooth Device */


public class ConnectThread extends Thread {
private String address;
private boolean connectionStatus;

ConnectThread(String MACaddress) {
address = MACaddress;
connectionStatus = true;
}

public void run() {


// When this returns, it will 'know' about the server,
// via it's MAC address.
try {
BluetoothDevice device =
mBluetoothAdapter.getRemoteDevice(address);

// We need two things before we can successfully connect


// (authentication issues aside): a MAC address, which we
// already have, and an RFCOMM channel.
// Because RFCOMM channels (aka ports) are limited in
// number, Android doesn't allow you to use them directly;
// instead you request a RFCOMM mapping based on a service
// ID. In our case, we will use the well-known SPP Service
// ID. This ID is in UUID (GUID to you Microsofties)
// format. Given the UUID, Android will handle the
// mapping for you. Generally, this will return RFCOMM 1,
// but not always; it depends what other BlueTooth services
// are in use on your Android device.
try {
btSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) {

56
connectionStatus = false;
}
}catch (IllegalArgumentException e) {
connectionStatus = false;
}

// Discovery may be going on, e.g., if you're running a


// 'scan for devices' search from your handset's Bluetooth
// settings, so we call cancelDiscovery(). It doesn't hurt
// to call it, but it might hurt not to... discovery is a
// heavyweight process; you don't want it in progress when
// a connection attempt is made.
mBluetoothAdapter.cancelDiscovery();

// Blocking connect, for a simple client nothing else can


// happen until a successful connection is made, so we
// don't care if it blocks.
try {
btSocket.connect();
} catch (IOException e1) {
try {
btSocket.close();
} catch (IOException e2) {
}
}

// Create a data stream so we can talk to server.


try {
outStream = btSocket.getOutputStream();
} catch (IOException e2) {
connectionStatus = false;
}

// Send final result


if (connectionStatus) {
mHandler.sendEmptyMessage(1);
}else {
mHandler.sendEmptyMessage(0);
}
}
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {


switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect

57
if (resultCode == Activity.RESULT_OK) {
// Show please wait dialog
myProgressDialog = ProgressDialog.show(this,
getResources().getString(R.string.pleaseWait),
getResources().getString(R.string.makingConnectionString), true);

// Get the device MAC address


deviceAddress =
data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Connect to device with specified MAC address
mConnectThread = new ConnectThread(deviceAddress);
mConnectThread.start();

}else {
// Failure retrieving MAC address
Toast.makeText(this, R.string.macFailed,
Toast.LENGTH_SHORT).show();
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled
} else {
// User did not enable Bluetooth or an error occured
Toast.makeText(this, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
finish();
}
}
}

public void write(byte data) {


if (outStream != null) {
try {
outStream.write(data);
} catch (IOException e) {
}
}
}

public void emptyOutStream() {


if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {

58
}
}
}

public void connect() {


// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}

public void disconnect() {


if (outStream != null) {
try {
outStream.close();
connectStat = false;
connect_button.setText(R.string.disconnected);
} catch (IOException e) {
}
}
}

private final SensorEventListener mSensorListener = new SensorEventListener() {

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}

@Override
public void onSensorChanged(SensorEvent event) {
// Checks whether to send steering command or not
long date = System.currentTimeMillis();
if (date - lastWrite > MOVE_TIME) {
xAccel.setText(" " + event.values[0]);
if (event.values[0] > 4.5) {
// Turn right
AttinyOut = (byte) (AttinyOut & 248);
AttinyOut = (byte) (AttinyOut | 4);
}else if (event.values[0] < -4.5) {
// Turn left
AttinyOut = (byte) (AttinyOut & 244);
AttinyOut = (byte) (AttinyOut | 8);
}else {
// Center the steering servo
AttinyOut = (byte) (AttinyOut & 240);
}
write(AttinyOut);
lastWrite = date;

59
}
}
};

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
// Show info about the author (that's me!)
aboutAlert.show();
return true;
}
return false;
}

@Override
public void onResume() {
super.onResume();
mySensorManager.registerListener(mSensorListener, accSensor,
SensorManager.SENSOR_DELAY_GAME);
}

@Override
public void onDestroy() {
emptyOutStream();
disconnect();
if (mSensorListener != null) {
mySensorManager.unregisterListener(mSensorListener);
}
super.onDestroy();
}
}

60
Chapter VIII

Conclusion &
Future
Enhancements
61
VIII. CONCLUSION
Our final product was a prototype modified RC car that can be driven from a PC or
other programmable Bluetooth Ready device. The car has the ability to move forward,
backward, turn left, turn right, and honk. It uses the original motors and chassis from the
RC car we purchased and incorporates our H-birdge, FET drivers, one PIC 16F877A, and a
Bluetooth module.
After spending many nights working on the video compression and transmission
components, we discovered that our particular Bluetooth module was not capable of
transmitting fast enough to stream live video and thusly fails to live up to true Blue Tooth
1.2 spec. Instead of transmitting at the maximum Bluetooth speed of 700kbps, it could only
send at 34.5 kbps tested. Attempting to transfer any faster overflows the internal buffer on
theHC-05 module and causes the on board processor to reset, dropping the Bluetooth
connection. Had we been able to transfer at full Bluetooth speed, highly compressed video
streaming would have been possible!
Our plans for the cell phone interface never fully materialized either. We were
unable to obtain a suitable cell phone for testing until two weeks before the project was

62
due. In those two weeks we spent some time working on an early version of the Motorola
Razor. Although the cell phone specifications explicitly states it is JSR-82 compatible, we
were unable to initiate a BSPP session with a PC much less the car due to limitations in the
current SDK.
Over all, the project was a great success in learning. We both gained knowledge and
experience in power systems, motors, video, video compression, and embedded systems. At
the same time we have an interesting prototype of a car to be proud of and the success of
our public demos at the University of Illinois Engineering Days.

We have successfully carried out this project of “MOBILE CONTROLLED ROBOT


THROUGH BLUETOOTH” for the partial fulfillment of requirement for completion of
Bachelors degree in Electronics and Communication Engineering.

The goal with which this project was taken by us has been achieved but the vision it yet to
be fulfilled. Towards the end of this ambitious venture we conclude that we have been able
to successfully complete a system for the measurement of Electricity Meter Reading
wirelessly with appreciable efficiency and accuracy. Our setup is capable of working in the
best of its ability in a range of about 100 meters under standard atmospheric conditions.

While working on this project we were exposed to various new principles and advanced
electronic gadgets. This has enhanced our understanding on various subjects and propelled
us to look forward for future enhancements possible in this system

On successful completion of our project we feel that we have contributed towards solving a
few problems of our society by putting our technical skills to use. The use of wireless
energy meter is expected to solve issues like average readings and bundle readings caused
due to absence of the house owners at the time of the reading collection. With this system,
house owners participation in the process of reading collection is avoided and the also the
manpower utilization by the Electricity Board is reduced. With this system, reading
collection, of a colony, locality or even a city is possible sitting at one point.

63
Limitations

Though we have tried our level best to come up with a flawless system, there are a few
limitations which need to be addressed. These limitations are mainly with reference to the
environmental consideration, the quality of work given by the system (output efficiency)
and the commercial use of this system.

They are:

1 – With our project we are adding to the already existing RF Noise

2 – With the large scale use of our system, there may arise problems similar to
the mobile communication problems. For example Crosstalk, Interference etc

3 – This project does not have any feedback for the House owner

4 – The commercial use our system cannot be carried out at the frequency at
which it is presently being carried out because, the band being used presently
is the one allocated for experimental and research purposes and any
commercial activity in it is punishable offence. A licensed band is required
for the same.

Future Enhancement Scope

Our Project has a great scope for future enhancement. A few changes and
modifications in the design can make it much more efficient and versatile. Today with the
existing hardware, we can expect it to work at fairly closer distances but in future we can
demand its use covering larger distances too.

64
We can extend this system with two technologies. One using GSM Module and the
other using TCP/IP Protocol. Firstly let us discuss the first one.

Chapter IX

REFRENCES
65
IX. REFRENCES

1. www.efy.com

2. www.nationalsemiconductor.com

3. www.icdiscription.com

4. www.electrosofts.com

5. www.uzzors.com

6. www.wikipedia.com

66

You might also like