android robot
android robot
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
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 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.
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.
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
H-Bridge
Figure 3.1: Operational Block Diagram
15
Chapter V
Description
Of
Components
16
Hardware Requirements
2. IC (16F877A) 1 220.00
17
20 PRINTING 2 250.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.
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
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.
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.
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
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.
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
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
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.
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.
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.
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
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.
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
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:
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:
Applications:
Industrial control
5.9. MOTOR DRIVER (L298)
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.
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.
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
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.
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
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.
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
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;
}
//////////////////////////////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;
/*
* 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;
// 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;
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");
// Set Sensor
mySensorManager =
(SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensors = mySensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
if(sensors.size() > 0) accSensor = sensors.get(0);
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();
}
}
};
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();
/**********************************************************************
* Buttons for controlling BluCar
*/
@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;
// 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;
}
});
ConnectThread(String MACaddress) {
address = MACaddress;
connectionStatus = true;
}
56
connectionStatus = false;
}
}catch (IllegalArgumentException e) {
connectionStatus = false;
}
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);
}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();
}
}
}
58
}
}
}
@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.
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:
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.
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