Você está na página 1de 106

I

INTRODUCTION TO
EMBEDDED SYSTEM

An embedded system is a computer system designed to perform one or a few dedicated


functionsoften with real-time computing constraints. It is embedded as part of a complete
device often including hardware and mechanical parts. By contrast, a general-purpose
computer, such as a personal computer (PC), is designed to be flexible and to meet a wide
range of end-user needs. Embedded systems control many devices in common use today.

Embedded systems are controlled by one or more main processing cores that are typically
either microcontrollers or digital signal processors (DSP).The key characteristic, however, is
being dedicated to handle a particular task, which may require very powerful processors. For
example, air traffic control systems may usefully be viewed as embedded, even though they
involve mainframe computers and dedicated regional and national networks between airports
and radar sites. (Each radar probably includes one or more embedded systems of its own.)

Since the embedded system is dedicated to specific tasks, design engineers can optimize it to
reduce the size and cost of the product and increase the reliability and performance. Some
embedded systems are mass-produced, benefiting from economies of scale.

Physically, embedded systems range from portable devices such as digital watches and MP3
players, to large stationary installations like traffic lights, factory controllers, or the systems
controlling nuclear power plants. Complexity varies from low, with a single microcontroller
chip, to very high with multiple units, peripherals and networks mounted inside a large
chassis or enclosure.

In general, "embedded system" is not a strictly definable term, as most systems have some
element of extensibility or programmability. For example, handheld computers share some
elements with embedded systems such as the operating systems and microprocessors which
power them, but they allow different applications to be loaded and peripherals to be
connected. Moreover, even systems which don't expose programmability as a primary feature
generally need to support software updates. On a continuum from "general purpose" to
"embedded", large application systems will have subcomponents at most points even if the
system as a whole is "designed to perform one or a few dedicated functions", and is thus
appropriate to call "embedded".

pg. 1
Variety in embedded systems
Embedded systems span all aspects of modern life and there are many examples of their use.

Telecommunications systems employ numerous embedded systems from telephone switches


for the network to mobile phones at the end-user. Computer networking uses dedicated
routers and network bridges to route data.

Consumer electronics include personal digital assistants (PDAs), mp3 players, mobile
phones, videogame consoles, digital cameras, DVD players, GPS receivers, and printers.
Many household appliances, such as microwave ovens, washing machines and dishwashers,
are including embedded systems to provide flexibility, efficiency and features. Advanced
HVAC systems use networked thermostats to more accurately and efficiently control
temperature that can change by time of day and season. Home automation uses wired- and
wireless-networking that can be used to control lights, climate, security, audio/visual,
surveillance, etc., all of which use embedded devices for sensing and controlling.

Transportation systems from flight to automobiles increasingly use embedded systems. New
airplanes contain advanced avionics such as inertial guidance systems and GPS receivers that
also have considerable safety requirements. Various electric motors — brushless DC motors,
induction motors and DC motors — are using electric/electronic motor controllers.
Automobiles, electric vehicles, and hybrid vehicles are increasingly using embedded systems
to maximize efficiency and reduce pollution. Other automotive safety systems include anti-
lock braking system (ABS), Electronic Stability Control (ESC/ESP), traction control (TCS)
and automatic four-wheel drive.

Medical equipment is continuing to advance with more embedded systems for vital signs
monitoring, electronic stethoscopes for amplifying sounds, and various medical imaging
(PET, SPECT, CT, MRI) for non-invasive internal inspections.

In addition to commonly described embedded systems based on small computers, a new class
of miniature wireless devices called motes are quickly gaining popularity as the field of
wireless sensor networking rises. Wireless sensor networking, WSN, makes use of
miniaturization made possible by advanced IC design to couple full wireless subsystems to
sophisticated sensors, enabling people and companies to measure a myriad of things in the
physical world and act on this information through IT monitoring and control systems. These
motes are completely self contained, and will typically run off a battery source for many
years before the batteries need to be changed or charged.

History
In the earliest years of computers in the 1930–40s, computers were sometimes dedicated to a
single task, but were far too large and expensive for most kinds of tasks performed by
embedded computers of today. Over time however, the concept of programmable controllers
evolved from traditional electromechanical sequencers, via solid state devices, to the use of
computer technology.

pg. 2
One of the first recognizably modern embedded systems was the Apollo Guidance Computer,
developed by Charles Stark Draper at the MIT Instrumentation Laboratory. At the project's
inception, the Apollo guidance computer was considered the riskiest item in the Apollo
project as it employed the then newly developed monolithic integrated circuits to reduce the
size and weight. An early mass-produced embedded system was the Autonetics D-17
guidance computer for the Minuteman missile, released in 1961. It was built from
transistorlogic and had a hard disk for main memory. When the Minuteman II went into
production in 1966, the D-17 was replaced with a new computer that was the first high-
volume use of integrated circuits. This program alone reduced prices on quad NAND gate
ICs from $1000/each to $3/each, permitting their use in commercial products.

Since these early applications in the 1960s, embedded systems have come down in price and
there has been a dramatic rise in processing power and functionality. The first microprocessor
for example, the Intel 4004, was designed for calculators and other small systems but still
required many external memory and support chips. In 1978 National Engineering
Manufacturers Association released a "standard" for programmable microcontrollers,
including almost any computer-based controllers, such as single board computers, numerical,
and event-based controllers.

As the cost of microprocessors and microcontrollers fell it became feasible to replace


expensive knob-based analog components such as potentiometers and variable capacitors
with up/down buttons or knobs read out by a microprocessor even in some consumer
products. By the mid-1980s, most of the common previously external system components had
been integrated into the same chip as the processor and this modern form of the
microcontroller allowed an even more widespread use, which by the end of the decade were
the norm rather than the exception for almost all electronics devices.

The integration of microcontrollers has further increased the applications for which
embedded systems are used into areas where traditionally a computer would not have been
considered. A general purpose and comparatively low-cost microcontroller may often be
programmed to fulfill the same role as a large number of separate components. Although in
this context an embedded system is usually more complex than a traditional solution, most of
the complexity is contained within the microcontroller itself. Very few additional components
may be needed and most of the design effort is in the software. The intangible nature of
software makes it much easier to prototype and test new revisions compared with the design
and construction of a new circuit not using an embedded processor.

Characteristics
1. Embedded systems are designed to do some specific task, rather than be a general-
purpose computer for multiple tasks. Some also have real-time performance
constraints that must be met, for reasons such as safety and usability; others may have
low or no performance requirements, allowing the system hardware to be simplified
to reduce costs.
2. Embedded systems are not always standalone devices. Many embedded systems
consist of small, computerized parts within a larger device that serves a more general
purpose. For example, the Gibson Robot Guitar features an embedded system for
tuning the strings, but the overall purpose of the Robot Guitar is, of course, to play

pg. 3
music. Similarly, an embedded system in an automobile provides a specific function
as a subsystem of the car itself.
3. The program instructions written for embedded systems are referred to as firmware,
and are stored in read-only memory or Flash memory chips. They run with limited
computer hardware resources: little memory, small or non-existent keyboard and/or
screen.

User interface

Embedded systems range from no user interface at all — dedicated only to one task — to
complex graphical user interfaces that resemble modern computer desktop operating systems.
Simple embedded devices use buttons, LEDs, graphic or character LCDs (for example
popular HD44780 LCD) with a simple menu system.

A more sophisticated devices use graphical screen with touch sensing or screen-edge buttons
provide flexibility while minimizing space used: the meaning of the buttons can change with
the screen, and selection involves the natural behavior of pointing at what's desired. Handheld
systems often have a screen with a "joystick button" for a pointing device.

Some systems provide user interface remotely with the help of serial (e.g. RS-232, USB, I²C,
etc.) or network (e.g. Ethernet) connection. In spite of installed client software and cables are
needed this approach usually gives a lot of advantages: extends the capabilities of embedded
system, avoids the cost of a display, simplifies BSP, allows to build rich user interface on PC.

One of the well established model in this direction is the combination of embedded web
server running on embedded device and user interface in web browser on PC (typical for IP
cameras and network routers).

Processors in embedded systems

Embedded processors can be broken into two broad categories: ordinary microprocessors
(μP) and microcontrollers (μC), which have many more peripherals on chip, reducing cost
and size. Contrasting to the personal computer and server markets, a fairly large number of
basic CPU architectures are used; there are Von Neumann as well as various degrees of
Harvard architectures, RISC as well as non-RISC and VLIW; word lengths vary from 4-bit to
64-bits and beyond (mainly in DSP processors) although the most typical remain 8/16-bit.
Most architectures come in a large number of different variants and shapes, many of which
are also manufactured by several different companies.

ASIC and FPGA solutions

A common configuration for very-high-volume embedded systems is the system on a chip


(SoC) which contains a complete system consisting of multiple processors, multipliers,
caches and interfaces on a single chip. SoCs can be implemented as an application-specific
integrated circuit (ASIC) or using a field-programmable gate array (FPGA).

Peripherals

Embedded Systems talk with the outside world via peripherals, such as:

pg. 4
• Serial Communication Interfaces (SCI): RS-232, RS-422, RS-485 etc.
• Synchronous Serial Communication Interface: I2C, SPI, SSC and ESSI (Enhanced
Synchronous Serial Interface)
• Universal Serial Bus (USB)
• Multi Media Cards (SD Cards, Compact Flash etc.)
• Networks: Ethernet, Controller Area Network, LonWorks, etc.
• Timers: PLL(s), Capture/Compare and Time Processing Units
• Discrete IO: aka General Purpose Input/Output (GPIO)
• Analog to Digital/Digital to Analog (ADC/DAC)

Tools

As for other software, embedded system designers use compilers, assemblers, and debuggers
to develop embedded system software. However, they may also use some more specific tools:

• In circuit debuggers or emulators.


• Utilities to add a checksum or CRC to a program, so the embedded system can check
if the program is valid.
• For systems using digital signal processing, developers may use a math workbench
such as Scilab / Scicos, MATLAB / Simulink, EICASLAB,
MathCadMathematica,orFlowStone DSP to simulate the mathematics. They might
also use libraries for both the host and target which eliminates developing DSP
routines as done in DSPnano RTOS and Unison Operating System.
• Custom compilers and linkers may be used to improve optimisation for the particular
hardware.
• An embedded system may have its own special language or design tool, or add
enhancements to an existing language such as Forth or Basic.
• Another alternative is to add a real-time operating system or embedded operating
system, which may have DSP capabilities like DSPnano RTOS.

Software tools can come from several sources:

• Software companies that specialize in the embedded market


• Ported from the GNU software development tools
• Sometimes, development tools for a personal computer can be used if the embedded
processor is a close relative to a common PC processor

As the complexity of embedded systems grows, higher level tools and operating systems are
migrating into machinery where it makes sense. For example, cellphones, personal digital
assistants and other consumer computers often need significant software that is purchased or
provided by a person other than the manufacturer of the electronics. In these systems, an open
programming environment such as Linux, NetBSD, OSGi or Embedded Java is required so
that the third-party software provider can sell to a large market.

Debugging

Embedded debugging may be performed at different levels, depending on the facilities


available. From simplest to most sophisticated they can be roughly grouped into the
following areas:

pg. 5
• Interactive resident debugging, using the simple shell provided by the embedded
operating system (e.g. Forth and Basic)
• External debugging using logging or serial port output to trace operation using either
a monitor in flash or using a debug server like the Remedy Debugger which even
works for heterogeneous multicore systems.
• An in-circuit debugger (ICD), a hardware device that connects to the microprocessor
via a JTAG or Nexus interface. This allows the operation of the microprocessor to be
controlled externally, but is typically restricted to specific debugging capabilities in
the processor.
• An in-circuit emulator replaces the microprocessor with a simulated equivalent,
providing full control over all aspects of the microprocessor.
• A complete emulator provides a simulation of all aspects of the hardware, allowing all
of it to be controlled and modified, and allowing debugging on a normal PC.

Unless restricted to external debugging, the programmer can typically load and run software
through the tools, view the code running in the processor, and start or stop its operation. The
view of the code may be as assembly code or source-code.

Because an embedded system is often composed of a wide variety of elements, the debugging
strategy may vary. For instance, debugging a software- (and microprocessor-) centric
embedded system is different from debugging an embedded system where most of the
processing is performed by peripherals (DSP, FPGA, co-processor). An increasing number of
embedded systems today use more than one single processor core. A common problem with
multi-core development is the proper synchronization of software execution. In such a case,
the embedded system design may wish to check the data traffic on the busses between the
processor cores, which requires very low-level debugging, at signal/bus level, with a logic
analyzer, for instance.

Reliability

Embedded systems often reside in machines that are expected to run continuously for years
without errors, and in some cases recover by themselves if an error occurs. Therefore the
software is usually developed and tested more carefully than that for personal computers, and
unreliable mechanical moving parts such as disk drives, switches or buttons are avoided.

Specific reliability issues may include:

1. The system cannot safely be shut down for repair, or it is too inaccessible to repair.
Examples include space systems, undersea cables, navigational beacons, bore-hole
systems, and automobiles.
2. The system must be kept running for safety reasons. "Limp modes" are less tolerable.
Often backups are selected by an operator. Examples include aircraft navigation,
reactor control systems, safety-critical chemical factory controls, train signals, engines
on single-engine aircraft.
3. The system will lose large amounts of money when shut down: Telephone switches,
factory controls, bridge and elevator controls, funds transfer and market making,
automated sales and service.

A variety of techniques are used, sometimes in combination, to recover from errors—both


software bugs such as memory leaks, and also soft errors in the hardware:

pg. 6
• watchdog timer that resets the computer unless the software periodically notifies the
watchdog
• subsystems with redundant spares that can be switched over to
• software "limp modes" that provide partial function
• Designing with a Trusted Computing Base (TCB) architecture ensures a highly secure
& reliable system environment
• An Embedded Hypervisor is able to provide secure encapsulation for any subsystem
component, so that a compromised software component cannot interfere with other
subsystems, or privileged-level system software. This encapsulation keeps faults from
propagating from one subsystem to another, improving reliability. This may also
allow a subsystem to be automatically shut down and restarted on fault detection.
• Immunity Aware Programming

High v/s low volume

For high volume systems such as portable music players or mobile phones, minimizing cost
is usually the primary design consideration. Engineers typically select hardware that is just
“good enough” to implement the necessary functions.

For low-volume or prototype embedded systems, general purpose computers may be adapted
by limiting the programs or by replacing the operating system with a real-time operating
system.

pg. 7
II
8051
MICROCONTROLLER

Intel 8051
Intel 8051 is CISC architecture which is easy to program in assembly language and also
has a good support for High level languages. The memory of the microcontroller can be
extended up to 64k. This microcontroller is one of the easiest microcontrollers to learn.
The 8051 microcontroller is in the field for more than 20 years. There are lots of books
and study materials readily available for 8051.

Derivatives
The best thing done by Intel is to give the designs of the 8051 microcontroller to
everyone. So it is not the fact that Intel is the only manufacture for the 8051 there more
than 20 manufactures, with each of minimum 20 models. Literally there are hundreds of
models of 8051 microcontroller available in market to choose. Some of the major
manufactures of 8051 are
�Atmel
�Philips
�Dallas

Philips
The Philips‘s 8051 derivatives has more number of features than in any microcontroller.
The costs of the Philips microcontrollers are higher than the Atmel’s which makes us to
choose Atmel more often than Philips

Dallas
Dallas has made many revolutions in the semiconductor market. Dallas’s 8051 derivative
is the fastest one in the market. It works 3 times as fast as a 8051 can process. But we are
unable to get more in India.

Atmel

These people were the one to master the flash devices. They are the cheapestmicrocontroller
available in the market. Atmel’s even introduced a 20pin variant of 8051named 2051. The
Atmel’s 8051 derivatives can be got in India less than 70 rupees. Thereare lots of cheap

pg. 8
programmers available in India for Atmel. So it is always good forstudents to stick with 8051
when you learn a new microcontroller.

Architecture of 8051

Architecture is must to learn because before learning new machine it is necessary to learn
the capabilities of the machine. This is some thing like before learning about the car you
cannot become a good driver. The architecture of the 8051 is given below.
The 8051 doesn’t have any special feature than other microcontroller. The only feature is
that it is easy to learn. Architecture makes us to know about the hardware features of the
microcontroller. The features of the 8051 are

�4K Bytes of Flash Memory


�128 x 8-Bit Internal RAM
�Fully Static Operation: 1 MHz to 24 MHz
�32 Programmable I/O Lines
�Two 16-Bit Timer/Counters
�Six Interrupt Sources (5 Vectored)
�Programmable Serial Channel
�Low Power Idle and Power Down Modes

The 8051 has a 8-Bit CPU that means it is able to process 8 bit of data at a time. 8051 has
235 instructions.

pg. 9
Some of the important registers and their functions are

Name Function
ACCUMULATOR All logical & arithmetical operations

Mainly used in Multiplication & Division


B

Keeps current status of ALU


Program Status Word (PSW)

Points the Stack


Stack Pointer (SP)

Program Counter (PC) Location of the next instruction

Every microprocessor & microcontroller uses clock signals. The clock signals are used to
synchronize CPU with other peripherals in the CPU. Clock signals are very much
important for a time critical jobs. If the oscillator used is not of good quality we will be
surely loosing lots of data in serial communication.
Let us see some basics of the 8051.

pg. 10
Pin diagram

Power supply

8051 can handle power supply of 3.5 volts to 7 volts with no problem. Always use a
Decoupling Capacitor between the Power supply and the Ground. Decoupling capacitors
are used to avoid the spikes. Pin 40 is for VCC and Pin 20 is for Gnd.

pg. 11
Reset Circuitry

As soon as you give the


power supply the 8051
doesn’t start. You need to
restart for the
microcontroller to start.
Restarting the
microcontroller is nothing but
giving a Logic 1 to
the reset pin at least for the 2
clock pulses. So it is good to
go for a small circuit which
can provide the 2 clock
pulses as soon as the
microcontroller is powered.
This is not a big circuit we
are just using a capacitor to
charge the microcontroller and
again discharging via resistor.

Crystals

Crystals provide the synchronization of the internal


function and to the peripherals.
Whenever ever we are using crystals we need to put the
capacitor behind it to make it
free from noises. It is good to go for a 33pf capacitor.
We can also resonators instead of costly crystal which
are low cost and external capacitor
can be avoided.
But the frequency of the resonators varies a lot. And it is
strictly not advised when used
for communications projects.
The 8051 operates based on an external crystal. This is
an electrical device which, when
energy is applied, emits pulses at a fixed frequency. One can find crystals of virtually any
frequency depending on the application requirements. When using an 8051, the most
common crystal frequencies are 12 megahertz and 11.059 megahertz--with 11.059 being
much more common. Why would anyone pick such an odd-ball frequency? There’s a real
reason for it--it has to do with generating baud rates and we’ll talk more about it in the
Serial Communication.For the remainder of this discussion we’ll assume that we’re using
an 11.059Mhz crystal.

pg. 12
Microcontrollers (and many other electrical systems) use crystals to syncrhronize
operations. The 8051 uses the crystal for precisely that: to synchronize it’s operation.
Effectively, the 8051 operates using what are called "machine cycles." A single machine
cycle is the minimum amount of time in which a single 8051 instruction can be executed.
although many instructions take multiple cycles.

A cycle is, in reality, 12 pulses of the crystal. That is to say, if an instruction takes one
machine cycle to execute, it will take 12 pulses of the crystal to execute. Since we know
the crystal is pulsing 11,059,000 times per second and that one machine cycle is 12
pulses, we can calculate how many instruction cycles the 8051 can execute per second:
11,059,000 / 12 = 921,583

This means that the 8051 can execute 921,583 single-cycle instructions per second. Since
a large number of 8051 instructions are single-cycle instructions it is often considered
that the 8051 can execute roughly 1 million instructions per second, although in reality it
is less--and, depending on the instructions being used, an estimate of about 600,000
instructions per second is more realistic.

For example, if you are using exclusively 2-cycle instructions you would find that the
8051 would execute 460,791 instructions per second. The 8051 also has two really slow
instructions that require a full 4 cycles to execute--if you were to execute nothing but
those instructions you’d find performance to be about 230,395 instructions per second.
It is again important to emphasize that not all instructions execute in the same amount of
time. The fastest instructions require one machine cycle (12 crystal pulses), many others
require two machine cycles (24 crystal pulses), and the two very slow math operations
require four machine cycles (48 crystal pulses).

NOTE: Many 8051 derivative chips change instruction timing. For example, many
optimized versions of the 8051 execute instructions in 4 oscillator cycles instead of 12;
such a chip would be effectively 3 times faster than the 8051 when used with the same
11.059 Mhz crystal.

Since all the instructions require different amounts of time to execute a very obvious
question comes to mind: How can one keep track of time in a time-critical application if
we have no reference to time in the outside world?

Luckily, the 8051 includes timers which allow us to time events with high precision--
which is the topic.

pg. 13
Memories in 8051
The 8051 has three very general types of memory. To effectively program the 8051 it is
necessary to have a basic understanding of these memory types.

The memory types are illustrated in the following graphic.


They are: On-Chip Memory,
External Code Memory, and External RAM.
On-Chip Memory refers to any memory (Code, RAM, or
other) that physically exists on
the microcontroller itself. On-chip memory can be of several
types, but we'll get into that
shortly.

External Code Memory is code (or program) memory that resides off-chip. This is often
in the form of an external EPROM.

External RAM is RAM memory that resides off-chip. This is often in the form of
standard static RAM or flash RAM.

Code memory
Code memory is the memory that holds the actual 8051 program that is to be run. This
memory is limited to 64K and comes in many shapes and sizes: Code memory may be
foundon-chip, either burned into the microcontroller as ROM or EPROM. Code may
also be stored completely off-chip in an external ROM or, more commonly, an external
EPROM. Flash RAM is also another popular method of storing a program. Various
combinations of these memory types may also be used--that is to say, it is possible to
have 4K of code memory on-chip and 64k of code memory off-chip in an EPROM.
When the program is stored on-chip the 64K maximum is often reduced to 4k, 8k, or 16k.
This varies depending on the version of the chip that is being used. Each version offers
specific capabilities and one of the distinguishing factors from chip to chip is how much
ROM/EPROM space the chip has.

However, code memory is most commonly implemented as off-chip EPROM. This is


especially true in low-cost development systems and in systems developed by students.

External RAM
As an obvious opposite of Internal RAM, the 8051 also supports what is called External
RAM.
As the name suggests, External RAM is any random access memory which is found offchip.
Since the memory is off-chip it is not as flexible in terms of accessing, and is also
slower. For example, to increment an Internal RAM location by 1 requires only 1
instruction and 1 instruction cycle. To increment a 1-byte value stored in External RAM
requires 4 instructions and 7 instruction cycles. In this case, external memory is 7 times
slower!

pg. 14
What External RAM loses in speed and flexibility it gains in quantity. While Internal
RAM is limited to 128 bytes (256 bytes with an 8052), the 8051 supports External RAM
up to 64K.

On-Chip Memory
The 8051 includes a certain amount of on-chip memory. On-chip memory is really one of
two types: Internal RAM and Special Function Register (SFR) memory. The layout of the
8051's internal memory is presented in the following memory map:
As is illustrated in this map, the 8051 has a bank of 128 bytes of Internal RAM. This
Internal RAM is found on-chip on the 8051 so it is the fastest RAM available, and it is
also the most flexible in terms of reading, writing, and modifying it’s contents. Internal
RAM is volatile, so when the 8051 is reset this memory is cleared.
The 128 bytes of internal ram is subdivided as shown on the memory map. The first 8
bytes (00h - 07h) are "register bank 0". By manipulating certain SFRs, a program may
choose to use register banks 1, 2, or 3. These alternative register banks are located in
internal RAM in addresses 08h through 1Fh.
Bit Memory also lives and is part of internal RAM. We'll talk more about bit memory
very shortly, but for now just keep in mind that bit memory actually resides in internal
RAM, from addresses 20h through 2Fh.
The 80 bytes remaining of Internal RAM, from addresses 30h through 7Fh, may be used
by user variables that need to be accessed frequently or at high-speed. This area is also
utilized by the microcontroller as a storage area for the operating stack. This fact severely
limits the 8051’s stack since, as illustrated in the memory map, the area reserved for the
stack is only 80 bytes--and usually it is less since this 80 bytes has to be shared between
the stack and user variables.

Register Banks
The 8051 uses 8 "R" registers which are used in many of its instructions. These "R"
registers are numbered from 0 through 7 (R0, R1, R2, R3, R4, R5, R6, and R7). These
registers are generally used to assist in manipulating values and moving data from one
memory location to another. For example, to add the value of R4 to the Accumulator, we
would execute the following instruction:

Bit Memory
The 8051, being a communications-oriented microcontroller, gives the user the ability to
access a numberof bit variables. These variables may be either 1 or 0.
There are 128 bit variables available to the user, numberd 00h through 7Fh. The user may
make use ofthese variables with commands such as SETB and CLR. For example, to set bit
number 24 (hex) to 1 youwould execute the instruction:
SETB 24h

It is important to note that Bit Memory is really a part of Internal RAM. In fact, the 128 bit
variables
occupy the 16 bytes of Internal RAM from 20h through 2Fh. Thus, if you write the value FFh
to Internal
RAM address 20h you’ve effectively set bits 00h through 07h. That is to say that:

Programming Tip: By default, the 8051 initializes the Stack Pointer (SP) to 07h when the

pg. 15
Microcontroller is booted. This means that the stack will start at address 08h and expand
upwards.
If you will be using the alternate register banks (banks 1, 2 or 3) you must initialize the stack
Pointer to an address above the highest register bank you will be using, otherwise the stack
will
Overwrite your alternate register banks. Similarly, if you will be using bit variables it is
usually a
Good idea to initialize the stack pointer to some value greater than 2Fh to guarantee that your
bit
Variables are protected from the stack.

Special Function Register (SFR) Memory


Special Function Registers (SFRs) are areas of memory that control specific functionality
Of the 8051 processor. For example, four SFRs permit access to the 8051’s 32
Input/output lines. Another SFR allows a program to read or write to the 8051’s serial
port. Other SFRs allow the user to set the serial baud rate, control and access timers, and
configure the 8051’s interrupt system.
When programming, SFRs have the illusion of being Internal Memory. For example, if
You want to write the value "1" to Internal RAM location 50 hex you would execute the
Instruction:

Other SFRs
All derivative microcontrollers of the 8051 must support these basic SFRs in order to
maintain compatibility with the underlying MSCS51 standard. A common practice when
semiconductor firms wish to develop a new 8051 derivative is to add additional SFRs to
support new functions that exist in the new chip.

For example, the Dallas Semiconductor DS80C320 is upwards compatible with the 8051.
This means that any program that runs on a standard 8051 should run without
modification on the DS80C320. This means that all the SFRs defined above also apply to
the Dallas component.

However, since the DS80C320 provides many new features that the standard 8051 does
not, there must be some way to control and configure these new features. This is
accomplished by adding additional SFRs to those listed here. For example, since the
DS80C320 supports two serial ports (as opposed to just one on the 8051), the SFRs
SBUF2 and SCON2 have been added. In addition to all the SFRs listed above, the
DS80C320 also recognizes these two new SFRs as valid and uses their values to
determine the mode of operation of the secondary serial port. Obviously, these new SFRs
have been assigned to SFR addresses that were unused in the original 8051. In this
manner, new 8051 derivative chips may be developed which will run existing 8051
programs.

pg. 16
Programming Tip: If you write a program that utilizes new SFRs that are specific to a given
derivative chip and not included in the above SFR list, your program will not run properly on
a standard 8051 where that SFR does not exist. Thus, only use non-standard SFRs if you are
sure that your program will only have to run on that specific microcontroller. Likewise, if you
write code that uses non-standard SFRs and subsequently share it with a third-party, be sure
to let that party know that your code is using non-standard SFRs to save them the headache of
realizing that due to strange behaviour at run-time.

pg. 17
TIMERS

The 8051 comes equipped with two timers, both of which may be controlled, set, read,
and configured individually. The 8051 timers have three general functions:

1) Keeping time and/or calculating the amount of time between events,


2) Counting the events themselves,
3) Generating baud rates for the serial port.

The three timer uses are distinct so we will talk about each of them separately. The first
two uses will be discussed now while the use of timers for baud rate generation will be
discussed with serial ports.

How does a timer count?


How does a timer count? The answer to this question is very simple: A timer always
counts up. It doesn’t matter whether the timer is being used as a timer, a counter, or a
baud rate generator: A timer is always incremented by the microcontroller.

USING TIMERS TO MEASURE TIME


Obviously, one of the primary uses of timers is to measure time. We will discuss this use
of timers first and will subsequently discuss the use of timers to count events. When a
timer is used to measure time it is also called an "interval timer" since it is measuring the
time of the interval between two events.

How long does a timer take to count?


When a timer is in interval timer mode (as opposed to event counter mode) and correctly
configured, it will increment by 1 every machine cycle. A single machine cycle consists
of 12 crystal pulses. Thus a running timer will be incremented:

11,059,000 / 12 = 921,583
921,583 times per second.

Unlike instructions--some of which require 1 machine cycle,


others 2, and others 4--the timers are consistent: They will always be incremented once
per machine cycle. Thus if a timer has counted from 0 to 50,000 you may calculate:

50,000 / 921,583 = .0542


.0542 seconds have passed.

In plain English, about half of a tenth of a second, or one twentieth of a second.


Obviously it’s not very useful to know .0542 seconds have passed. If you want to execute
an event once per second you’d have to wait for the timer to count from 0 to 50,000 18.45
times. How can you wait "half of a time?" You can’t. So we come to another important
calculation.

Let’s say we want to know how many times the timer will be incremented in .05 seconds.
We can do simple multiplication:

pg. 18
.05 * 921,583 = 46,079.15.

This tells us that it will take .05 seconds (1/20th of a second) to count from 0 to 46,079.
Actually, it will take it .049999837 seconds--so we’re off by .000000163 seconds--
however, that’s close enough. Consider that if you were building a watch based on the
8051 and made the above assumption your watch would only gain about one second
every 2 months. Again, I think that’s accurate enough for most applications--I wish my
watch only gained one second every two months!

Obviously, this is a little more useful. If you know it takes 1/20th of a second to count
from 0 to 46,079 and you want to execute some event every second you simply wait for
the timer to count from 0 to 46,079 twenty times; then you execute your event, reset the
timers, and wait for the timer to count up another 20 times. In this manner you will
effectively execute your event once per second, accurate to within thousandths of a
second.

Thus, we now have a system with which to measure time. All we need to review is how
to control the timers and initialize them to provide us with the information we need.

Timer SFRs
As mentioned before, the 8051 has two timers which each function essentially the same
way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs
(TMOD and TCON) which control the timers, and each timer also has two SFRs
dedicated solely to itself (TH0/TL0 and TH1/TL1).
We’ve given SFRs names to make it easier to refer to them, but in reality an SFR has a
numeric address. It is often useful to know the numeric address that corresponds to an
SFR name. The SFRs relating to timers are:
SFR Name Description SFR Address
TH0 Timer 0 High Byte 8Ch
TL0 Timer 0 Low Byte 8Ah
TH1 Timer 1 High Byte 8Dh
TL1 Timer 1 Low Byte 8Bh
TCON Timer Control 88h
TMOD Timer Mode 89h
When you enter the name of an SFR into an assembler, it internally converts it to a
number. For example, the command:
MOV TH0,#25h
moves the value 25h into the TH0 SFR. However, since TH0 is the same as SFR address
8Ch this command is equivalent to:
MOV 8Ch,#25h
Now, back to the timers. First, let’s talk about Timer 0.
Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0. Without making
things too complicated to start off with, you may just think of this as the high and low
byte of the timer. That is to say, when Timer 0 has a value of 0, both TH0 and TL0 will
contain 0. When Timer 0 has the value 1000, TH0 will hold the high byte of the value (3
decimal) and TL0 will contain the low byte of the value (232 decimal). Reviewing
low/high byte notation, recall that you must multiply the high byte by 256 and add the
low byte to calculate the final value. That is to say:
TH0 * 256 + TL0 = 1000
3 * 256 + 232 = 1000

pg. 19
Timer 1 works the exact same way, but it’s SFRs are TH1 and TL1.
Since there are only two bytes devoted to the value of each timer it is apparent that the
maximum value a timer may have is 65,535. If a timer contains the value 65,535 and is
subsequently incremented, it will reset--or overflow--back to 0.

The TMOD SFR

Let’s first talk about our first control SFR: TMOD (Timer Mode). The TMOD SFR is
used to control the mode of operation of both timers. Each bit of the SFR gives the
microcontroller specific information concerning how to run a timer. The high four bits
(bits 4 through 7) relate to Timer 1 whereas the low four bits (bits 0 through 3) perform
the exact same functions, but for timer 0.
The individual bits of TMOD have the following functions:
TMOD (89h) SFR

TxM1 TxM0
Timer Mode Description of Mode
00 ----------- 0 13-bit Timer.
0 1 -----------1 16-bit Timer
1 0 ----------- 2 8-bit auto-reload
1 1 -----------3 Split timer mode

13-bit Time Mode (mode 0)


Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to
maintain compatibility with it’s predecessor, the 8048. Generally the 13-bit timer mode is
not used in new development.
When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is incremented
from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two
timer bytes are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in
essence, the timer can only contain 8192 values. If you set a 13-bit timer to 0, it will
overflow back to zero 8192 machine cycles later.
Again, there is very little reason to use this mode and it is only mentioned so you won’t
be surprised if you ever end up analysing archaic code which has been passed down
through the generations .

16-bit Time Mode (mode 1)

Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions just
like 13-bit mode except that all 16 bits are used.
TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and
causesTHx to be incremented by 1. Since this is a full 16-bit timer, the timer may
contain up to 65536 distinct values. If you set a 16-bit timer to 0, it will overflow back to
0 after 65,536 machine cycles.

8-bit Time Mode (mode 2)

Timer mode "2" is an 8-bit auto-reload mode. What is that, you may ask? Simple. When
a timer is in mode 2, THx holds the "reload value" and TLx is the timer itself. Thus, TLx

pg. 20
starts counting up. When TLx reaches 255 and is subsequently incremented, instead of
resetting to 0 (as in the case of modes 0 and 1), it will be reset to the value stored in THx.
For example, let’s say TH0 holds the value FDh and TL0 holds the value FEh. If we were
to watch the values of TH0 and TL0 for a few machine cycles this is what we’d see:
Machine Cycle TH0 Value TL0 Value
1 FDhFEh
2 FDhFFh
3 FDhFDh
4 FDhFEh
5 FDhFFh
6 FDhFDh
7 FDhFEh

As you can see, the value of TH0 never changed. In fact, when you use mode 2 you
almost always set THx to a known value and TLx is the SFR that is constantly
incremented.
What’s the benefit of auto-reload mode? Perhaps you want the timer to always have a
value from 200 to 255. If you use mode 0 or 1, you’d have to check in code to see if the
timer had overflowed and, if so, reset the timer to 200. This takes precious instructions of
execution time to check the value and/or to reload it. When you use mode 2 the
microcontroller takes care of this for you. Once you’ve configured a timer in mode 2 you
don’t have to worry about checking to see if the timer has overflowed nor do you have to
worry about resetting the value--the microcontroller hardware will do it all for you.
The auto-reload mode is very commonly used for establishing a baud rate which we will
talk more about in the Serial Communications.

Split Timer Mode (mode 3)

Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially
becomes two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0.
Both timers count from 0 to 255 and overflow back to 0. All the bits that are related to
Timer 1 will now be tied to TH0.
While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into
modes 0, 1 or 2 normally--however, you may not start or stop the real timer 1 since the
bits that do that are now linked to TH0. The real timer 1, in this case, will be incremented
every machine cycle no matter what.
The only real use I can see of using split timer mode is if you need to have two separate
timers and, additionally, a baud rate generator. In such case you can use the real Timer 1
as a baud rate generator and use TH0/TL0 as two separate timers.

The TCON SFR

Finally, there’s one more SFR that controls the two timers and provides valuable
information about them. The TCON SFR has the following structure:
TCON (88h) SFR
Bit Name Bit
Address Explanation of Function Timer
7 TF1 8Fh Timer 1 Overflow. This bit is set by the microcontroller when
Timer 1 overflows. 1
6 TR1 8Eh Timer 1 Run. When this bit is set Timer 1 is turned on. When this
bit is clear Timer 1 is off. 1
5 TF0 8Dh Timer 0 Overflow. This bit is set by the microcontroller when

pg. 21
Timer 0 overflows. 0
4 TR0 8Ch Timer 0 Run. When this bit is set Timer 0 is turned on. When this
bit is clear Timer 0 is off. 0
As you may notice, we’ve only defined 4 of the 8 bits. That’s because the other 4 bits of
the SFR don’t have anything to do with timers--they have to do with Interrupts and they
will be discussed with interrupts.
A new piece of information in this chart is the column "bit address." This is because this
SFR is "bit-addressable." What does this mean? It means if you want to set the bit TF1--
which is the highest bit of TCON--you could execute the command:
MOV TCON, #80h
... or, since the SFR is bit-addressable, you could just execute the command:
SETB TF1
This has the benefit of setting the high bit of TCON without changing the value of any of
the other bits of the SFR. Usually when you start or stop a timer you don’t want to
modify the other values in TCON, so you take advantage of the fact that the SFR is
bitaddressable.

Initializing a Timer
Now we are ready to write code that will initialize the timer and start it running.
As you’ll recall, we first must decide what mode we want the timer to be in. In this case
we want a 16-bit timer that runs continuously; that is to say, it is not dependent on any
external pins.
We must first initialize the TMOD SFR. Since we are working with timer 0 we will be
using the lowest 4 bits of TMOD. The first two bits, GATE0 and C/T0 are both 0 since
we want the timer to be independent of the external pins. 16-bit mode is timer mode 1 so
we must clear T0M1 and set T0M0. Effectively, the only bit we want to turn on is bit 0 of
TMOD. Thus to initialize the timer we execute the instruction:
MOV TMOD,#01h
Timer 0 is now in 16-bit timer mode. However, the timer is not running. To start the
timer running we must set the TR0 bit We can do that by executing the instruction:
SETB TR0
Upon executing these two instructions timer 0 will immediately begin counting, being
incremented once every machine cycle (every 12 crystal pulses).

Reading the Timer


There are two common ways of reading the value of a 16-bit timer; which you use
depends on your specific application. You may either read the actual value of the timer as
a 16-bit number, or you may simply detect when the timer has overflowed.

Reading the value of a Timer


If your timer is in an 8-bit mode--that is, either 8-bit AutoReload mode or in split timer
mode--then reading the value of the timer is simple. You simply read the 1-byte value of
the timer and you’re done.
However, if you’re dealing with a 13-bit or 16-bit timer the chore is a little more
complicated. Consider what would happen if you read the low byte of the timer as 255,
then read the high byte of the timer as 15. In this case, what actually happened was that
the timer value was 14/255 (high byte 14, low byte 255) but you read 15/255. Why?
Because you read the low byte as 255. But when you executed the next instruction a
small amount of time passed--but enough for the timer to increment again at which time
the value rolled over from 14/255 to 15/0. But in the process you’ve read the timer as
being 15/255. Obviously there’s a problem there.
pg. 22
The solution? It’s not too tricky, really. You read the high byte of the timer, then read the
low byte, then read the high byte again. If the high byte read the second time is not the
same as the high byte read the first time you repeat the cycle. In code, this would appear
as:
REPEAT: MOV A,TH0
MOV R0,TL0
CJNE A,TH0,REPEAT
...
In this case, we load the accumulator with the high byte of Timer 0. We then load R0
with the low byte of Timer 0. Finally, we check to see if the high byte we read out of
Timer 0--which is now stored in the Accumulator--is the same as the current Timer 0
high byte. If it isn’t it means we’ve just "rolled over" and must reread the timer’s value--
which we do by going back to REPEAT. When the loop exits we will have the low byte
of the timer in R0 and the high byte in the Accumulator.
Another much simpler alternative is to simply turn off the timer run bit (i.e. CLR TR0),
read the timer value, and then turn on the timer run bit (i.e. SETB TR0). In that case, the
timer isn’t running so no special tricks are necessary. Of course, this implies that your
timer will be stopped for a few machine cycles. Whether or not this is tolerable depends
on your specific application.

Detecting Timer Overflow


Often it is necessary to just know that the timer has reset to 0. That is to say, you are not
particularly interest in the value of the timer but rather you are interested in knowing
when the timer has overflowed back to 0.
Whenever a timer overflows from it’s highest value back to 0, the microcontroller
automatically sets the TFx bit in the TCON register. This is useful since rather than
checking the exact value of the timer you can just check if the TFx bit is set. If TF0 is set
it means that timer 0 has overflowed; if TF1 is set it means that timer 1 has overflowed.
We can use this approach to cause the program to execute a fixed delay. As you’ll recall,
we calculated earlier that it takes the 8051 1/20th of a second to count from 0 to 46,079.
However, the TFx flag is set when the timer overflows back to 0. Thus, if we want to use
theTFx flag to indicate when 1/20th of a second has passed we must set the timer
initially to 65536 less 46079, or 19,457. If we set the timer to 19,457, 1/20th of a second
later the timer will overflow. Thus we come up with the following code to execute a
pause of 1/20th of a second:

MOV TH0,#76;High byte of 19,457 (76 * 256 = 19,456)


MOV TL0,#01;Low byte of 19,457 (19,456 + 1 = 19,457)
MOV TMOD,#01;Put Timer 0 in 16-bit mode
SETB TR0;Make Timer 0 start counting
JNB TF0,$;If TF0 is not set, jump back to this same instruction

In the above code the first two lines initialize the Timer 0 starting value to 19,457. The
next two instructions configure timer 0 and turn it on. Finally, the last instruction JNB
TF0,$, reads "Jump, if TF0 is not set, back to this same instruction." The "$" operand
means, in most assemblers, the address of the current instruction. Thus as long as the
timer has not overflowed and the TF0 bit has not been set the program will keep
executing this same instruction. After 1/20th of a second timer 0 will overflow, set the
TF0 bit, and program execution will then break out of the loop.

pg. 23
Timing the length of events
The 8051 provides another cool toy that can be used to time the length of events.
For example, let's say we're trying to save electricity in the office and we're interested in
how long a light is turned on each day. When the light is turned on, we want to measure
time. When the light is turned off we don't. One option would be to connect the
lightswitch to one of the pins, constantly read the pin, and turn the timer on or off based
on the state of that pin. While this would work fine, the 8051 provides us with an easier
method of accomplishing this.
Looking again at the TMOD SFR, there is a bit called GATE0. So far we've always
cleared this bit because we wanted the timer to run regardless of the state of the external
pins. However, now it would be nice if an external pin could control whether the timer
was running or not. It can. All we need to do is connect the lightswitch to pin INT0
(P3.2) on the 8051 and set the bit GATE0. When GATE0 is set Timer 0 will only run if
P3.2 is high. When P3.2 is low (i.e., the lightswitch is off) the timer will automatically be
stopped.
Thus, with no control code whatsoever, the external pin P3.2 can control whether or not
our timer is running or not.

USING TIMERS AS EVENT COUNTERS


We've discussed how a timer can be used for the obvious purpose of keeping track of
time. However, the 8051 also allows us to use the timers to count events.
How can this be useful? Let's say you had a sensor placed across a road that would send a
pulse every time a car passed over it. This could be used to determine the volume of
traffic on the road. We could attach this sensor to one of the 8051's I/O lines and
constantly monitor it, detecting when it pulsed high and then incrementing our counter
when it went back to a low state. This is not terribly difficult, but requires some code.
Let's say we hooked the sensor to P1.0; the code to count cars passing would look
something like this:
JNB P1.0,$ ;If a car hasn't raised the signal, keep waiting
JB P1.0,$ ;The line is high which means the car is on the sensor right now
INC COUNTER ;The car has passed completely, so we count it

As you can see, it's only three lines of code. But what if you need to be doing other
processing at the same time? You can't be stuck in the JNB P1.0,$ loop waiting for a car
to pass if you need to be doing other things. Of course, there are ways to get around even
this limitation but the code quickly becomes big, complex, and ugly.
Luckily, since the 8051 provides us with a way to use the timers to count events we don't
have to bother with it. It is actually painfully easy. We only have to configure one
additional bit.
Let's say we want to use Timer 0 to count the number of cars that pass. If you look back
to the bit table for the TCON SFR you will there is a bit called "C/T0"--it's bit 2
(TCON.2). Reviewing the explanation of the bit we see that if the bit is clear then timer 0
will be incremented every machine cycle. This is what we've already used to measure
time. However, if we set C/T0 timer 0 will monitor the P3.4 line. Instead of being
incremented every machine cycle, timer 0 will count events on the P3.4 line. So in our
case we simply connect our sensor to P3.4 and let the 8051 do the work. Then, when we
want to know how many cars have passed, we just read the value of timer 0--the value of
timer 0 will be the number of cars that have passed.
So what exactly is an event? What does timer 0 actually "count?" Speaking at the
electrical level, the 8051 counts 1-0 transitions on the P3.4 line. This means that when a

pg. 24
car first runs over our sensor it will raise the input to a high ("1") condition. At that point
the 8051 will not count anything since this is a 0-1 transition. However, when the car has
passed the sensor will fall back to a low ("0") state. This is a 1-0 transition and at that
instant the counter will be incremented by 1.
It is important to note that the 8051 checks the P3.4 line each instruction cycle (12 clock
cycles). This means that if P3.4 is low, goes high, and goes back low in 6 clock cycles it
will probably not be detected by the 8051. This also means the 8051 event counter is only
capable of counting events that occur at a maximum of 1/24th the rate of the crystal
frequency. That is to say, if the crystal frequency is 12.000 Mhz it can count a maximum
of 500,000 events per second (12.000 Mhz * 1/24 = 500,000). If the event being counted
occurs more than 500,000 times per second it will not be able to be accurately counted by
the 8051.

pg. 25
SERIAL COMMUNICATION
One of the 8051’s many powerful features is it’s integrated UART, otherwise known as a
serial port. The fact that the 8051 has an integrated serial port means that you may very
easily read and write values to the serial port. If it were not for the integrated serial port,
writing a byte to a serial line would be a rather tedious process requring turning on and
off one of the I/O lines in rapid succession to properly "clock out" each individual bit,
including start bits, stop bits, and parity bits.

However, we do not have to do this. Instead, we simply need to configure the serial port’s
operation mode and baud rate. Once configured, all we have to do is write to an SFR to
write a value to the serial port or read the same SFR to read a value from the serial port.
The 8051 will automatically let us know when it has finished sending the character we
wrote and will also let us know whenever it has received a byte so that we can process it.
We do not have to worry about transmission at the bit level--which saves us quite a bit of
coding and processing time.

Setting the Serial Port Mode


The first thing we must do when using the 8051’s integrated serial port is, obviously,
configure it. This lets us tell the 8051 how many data bits we want, the baud rate we will
be using, and how the baud rate will be determined.
First, let’s present the "Serial Control" (SCON) SFR and define what each bit of the SFR
represents:
Bit Name Bit Addres Explanation of Function
7 SM0 9Fh Serial port mode bit 0
6 SM1 9Eh Serial port mode bit 1.
5 SM2 9Dh Mutliprocessor Communications Enable (explained later)
4 REN 9Ch Receiver Enable. This bit must be set in order to receive characters.
3 TB8 9Bh Transmit bit 8. The 9th bit to transmit in mode 2 and 3.
2 RB8 9Ah Receive bit 8. The 9th bit received in mode 2 and 3.
1 TI 99h Transmit Flag. Set when a byte has been completely transmitted.
0 RI 98h Receive Flag. Set when a byte has been completely received.
Additionally, it is necessary to define the function of SM0 and SM1 by an additional
table:
SM0 SM1 Serial Mode Explanation Baud Rate
0 0 0 8-bit Shift Register Oscillator / 12
0 1 1 8-bit UART Set by Timer 1 (*)
1 0 2 9-bit UART Oscillator / 32 (*)
1 1 3 9-bit UART Set by Timer 1 (*)
(*) Note: The baud rate indicated in this table is doubled if PCON.7 (SMOD) is set.
The SCON SFR allows us to configure the Serial Port. Thus, we’ll go through each bit
and review it’s function.

The first four bits (bits 4 through 7) are configuration bits.

Bits SM0 and SM1 let us set the serial mode to a value between 0 and 3, inclusive. The
four modes are defined in the chart immediately above. As you can see, selecting the

pg. 26
Serial Mode selects the mode of operation (8-bit/9-bit, UART or Shift Register) and also
determines how the baud rate will be calculated. In modes 0 and 2 the baud rate is fixed
based on the oscillator’s frequency. In modes 1 and 3 the baud rate is variable based on
how often Timer 1 overflows. We’ll talk more about the various Serial Modes in a
moment.

The next bit, SM2, is a flag for "Multiprocessor communication." Generally, whenever a
byte has been received the 8051 will set the "RI" (Receive Interrupt) flag. This lets the
program know that a byte has been received and that it needs to be processed. However,
when SM2 is set the "RI" flag will only be triggered if the 9th bit received was a "1".
That is to say, if SM2 is set and a byte is received whose 9th bit is clear, the RI flag will
never be set. This can be useful in certain advanced serial applications. For now it is safe
to say that you will almost always want to clear this bit so that the flag is set upon
reception of any character.

The next bit, REN, is "Receiver Enable." This bit is very straightforward: If you want to
receive data via the serial port, set this bit. You will almost always want to set this bit.
The last four bits (bits 0 through 3) are operational bits. They are used when actually
sending and receiving data--they are not used to configure the serial port.

The TB8 bit is used in modes 2 and 3. In modes 2 and 3, a total of nine data bits are
transmitted. The first 8 data bits are the 8 bits of the main value, and the ninth bit is taken
from TB8. If TB8 is set and a value is written to the serial port, the data’s bits will be
written to the serial line followed by a "set" ninth bit. If TB8 is clear the ninth bit will be
"clear."

The RB8 also operates in modes 2 and 3 and functions essentially the same way as TB8,
but on the reception side. When a byte is received in modes 2 or 3, a total of nine bits are
received. In this case, the first eight bits received are the data of the serial byte received
and the value of the ninth bit received will be placed in RB8.

TI means "Transmit Interrupt." When a program writes a value to the serial port, a certain
amount of time will pass before the individual bits of the byte are "clocked out" the serial
port. If the program were to write another byte to the serial port before the first byte was
completely output, the data being sent would be garbled. Thus, the 8051 lets the program
know that it has "clocked out" the last byte by setting the TI bit. When the TI bit is set,
the program may assume that the serial port is "free" and ready to send the next byte.

Finally, the RI bit means "Receive Interrupt." It funcions similarly to the "TI" bit, but it
indicates that a byte has been received. That is to say, whenever the 8051 has received a
complete byte it will trigger the RI bit to let the program know that it needs to read the
value quickly, before another byte is read.

pg. 27
Setting the Serial Port Baud Rate
Once the Serial Port Mode has been configured, as explained above, the program must
configure the serial port’s baud rate. This only applies to Serial Port modes 1 and 3. The
Baud Rate is determined based on the oscillator’s frequency when in mode 0 and 2. In
mode 0, the baud rate is always the oscillator frequency divided by 12. This means if
you’re crystal is 11.059Mhz, mode 0 baud rate will always be 921,583 baud. In mode 2
the baud rate is always the oscillator frequency divided by 64, so a 11.059Mhz crystal
speed will yield a baud rate of 172,797.
In modes 1 and 3, the baud rate is determined by how frequently timer 1 overflows. The
more frequently timer 1 overflows, the higher the baud rate. There are many ways one
can cause timer 1 to overflow at a rate that determines a baud rate, but the most common
method is to put timer 1 in 8-bit auto-reload mode (timer mode 2) and set a reload value
(TH1) that causes Timer 1 to overflow at a frequency appropriate to generate a baud rate.
To determine the value that must be placed in TH1 to generate a given baud rate, we may
use the following equation (assuming PCON.7 is clear).
TH1 = 256 - ((Crystal / 384) / Baud)

If PCON.7 is set then the baud rate is effectively doubled, thus the equation becomes:
TH1 = 256 - ((Crystal / 192) / Baud)

For example, if we have an 11.059Mhz crystal and we want to configure the serial port to
19,200 baud we try plugging it in the first equation:

TH1 = 256 - ((Crystal / 384) / Baud)


TH1 = 256 - ((11059000 / 384) / 19200 )
TH1 = 256 - ((28,799) / 19200)
TH1 = 256 - 1.5 = 254.5

As you can see, to obtain 19,200 baud on a 11.059Mhz crystal we’d have to set TH1 to
254.5. If we set it to 254 we will have achieved 14,400 baud and if we set it to 255 we
will have achieved 28,800 baud. Thus we’re stuck...
But not quite... to achieve 19,200 baud we simply need to set PCON.7 (SMOD). When
we do this we double the baud rate and utilize the second equation mentioned above.
Thus we have:

TH1 = 256 - ((Crystal / 192) / Baud)


TH1 = 256 - ((11059000 / 192) / 19200)
TH1 = 256 - ((57699) / 19200)
TH1 = 256 - 3 = 253

Here we are able to calculate a nice, even TH1 value. Therefore, to obtain 19,200 baud
with an 11.059MHz crystal we must:
1. Configure Serial Port mode 1 or 3.
2. Configure Timer 1 to timer mode 2 (8-bit auto-reload).
3. Set TH1 to 253 to reflect the correct frequency for 19,200 baud.
4. Set PCON.7 (SMOD) to double the baud rate.

Writing to the Serial Port

pg. 28
Once the Serial Port has been propertly configured as explained above, the serial port is
ready to be used to send data and receive data. If you thought that configuring the serial
port was simple, using the serial port will be a breeze.
To write a byte to the serial port one must simply write the value to the SBUF (99h) SFR.
For example, if you wanted to send the letter "A" to the serial port, it could be
accomplished as easily as:
MOV SBUF,#’A’
Upon execution of the above instruction the 8051 will begin transmitting the character
via the serial port. Obviously transmission is not instantaneous--it takes a measureable
amount of time to transmit. And since the 8051 does not have a serial output buffer we
need to be sure that a character is completely transmitted before we try to transmit the
next character.
The 8051 lets us know when it is done transmitting a character by setting the TI bit in
SCON. When this bit is set we know that the last character has been transmitted and that
we may send the next character, if any. Consider the following code segment:

CLR TI ;Be sure the bit is initially clear


MOV SBUF,#’A’ ;Send the letter ‘A’ to the serial port
JNB TI,$;Pause until the TI bit is set.

The above three instructions will successfully transmit a character and wait for the TI bit
to be set before continuing. The last instruction says "Jump if the TI bit is not set to $"--$,
in most assemblers, means "the same address of the current instruction." Thus the 8051
will pause on the JNB instruction until the TI bit is set by the 8051 upon successful
transmission of the character.

Reading the Serial Port


Reading data received by the serial port is equally easy. To read a byte from the serial
port one just needs to read the value stored in the SBUF (99h) SFR after the 8051 has
automatically set the RI flag in SCON.
For example, if your program wants to wait for a character to be received and
subsequently read it into the Accumulator, the following code segment may be used:

JNB RI,$;Wait for the 8051 to set the RI flag


MOV A,SBUF;Read the character from the serial port

The first line of the above code segment waits for the 8051 to set the RI flag; again, the
8051 sets the RI flag automatically when it receives a character via the serial port. So as
long as the bit is not set the program repeats the "JNB" instruction continuously.
Once the RI bit is set upon character reception the above condition automatically fails
and program flow falls through to the "MOV" instruction which reads the value.

pg. 29
INTERRUPTS
As the name implies, an interrupt is some event which interrupts normal program
execution. Program flow is always sequential, being altered only by those instructions which
expressly cause program flow to deviate in some way. However, interrupts give us a
mechanism to "put on hold" the normal program flow, execute a subroutine, and then
resume normal program flow as if we had never left it. This subroutine, called an
interrupt handler, is only executed when a certain event (interrupt) occurs. The event may
be one of the timers "overflowing," receiving a character via the serial port, transmitting a
character via the serial port, or one of two "external events." The 8051 may be configured
so that when any of these events occur the main program is temporarily suspended and
control passed to a special section of code which presumably would execute some
function related to the event that occured. Once complete, control would be returned to
the original program. The main program never even knows it was interrupted.
The ability to interrupt normal program execution when certain events occur makes it
much easier and much more efficient to handle certain conditions. If it were not for
interrupts we would have to manually check in our main program whether the timers had
overflown, whether we had received another character via the serial port, or if some
external event had occured. Besides making the main program ugly and hard to read,
such a situation would make our program inefficient since we’d be burning precious
"instruction cycles" checking for events that usually don’t happen.
For example, let’s say we have a large 16k program executing many subroutines
performing many tasks. Let’s also suppose that we want our program to automatically
toggle the P3.0 port every time timer 0 overflows. The code to do this isn’t too difficult:
JNB TF0,SKIP_TOGGLE
CPL P3.0
CLR TF0
SKIP_TOGGLE: ...

Since the TF0 flag is set whenever timer 0 overflows, the above code will toggle P3.0
every time timer 0 overflows. This accomplishes what we want, but is inefficient. The
JNB instruction consumes 2 instruction cycles to determine that the flag is not set and
jump over the unnecessary code. In the event that timer 0 overflows, the CPL and CLR
instruction require 2 instruction cycles to execute. To make the math easy, let’s say the
rest of the code in the program requires 98 instruction cycles. Thus, in total, our code
consumes 100 instruction cycles (98 instruction cycles plus the 2 that are executed every
iteration to determine whether or not timer 0 has overflowed). If we’re in 16-bit timer
mode, timer 0 will overflow every 65,536 machine cycles. In that time we would have
performed 655 JNB tests for a total of 1310 instruction cycles, plus another 2 instruction
cycles to perform the code. So to achieve our goal we’ve spent 1312 instruction cycles.
So 2.002% of our time is being spent just checking when to toggle P3.0. And our code is
ugly because we have to make that check every iteration of our main program loop.
Luckily, this isn’t necessary. Interrupts let us forget about checking for the condition. The
microcontroller itself will check for the condition automatically and when the condition is
met will jump to a subroutine (called an interrupt handler), execute the code, then return.
In this case, our subroutine would be nothing more than:
CPL P3.0

pg. 30
RETI

First, you’ll notice the CLR TF0 command has disappeared. That’s because when the
8051 executes our "timer 0 interrupt routine," it automatically clears the TF0 flag. You’ll
also notice that instead of a normal RET instruction we have a RETI instruction. The
RETI instruction does the same thing as a RET instruction, but tells the 8051 that an
interrupt routine has finished. You must always end your interrupt handlers with RETI.
Thus, every 65536 instruction cycles we execute the CPL instruction and the RETI
instruction. Those two instructions together require 3 instruction cycles, and we’ve
accomplished the same goal as the first example that required 1312 instruction cycles. As
far as the toggling of P3.0 goes, our code is 437 times more efficient! Not to mention it’s
much easier to read and understand because we don’t have to remember to always check
for the timer 0 flag in our main program. We just setup the interrupt and forget about it,
secure in the knowledge that the 8051 will execute our code whenever it’s necessary.
The same idea applies to receiving data via the serial port. One way to do it is to
continuously check the status of the RI flag in an endless loop. Or we could check the RI
flag as part of a larger program loop. However, in the latter case we run the risk of
missingcharacters--what happens if a character is received right after we do the check,
the rest of our program executes, and before we even check RI a second character has
come in. We will lose the first character. With interrupts, the 8051 will put the main
program "on hold" and call our special routine to handle the reception of a character.
Thus, we neither have to put an ugly check in our main code nor will we lose characters.

What Events Can Trigger Interrupts, and where do they go?


We can configure the 8051 so that any of the following events will cause an interrupt:
• Timer 0 Overflow.
• Timer 1 Overflow.
• Reception/Transmission of Serial Character.
• External Event 0.
• External Event 1.
In other words, we can configure the 8051 so that when Timer 0 Overflows or when a
character is sent/received, the appropriate interrupt handler routines are called.
Obviously we need to be able to distinguish between various interrupts and executing
different code depending on what interrupt was triggered. This is accomplished by
jumping to a fixed address when a given interrupt occurs.
Interrupt Flag Interrupt Handler Address
External 0 IE0 0003h
Timer 0 TF0 000Bh
External 1 IE1 0013h
Timer 1 TF1 001Bh
Serial RI/TI 0023h
By consulting the above chart we see that whenever Timer 0 overflows (i.e., the TF0 bit
is set), the main program will be temporarily suspended and control will jump to 000BH.
It is assumed that we have code at address 000BH that handles the situation of Timer 0
overflowing.

Setting Up Interrupts
By default at powerup, all interrupts are disabled. This means that even if, for example,
the TF0 bit is set, the 8051 will not execute the interrupt. Your program must specifically
tell the 8051 that it wishes to enable interrupts and specifically which interrupts it wishes

pg. 31
to enable.
Your program may enable and disable interrupts by modifying the IE SFR (A8h):
Bit Name Bit Address Explanation of Function
7 EA AFh Global Interrupt Enable/Disable
6 - AEh Undefined
5 - ADh Undefined
4 ES Ach Enable Serial Interrupt
3 ET1 ABh Enable Timer 1 Interrupt
2 EX1 AAh Enable External 1 Interrupt
1 ET0 A9h Enable Timer 0 Interrupt
0 EX0 A8h Enable External 0 Interrupt
As you can see, each of the 8051’s interrupts has its own bit in the IE SFR. You enable a
given interrupt by setting the corresponding bit. For example, if you wish to enable Timer
1 Interrupt, you would execute either:

MOV IE,#08h or SETB ET1


Both of the above instructions set bit 3 of IE, thus enabling Timer 1 Interrupt. Once
Timer 1 Interrupt is enabled, whenever the TF1 bit is set, the 8051 will automatically put
"on hold" the main program and execute the Timer 1 Interrupt Handler at address 001Bh.
However, before Timer 1 Interrupt (or any other interrupt) is truly enabled, you must also
set bit 7 of IE. Bit 7, the Global Interupt Enable/Disable, enables or disables all interrupts
simultaneously. That is to say, if bit 7 is cleared then no interrupts will occur, even if all
the other bits of IE are set. Setting bit 7 will enable all the interrupts that have been
selected by setting other bits in IE. This is useful in program execution if you have
timecritical code that needs to execute. In this case, you may need the code to execute from
start to finish without any interrupt getting in the way. To accomplish this you can simply
clear bit 7 of IE (CLR EA) and then set it after your time-criticial code is done.
So, to sum up what has been stated in this section, to enable the Timer 1 Interrupt the
most common approach is to execute the following two instructions:

SETB ET1
SETB EA

Thereafter, the Timer 1 Interrupt Handler at 01Bh will automatically be called whenever
the TF1 bit is set (upon Timer 1 overflow).

Polling Sequence
The 8051 automatically evaluates whether an interrupt should occur after every instruction. When checking
for interrupt conditions, it checks them in the following order:
• External 0 Interrupt
• Timer 0 Interrupt
• External 1 Interrupt
• Timer 1 Interrupt
• Serial Interrupt
This means that if a Serial Interrupt occurs at the exact same instant that an External 0 Interrupt occurs, the
External 0 Interrupt will be executed first and the Serial Interrupt will be executed once the External 0
Interrupt has completed.

Interrupt Priorities
The 8051 offers two levels of interrupt priority: high and low. By using interrupt
priorities you may assign higher priority to certain interrupt conditions.
For example, you may have enabled Timer 1 Interrupt which is automatically called
every time Timer 1 overflows. Additionally, you may have enabled the Serial Interrupt

pg. 32
which is called every time a character is received via the serial port. However, you may
consider that receiving a character is much more important than the timer interrupt. In
this case, if Timer 1 Interrupt is already executing you may wish that the serial interrupt
itself interrupts the Timer 1 Interrupt. When the serial interrupt is complete, control
passes back to Timer 1 Interrupt and finally back to the main program. You may
accomplish this by assigning a high priority to the Serial Interrupt and a low priority to
the Timer 1 Interrupt.
Interrupt priorities are controlled by the IP SFR (B8h). The IP SFR has the following
format:
Bit Name Bit Address Explanation of Function
7 - - Undefined
6 - - Undefined
5 - - Undefined
4 PS BCh Serial Interrupt Priority
3 PT1 BBhTimer 1 Interrupt Priority
2 PX1 Bah External 1 Interrupt Priority
1 PT0 B9h Timer 0 Interrupt Priority
0 PX0 B8h External 0 Interrupt Priority
When considering interrupt priorities, the following rules apply:
• Nothing can interrupt a high-priority interrupt--not even another high priority
interrupt.
• A high-priority interrupt may interrupt a low-priority interrupt.
• A low-priority interrupt may only occur if no other interrupt is already executing.
• If two interrupts occur at the same time, the interrupt with higher priority will
execute first. If both interrupts are of the same priority the interrupt which is
serviced first by polling sequence will be executed first.

What Happens When an Interrupt Occurs?


When an interrupt is triggered, the following actions are taken automatically by the
microcontroller:
• The current Program Counter is saved on the stack, low-byte first.
• Interrupts of the same and lower priority are blocked.
• In the case of Timer and External interrupts, the corresponding interrupt flag is
cleared.
• Program execution transfers to the corresponding interrupt handler vector address.
• The Interrupt Handler Routine executes.
Take special note of the third step: If the interrupt being handled is a Timer or External
interrupt, the microcontroller automatically clears the interrupt flag before passing
control to your interrupt handler routine. This means it is not necessary that you clear the
bit in your code.

What Happens When an Interrupt Ends?


An interrupt ends when your program executes the RETI (Return from Interrupt)
instruction. When the RETI instruction is executed the following actions are taken by the
microcontroller:
• Two bytes are popped off the stack into the Program Counter to restore normal
program execution.
• Interrupt status is restored to its pre-interrupt status.

Serial Interrupts
Serial Interrupts are slightly different than the rest of the interrupts. This is due to the fact

pg. 33
that there are two interrupt flags: RI and TI. If either flag is set, a serial interrupt is
triggered. As you will recall from the section on the serial port, the RI bit is set when a
byte is received by the serial port and the TI bit is set when a byte has been sent.
This means that when your serial interrupt is executed, it may have been triggered
because the RI flag was set or because the TI flag was set--or because both flags were set.
Thus, your routine must check the status of these flags to determine what action is
appropriate. Also, since the 8051 does not automatically clear the RI and TI flags you
must clear these bits in your interrupt handler.

A brief code example is in order:


INT_SERIAL: JNB RI,CHECK_TI ;If the RI flag is not set, we jump to check TI
MOV A,SBUF;If we got to this line, it’s because the RI bit *was* set
CLR RI ;Clear the RI bit after we’ve processed it
CHECK_TI: JNB TI,EXIT_INT ;If the TI flag is not set, we jump to the exit point
CLR TI ;Clear the TI bit before we send another character
MOV SBUF,#’A’ ;Send another character to the serial port
EXIT_INT: RETI

As you can see, our code checks the status of both interrupts flags. If both flags were set,
both sections of code will be executed. Also note that each section of code clears its
corresponding interrupt flag. If you forget to clear the interrupt bits, the serial interrupt
will be executed over and over until you clear the bit. Thus it is very important that you
always clear the interrupt flags in a serial interrupt.

Important Interrupt Consideration: Register Protection


One very important rule applies to all interrupt handlers: Interrupts must leave the
processor in the same state as it was in when the interrupt initiated.
Remember, the idea behind interrupts is that the main program isn’t aware that they are
executing in the "background." However, consider the following code:

CLR C ;Clear carry


MOV A,#25h ;Load the accumulator with 25h
ADDC A,#10h ;Add 10h, with carry

After the above three instructions are executed, the accumulator will contain a value of
35h.
But what would happen if right after the MOV instruction an interrupt occured. During
this interrupt, the carry bit was set and the value of the accumulator was changed to 40h.
When the interrupt finished and control was passed back to the main program, the ADDC
would add 10h to 40h, and additionally add an additional 1h because the carry bit is set.
In this case, the accumulator will contain the value 51h at the end of execution.
In this case, the main program has seemingly calculated the wrong answer. How can 25h
+ 10h yield 51h as a result? It doesn’t make sense. A programmer that was unfamiliar
with interrupts would be convinced that the microcontroller was damaged in some way,
provoking problems with mathematical calculations.
What has happened, in reality, is the interrupt did not protect the registers it used.
Restated: An interrupt must leave the processor in the same state as it was in when the
interrupt initiated.
What does this mean? It means if your interrupt uses the accumulator, it must insure that
the value of the accumulator is the same at the end of the interrupt as it was at the
beginning. This is generally accomplished with a PUSH and POP sequence.

pg. 34
For example:
PUSH ACC
PUSH PSW
MOV A,#0FFh
ADD A,#02h
POP PSW
POP ACC
The guts of the interrupt is the MOV instruction and the ADD instruction. However,
these two instructions modify the Accumulator (the MOV instruction) and also modify
the value of the carry bit (the ADD instruction will cause the carry bit to be set). Since an
interrupt routine must guarantee that the registers remain unchanged by the routine, the
routine pushes the original values onto the stack using the PUSH instruction. It is then
free to use the registers it protected to its heart’s content. Once the interrupt has finished
its task, it pops the original values back into the registers. When the interrupt exits, the
main program will never know the difference because the registers are exactly the same
as they were before the interrupt executed.
In general, your interrupt routine must protect the following registers:
• PSW
• DPTR (DPH/DPL)
• PSW
• ACC
•B
• Registers R0-R7

Remember that PSW consists of many individual bits that are set by various 8051
instructions. Unless you are absolutely sure of what you are doing and have a complete
understanding of what instructions set what bits, it is generally a good idea to always
protect PSW by pushing and popping it off the stack at the beginning and end of your
interrupts.
Note also that most assemblers (in fact, ALL assemblers that I know of) will not allow
you to execute the instruction:

PUSH R0
This is due to the fact that depending on which register bank is selected, R0 may refer to
either internal ram address 00h, 08h, 10h, or 18h. R0, in and of itself, is not a valid
memory address that the PUSH and POP instructions can use.
Thus, if you are using any "R" register in your interrupt routine, you will have to push
that register’s absolute address onto the stack instead of just saying PUSH R0. For
example, instead of PUSH R0 you would execute:

PUSH 00h
Of course, this only works if you’ve selected the default register set. If you are using an
alternate register set, you must PUSH the address which corresponds to the register you
are using.

Common Problems with Interrupts


Interrupts are a very powerful tool available to the 8051 developer, but when used
incorrectly they can be a source of a huge number of debugging hours. Errors in interrupt
routines are often very difficult to diagnose and correct.

pg. 35
If you are using interrupts and your program is crashing or does not seem to be
performing as you would expect, always review the following interrupt-related issues:

• Register Protection: Make sure you are protecting all your registers, as explained
above. If you forget to protect a register that your main program is using, very
strange results may occur. In our example above we saw how failure to protect
registers caused the main program to apparently calculate that 25h + 10h = 51h. If
you witness problems with registers changing values unexpectedly or operations
producing "incorrect" values, it is very likely that you’ve forgotten to protect
registers. ALWAYS PROTECT YOUR REGISTERS.

• Forgetting to restore protected values: Another common error is to push


registers onto the stack to protect them, and then forget to pop them off the stack
before exiting the interrupt. For example, you may push ACC, B, and PSW onto
the stack in order to protect them and subsequently pop only ACC and PSW off
the stack before exiting. In this case, since you forgot to restore the value of "B",
an extra value remains on the stack. When you execute the RETI instruction the
8051 will use that value as the return address instead of the correct value. In this
case, your program will almost certainly crash.
ALWAYS MAKE SURE YOU POP THE SAME NUMBER OF VALUES OFF
THE STACK AS YOU PUSHED ONTO IT.

• Using RET instead of RETI: Remember that interrupts are always terminated with
the RETI instruction. It is easy to inadvertantly use the RET instruction instead.
However, the RET instruction will not end your interrupt. Usually, using a RET
instead of a RETI will cause the illusion of your main program running normally,
but your interrupt will only be executed once. If it appears that your interrupt
mysteriously stops executing, verify that you are exiting with RETI.

pg. 36
III
ROBOTICS

Robotics is the engineering science and technology of robots, and their design, manufacture,
application, and structural disposition. Robotics is related to electronics, mechanics, and
software. The word robot was introduced to the public by Czech writer KarelČapek in his
play R.U.R. (Rossum's Universal Robots), published in 1920. The term "robotics" was coined
by Isaac Asimov in his 1941 science fiction short-story "Liar!"

Orgin
Stories of artificial helpers and companions and attempts to create them have a long history,
but fully autonomous machines only appeared in the 20th century. The first digitally operated
and programmable robot, the Unimate, was installed in 1961 to lift hot pieces of metal from a
die casting machine and stack them. Today, commercial and industrial robots are in
widespread use performing jobs more cheaply or more accurately and reliably than humans.
They are also employed in jobs which are too dirty, dangerous, or dull to be suitable for
humans. Robots are widely used in manufacturing, assembly, and packing; transport; earth
and space exploration; surgery; weaponry; laboratory research; safety; and mass production
of consumer and industrial goods.

According to the Oxford English Dictionary, the word robotics was first used in print by
Isaac Asimov, in his science fiction short story "Liar!", published in May 1941 in Astounding
Science Fiction. Asimov was unaware that he was coining the term; since the science and
technology of electrical devices is electronics, he assumed robotics already referred to the
science and technology of robots. However, in some of Asimov's other works, he states that
the first use of the word robotics was in his short story Runaround (Astounding Science
Fiction, March 1942). The word robotics was derived from the word robot, which was
introduced to the public by Czech writer KarelČapek in his play R.U.R. (Rossum's Universal
Robots), which premiered in 1921.

pg. 37
Structure

The structure of a robot is usually mostly mechanical and can be called a kinematic chain (its
functionality being similar to the skeleton of the human body). The chain is formed of links
(its bones), actuators (its muscles), and joints which can allow one or more degrees of
freedom. Most contemporary robots use open serial chains in which each link connects the
one before to the one after it. These robots are called serial robots and often resemble the
human arm. Some robots, such as the Stewart platform, use a closed parallel kinematical
chain. Other structures, such as those that mimic the mechanical structure of humans, various
animals, and insects, are comparatively rare. However, the development and use of such
structures in robots is an active area of research (e.g. biomechanics). Robots used as
manipulators have an end effector mounted on the last link. This end effector can be anything
from a welding device to a mechanical hand used to manipulate the environment.

Power source

At present, mostly (lead-acid) batteries are used, but potential power sources could be:

• pneumatic (compressed gases)


• hydraulics (compressed liquids)
• flywheel energy storage
• organic garbage (through anaerobic digestion)
• faeces (human, animal); may be interesting in a military context as feces of small combat
groups may be reused for the energy requirements of the robot assistant (see DEKA's project
Slingshot stirling engine on how the system would operate)
• still untested energy sources (e.g. Joe Cell, ...)
• radioactive source (such as with the proposed Ford car of the '50); to those proposed in
movies such as Red Planet

Actuators

Actuators are like the "muscles" of a robot, the parts which convert stored energy into
movement. By far the most popular actuators are electric motors that spin a wheel or gear,
and linear actuators that control industrial robots in factors. But there are some recent
advances in alternative types of actuators, powered by electricity, chemicals, or compressed
air:

• Electric motors: The vast majority of robots use electric motors, often brushed and brushless
DC motors in portable robots or AC motors in industrial robots and CNC machines.
• Linear Actuators: Various types of linear actuators move in and out instead of by spinning,
particularly when very large forces are needed such as with industrial robotics. They are
typically powered by compressed air (pneumatic actuator) or an oil (hydraulic actuator).
• Series Elastic Actuators: A spring can be designed as part of the motor actuator, to allow
improved force control. It has been used in various robots, particularly walking humanoid
robots.
• Air muscles: (Also known as Pneumatic Artificial Muscles) are special tubes that contract
(typically upto 40%) when air is forced inside it. They have been used for some robot
applications.
• Muscle wire: (Also known as Shape Memory Alloy, Nitinol or Flexinol Wire) is a material
that contracts slightly (typically under 5%) when electricity is run through it. They have been
used for some small robot applications.

pg. 38
• Piezo motor: A recent alternative to DC motors are piezo motors or ultrasonic motors. These
work on a fundamentally different principle, whereby tiny piezoceramic elements, vibrating
many thousands of times per second, cause linear or rotary motion. There are different
mechanisms of operation; one type uses the vibration of the piezo elements to walk the motor
in a circle or a straight line.[23] Another type uses the piezo elements to cause a nut to vibrate
and drive a screw. The advantages of these motors are nanometer resolution, speed, and
available force for their size.[24] These motors are already available commercially, and being
used on some robots.[25][26]
• Elastic nanotubes: These are a promising, early-stage experimental technology. The absence
of defects in nanotubes[disambiguation needed] enables these filaments to deform elastically by several
percent, with energy storage levels of perhaps 10 J/cm3 for metal nanotubes. Human biceps
could be replaced with an 8 mm diameter wire of this material. Such compact "muscle" might
allow future robots to outrun and outjump humans.[27]

SENSING

Touch

Current robotic and prosthetic hands receive far less tactile information than the human hand.
Recent research has developed a tactile sensor array that mimics the mechanical properties
and touch receptors of human fingertips. The sensor array is constructed as a rigid core
surrounded by conductive fluid contained by an elastomeric skin. Electrodes are mounted on
the surface of the rigid core and are connected to an impedance-measuring device within the
core. When the artificial skin touches an object the fluid path around the electrodes is
deformed, producing impedance changes that map the forces received from the object. The
researchers expect that an important function of such artificial fingertips will be adjusting
robotic grip on held objects.

In 2009, scientists from several European countries and Israel developed a prosthetic hand,
called SmartHand, which functions like a real one, allowing patients to write with it, type on
a keyboard, play piano and perform other fine movements. The prosthesis has sensors which
enable the patient to sense real feeling in its fingertips.

Manipulation

Robots which must work in the real world require some way to manipulate objects; pick up,
modify, destroy, or otherwise have an effect. Thus the 'hands' of a robot are often referred to
as end effectors, while the arm is referred to as a manipulator. Most robot arms have
replaceable effectors, each allowing them to perform some small range of tasks. Some have a
fixed manipulator which cannot be replaced, while a few have one very general purpose
manipulator, for example a humanoid hand.

• Mechanical Grippers: One of the most common effectors is the gripper. In its simplest
manifestation it consists of just two fingers which can open and close to pick up and let go of
a range of small objects. Fingers can for example be made of a chain with a metal wire run
trough it.
• Vacuum Grippers: Pick and place robots for electronic components and for large objects
like car windscreens, will often use very simple vacuum grippers. These are very simple
astrictive devices, but can hold very large loads provided the prehension surface is smooth
enough to ensure suction.

pg. 39
• General purpose effectors: Some advanced robots are beginning to use fully humanoid
hands, like the Shadow Hand, MANUS, and the Schunk hand. These highly dexterous
manipulators, with as many as 20 degrees of freedom and hundreds of tactile sensors.

For the definitive guide to all forms of robot endeffectors, their design, and usage consult the
book "Robot Grippers".

Human-robot interaction

If robots are to work effectively in homes and other non-industrial environments, the way
they are instructed to perform their jobs, and especially how they will be told to stop will be
of critical importance. The people who interact with them may have little or no training in
robotics, and so any interface will need to be extremely intuitive. Science fiction authors also
typically assume that robots will eventually be capable of communicating with humans
through speech, gestures, and facial expressions, rather than a command-line interface.
Although speech would be the most natural way for the human to communicate, it is quite
unnatural for the robot. It will be quite a while before robots interact as naturally as the
fictional C-3PO.

• Speech recognition: Interpreting the continuous flow of sounds coming from a human
(speech recognition), in real time, is a difficult task for a computer, mostly because of the
great variability of speech. The same word, spoken by the same person may sound different
depending on local acoustics, volume, the previous word, whether or not the speaker has a
cold, etc.. It becomes even harder when the speaker has a different accent. Nevertheless, great
strides have been made in the field since Davis, Biddulph, and Balashek designed the first
"voice input system" which recognized "ten digits spoken by a single user with 100%
accuracy" in 1952. Currently, the best systems can recognize continuous, natural speech, up
to 160 words per minute, with an accuracy of 95%.
• Gestures: One can imagine, in the future, explaining to a robot chef how to make a pastry, or
asking directions from a robot police officer. On both of these occasions, making hand
gestures would aid the verbal descriptions. In the first case, the robot would be recognizing
gestures made by the human, and perhaps repeating them for confirmation. In the second
case, the robot police officer would gesture to indicate "down the road, then turn right". It is
quite likely that gestures will make up a part of the interaction between humans and robots. A
great many systems have been developed to recognize human hand gestures.
• Facial expression:Facial expressions can provide rapid feedback on the progress of a dialog
between two humans, and soon it may be able to do the same for humans and robots. Robotic
faces have been constructed by Hanson Robotics using their elastic polymer called Frubber,
allowing a great amount of facial expressions due to the elasticity of the rubber facial coating
and imbedded subsurface motors (servos) to produce the facial expressions. The coating and
servos are built on a metal skull. A robot should know how to approach a human, judging by
their facial expression and body language. Whether the person is happy, frightened, or crazy-
looking affects the type of interaction expected of the robot. Likewise, robots like Kismet and
the more recent addition, Nexi can produce a range of facial expressions, allowing it to have
meaningful social exchanges with humans.
• Artificial emotionsArtificial emotions can also be imbedded and are composed of a sequence
of facial expressions and/or gestures. As can be seen from the movie Final Fantasy: The
Spirits Within, the programming of these artificial emotions is quite complex and requires a

pg. 40
great amount of human observation. To simplify this programming in the movie, presets were
created together with a special software program. This decreased the amount of time needed
to make the film. These presets could possibly be transferred for use in real-life robots.
• Personality: Many of the robots of science fiction have a personality, something which may
or may not be desirable in the commercial robots of the future. Nevertheless, researchers are
trying to create robots which appear to have a personality: i.e. they use sounds, facial
expressions, and body language to try to convey an internal state, which may be joy, sadness,
or fear. One commercial example is Pleo, a toy robot dinosaur, which can exhibit several
apparent emotions.

pg. 41
Control

The mechanical structure of a robot must be controlled to perform tasks. The control of a robot
involves three distinct phases - perception, processing, and action (robotic paradigms). Sensors give
information about the environment or the robot itself (e.g. the position of its joints or its end effector).
This information is then processed to calculate the appropriate signals to the actuators (motors) which
move the mechanical.

The processing phase can range in complexity. At a reactive level, it may translate raw sensor
information directly into actuator commands. Sensor fusion may first be used to estimate
parameters of interest (e.g. the position of the robot's gripper) from noisy sensor data. An
immediate task (such as moving the gripper in a certain direction) is inferred from these
estimates. Techniques from control theory convert the task into commands that drive the
actuators.

Cognitive models try to represent the robot, the world, and how they interact. Pattern
recognition and computer vision can be used to track objects. Mapping techniques can be
used to build maps of the world. Finally, motion planning and other artificial intelligence
techniques may be used to figure out how to act. For example, a planner may figure out how
to achieve a task without hitting obstacles, falling over, etc.

Dynamics and kinematics


The study of motion can be divided into kinematics and dynamics. Direct kinematics refers to
the calculation of end effector position, orientation, velocity, and acceleration when the
corresponding joint values are known. Inverse kinematics refers to the opposite case in which
required joint values are calculated for given end effector values, as done in path planning.
Some special aspects of kinematics include handling of redundancy (different possibilities of
performing the same movement), collision avoidance, and singularity avoidance. Once all
relevant positions, velocities, and accelerations have been calculated using kinematics,
methods from the field of dynamics are used to study the effect of forces upon these
movements. Direct dynamics refers to the calculation of accelerations in the robot once the
applied forces are known. Direct dynamics is used in computer simulations of the robot.
Inverse dynamics refers to the calculation of the actuator forces necessary to create a
prescribed end effector acceleration. This information can be used to improve the control
algorithms of a robot.

Automatic waste container


An automatic waste container is a waste container which is automatic. This helps prevent
the bin lids becoming clogged with trash.

It has an infrared system that allows it to detect human presence and open or close the waste
container.

These wastes containers are mostly made of stainless steel.

pg. 42
In the European Union, they can be purchased for the price of 100 euros.

LIST OF MATERIALS TO BE USED

IR Photo receiver

IR Photo Transmitter

Printed Circuit Board (PCB)

General purposeVariable resistance (Preset)


20K ohm

LM324 IC
(quad high gain, frequency
compensated op amp)
Bidirectional DC Motor Speed
controller
14 Pin DIP

Standard LED

pg. 43
Fixed Resistor

Table II

Parts list for Microcontroller and motor circuit

Bread Board

8051 Microcontroller

DIPCrystal

pg. 44
Ceramic capacitor

ULN2803 IC
(Darlington Array)
18 Pin IC

DIP7805 IC
(Voltage regulator)

pg. 45
IIIParts list for Robot structure

Geared DC Motor

Castor wheel

Wheels

Double sided tape

Nuts and bolts

Screws

pg. 46
Fixed Resistors
Resistors are one of the most commonly used components in
electronics. As its name implies,resistors resist the flow of
electrons. They are used to add resistance to a circuit.The
color bands around the resistors are color codes that tell
you its resistance value. Recall that
resistance is measured in ohms.

The tolerance band indicates the accuracy of the values. A5% tolerance (gold band) for
example, indicates that theresistor will be within 5% of its value. For most applications,
a resistor within 5% tolerance should be sufficient.To get the value of a resistor, hold the
resistor so that thetolerance band is on the right.The first two color bands from the left are
the significantfigures - simply write down the numbers represented by thecolors. The third
band is the multiplier - it tells you howmany zeros to put after the significant figures.
Put them alltogether and you have the value.

NOTE: There are resistors with more bands and othertypes for specific applications.
However, 4 band resistors(the ones discussed here) are the most common and
should work for most projects.One last important note about resistors is their wattage
rating. You should not use a 1/4 wattresistor in a circuit that has more than 1/4 watt of
power flowing. For example, it is NOT okay touse a 1/4 watt resistor in a 1/2 watt circuit.
However, it is okay to use a 1/2 watt resistor in a ¼watt circuit.

pg. 47
Capacitors
Capacitors are the second most commonly used component in electronics. They can be
thought of as tiny rechargeable batteries -- Capacitors can be charged and discharged. The
amount ofcharge that a capacitor can hold is measured in Farads or the letter F. However,
1F is too largefor capacitors, so microfarads (µF) and Picofarads (pF) are used.
Micro = 1/1,000,000 and pico = 1/1,000,000,000,000
So 100,000pF = 0.1µF = 0.0000001F
We will only be discussing two types of the most commonly used capacitors: Ceramic and
Electrolytic.

• Ceramic capacitor
is brown and has a disc shape. These capacitors are non-polarized,
meaning that you can connect them in any way. To find the value, you simply decode the
3 digit number on the surface of the capacitor. The coding is just like the resistor color
codes except that they used numbers instead of colors. The first 2 digit are the significant
figures and the third digit is the multiplier. These capacitors are measured in pF.

• Electrolytic Capacitors
has a cylinder shape. These capacitors are polarized so you must
connect the negative side in the right place. The value of the resistor as well as the
negative
side is clearly printed on the capacitor. These capacitors are measured in µF.

pg. 48
Variable resistors

Horizontally Adjustable Presets


These are miniature versions of the standard variable resistor.
They are designed to be mounted directly onto the circuit
board and adjusted only when the circuit is built. For example,

to set the frequency of an alarm tone or the sensitivity of a light-sensitive circuit. A small
screwdriver or similar tool is to adjust presets

Preset Symbol
Presets are much cheaper than standard variable resistors so they are sometimes used in
projects where a standard variable resistor would normally be used.

Multiturn presets
are used where very precise adjustments must be made. The screw must be
turned many times (10+) to move the slider from one end of the track to the other, giving
very finecontrol.
A variable resistor is a potentiometer with only two connecting wires instead of three.
However, although the actual component is the same, it does a very different job. The pot
allows us to control the potential passed through a circuit. The variable resistance lets us
adjust the resistance between two points in a circuit.A variable resistance is useful when

pg. 49
we don't know in advance what resistor value will berequired in a circuit. By usingpots
as an adjustable resistor we can set the right value oncethe circuit is working. Controls like
this are often called 'presets' because they are set by themanufacturer before the circuit is
sent to the customer. They're usually hidden away insidethe case of the equipment, away
from the fingers of the users!

INTEGRATED CIRCUITS

Overview
• IC's, often called "chips", come in several shapes and sizes.
• Most common are 8, 14, or 16 pin dual in line (dil) chips.
• IC's can be soldered directly into printed circuit boards, or may plug into sockets which
have already been soldered into the board.
• When soldering, ensure that the IC (or the socket) is the correct way round and that no
pins have been bent underneath the body.
• When fitting new IC's it is often necessary to bend the pins in slightly, in order to fit it
intothe board (or socket).
• Some IC's are damaged by the static electricity which most people carry on their bodies.
They should be stored in conductive foam or wrapped in tin foil. When handling them,
discharge yourself periodically by touching some metalwork which is earthed, such as a
radiator.

Pin numbering on a Typical IC


The value of the output voltage from simple power supplies is often not accurate enough
for someelectronic circuits.The power supply voltage can also vary due to changes in the
mains supply, or variations in thecurrent taken by the load.Therefore a regulator circuit, as
shown above (sometimes called a stabiliser) is added betweenthe power supply and the
load.

The 7805 supplies 5 volts at 1 amp maximum with an input of 7-25 volts.
The 7812 supplies 12 volts at 1 amp with an input of 14.5-30 volts.
The 7815 supplies 15 volts at 1 amp with an input of 17.5-30 volts.
The 7824 supplies 24 volts at 1 amp with an input of 27-38 volts.
The 7905, 7912, 7915 and 7924 are similar but require a negative voltage in and give a
negativevoltage out.

Note that the electrolytic 10 uF must be reversed for negative supplies. Ensure that the
workingvoltage of this component is sufficient. Say 25V for the 5, 12, and 15 volt upplies
and 63V for the24 volt supply.The other two capacitors can be 100nF/100 volt
working.The 78L series can supply 100mA and the 78S can supply 2 amps.

pg. 50
ULN 2803 :
EIGHT DARLINGTON ARRAYS
High-voltage High current Darlington
transistor array
• EightDarlingtons with common emitters.
• Output current to 500mA.
• Output voltage to 50 V.
• Integral suppression diodes.
• Output can be programmed.
• Inputs pinned opposite outputs to simplify board layout.
• Versions for all popular logic families.

DESCRIPTION
The ULN2801A-ULN2805Aeach contains eight
Darlingtontransistors with common emitters and integral
suppressiondiodes for inductive loads. Each Darlington
features a peak loadcurrent rating of 600mA (500mA
continuous) and can withstandat least50V in the off

pg. 51
state. Outputs may be paralleled for higher
current capability.The output of the ULN2803 is "inverted". Thismeans that a HIGH at
the input becomesa LOW at the corresponding output line. e.g. If themotor line connected
to pin 1 goes HIGH, pin 18
on the ULN2803 will go LOW (switch off).The ULN2803 is described as a "8-line
driver".
This means that it contains the circuitry to control
eight individual output lines, each actingindependently of the others. The IC can be
thought of a 8-line 'black box'.

LM 324 IC 14pin DIP

Picture of the LM324 IC:

LM324 - Quad Operational


Amplifier
• The LM 324 is a
QUAD OP-AMP.
• Minimum supply voltage 6v
• Maximum supply voltage 15v
• Max current per output 15mA
• Maximum speed of operation 5MHz

pg. 52
LEDs

pg. 53
Symbol
LED
Definition:
LightEmittingDiodes(LEDs)are compound semiconductor devices thatconvert electricity
to light when biased in theforward direction. Because of its small size,
ruggedness, fast switching, low power andcompatibility with integrated circuitry, LED
was developed for many indicator-typeapplications.Today, advanced high-brightness
LEDs arethe next generation of lighting technologyand are currently being installed in a
varietyof lighting applications. As a result ofbreakthroughs in material efficiencies and
optoelectronic packaging design, LEDs areno longer used in just indicator lamps. They
are used as a light source for illumination formonochromatic applications such as traffic
signals, brake lights and commercial signage.

LED Benefits
- Energy Efficient
- Compact Size
- Low Wattage
- Low Heat
- Long Life
- Extremely Robust
- Compatible with Integrated Circuits

pg. 54
LED Structure
-CHIP
-LEAD FRAME
-GOLD WIRE
-EPOXY RESIN (Plastic Mold Package)
-CATHODE
-ANODE

Classified:
Classification of LED is defined by Spectrum.

Visible LED:
Based on Max. Spectrum, we produce Red,
Orange, Yellow, Green, Blue and White.

Infrared LED
(IR LED)

Applications of LED:
- Visible LED: General Purpose. Application in various industry including Indication
devices forElectronic Appliance, Measuring Instrument etc.

- Bi-Color (Dual Color) LED: Charger for Cellular Phone, Showcase Board, Traffic
Board inHighway etc.
- High & Ultra Brightness LED: Full Color Display for Indoor / Outdoor, Automotive
SignalLamp, High-mount Lamp, Indoor Lamp, Traffic Signal Lamp etc.
- Infrared LED: With High Output capacity, IR LED is used in Remote Control, IrDa
(Infrared DataStorage Devices) etc.

pg. 55
pg. 56
How to design and create a project?
A design procedure is a series of steps which guide you through any electronic design-and-
makeprocess. Sticking to the procedure will help deliver a first-class product.Once you
have defined the purpose of your project, there are two important documents you needto
write. These are:
• Thedesign brief

- a short statement of the problem to be solved. The brief should outline


the design problem you are tackling, perhaps including one or two of the envisaged
design features. Next comes
• Thedesign specification.
This is a longer document, including full details of thefunctional and design features of the
finished electronic product - as well as informationon weight and size, maintenance, cost
and safety.The specification for an electronic product should include electronic factors
such as componentdetails, maximum working voltages, maximum currents, and
temperature or frequency ranges.

Ergonomics and aesthetics


The factors which make a product efficient, safe and comfortable to use are called
ergonomics.Considerations of style - the things which make a product look and feel good
- are calledaesthetics. You need to consider both ergonomic and aesthetic factors when
planning yourdesigns.When designing circuits, for example, ensure that switches and other
control components areplaced so that they can be easily reached, and that output
components such as LEDs can beeasily seen.A product's style is a more subjective matter,
as different people may have different ideas of whatlooks good. Think about contemporary
style, about what is currently fashionable, when designingyour product. You may not want
to follow the fashion - but you still need to know what it is!

pg. 57
Circuit modeling
Circuits can be modeled to make sure they work the way you want them to. Circuit
modeling canbe done either using a computer modeling application, or on a prototype
board - also called abreadboardorVero board
- a board covered with small sockets into which components can beplugged and connected
up.The graphic shows a breadboard with holes connected in two long rows at the top and
bottom,and columns of five linked holes elsewhere. Electronic components and wires can
be simplyplugged into the board in order to make any required circuit connections. The
top and bottomrows act as power supply channels for the circuit.

pg. 58
A breadboard prototype for a 555 mono stable timer circuit might look like this:

Evaluation and testing


Evaluation and testing is about making sure that the product stays on track with the design
specification. You should plan to evaluate and test your project at a number of key stages
ofdesign and manufacture. These stages are referred to as
critical control points.The critical control points for evaluation and testing an electronic
product are:

1.Initial designphase. Check that you have used the correct value components, and that
the various systems work together. These checks can be done using a computer-
simulation package.

2.Breadboardphase. Use thebreadboardto check whether the circuit works properly.


Test each part of the circuit using amillimeterorlogic probe.

3.PCBlayout. Check that the components are in the correct positions and that you have
used the optimum track layout. Make sure that components are located neatly and that
joints are well-soldered.

4.Manufacturing and packagingphase. After manufacture, check that the product


conforms to its specification. During packaging, check that the product fits securely in the
package, and that any conducting parts are insulated.

pg. 59
5. Finally, theanalysisphase. Look back over the design and making process. Analyse
how well it went, noting down any modifications and improvements you would make if
you were to do it again. These notes are an important part of your design portfolio.

Keep notes!
Make a note of each stage in your design process. If possible, illustrate your notes with
digitalphotographs and/or graphics. Here are some of the things you should include in your
notes:

Theory of Operation
A line sensor in its simplest form is a sensor capable of detecting a contrast between
adjacent
surfaces, such as difference in color, roughness, or magnetic properties. The simplest
would be detecting a difference in color, for example black and white surfaces. Using
simple
optoelectronics, such as infrared photo-transistors, color contrast can easily be detected.
Infraredemitter/detectors or photo-transistors are inexpensive and are easy to interface to a
microcontroller.The theory of operation is simple and for brevity, only the basics will be
considered. For moreinformation about the physics of these sensors, please refer to an
optoelectronics and heattransfer text. Suffice for now; we will consider the basic effects of
light and what happens when itshines on a black or white surface. When light shines on a
white surface, most of the incominglight is reflected away from the surface. In contrast,
most of the incoming light is absorbed if thesurface is black. Therefore, by shining light
on a surface and having a sensor to detect theamount of light that is reflected, a contrast
between black and white surfaces can be detected.
Figure 1 shows an illustration of the basics just covered.

pg. 60
Figure 1Light reflecting off a white and black surface.

More light is reflected from the white surface compared to the black surface.
Using what we know about black and white surfaces, the objective of tracking a line is
simple canbe achieved using the appropriate sensors. In this article, we will consider the
use of two pairs ofemitter and detector as shown in Figure 2 below. The drive
configuration for the robot isassumed to be differential, i.e., like the tracks of an army tank
vehicle. From the figure, the twopairs of sensors are used to keep the robot on the line as
it moves. Each sensor output ismonitored to determine the location of the tape relative to
the robot. The main objective of therobot is to position itself such that the tape line falls
between the two extreme sensors. If the tapeline ever ventures past these two extreme
sensors, then the robot corrects by turning in theappropriate direction to maintain tracking.
Two different types of light sensors set up in theconfiguration shown below will be used
for line tracking.

Figure 2Top view of a robot, using two pairs of emitter and detector sensors for line
following.

pg. 61
Using the breadboard
The following picture shows a standard breadboard that we are going to use in our project
for
making the circuit for the Line following robot. The bread board has many strips of metal
(copper
usually) which run underneath the board.

Figure 3Standard breadboard

Figure 4Connections in a breadboard


The metal strips are laid out as shown in Figure 2. These strips connect the holes on the
top of
the board. This makes it easy to connect components together to build circuits. To use the
breadboard, the legs of components are placed in the holes (the sockets). The holes are
made so thatthey will hold the component in place. Each hole is connected to one of the
metal strips runningunderneath the board.
Each wire forms a node. A node is a point in a circuit where two components are
connected.
pg. 62
Connections between different components are formed by putting their legs in a common
node.On the bread board, a node is the row of holes that are connected by the strip of
metal
underneath.The long top and bottom row of holes are usually used for power supply
connections. The rest ofthe circuit is built by placing components and connecting them
together with jumper wires. Thenwhen a path is formed by wires and components from the
positive supply node to the negativesupply node, we can turn on the power and current
flows through the path and the circuit comesalive.For chips with many legs (ICs), place
them in the middle of the board so that half of the legs areon one side of the middle line
and half are on the other side. A complete circuit looks like this.

Figure 5A complete circuits in a breadboard

Construction Of Robot
Setting up the power supply in the bread board
Summary of circuit features
• Brief description of operation: Gives out well regulated +5V output.
• Circuit performance: Very stable +5V output voltage, reliable operation.
• Applications: Part of electronics devices, small laboratory power supply.
• Power supply voltage: Unregulated DC 8-18V power supply.
• Power supply current: Needed output current + 5 mili Ampere.

Circuit description
This circuit is a small +5V power supply, which is useful when experimenting with digitalelectronics. Small
inexpensive wall transformers with variable output voltage are available fromany electronics shop and
supermarket. Those transformers are easily available, but usually theirvoltage regulation is very poor, which
makes then not very usable for digital circuit experimenterunless a better regulation can be achieved in some
way. The following circuit is the answer to theproblem. This circuit can give +5V output at about 150 mA
current, but it can be increased to 1 Awhen good cooling is added to 7805 regulator chip.The capacitors
must have enough high voltage rating to safely handle the input voltage feed tocircuit. The circuit is very
easy to build for example into a piece of bread board.

pg. 63
Pin configuration of the 7805 regulator IC.
• 1. Unregulated voltage in
• 2. Ground
• 3. Regulated voltage out
The following steps are followed to set up the power supply in the breadboard.

Step 1: Place the 7805 Voltage regulator IC in the bread board as shown in the picture.

Step 2: Connect the pin 2 of the 7805 with the inner line of the bread board (left side) with a
black color single stranded wire as shown in the picture.

Step 3
Connect the pin 3 of the 7805 with the outer line of the bread board (left side) with a
red color single stranded wire as shown in the picture.

pg. 64
Step 4: Connect the inner line of the left side of the bread board with the inner line of theright side of
the bread board using a black color wire as shown in the picture.

Step 5:
Connect
the outer line of the left side of the bread board with the outer line of theright side of the bread board
using a red color wire as shown in the picture.

Step 6: Connect the positive line of the unregulated supply (adapter/battery) with the pin 1of 7805 IC.

Step 7: Connect the ground line of the unregulated supply (adapter/battery) with the pin 2of 7805 IC.

Now the entire outer line of the breadboard carries a 5 V regulated power supply and the entire
inner line carries ground.

pg. 65
Infrared Sensors
Constructing the line sensor is straightforward. I would recommend that a prototype be made to
test the operation of the sensor before committing to any permanent construction. Suggestions
are presented below relating to sensor separation and placement, but you should experiment with
your own configuration to see what works best.

Theory
The infrared emitter and detector sensors are shown below in Figure 6. You can buy these from a
number of vendors and depending on where they were purchased, the sensors shown in Figure 6
may differ in color and packaging from ones you're using. The following picture shows the most
commonly found detector and emitter pair.

Figure Infrared emitter and detector sensors.

The circuit diagram is shown below in Figure and only one set of emitter/detector sensor is
depicted. Pay close attention to theanode (+ve)andcathode (GND)
of these sensors. Usuallythe longer leg is the anode (+ve) and shorter leg is cathode (GND) in most LEDs
including theInfrared Emitter. However in case of the Detector it is opposite, that is the longer led is the
cathode (GND) and the shorter leg is the anode (+ve).

Figure Circuit diagram for the infrared emitter/detector line sensor for the AT89c52microcontroller.

pg. 66
Figure The IR circuit for 2 sensors

The sensor for the line following robot needs to be able to distinguish between the black tape andthe white
floor. IR sensors will be used instead of visible light sensors because visible lightsensors are easily
interfered with by ambient light and shadow. The longer wavelength of IRcreates a stronger, more reliable
signal while still being absorbed by the black tape.A comparator will be used as a simple analog to digital
converter to create a digital signal to sendto the control stage of the robot. These sensors operate by either
creating or removing a path to
ground. When the IR transistor is not receiving a signal the collector voltage is forced into thecomparator.
When the IR transistor receives a signal, a path to ground is created and a lowervoltage is sent to the
comparator.

pg. 67
IV
iBOT
CONTROLLER BOARD
iBot is an ideal way to venture into the field of autonomous robotics. The iBot
controller board is simple yet feature packed so as to cater to a wide range of applications.
This kit is based around the popular 8051 microcontroller architecture and strives to bridge
the gap between concepts been taught in the classrooms and actually implementing them
practically. iBot is essentially related to a variety of fields comprising of embedded C
programming, microcontrollers, electronics and mechanics. And since the controller is so
closely related to the academic curriculum, user would find it very easy to work with.
With this kit the user shall have a hands-on experience of working with different sensors,
such as line sensing modules and IR proximity sensors, use of different actuators like DC
geared and stepper motors, their drivers, LCD interfacing and serial communication with
thePC.iBot follows a modular approach throughout its construction, so the user can easily
add newfeatures and behaviors from line following, obstacle avoiding to swarm robotics
and a basicmicromouse. It can also be used as a generic embedded systems development
platform.

pg. 68
The iBot Controller Board

The iBot Controller Board is based around the Philips 89V51RD2 microcontroller.

Features:

• Built around the popular 89V51RD2 microcontroller with ample of program


memory
(64Kb)

• 8 channels of motor control, capable of driving 4 dc motors or 2 stepper motors at a


time.

• Onboard detachable 16x2 LCD for enhanced interaction.

• 8 digital input channels for sensor interfacing.

• Onboard RS232 level shifter for direct communication with a computer.

• 4 general purpose LEDs and Switches.

pg. 69
Parts identification:
• Power On Switch: It’s a basic push to on - push to off type switch.
• IC 7805: It’s a three terminal linear 5 volt regulator used to supply the
microcontroller andother peripherals.
• Motor Enable switch: This switch is used to enable/disable the motor driver chips
hence inturn enabling/disabling the motors.
• Reset Switch: This switch is used to reset the microcontroller.

• IC 555: This general purpose timer is used in the mono-stable mode to


automatically resetthe microcontroller during programming.
• MAX 232: This chip takes care of the voltage conversions needed to communicate
with thePC’s RS232 (Serial/ COM) port.
• L293D: It is a 4 channel motor driver with 600mA of current per channel and has
inbuiltclamp diodes. The board contains two such chips.
• Potentiometer (Pot): The potentiometer is used to vary the contrast of the LCD.
• Sensor port: At a time, 8 individual sensor modules can be connected to this port.
The portalso provides a 5V supply needed drive the sensors.

pg. 70
• DB 9 connector: This is a 9 pin connector used to connect to the PC’s COM port
duringprogramming or for general UART communications.
• Switch array: Four general purpose switches are connected in the active-low
configuration.
• Crystal: A crystal sets the microcontroller’s clock frequency to 11.0592 MHz.
• Beeper: Connected in the active low mode, the beeper can easily be used to get
audible
feedbacks from the controller.

Motor Connections PORTS


M1 P2.0, P2.1
M2 P2.2, P2.3
M3 P2.4, P2.5
M4 P2.6, P2.7

Switches
(active low)
Sw1 P3.2
Sw2 P3.3
Sw3 P3.4
Sw4 P3.5

LEDs
(active low)
D1 P3.0
D2 P3.1
D3 P3.6
D4 P3.7

LCD
Data P0.4 to P0.7
Control pins P0.0 to P0.2

ISP
RXD P3.0
TXD P3.1
P1.0 to P1.7

Sensor Connectors
Misc
Buzzer P0.3
Crystal (11.0592Mhz) Pin 18 and 19
Reset Switch Pin 9

pg. 71
The line sensing module

The line sensing module is designed to detect a white line on a black surface from an ideal
distance of 10mm to 20mm. The module detects the line by measuring the intensity of
reflected Infrared (IR) light. The sensor can be tuned to detect various contrasts, say white
line on a green surface or a white line on a black surface.
The red indicator led lights up whenever in encounters a reflecting surface (white line)

pg. 72
Tuning the line sensing module:
You need the power supply/battery, controller board, sensor module and a screw driver.
Step 1: Connect you module to one of the sensor port on the iBot controller. Refer the
adjoining figure for reference.

Step 2: Turn on the power supply of your iBot controller.

Step 3: Place your sensor at a distance of approximately2cm above the surface that you
“don’t” want to detect, eg.,
a black surface.
Step 4: Using the screw driver, turn the potentiometer ineither direction. You will notice
that the indicator LEDlights up at a particular point and goes off at another point.Now, in
order to properly tune to the sensor, you need toturn the pot to such a point that the LED
just turns off.
Step 5: Now when you place you sensor on a reflectivesurface (such as white) you’ll see
the indicator LED glows.That’s it! We now have our Line Sensing Module all tuned

pg. 73
up!

Specifications
Input Voltage: 5Volts
Optimum detecting distance: 10mm
IR Proximity Sensor Module

The IR proximity sensor module is based around the TSOP sensor, commonly used in TV
remote receivers. This module is able to detect objects at a distance of 5cm to 15cm. The
maximum detectable distance varies in accordance with the color and texture of the object.
For example, a white object can be easily detected from a distance of 15cm while a black
object would be detectable from a maximum distance of 5cm.

pg. 74
Tuning the obstacle detection module:

You need the power supply/battery, controller board, IR proximity sensor module and a
screw driver.
The sensors can be tuned so as to change the maximum detectable distance. This can be
varied by changing the intensity of the IR emitter.
Step 1: Connect you module to one of the sensor port on the iBot controller. Refer the
adjoining figure for reference.
Step 2: Turn on the power supply of your iBot controller.

Step 3: With the help of a screw driver, turnthe potentiometer in such a way that the
indicator LED just turns off. (if its alreadyturned off, skip this step)

Step 4: Place an object (non-black) in front ofthe module at a distance of about 10cm and
turn the potentiometer such that the indicatorLED just lights up. This step makes sure that
the same object would always be detected at amaximum distance of 10cm.
Similarly, you could move the object and turnyour potentiometer to achieve an optimum
distance.
pg. 75
Specifications:
Operating Voltage: 5Volts
Detectable distance: 5cm to 15cm

NOTE:
IR light is invisible to the human eye but digital cameras like webcams or cell-phone
cameras are capable of detecting it. Point your camera towards the IR emitter (while
turned
on) and see for yourself! This is a very handy debugging tool.

The DC Power Supply and Battery

Power Supply:
The DC Power supply provides 9Volts and a max current of up to 1A. It also has a
provision
to safely charge the 9.6V Ni-Mh battery pack at a constant preset current.
(Photo of the power supply)
Add schematic.

pg. 76
The Battery Pack:
The battery pack consists of 8 AA Ni-Mh Cells of 1.2V each, rated at 1300mAh. Thus, the
total voltage rating of the battery pack is of 9.6Volts. In order to charge the pack, simply
connect its plug to the charger port and turn on the supply. A full charge would take about
10
to 12hrs.

iBot Controller’s first test run


Your iBot controller board comes pre-programmed with some sample programs to get you
started.
Here’s what you need for your boards first test run:

•The iBot Controller Board


•LCD module
•The Power Supply
•One iBot DC motor
•Line sensing module
•IR Proximity sensor
•Screwdriver

Step 1:
Connect the LCD module to the iBot controller board as shown in the figure. The
connector
would plug in with a small amount of force.

Step2:

pg. 77
Connect the power supply connector to the board. Turn on the power supply and then
press
the power switch on the controller. The blue power LED will now light up and a welcome
message will appear on the LCD. Adjust the contrast pot for optimum text viewing.

Step 3:
Now, you shall see the program list, two at a time. Use the switches to scroll up and down
the
menu and select the respective programs.
Switch 1: scroll up
Switch 2: scroll down
Switch 3: select

Loading a new program into the iBOT controller


board
Checklist:

•iBot controller board


•Serial Cable
•Power Supply
•KEIL
•Flash Magic
•Some patience

We have collected all the tools and are ready for some coding. I assume that you have
installed TRIC and Flash Magic on your PCs.

STEP 1
To create a new project file select New Project from the Project Menu. This opens a
standard
Windows dialog box asking for project file name. Generally its a good idea to save
different
projects in different folders. So we shall use Create New Folder in this dialog to get a new
emptyfolder.Select this folder and enter the file name for the new project, i.e. Project1.keil
creates a new project file with the name PROJECT1.trc. The project name appears in the
Project Window..

pg. 78
STEP 2
Create a new source file by clicking on File — New. This opens an empty editor window
to
write the source code. TRIC enables the C color syntax highlighting. Now save the file
with
the extension *.C (default). We shall save our example under the name EXAMPLE.C.

EXAMPLE.C
.
pg. 79
/* Program to blink an LED */
#include<p89v51rd2.h>
/*we include the necessary header file here which depends on the type of
microcontroller we use. There are separate header files for separate
microcontrollers in SDCC.*/
void delay(unsigned intdela) /*This a simple delay function using
the nested ‘for loop’ */
{
unsignedinti,j;
for(i=0;i<=1000;i++)
for(j=0;j<=dela;j++);
}
void main(void) //main program begins here
{
while (1) //since there is no where to return
//we put it in an infinite loop
{
RXD=0; //LED 1 is on pin RXD at PORT 3_1, we
//turn it ON
delay (20); //wait for a short time
RXD=1; //turn the LED 1 OFF
delay(20); //wait for a short time

pg. 80
pg. 81
STEP 3
Once we have created a source file we need to add this to our project. To do this click on
Project - Add Main File. The option Add Main Files opens the standard files dialog. Select
the file EXAMPLE.C that we just created. If the main file has more than one file then we
can
add more files using the option Add Sub File. The name of the added files can be seen in
the
Project workspace.

pg. 82
STEP 4
Finally we can compile our project by clicking on Project - Compile option, which
displays
errors and warnings if any in the source code otherwise generates the EXAMPLE.ihx.

pg. 83
PROJECT REPORT
V
Line Following Robot
Time to actually build a robot! Let’s put everything that we learned tillnow in our next
program. Line following is one of the simplest task arobot can perform. There are many
algorithms and sensor configurationsdesigned to do this.
Basically, the robot will always try to get the sensors on the linealternately, thus moving in a
‘zig-zag’ path and eventually follow theline. The following code is written to follow a ‘black’
line on a ‘white’

What is a line follower?

Line follower is a machine that can follow a path. The path can be visible like a black line on
a white surface (or vice-versa) or it can be invisible like a magnetic field.
Why build a line follower?
Sensing a line and maneuvering the robot to stay on course, while constantly correcting
wrong moves using feedback mechanism forms a simple yet effective closed loop system. As
a programmer you get an opportunity to ‘teach’ the robot how to follow the line thus giving it
a human-like property of responding to stimuli.

pg. 84
Practical applications of a line follower: Automated cars running on roads with embedded
magnets; guidance system for industrial robots moving on shop floor etc.
Prerequisites:
Knowledge of basic digital and analog electronics.
C Programming Sheer interest, an innovative brain and perseverance!
OVERVIEW

Circuit model of Line Follower Robot

In the line follower robot project we have used 3 pairs of IR (infra-red) emitter/sensor. The
sensor on getting blocked or unblocked sends combination of high/low signals to AT89C51
microcontroller which are processed and appropriate signals are sent to L293D (motor driver
chip) which switches on/off the motors so as to keep the robot moving in one direction.

pg. 85
BLOCK DIAGRAM OF LINE FOLLOWER ROBOT:-

CIRCUIT DIAGRAM OF LINE FOLLOWER ROBOT:-

pg. 86
The microcontroller receives signals from the Infrared Sensor circuit. The code burnt inside
the EEPROM processes the signal and send appropriate signals to the L293D and turns on/off
the motors shown in the figure above. The program that processes the signals received from
the LM339 is given on the page later of this project report and the code has been
implemented using microcontroller programming in assembly.

pg. 87
Design of Microcontroller Programmer

Design of microcontroller programmer

The circuit shown above is microcontroller programmer (AT89CXXseries). It burns the HEX
code of the microcontroller program in the EEPROM of the microcontroller using the parallel
port of the computer.

ISP

pg. 88
In-System Programming (abbreviated ISP) is the ability of some programmable logic
devices, microcontrollers, and other programmable electronic chips to be programmed while
installed in a complete system, rather than requiring the chip to be programmed prior to
installing it into the system.
The primary advantage of this feature is that it allows manufacturers of electronic devices to
integrate programming and testing into a single production phase, rather than requiring a
separate programming stage prior to assembling the system. This may allow manufacturers to
program the chips in their own system's production line instead of buying preprogrammed
chips from a manufacturer or distributor, making it feasible to apply code or design changes
in the middle of a production run. Typically, chips supporting ISP have internal circuitry to
generate any necessary programming voltage from the system's normal supply voltage, and
communicate with the programmer via a serial protocol. Most programmable logic devices
use proprietary protocols or protocols defined by older standards. In systems complex enough
to require moderately large glue logic.

DESIGN OF INFRARED SENSOR CIRCUIT:


Principle of operation of the I.R. L.E.D. and Phototransistor:-
A Photodiode is a p-n junction or p-i-n structure. When an infrared photon of sufficient
energy strikes the diode, it excites an electron thereby creating a mobile electron and a
positively charged electron hole. If the absorption occurs in the junction's depletion region, or
one diffusion length away from it, these carriers are swept from the junction by the built-in
field of the depletion region, producing a photocurrent. Photodiodes can be used under either
zero bias (photovoltaic mode) or reverse bias (photoconductive mode). Reverse bias induces
only little current (known as saturation or back current) along its direction. But a more
important effect of reverse bias is widening of the depletion layer (therefore expanding the
reaction volume) and strengthening the photocurrent when infrared falls on it. There is a limit
on the distance between I.R. L.E.D. and infrared sensor for the pair to operate in the desired
manner. In our case distance is about 5mm.

Infra-Red emitter sends out IR pulses.

Position calculation is done through


intensity of reflected light received by
the detector.
Ambient interference is negligible.

pg. 89
POSITIONING OF SENSORS:-

EMITTER DETECTOR

0.5cm

The resistance of the sensor decreases when IR (infrared) light falls on it. A good sensor will
have near zero resistance in presence of light and a very large resistance in absence of light.
Whether the sensors are Light Dependent Resistors, laser diode, Infrared Sensors, Ultrasonic
Sensors or anything else,the outputs of the sensor modules are fed to the Non-inverting input
of a comparator . The reference voltage of the comparator is fed to the inverting input of the
comparator by a trim pot or a tuning device connected between the supply lines. LM339 is a
comparator IC that digitizes the analog signal from the sensor array. Since the output of
LM339 is TTL compatible it can be directly fed to the master microcontroller.

The generalized connection diagram of Sensor Interfacing with microcontroller is shown


below:-

pg. 90
CONNECTING INFRARED MODULE WITH MICROCONTROLLER MCS-51

When the sensor/emitter pair is on shining surface sensor is on i.e. in low impedance mode
which one can easily view as L.E.D. corresponding to that sensor doesn’t glow. The output of
the opamp is HIGH SIGNAL and this HIGH SIGNAL is given to the microcontroller and
when the sensor is on normal non-reflecting surface it’s off i.e. in HIGH IMPEDANCE state
which one can easily view as L.E.D. corresponding to that sensor glows up and LOW
SIGNAL is given to the microcontroller.

Infra-Red Sensor Array

pg. 91
Black Wire – Output Voltage
Red Wire - +5V
Brown Wire - Gnd

ANALOG TO DIGITAL CONVERTER:-

It is clear that the output of the potential divider is an analog voltage. But Microcontroller
does not accept the analog voltage. So we need to convert the analog voltage to digital before
we feed it to the microcontroller.
For this conversion we can use
1. Comparators
2. ADCs

pg. 92
COMPARATOR LM339

+ V0 = High when V+ > V-

V+ V0 = Low when V+ < V-


V0 V0 = High when V+ > V-
V0 = Low when V+ < V-
-
V-

LM339 COMPARATOR:-

PIN DIAGRAM OF LM339:-

This device consists of four independent precision voltage comparators with an offset voltage
specifications as low as 2mV. This comparator is designed to specifically operate from a
single power supply over a wide range of voltages. Operation from split power supplies is
also possible. This comparator also has a unique characteristic which is that the input

pg. 93

PIN
common-mode voltage range includes ground even though operated from a single power
supply voltage.

FUNCTION OF THE COMPARATOR:-

V+ + HIGH

V+ >V -

V- - 0V

V+ + LOW

V + <V -

V- - 0V

MICROCONTROLLER:-

PIN DIAGRAM OF AT89C51:-

pg. 94
PIN DIAGRAM OF AT89C51
The AT89C51 is a low-power, high-performance CMOS 8-bit microcomputer with 4Kbytes
of Flash Programmable and Erasable Read Only Memory (PEROM). The device is
manufactured using Atmel’s high density nonvolatile memory technology and is compatible
with the industry standard MCS-51Ô instruction set and pinout. The on-chip Flash allows the
program memory to be reprogrammed in-system or by a conventional nonvolatile memory
programmer. By combining a versatile 8-bit CPU with Flash on a monolithic chip, the Atmel
AT89C51 is a powerful microcomputer which provides a highly flexible and cost effective
solution to many embedded control applications. The AT89C51 provides the following
standard features: 4Kbytes of Flash, 128 bytes of RAM, 32 I/O lines, two 16-bit
timer/counters, five vector two-level interrupt architecture, a full duplex serial port, on-chip
oscillator and clock circuitry. In addition, the AT89C51 is designed with static logic for
operation down to zero frequency and supports two software selectable power saving modes.

pg. 95
The Idle Mode stops the CPU while allowing the RAM, timer/counters, serial port and
interrupt system to continue functioning. The Power down Mode saves the RAM contents but
freezes the oscillator disabling all other chip functions until the next hardware reset.

PICTURE OF THE MICROCONTROLLER

pg. 96
ONBOARD PIN CONNECTIONS:-

pg. 97
BIPOLAR MOTOR DRIVER:-

pg. 98
L293D is a bipolar motor driver IC. This is a high voltage, high current pushpull four channel
driver compatible to TTL logic levels and drive inductive loads. It has 600 mA output current
capability per channel and internal clamp diodes.
The L293 is designed to provide bidirectional drive currents of upto 1 A at voltages from 4.5
V to 36 V. The L293D is designed to provide bidirectional drive currents of up to 600-mA at
voltages from 4.5 V to 36 V. Both devices are designed to drive inductive loads such as
relays, solenoids, dc and bipolar stepping motors, as well as other high-current/high-voltage
loads in positive supply applications. All inputs are TTL compatible. Each output is a
complete totem-pole drive circuit, with a Darlington transistor sink and a pseudo-Darlington
source. Drivers are enabled in pairs, with drivers 1 and 2 enabled by 1,2EN and drivers 3 and
4 enabled by 3,4EN. When an enable input is high, the associated drivers are enabled, and
their outputs are active and in phase with their inputs. When the enable input is low, those
drivers are disabled, and their outputs are off and in the high-impedance state. With the
proper data inputs, each pair of drivers forms a full-H (or bridge) reversible drive suitable for
solenoid or motor applications

VCC1 - LOGIC
SUPPLY=5V 16 8
L_IN1 1 3 LM+ OUTPUT FOR
MOTOR1
L_IN2 2 14 LM-
L_EN 15
INPUT
LINES
L293D
R_IN1 7 6 RM+ OUTPUT FOR
R_IN2 9 11 RM- MOTOR2

R_EN 10

4 5 12 13

GND
PIN DIAGRAM OF L293D

The Device is a monolithic integrated high voltage, high current four channel driver designed
to accept standard DTL or TTL logic levels and drive inductive loads (such as relays
solenoides, DC and stepping motors) and switching power transistors. To simplify use as two
bridges each pair of channels is equipped with an enable input. A separate supply input is

pg. 99
provided for the logic, allowing operation at a lower voltage and internal clamp diodes are
included. This device is suitable for use in switching applications at frequencies up to 5 kHz.
The L293D is assembled in a 16 lead plastic packaage which has 4 center pins connected
together and used for heatsinking The L293DD is assembled in a 20 lead surface mount
which has 8 center pins connected together and used for heatsinking.

PIN CONNECTIONS:-

CONNECTION DIAGRAM FOR DRIVING BIPOLAR DC MOTOR

pg. 100
MOTOR DRIVING:-

EN IN 1 IN 2 Motor Status

0 X X Stopped

1 0 0 Stopped

1 1 1 Stopped

1 1 0 CW

1 0 1 CCW

pg. 101
PICTURE OF BIPOLAR MOTOR DRIVER

pg. 102
DC MOTORS:-

These are very commonly used in robotics. DC motors can rotate in both directions
depending upon the polarity of current through the motor. These motors have free running
torque and current ideally zero. These motors have high speed which can be reduced with the
help of gears and traded off for torque. Speed Control of DC motors is done through Pulse
Width Modulation techniques, i.e. sending the current in intermittent bursts. PWM can be
generated by 555 timer IC with adjusted duty cycle. Varying current through the motor varies
the torque.

PICTURE OF DC MOTOR USED

pg. 103
Obstacle Avoiding robot
Obstacle avoiding behavior is a prerequisite in any mobile roboticapplication. In this project we will learn to add
such a behavior in ouriBOT.Here’s a simple algorithm:

Step 1:
check if right ir proximity sensor is active; if active, turn leftfor a while
Step 2:
check if left ir proximity sensor is active; if active, turn rightfor a while
Step 3: else move forward
Step 4: goto step 1
// OBSTACLE AVOIDING ROBOT //
//Right proximity sensor connected to PORT1.2
//Left proximity sensor connected to PORT1.3
//Right motor connected at M2
//Left motor connected at M1

#include<P89V51RD2.h> //we include the necessary header file here


#include<delay.h>
#define forward 0x05; // 0000
01 01
#define turnleft 0x06; // 0000
01 10
left motor = backwards,
// right motor = forward
#define turnright 0x09; // 0000
10 01
left motor = forward,
// right motor = backwards
#define obst_right P1_2
#define obst_left P1_3
void main(void) //main program begins here
{
P1=0xff; //initialize PORT 1 as input (sensors)
P2=0x00; //initialize PORT 2 as output (motors)
while (1) //since there is no where to return,
//we put it in an infinite loop
{
if (obst_right==0) //check if right sensor has detected an obstacle
{
P2=turnleft; //if detected, turn left for some time
DELAY(30);
}
if (obst_left==0) //check if left sensor has detected an obstacle
{
P2=turnright; //if detected, turn right for some time
DELAY(30);
}
else
{
P2=forward; //else go forward
}
}
}
By changing the delay variable we can make the robot turn for somespecific degrees after it detects an obstacle.
But the turns will not beprecise since they will change as the battery drains.

pg. 104
Note:
In this particular case, the turning would be ‘in place’ i.e., whileturning, both the motors will run in opposite
direction unlike the line follower, where the turns were turning by ‘stopping’ either of the motor.

PROBLEMS ENCOUNTERED:-

• The ISP programmer requires dedicated supply of 9V from the USB of your P.C. Extern
supply of other than 9V generates error while writing the HEX code to the Microcontroller.
The programmer was soldered 3 times before it could successfully program the chip.
• The program was difficult to implement as it was our first encounter with microcontroller
programming in assembly.
• The large number of interconnections in the circuit made it too difficult to solder.
• The IR sensors burnt up on soldering so we have to use temperature controlled soldering
iron.
• In the model designed to show line follower robot, electric motors ought to be bidirectional
and of low wattage i.e. should draw lesser current otherwise the motor can draw current to
such a level to burn up the entire circuit.

pg. 105
REFERENCES AND RESOURCES:-

Books:
1) The 8051 Microcontroller and Embedded Systems Using
Assembly and C By Muhammad Ali Mazidi, Janice Gillispie
Mazidi&Rolin D. McKinlay

Websites referred:
1) Atmel Corp. Makers of the AVR microcontroller
www.atmel.com
2) One of the best sites AVR site www.avrfreaks.net
3) One of the best site for Microcontroller projects
www.kmitl.ac.th
4) Keil™, the developer of Keilμvision www.keil.com
5) Information from www.wikipedia.com

pg. 106

Você também pode gostar