You are on page 1of 94

ACKNOWLEDGEMENT

With great pleasure we want to take this opportunity to express our


heartfelt gratitude to all the people who have helped us in making this
project work a grand success.

We are very much thankful to XXXX, Project Guide,


CMC, Hyderabad for giving us this opportunity to do this project. We
express our deep sense of gratitude to XXXX for his constant guidance
throughout our project work. Their timely suggestions and direct
involvement at different stages of the project work helped us in completing
our project successfully on time.

It has been a great pleasure and enlightening


experience to work under them during the course of this project. We are also
thankful to all those who helped us directly or indirectly.
LIST OF FIGURES
LIST OF TABLES
ABSTRACT
CONTENTS

Introduction to embedded systems


Technology used
Stepper motor
P89V51RD2 Microcontroller
Serial communication
Circuits and their operation
programming
Applications and advantages
Conclusion
Bibliography
INTRODUCTION TO EMBEDDED SYSTEMS

1.1.Introduction

Computer systems are found everywhere. It is probably no


surprise that millions of computing systems are built every year, destined
for desktop computers like personal computers, laptops, workstations,
mainframes and servers. What may be surprising is that billions of
computing systems are built every year for a very different purpose. They
are embedded with in larger electronic devices, repeatedly carrying out a
particular function. Often going completely unrecognized by the device's
user. Creating a precise definition of the embedded computing systems or
simply the embedded systems is not an easy task Here we will try to
define embedded systems.

Embedded systems are electronic devices that incorporate


microprocessors with in their implementations. The main purposes of the
microprocessor are to simplify the system design and provide flexibility
Having a microprocessor in the device means that removing the bugs,
making modifications, or adding new features are only matters of rewriting
the software that controls the device. Or in other words Embedded
computer systems are electronic systems that include a microcomputer to
perform a specific dedicated application the computer is hidden inside
these products Embedded systems are ubiquitous. Every week millions of
tiny computer chips come pouring out of factories like Motorola, Intel,
Philips, and Mitsubishi finding their way into our everyday products.

Our global economy, our production of food, our transportation


systems, our military defense organizations, our communication systems,
and even our quality of life depend on the efficiency and effectiveness of
these embedded systems. Unlike PCs, however embedded systems may
not have a disk drive and so the software is often stored in a read-only
memory (ROM) chip this means that modifying the software requires
either replacing or reprogramming the ROM.

Embedded systems are found in a variety of common electronic


devices, such as consumer electronics (cell phones. pagers, digital
cameras, camcorder, videocassette recorders, portable video games,
calculators and personal digital assistants), home appliances (microwave
ovens, answering machines, thermostats, home security systems,
washing machines and lighting machines). Office automation (fax
machines, copiers, printers and scanners), business equipment (cash
registers, curbside check-in alarm system, card readers, product scanners
and automated teller machines), and automobiles (transmission control,
cruise control, fuel injection, anti lock brakes, active suspension and wheel
alignment) One might say that nearly any device that runs on electricity
either already or soon it will have a computing system embedded within it.

Although embedded computers typically cost far less than desktop


computers, their quantities are huge. For example in 1999, if a typical
American house have had one desktop computer, but each one had
between 35 and 50 embedded computers .With that number expected to
rise to nearly 300 by 2005.Today's embedded systems are so inexpensive
that they are used in almost all electronics products in our life. In many
cases we are not aware that a computer is present and so don't realize
just how pervasive they have become.

For example, although the typical family may own one or two
personal computers, the number of embedded computers found with in
their home and cars and among their personal belongings is much
greater.

Embedded application programs present some new challenges


such as reliability, performance and cost.

Reliability expectations will place greater responsibility on


programmers to eliminate bugs and to design our software to tolerate
errors and unexpected simulations Many embedded systems need to run
24 hours a day, seven days a week and 365 days an year. You can't just
"reboot" the system when something goes wrong. For this reason, good
coding practices and thorough testing take on a new level ofimpol1ance in
the realm of embedded processors

Performance goals force us to learn and apply new techniques


such as multitasking and multi-scheduling. The need to communicate
directly with the sensors, actuators, keypads, displays, etc., will require
programmers to have a better understanding of how alternative methods
for performing input and output provide opportunities to trade speed,
complexity and cost. Although we'll usually program in a high level
language for better productivity, use of these alternatives will occasionally
require that we drop to the level of computer and program directly in
assembly language.

Embedded systems have several common characteristics that


distinguish such systems from other computing systems

1. Single-functioned:

An embedded system usually executes a specific program


repeatedly. For example a pager is always a pager In contrast,, a desktop
computer executes a variety of programs, like spread sheets. word
processors and video games with new programs added frequently Of
course there are exceptions. One case is that where an embedded system
s program is updated with a newer program version. For example some
cell phones can be updated in such a manner. A second case Is where
several programs are swapped In and out of the system due to size
limitations For c\ample, some missiles run one program while in cruise
mode, then load a second program Corm locking on to the target
Nevertheless we can see that c\en these' exceptions represent systems
with a specific function

2. Tightly constrained:

All computing systems have constraints design metrics those on


embedded systems can be especially tight . design metric IS measure of
implementation's features such as cost. SI7C, performance and power.
Embedded system often must cost just a few dollars must he sized to fit in
on a single chip, must perform fast enough to process detail n the recall
time,. And must consume minimum power to extend the battery period or
prevent the necessity of a cooling fan.

3. Reactive and real time:

Many embedded systems must continually react to the changes in


the system's environment and must compute certain results in real time
without delay. For example a car's cruise controller continually monitors
and reacts to speed and break sensors. It must compute the acceleration
or the deceleration amounts repeatedly with in a limited time; a delayed
computation could result in a failure to maintain control of the car.

In contrast a desktop system focuses on the computations with


relatively infrequent (from the computer's perspective) reactions to the
input devices. In additions delay in those computations, while perhaps
inconvenient to the computer user, but does not result in any system
failure.

1.2. Embedded processors

The embedded systems that found in most of the consumer products


employ a single <;:hip controller that includes the microprocessor, a
limited amount of memory, and a few simple input/output devices. By far
the vast majority of embedded systems are in production today are based
on the older 4-bit, 8-bit or 16-bit processors. Although 32-bit processors
account for a small percentage of the current market, their use in
embedded systems is growing at the faster rate. As shown in the figure
below, 32-bit and 64-bit processors are rapidly replacing their processors
in the new embedded designs. In 1998, almost 250 million 32-bit
embedded processors were shipped compared to only 100 million desktop
computers

1.3. Programming language that are used.

Although it is necessary tl1 code some small pans (If an embedded


application program in assembly language most of the code in even the
simplest application is written in the high level language Traditionally. the
choice of language has been (and continues to be) C programs written C
are very portable from one compiler and or target compiler to another
compiler C compilers are available for a number of different target
processors, and they generate very efficient code.

Despite the popularity of C and Java for desktop application


programming they are rarely used in the embedded systems programming
because the large runtime overhead required supporting some of their
features. For example even a relatively simple C++ program will produce
twice as much code as the same program written in the C language, and
the situation is much worse for large programs that make extensive use of
the run-time library.

EC++ (Embedded C++) is a new language that is a proper subset


of C++ that has many of its object oriented facilities but that omits those
non-essential features that increase the code size and impair run-time
performance. EC++ was designed by a group of Japanese
microprocessor manufacturer called EC++ Technical Group. The
language has generated a lot of interest in the embedded community and
will undoubtedly finds its way into the embedded applications as soon as
commercial compilers become widely available for a large number of
target processors

Uniqueness of building an embedded application

To understand this first we have to be familiar with the tools and


software components used to build a desktop application program and
load it into the memory for execution. This process is summarized in the
fig.

Object files executable

Compiler Image file

LINKER
Assembler Loader
Run-time library

Operating system image


Boot process
Fig.: The build and load process for desktop application
program

When you want to run a desktop application program, its


executable image is loaded from the disk into the memory by a part of the
operating system known as the loader. The operating system itself there in
the memory put there ,during the boot process

The desktop system is intended to run a number of different


application programs, Thus a read/write main memory is used so that an
entirely different application program can be quickly and easily loaded into
the memory, replacing the previous application whenever necessary,

Unlike general-purpose desktop systems, embedded systems are


designed to serve a single purpose, Once the embedded software is there
in the memory, there is usually no reason to change it. This allows a less-
expensive read-only memory to be used for permanent storage of the
program, Since there is no need to store the program on disk, a significant
amount of software can be eliminated that would otherwise be necessary
to support a file system,
Executable

object files image file ROM image


Compiler

LINKER LOCATE
Assembler R

Re-entrant library
ROM burner
Real-time Kernel

Fig. The build and load process for embedded application


program

Both the application's software and a reed-lime kernel are stored in


the same read only memory as a single program image, A real-lime kernel
is a one which manages the processor time and memory)' utilization
among a number of concurrent threads With no need for a file system, the
kernel is much smaller than a regular operating system and is easily linked
into the program as yet another object file as shown in the above figure

In general. the same kinds of software-development tools are used


to build both embedded and desktop applications Although tool suites
designed especially for ell1bedded-application development are
commercially available, in many cases it is possible to use the same
compiler, assembler and linker that you use for the desktop applications
There are two important difference, however. First, the run-time library that
comes with the compilers for desktop applications is usually not intended
for multitasking applications and must be replaced by the one that is re-
entrant Second, additional software called locator is required to convert
the linker's output to a form suitable for storing in read-only memory.
When a desktop operating system loads an executable program image
produced by a linker in to memory, it has to modify a few bytes whose
values depend on the address where the program is to be loaded. Before
we can use such an executable image to permanently store our
embedded program in a read-only memory, we must perform the same
"fix-ups" using the program called a locator

. 1.4. Size of typical embedded programs

We've grown used to desktop application programs that require


several megabytes of memory and disk space. So it is surprising how little
memory is used in embedded products, especially when you consider that
both the embedded applications and its real-time kernel are stored in
memory. If we consider a real time embedded device the FAX Machine as
an example with a RAM of 2048 bytes and ROM of 32KB and with a 16 bit
microprocessor then the total RAM actually used is 66% and amount used
by kernel is 19%and for ROM the total memory used is 90% and the
amount used by kernel is 8.7%.

1.5. Difference between Embedded Systems (ES) and PC (computer)

Embedded systems differ from a normal PC in several ways. Even


though the ES is capable of computation and other jobs done by PC, it is
not a complete PC It may not have a key board, a monitor or even for that
matter a processor. We do have an ES with all these, but not a must. PCs
are usually applicable to build general purpose software and most of the
applications we build are reusable. In case of ES, most of the
development might start from scratch The ES might he specific to some
application and components used in them might be home made But the
latest ES technology enables one to use general-purpose hardware
and components, which can re used. The as of the Embedded systems
might not be complete, but only the basic functionalities of OS are taken in
a real time environment.

1.6. Parts of Embedded Systems

An Embedded system is mainly comprised of

a) Hardware

b) Real time Operating system (RTOS) c) Processor

d) Serial port, n/w port. j/o peripheral port

e) Sensors and actuators

f) Mechanical parts

1.7.Characteristics of Embedded Systems

a) Applications using ES must be reliable safe and secure

b) High efficiency

c) Mostly fixed set of application systems

d) Frequently reading, processing and controlling physical quantities

e) Must react after. guaranteed time limit

f) Most of the functionalities of the ES are implemented in software

Common microprocessors used for ES

a) ZilogZ8 family
b) Intel 8051

c) X86 family

d) Motorola 68k family

e) PowerPC family

1.8.Introduction to applications of embedded system

Embedded controllers may be found in many different kinds of


system and are used for many different applications. The list, which
follows, is indicative rather than exhaustive. An item in the list may be
relevant to a particular company because either

(a) It is or involves a core process or product,

(b) It is or involves an ancillary function or service performed by the


company

(c) It refers to a product or service provided by a contractor under some


form of agreement and the vulnerability of the supplier may need to be
considered.

Required skill sets to work on ES.

Intel Processors & Controllers Micro controllers

DSP Processors

C++,C

Lab View
Mat Lab

RTOS (Real Time Operating System)

VX Works

ADA (Aerospace)

Hardware design & testing

VHDL

1.9.List of applications of embedded systems

(a) Manufacturing and process


control

Manufacturing plants

Water and sewage systems

J>power stations
Power grid systems

Oil refineries and related storage facilities

bottling plants

Automated factories

Simulators

Test equipment for control system development, maintenance and


testing

(b) Construction industry

Surveying and location equipment Construction plant

(c) Transport

Aero planes

Trains

Buses

Marine craft (known cases include radar mapping; ballast


monitoring, cargo loading; ship performance monitoring; engine room
vibration monitor; service aid for ships control; ship main control system)

Automobiles

Fuel services

Air Traffic Control Systems

Signaling systems

Radar systems
Traffic lights

Ticketing systems/machines

Car parking and other meters

(d) Buildings and premises

Electrical supply -supply, measurement, control, protection Backup


lighting and generators

Fire control systems

Heating and Ventilating systems

Lifts, elevators, escalators

Security systems

Security cameras

Safes and vaults

Door locks

(e) Domestic services

Catering

Cleaning

(f) Communications

Telephone exchange
Cable systems

Telephone switches

Data switching equipment (X.25, SMDS, Frame Relay, etc.) Satellites

(g) Office systems and mobile equipment

Telephone systems

Faxes

Copier

Time recording systems Mobile telephones Still and video


cameras

(h) Banking, finance and commercial

Automated teller systems

Credit card systems

Point of sale systems including scanner/cash systems

(i) Medical diagnostics, monitoring and life support

Heart defibrillators

Pacemaker monitors

Patient information systems


Patient monitoring systems

Pharmaceutical control and dispensing systems, e.g. infusion pumps X-


ray equipment

(j) Testing, monitoring and diagnostic systems

Energy metering Environmental-monitoring equipment

(k) Industrial functions of embedded systems

Multi-loop control and monitoring - DCS, SCADA, telemetry

Panel mounted devices - Control, display, recording and operations

Safety and security - Alarm and trip systems, fire and gas systems,
buildings and facilities security

Field devices - measurement, actuation

Analytical systems - Laboratory systems; on-line/ plant systems

Electrical supply - supply, measurement, control, protection

Tools - for design, documentation, testing, maintenance


MICROCONTROLLER

Introduction to Micro controller:


Why we need a microprocessor/controller:

• The microprocessor is the core of computer systems.


• Nowadays many communications, digital entertainment, portable devices, are
controlled by them.
• A designer should know what types of components he needs, ways to reduce production
costs and product reliable.

Different aspects of a microprocessor/controller:

• Hardware: Interface to the real world


• Software: order how to deal with inputs

The necessary tools for a microprocessor/controller:

• CPU: Central Processing Unit


• I/O: Input /Output
• Bus: Address bus & Data bus
• Memory: RAM &ROM
• Timer
• Interrupt
• Serial Port
• Parallel port

MICROPROCESSOR:
General-purpose microprocessor

• CPU for Computers


• No RAM, ROM, I/O on CPU chip itself
• Example: Intel’s x86, Motorola’s 680x0

General purpose microprocessor system:

Data Bus

CPU Serial
General RAM ROM I/O COM
Purpose Timer Port
PORT
Micro-
Processo
r

Address Bus

General purpose microprocessor system

MICROCONTROLLER:

• A smaller computer
• On-chip RAM, ROM, I/O ports...
• Example: Motorola’s 6811, Intel’s 8051, Zilog’s Z8 and PlC 16X
A single chip microcontroller:

CPU RAM ROM


I/O PORT TIMER SERIAL COM PORT

MICROPROCESSOR vs. MICROCONTROLLER


MICROPROCESSOR

• CPU is stand-alone, RAM, ROM, I/O, timer are separate


• Designer can decide on the amount of ROM, RAM and I/O ports.
• Expansive
• versatility
• general-purpose

MICROCONTROLLER

• CPU, RAM, ROM, I/O and timer are all on a single chip
• fix amount of on-chip ROM, RAM, I/O ports
• for applications in which cost, power and space are critical
• Single-purpose

EMBEDDED SYSTEM:

• Embedded system means the processor is embedded into that application.


• An embedded product uses a microprocessor or microcontroller to do one task only.
• In an embedded system, there is only one application software that is typically burned
into ROM.
Example: Printer, keyboard, video game player

Three criteria in Choosing a Microcontroller:

1. Meeting the computing needs of the task efficiently and cost effectively

• Speed, the amount of ROM and RAM, the number of 1/0 ports and timers, size,
packaging, power consumption
• easy to upgrade
• cost per unit
2. Availability of software development tools
• assemblers, debuggers, C compilers, emulator, simulator, technical support

3. Wide availability and reliable sources of the microcontrollers.


Introduction to Stepper Motors
A stepper motor is a permanent magnet or variable reluctance dc motor that has the
following performance characteristics:

1. rotation in both directions,

2. precision angular incremental changes,

3. repetition of accurate motion or velocity profiles,

4. a holding torque at zero speed, and

5. capability for digital control.

A stepper motor can move in accurate angular increments knows as steps in response to
the application of digital pulses to an electric drive circuit from a digital controller. The
number and rate of the pulses control the position and speed of the motor shaft.
Generally, stepper motors are manufactured with steps per revolution of 12, 24, 72, 144,
180, and 200, resulting in shaft increments of 30, 15, 5, 2.5, 2, and 1.8 degrees per step.

Stepper motors are either bipolar, requiring two power sources or a switchable polarity
power source, or unipolar, requiring only one power source. They are powered by dc
current sources and require digital circuitry to produce the coil energizing sequences for
rotation of the motor. Feedback is not always required for control, but the use of an
encoder or other position sensor can ensure accuracy when it is essential. The advantage
of operating without feedback is that a closed loop control system is not required.
Generally, stepper motors produce less than 1 horsepower(746W) and are therefore
frequently used in low-power position control applications.

HOW STEPPER MOTORS WORK

We've all experimented with small "hobby motors", or free-spinning DC motors. Have you ever
tried to position something accurately with one? It can be pretty difficult. Even if you get the timing
just right for starting and stopping the motor, the armature does not stop immediately. DC motors
have a very gradual acceleration and deceleration curves; stabilization is slow. Adding gearing to
the motor will help to reduce this problem, but overshoot is still present and will throw off the
anticipated stop position. The only way to effectively use a DC motor for precise positioning is to
use a servo. Servos usually implement a small DC motor, a feedback mechanism (usually a
potentiometer with attached to the shaft by gearing or other means), and a control circuit which
compares the position of the motor with the desired position, and moves the motor accordingly.
This can get fairly complex and expensive for most hobby applications.

Stepper motors, however, behave differently than standard DC motors. First of all, they cannot
run freely by themselves. Stepper motors do as their name suggests -- they "step" a little bit at a
time.Stepper motors also differ from DC motors in their torque-speed relationship. DC motors
generally are not very good at producing high torque at low speeds, without the aid of a gearing
mechanism. Stepper motors, on the other hand, work in the opposite manner. They produce the
highest torque at lowspeeds. Stepper motors also have another characteristic, holding torque,
which is not present in DC motors. Holding torque allows a stepper motor to hold its position
firmly when not turning. This can be useful for applications where the motor may be starting and
stopping, while the force acting against the motor remains present. This eliminates the need for a
mechanical brake mechanism. Steppers don't simply respond to a clock signal, they have several
windings which need to be energized in the correct sequence before the motor's shaft will rotate.
Reversing the order of the sequence will cause the motor to rotate the other way. If the control
signals are not sent in the correct order, the motor will not turn properly. It may simply buzz and
not move, or it may actually turn, but in a rough or jerky manner. A circuit which is responsible for
converting step and direction signals into winding energization patterns is called a translator.
Most stepper motor control systems include adriver in addition to the translator, to handle the
current drawn by the motor's windings.

A basic example of the "translator


+ driver" type of configuration.
Notice the separate voltages for
logic and for the stepper motor.
Usually the motor will require a
different voltage than the logic
portion of the system. Typically
logic voltage is +5 Vdc and the
stepper motor voltage can range
from +5 Vdc up to about +48 Vdc.
The driver is also an "open
Figure 1.1 - A typical translator / driver connection collector" driver, wherein it takes
its outputs to GND to activate the
motor's windings. Most
semiconductor circuits are more
capable of sinking(providing a
GND or negative voltage) than
sourcing (outputting a positive
voltage).

COMMON CHARACTERISTICS OF STEPPER MOTORS:


Stepper motors are not just rated by voltage. The following elements characterize a given
steppermotor:

Voltage
Stepper motors usually have a voltage rating. This is either printed directly on the unit, or is
specified in the motor's datasheet. Exceeding the rated voltage is sometimes necessary to obtain
the desired torque from a given motor, but doing so may produce excessive heat and/or shorten
the life of the motor.

Resistance
Resistance-per-winding is another characteristic of a stepper motor. This resistance will
determine current draw of the motor, as well as affect the motor's torque curve and maximum
operating speed.
Degrees per step
This is often the most important factor in choosing a stepper motor for a given application. This
factor specifies the number of degrees the shaft will rotate for each full step. Half step operation
of the motor will double the number of steps/revolution, and cut the degrees-per-step in half. For
unmarked motors, it is often possible to carefully count, by hand, the number of steps per
revolution of the motor. The degrees per step can be calculated by dividing 360 by the number of
steps in 1 complete revolution Common degree/step numbers include: 0.72, 1.8, 3.6, 7.5, 15, and
even 90. Degrees per step is often referred to as the resolution of the motor. As in the case of an
unmarked motor, if a motor has only the number of steps/revolution printed on it, dividing 360 by
this number will yield the degree/step value.

Theory

Unipolar stepper motor

Fig.1 A unipolar stepper motor

Unipolar stepping motors with 5 or 6 wires are usually wired as shown in the schematic
in Figure 1, with a center tap on each of two windings. In use, the center taps of the
windings are typically wired to the positive supply, and the two ends of each winding are
alternately grounded to reverse the direction of the field provided by that winding. An
animated GIF of figure 1.2 is available. The motor cross section shown in Figure 1 is of a
30 degree per step motor -- the difference between these two motor types is not relevant
at this level of abstraction. Motor winding number 1 is distributed between the top and
bottom stator pole, while motor winding number 2 is distributed between the left and
right motor poles. The rotor is a permanent magnet with 6 poles, 3 south and 3 north,
arranged around its circumfrence. For higher angular resolutions, the rotor must have
proportionally more poles. The 30 degree per step motor in the figure is one of the most
common permanent magnet motor designs, although 15 and 7.5 degree per step motors
are widely available. As shown in the figure, the current flowing from the center tap of
winding 1 to terminal a causes the top stator pole to be a north pole while the bottom
stator pole is a south pole. This attracts the rotor into the position shown. If the power to
winding 1 is removed and winding 2 is energised, the rotor will turn 30 degrees, or one
step. To rotate the motor continuously, we just apply power to the two windings in
sequence. Assuming positive logic, where a 1 means turning on the current through a
motor winding, the following two control sequences will spin the motor illustrated in
Figure 1 clockwise 24 steps or 4 revolutions:
Winding 1a 1000100010001000100010001
Winding 1b 0010001000100010001000100
Winding 2a 0100010001000100010001000
Winding 2b 0001000100010001000100010
time --->
Winding 1a 1100110011001100110011001
Winding 1b 0011001100110011001100110
Winding 2a 0110011001100110011001100
Winding 2b 1001100110011001100110011
time --->

Note that the two halves of each winding are never energized at the same time. Both
sequences shown above will rotate a permanent magnet one step at a time. The top
sequence only powers one winding at a time, as illustrated in the figure above; thus, it
uses less power. The bottom sequence involves powering two windings at a time and
generally produces a torque about 1.4 times greater than the top sequence while using
twice as much power.

Bipolar stepper motor

Fig 2. A bipolar stepper motor

Bipolar permanent magnet and hybrid motors are constructed with exactly the same
mechanism as is used on unipolar motors, but the two windings are wired more simply,
with no center taps. Thus, the motor itself is simpler but the drive circuitry needed to
reverse the polarity of each pair of motor poles is more complex. The schematic in Figure
2 shows how such a motor is wired, while the motor cross section shown here is exactly
the same as the cross section shown in Figure 1. The drive circuitry for such a motor
requires an H-bridge control circuit for each winding. Briefly, an H-bridge allows the
polarity of the power applied to each end of each winding to be controlled independently.
The control sequences for single stepping such a motor are shown below, using + and -
symbols to indicate the polarity of the power applied to each motor terminal:

Terminal 1a +---+---+---+---
Terminal 1b --+---+---+---+-
Terminal 2a -+---+---+---+--
Terminal 2b ---+---+---+---+
time --->
Note that these sequences are identical to those for a unipolar permanent magnet motor,
at an abstract level, and that avove the level of the H-bridge power switching electronics,
the control systems for the two types of motor can be identical. Note that many full H-
bridge driver chips have one control input to enable the output and another to control the
direction. Given such bridge chips, one for eachwinding, the following control sequences
will spin the motor identically to the control sequences given above:

Enable 1 1111111111111111
Direction 1 1100110011001100
Enable 2 1111111111111111
Direction 2 0110011001100110
time --->

To distinguish a bipolar permanent magnet motor from other 4 wire motors, measure the
resistances between the different terminals. It is worth noting that some permanent
magnet stepping motors have 4 independent windings, organized as two sets of two.
Within each set, if the two windings are wired in series, the result can be used as a high
voltage bipolar motor. If they are wired in parallel, the result can be used as a low voltage
bipolar motor. If they are wired in series with a center tap, the result can be used as a low
voltage unipolar motor.

Driving Stepper Motors with the L293D


The L293D contains two H-bridges (for more information on H-bridges, click here.) for
driving small DC motors. It can also be used to drive stepper motors because stepper
motors are, in fact, two(or more) coils being driven in a sequence, backwards and
forwards. One L293D can, in theory, drive one bi-polar 2 phase stepper motor, if you
supply the correct sequence.

We are going to show how to drive a bipolar and a unipolar stepper motor with the
L293D. The bipolar stepper motor and the unipolar stepper motor we used were bought
from Jameco. (part# 105881 and 105890 respectively). Both of the bipolar and unipolar
stepper motors are 3.6 degrees/step motors.

Bipolar Stepper Motor

The L293D chip has 16 pins. Here is how each of the pins should be connected:

Pin 1, 9 Enable pins. Hook them together and you can either keep them high and run the
motor all the time, or you can control them with you own controller(e.g. 68HC11).

Pin 3, 6, 11, 14 Here is where you plug in the two coils. To tell which wires correspond
to each coil, you can use a mulitmeter to measure the resistance between the wires. The
wires correspond to the same coil has a much lower resistance than wires correspond to
different coils. (This method only applies to bipolar stepper motors. For unipolar stepper
motors, you have to refer to the spec. sheet to tell which wires correspond to each coil.)
You can then get one coil hooked up to pin 3,6 and another one hooked up to pin 11, 14.

Pin 4, 5, 12, 13 Gets hooked to ground.

Pin 8 Motor voltage, for the motors we are using, it is 12V.

Pin 16 +5V. It is the power supply of the chip and it's a good idea to keep this power
supply separate from your motor power.

Pin 2, 7, 10, 15 Control signals. Here is where you supply the pulse sequence. The
following is how you pulse them for a single-cycle (to move the motor in the opposite
direction, just reverse the steps. i.e. from step 4 to step1):

Coil 1a Coil 2a Coil 1b Coil 2b


Step 1 High High Low Low
Step 2 Low High High Low
Step 3 Low Low High High
Step 4 High Low Low High

In our example, we use the digital outputs of the Handy Board to generate the above
pulse. The SPI pins on the connector on the middle right edge of the Handy Board can be
configured as digital outputs. Do a poke(0x1009, 0x3c) to make them outputs; then they
are mapped o the middle 4 bits of address 0x1008 (SS= bit 5, SCK=bit 4, MOSI=bit 3,
MISO=bit 2). Poke to that address (0x1008) to set them.

Here is the code fragment to generate the pulses:

int address=0x1008;
float x=0.005;
int i;
int t=100;
poke (0x1009, 0x3c);
for(i=0; i<t, i++){
poke(address, 00001100);
sleep(x);
poke(address, 00011000);
sleep(x);
poke(address, 00110000);
sleep(x);
poke(address, 00100100);
sleep(x);
}

In the above code fragment, the variable x controls how much time the controller should
wait between each steps and this consequently determines the speed of the motor. The
variable t determines how many cycles controller should drive the motor and so this
control the angular position of the shaft.

Unipolar Stepper Motor

Driving a unipolar stepper motor with the L293D is very similar to driving a bipolar
stepper motor. The pulse sequence is the same and you can use the code fragment above
to generate the pulse sequence. The only difference between driving a unipolar stepper
motor and driving a bipolar stepper motor is that there is an extra wire in a unipolar
stepper motor you have to hook up. You can hook it up to the +5V supply and the wires
are hooked up in the same way as those in the bipolar stepper motor.

Driving a Stepper Motor with the Handy Board


In the previous section, we show how we can drive the bipolar stepper motor and the
unipolar stepper motor with the L293D chip. The Handy Board also has two on-board
L293D chips which can drive up to 4 DC motors. As mentioned before, stepper motors
are simply two(or more) coils that are driven in sequences. So, in theory, we can drive
stepper motors using the motor drivers on the Handy Board directly.

Bipolar stepper motor

The pulse sequence of driving the bipolar stepper motor shown in the previous section
can be interpreted as driving two different motors forwards and backwards. So, we can
use the IC library functions for controlling the DC motors to drive the stepper motors, if
we generate the correct pulse sequence. In the IC library, the function fd( ) is used to
drive the DC motor in the forward direction and the function bk( ) is used to drive the DC
motor in the backward direction. So, the fd ( ) fucntion will set one end of the
corresponding motor high and the other end low. The bk ( ) function will just set the
polarity of the motor in an opposite way. For example, the code fd(0) will set the the
positive end of motor 0 to high (+5V) and the negative end of motor 0 to low (0V). So,
we can generate the same pulse sequence as the one shown in the previous section, using
a sequence of fd( ) and bk( ) functions. Suppose we plug coil 1 of the stepper motor into
the motor 0 input of the Handy Board and coil 2 of the stepper motor into the motor 1
input of the Handy Board. The following C code fragment will generate the correct
sequence of driving the stepper motor:

void main()
{ float x=0.001;
while(1){
fd(0);
fd(1);
sleep(x);
bk(0);
fd(1);
sleep(x);
bk(0);
bk(1);
sleep(x);
fd(0);
bk(1);
sleep(x);
}
}

Again, the variable x controls how long the processor should wait between each step and
it determines the speed of the stepper motor. In the above example, the motor is set to
rotate forever but you can use a for loop instead to set how much the motor should turn.

Unipolar Stepper Motor

Driving a unipolar stepper motor using the Handy Board directly is the same as driving
the bipolar stepper motor with the Handy Board. You can use the same code fragment to
drive the unipolar stepper motor. The only difference is you have to connect the extra
common wire to the +5V supply.
P89V51RD2
8-bit 80C51 5 V low power 16/32/64 kB Flash microcontroller
with 1 kB RAM

General description
The P89V51RB2/RC2/RD2 are 80C51 microcontrollers with 16/32/64 kB Flash and
1024 bytes of data RAM.

A key feature of the P89V51RB2/RC2/RD2 is its X2 mode option. The design


engineer can choose to run the application with the conventional 80C51 clock rate
(12 clocks per machine cycle) or select the X2 mode (6 clocks per machine cycle) to
achieve twice the throughput at the same clock frequency. Another way to benefit
from this feature is to keep the same performance by reducing the clock frequency by
half, thus dramatically reducing the EMI.

The Flash program memory supports both parallel programming and in serial
In-System Programming (ISP). Parallel programming mode offers gang-programming
at high speed, reducing programming costs and time to market. ISP allows a device
to be reprogrammed in the end product under software control. The capability to
field/update the application firmware makes a wide range of applications possible.

The P89V51RB2/RC2/RD2 is also In-Application Programmable (IAP), allowing the


Flash program memory to be reconfigured even while the application is running.

Features
80C51 Central Processing Unit
5 V Operating voltage from 0 MHz to 40 MHz
16/32/64 kB of on-chip Flash user code memory with ISP (
Programming) and IAP (In-Application Programming)
Supports 12-clock (default) or 6-clock mode selection via software
SPI (Serial Peripheral Interface) and enhanced UART
PCA (Programmable Counter Array) with PWM and Capture/
Four 8-bit I/O ports with three high-current Port 1 pins (16
Three 16-bit timers/counters
Programmable watchdog timer
Eight interrupt sources with four priority levels
Second DPTR register
Low EMI mode (ALE inhibit)
TTL- and CMOS-compatible logic levels
Brown-out detection
Low power modes
-Power-down mode with external interrupt wake-up
-Idle mode
DIP40, PLCC44 and TQFP44 packages
Block diagram

P89V51RB2/RC2/RD2 block diagram.


Symbol Pin Type Description
P0.0 to P0.7 39-32 I/O Port 0: Port 0 is an 8-bit
open drain bi-directional
I/O
port. Port 0 pins that have
‘1’s written to them float,
and
in this state can be used
as high-impedance
inputs.
Port 0 is also the
multiplexed low-order
address and
data bus during accesses
to external code and data
memory. In this
application, it uses strong
internal
pull-ups when
transitioning to ‘1’s. Port 0
also receives
the code bytes during the
external host mode
programming, and
outputs the code bytes
during the
external host mode
verification. External pull-
ups are
required during program
verification or as a
general
purpose I/O port.

P1.0 to P1.7 1-8 I/O with internal pull-up Port 1: Port 1 is an 8-bit
bi-directional I/O port with
internal pull-ups. The Port
1 pins are pulled high by
the
internal pull-ups when ‘1’s
are written to them and
can
be used as inputs in this
state. As inputs, Port 1
pins that
are externally pulled LOW
will source current (IIL)
because of the internal
pull-ups. P1.5, P1.6, P1.7
have
high current drive of 16
mA. Port 1 also receives
the
low-order address bytes
during the external host
mode
programming and
verification.
P1.0 1 I/O T2: External count input
to Timer/Counter 2 or
Clock-out from
Timer/Counter 2

P1.1 2 I T2EX: Timer/Counter 2


capture/reload trigger and
direction control

P1.2 3 I ECI: External clock input.


This signal is the external
clock input for the PCA.

P1.3 4 I/O CEX0: Capture/compare


external I/O for PCA
Module 0.
Each capture/compare
module connects to a
Port 1 pin
for external I/O. When not
used by the PCA, this pin
can
handle standard I/O.

P1.4 5 I/O SS: Slave port select


input for SPI
CEX1: Capture/compare
external I/O for PCA
Module 1

P1.5 6 I/O MOSI: Master Output


Slave Input for SPI
CEX2: Capture/compare
external I/O for PCA
Module 2

P1.6 7 I/O MISO: Master Input Slave


Output for SPI
CEX3: Capture/compare
external I/O for PCA
Module 3

P1.7 8 I/O SCK: Master Output


Slave Input for SPI
CEX4: Capture/compare
external I/O for PCA
Module 4

P2.0 toP2.7 21-28 I/O Port 2: Port 2 is an 8-bit


with internal bi-directional I/O port with
pull-up internal pull-ups. Port 2
pins are pulled HIGH by
the
internal pull-ups when ‘1’s
are written to them and
can
be used as inputs in this
state. As inputs, Port 2
pins that
are externally pulled LOW
will source current (IIL)
because of the internal
pull-ups. Port 2 sends the
high-order address byte
during fetches from
external
program memory and
during accesses to
external Data
Memory that use 16-bit
address (MOVX@DPTR).
In this
application, it uses strong
internal pull-ups when
transitioning to ‘1’s. Port 2
also receives some
control
signals and a partial of
high-order address bits
during
the external host mode
programming and
verification.

P3.0 to 10-17 I/O Port 3: Port 3 is an 8-bit


P3.7 with internal bidirectional I/O port with
pull-up internal pull-ups. Port 3
pins are pulled HIGH by
the
internal pull-ups when ‘1’s
are written to them and
can
be used as inputs in this
state. As inputs, Port 3
pins that
are externally pulled LOW
will source current (IIL)
because of the internal
pull-ups. Port 3 also
receives
some control signals and
a partial of high-order
address
bits during the external
host mode programming
and
verification.

P3.0 10 I RXD: serial input port

P3.1 11 O TXD: serial output port

P3.2 12 I INT0: external interrupt 0


input

P3.3 13 I INT1: external interrupt 1


input
P3.4 14 I T0: external count input
to Timer/Counter 0

P3.5 15 I T1: external count input


to Timer/Counter 1

P3.6 16 O WR: external data


memory write strobe

P3.7 17 O RD: external data


memory read strobe

PSEN 29 I/O Program Store Enable:


PSEN is the read strobe
for
external program
memory. When the
device is executing
from internal program
memory, PSEN is
inactive
(HIGH). When the device
is executing code from
external program
memory, PSEN is
activated twice each
machine cycle, except
that two PSEN activations
are
skipped during each
access to external data
memory. A
forced HIGH-to-LOW
input transition on the
PSEN pin
while the RST input is
continually held HIGH for
more
than 10 machine cycles
will cause the device to
enter
external host mode
programming.

RST 9 I Reset: While the


oscillator is running, a
HIGH logic state
on this pin for two
machine cycles will reset
the device. If
the PSEN pin is driven by
a HIGH-to-LOW input
transition while the RST
input pin is held HIGH,
the
device will enter the
external host mode,
otherwise the
device will enter the
normal operation mode.
EA 31 I External Access
Enable: EA must be
connected to VSS
in order to enable the
device to fetch code from
the
external program
memory. EA must be
strapped to VDD
for internal program
execution. However,
Security lock
level 4 will disable EA,
and program execution is
only
possible from internal
program memory. The EA
pin can
tolerate a high voltage of
12 V.

ALE/ 30 I/O Address Latch Enable:


PROG ALE is the output signal
for
latching the low byte of
the address during an
access to
external memory. This pin
is also the programming
pulse input (PROG) for
flash programming.
Normally the
ALE[1] is emitted at a
constant rate of 1⁄ 6 the
crystal
frequency[2] and can be
used for external timing
and
clocking. One ALE pulse
is skipped during each
access
to external data memory.
However, if AO is set to
‘1’,
ALE is disabled.

NC - I/O No Connect
XTAL1

XTAL1 19 I Crystal 1: Input to the


inverting oscillator
amplifier and
input to the internal clock
generator circuits.

XTAL2 18 O Crystal 2: Output from


the inverting oscillator
amplifier.
VDD 40 I Power supply

VSS 20 I Ground

[1] ALE loading issue: When ALE pin experiences higher loading (>30 pF) during
the reset, the microcontroller may accidentally enter into
modes other than normal working mode. The solution is to add a pull-up resistor
of 3 kΩ to 50 kΩ to VDD, e.g., for ALE pin.
[2] For 6-clock mode, ALE is emitted at 1⁄ 3 of crystal frequency.

Special function registers

Remark: Special Function Registers (SFRs) accesses are restricted in the


following
ways:
• User must not attempt to access any SFR locations not defined.
• Accesses to any defined SFR locations must be strictly for the functions for the
SFRs.
• SFR bits labeled ‘-’, ‘0’ or ‘1’ can only be written and read as follows:
– ‘-’ Unless otherwise specified, must be written with ‘0’, but can return any value
when read (even if it was written with ‘0’). It is a reserved bit and may be used in
future derivatives.
– ‘0’ must be written with ‘0’, and will return a ‘0’ when read.
– ‘1’ must be written with ‘1’, and will return a ‘1’ when read.

Functional description

Memory organization

The device has separate address spaces for program and data memory.

Flash program memory bank selection

There are two internal flash memory blocks in the device. Block 0 has 16/32/64
kB and is organized as 128/256/512 sectors, each sector consists of 128 Bytes.
Block contains the IAP/ISP routines and may be enabled such that it overlays the
first 8 kB of the user code memory. The overlay function is controlled by the
combination of the Software Reset Bit (SWR) at FCF.1 and the Bank Select Bit
(BSEL) at FCF.0. The combination of these bits and the memory source used for
instructions is shown in the below Table.

Table: Code memory bank selection

SWR (FCF.1) BSEL (FCF.0) addresses from 0000h addresses above 1FFFh
to 1FFFh

0 0 Bootcode (in Block 1) User code (in Block 0)

0 1 User code (in Block 0)

1 0

1 1

Access to the IAP routines in Block 1 may be enabled by clearing the BSEL bit
(FCF.0), provided that the SWR bit (FCF.1) is cleared. Following a power-on
sequence, the bootcode is automatically executed and attempts to autobaud to a
host. If no autobaud occurs within approximately 400 ms and the SoftICE flag is
not set, control will be passed to the user code. A software reset is used to
accomplish this control transfer and as a result the SWR bit will remain set.
Therefore the user's code will need to clear the SWR bit in order to access
the IAP routines in Block
However, caution must be taken when dynamically changing the BSEL bit. Since
this will cause different physical memory to be mapped to the logical program
address space, the user must avoid clearing the BSEL bit when executing
user code within the address range 0000H to 1FFFH.

Power-on reset code execution

At initial power up, the port pins will be in a random state until the oscillator has
started and the internal reset algorithm has weakly pulled all pins high. Powering
up the device without a valid reset could cause the MCU to start executing
instructions from an indeterminate location. Such undefined states may
inadvertently corrupt the code in the flash. A system reset will not affect the 1 kB
of on-chip RAM while the device is running, however, the contents of the on-chip
RAM during power up are indeterminate.
When power is applied to the device, the RST pin must be held high long enough
for the oscillator to start up (usually several milliseconds for a low frequency
crystal), in addition to two machine cycles for a valid power-on reset. An example
of a method to extend the RST signal is to implement a RC circuit by connecting
the RST pin to VDD through a 10 F capacitor and to VSS through an 8.2KW
resistor as shown in the above table.
Note that if an RC circuit is being used, provisions should be made to
ensure the VDD rise time does not exceed 1 millisecond and the oscillator start-
up time does not exceed 10 milliseconds.
For a low frequency oscillator with slow start-up time the reset signal must be
extended in order to account for the slow start-up time. This method maintains
the necessary relationship between VDD and RST to avoid programming at an
indeterminate location, which may cause corruption in the code of the flash. The
power-on detection is designed to work during initial power up, before the voltage
reaches the brown-out detection level. The POF flag in the PCON register is set
to indicate an initial power up condition. The POF flag will remain active until
cleared by software.
Following a power-on or external reset the P89V51RB2/RC2/RD2 will force the
SWR and BSEL bits (FCF[1:0]) = 00. This causes the bootblock to be mapped
into the lower 8 kB of code memory and the device will execute the ISP code in
the boot block and attempt to autobaud to the host. If the autobaud is successful
the device will remain in ISP mode. If, after approximately 400 ms, the autobaud
is unsuccessful the boot block code will check to see if the SoftICE flag is set
(from a previous programming operation). If the SoftICE flag is set the device will
enter SoftICE mode. If the SoftICE flag is cleared, the bootcode will execute a
software reset causing the device to execute the user code from block 0 starting
at address 0000h. Note that an external reset applied to the RST pin has the
same effect as a power-on reset.
Power-on reset circuit.

Software reset

A software reset is executed by changing the SWR bit (FCF.1) from ‘0’ to ‘1’. A
software reset will reset the program counter to address 0000H and force both
the SWR and BSEL bits (FCF[1:0]) =10. This will result in the lower 8 kB of the
user code memory being mapped into the user code memory space. Thus the
user's code will be executed starting at address 0000h. A software reset will not
change WDTC.2 or RAM data. Other SFRs will be set to their reset values.

Brown-out detect reset

The device includes a brown-out detection circuit to protect the system from
severe supply voltage fluctuations. The P89V51RB2/RC2/RD2's brown-out
detection threshold is 2.35 V. When VDD drops below this voltage threshold, the
brown-out detect triggers the circuit to generate a brown-out interrupt but the
CPU still runs until the supplied voltage returns to the brown-out detection
voltage VBOD. The default operation for a brown-out detection is to cause a
processor reset.
VDD must stay below VBOD at least four oscillator clock periods before the
brown-out detection circuit will respond.
Brown-out interrupt can be enabled by setting the EBO bit (IEA.3). If EBO bit is
set and a brown-out condition occurs, a brown-out interrupt will be generated to
execute the program at location 004BH. It is required that the EBO bit be cleared
by software after the brown-out interrupt is serviced. Clearing EBO bit when the
brown-out condition is active will properly reset the device. If brown-out interrupt
is not enabled, a brown-out condition will reset the program to resume execution
at location 0000H.
A brown-out detect reset will clear the BSEL bit (FCF.0) but will not change the
SWR bit (FCF.1) and therefore will not change the banking of the lower 8 kB of
user code memory space.

Watchdog reset

Like a brown-out detect reset, the watchdog timer reset will clear the BSEL bit
(FCF.0) but will not change the SWR bit (FCF.1) and therefore will not change
the banking of the lower 8 kB of user code memory space.

The state of the SWR and BSEL bits after different types of resets is shown in
Below table. This results in the code memory bank selections as shown.

Reset source SWR bit result BSEL bit result addresses from addresses above
(FCF.1) (FCF.0) 0000h to 1FFFh
1FFFh

External reset 0 0 Bootcode (in Block 1) User code (in Block 0)

Power-on reset

Watchdog reset x 0 Retains state of


SWR bit. If SWR,
BSEL = 00 then uses
Bootcode.
If SWR, BSEL = 10
then uses
user code.

Brown-out detect Retains state of


reset SWR bit. If SWR,
BSEL = 00 then uses
Bootcode.
If SWR, BSEL = 10
then uses
user code.
Software reset 1 0 User code (in Block
0)

Data RAM memory

The data RAM has 1024 bytes of internal memory. The device can also address
up to 64 kB for external data memory.

Expanded data RAM addressing

The P89V51RB2/RC2/RD2 has 1 kB of RAM.

The device has four sections of internal data memory:

1. The lower 128 bytes of RAM (00H to 7FH) are directly and indirectly
addressable.

2. The higher 128 bytes of RAM (80H to FFH) are indirectly addressable.
3. The special function registers (80H to FFH) are directly addressable only.
4. The expanded RAM of 768 bytes (00H to 2FFH) is indirectly addressable by
the move external instruction (MOVX) and clearing the EXTRAM bit.

Since the upper 128 bytes occupy the same addresses as the SFRs, the RAM
must be accessed indirectly. The RAM and SFRs space are physically separate
even though they have the same addresses.

AUXR - Auxiliary register (address 8EH) bit allocation


Bit 7 6 5 4 3 2 1 0
Symbol - - - - - - EXTRAM AO

AUXR - Auxiliary register (address 8EH) bit description

Bit Symbol Description

7 to 2 - Reserved for future use. Should be


set to ‘0’ by user programs.

1 EXTRAM
Internal/External RAM access using
MOVX @Ri/@DPTR.
When ‘0’, core attempts to access
internal XRAM with address
specified in MOVX instruction. If
address supplied with this
instruction exceeds on-chip
available XRAM, off-chip XRAM is
going to be selected and accessed.
When ‘1’, every MOVX
@Ri/@DPTR instruction targets
external
data memory by default.

0 AO ALE off: disables/enables ALE. AO


= 0 results in ALE emitted at a
constant rate of 1⁄ 2 the oscillator
frequency. In case of AO = 1, ALE
is active only during a MOVX or
MOVC.

When instructions access addresses in the upper 128 bytes (above 7FH), the
MCU determines whether to access the SFRs or RAM by the type of instruction
given. If it is indirect, then RAM is accessed. If it is direct, then an SFR is
accessed. See the examples below.
Indirect Access:

MOV@R0, #data; R0 contains 90H

Register R0 points to 90H which is located in the upper address range. Data in
‘#data’ is written to RAM location 90H rather than port 1.
Direct Access:

MOV90H, #data; write data to P1


Data in ‘#data’ is written to port 1. Instructions that write directly to the address
write to the SFRs.
To access the expanded RAM, the EXTRAM bit must be cleared and MOVX
instructions must be used. The extra 768 bytes of memory is physically located
on the chip and logically occupies the first 768 bytes of external memory
(addresses 000H to 2FFH).

When EXTRAM = 0, the expanded RAM is indirectly addressed using the MOVX
instruction in combination with any of the registers R0, R1 of the selected bank or
DPTR. Accessing the expanded RAM does not affect ports P0, P3.6 (WR), P3.7
(RD), or P2. With EXTRAM = 0, the expanded RAM can be accessed as in the
following example.

Expanded RAM Access (Indirect Addressing only):

MOVX@DPTR, A DPTR contains 0A0H

DPTR points to 0A0H and data in ‘A’ is written to address 0A0H of the expanded
RAM rather than external memory. Access to external memory higher than 2FFH
using the MOVX instruction will access external memory (0300H to FFFFH) and
will perform in the same way as the standard 8051, with P0 and P2 as
data/address bus, and P3.6 and P3.7 as write and read timing signals.

When EXTRAM = 1, MOVX @Ri and MOVX @DPTR will be similar to the
standard 8051. Using MOVX @Ri provides an 8-bit address with multiplexed
data on Port 0.

Other output port pins can be used to output higher order address bits. This
provides external paging capabilities. Using MOVX @DPTR generates a 16-bit
address. This allows external addressing up the 64 kB. Port 2 provides the high-
order eight address bits (DPH), and Port 0 multiplexes the low order eight
address bits (DPL) with data.

Both MOVX @Ri and MOVX @DPTR generates the necessary read and write
signals (P3.6 - WR and P3.7 - RD) for external memory use. Table 9 shows
external data memory RD, WR operation with EXTRAM bit.

The stack pointer (SP) can be located anywhere within the 256 bytes of internal
RAM (lower 128 bytes and upper 128 bytes). The stack pointer may not be
located in any part of the expanded RAM.

External data memory RD, WR with EXTRAM bit

[1] Access limited to ERAM address within 0 to 0FFH; cannot access 100H to
02FFH.
Internal and external data memory structure.

Dual data pointers

The device has two 16-bit data pointers. The DPTR Select (DPS) bit in AUXR1
determines which of the two data pointers is accessed. When DPS = 0, DPTR0 is
selected; when DPS = 1, DPTR1 is selected. Quickly switching between the two
data pointers can be accomplished by a single INC instruction on AUXR1 (see
below figure)
Dual data pointer organization.

AUXR1 - Auxiliary register 1 (address A2H) bit allocation


Not bit addressable; Reset value 00H

Flash memory In-Application Programming

Flash organization

The P89V51RB2/RC2/RD2 program memory consists of a 16/32/64 kB block. An


In-System Programming (ISP) capability, in a second 8 kB block, is provided to
allow the user code to be programmed in-circuit through the serial port. There are
three methods of erasing or programming of the Flash memory that may be
used. First, the Flash may be programmed or erased in the end-user application
by calling low-level routines through a common entry point (IAP). Second, the on-
chip ISP boot loader may be invoked. This ISP boot loader will, in turn, call low-
level routines through the same common entry point that can be used by the end-
user application. Third, the Flash may be programmed or erased using the
parallel method by using a commercially available EPROM programmer which
supports this device.

Boot block (Block 1)

When the microcontroller programs its own Flash memory, all of the low level
details are handled by code that is contained in Block 1. A user program calls the
common entry point in the Block 1 with appropriate parameters to accomplish the
desired operation. Boot block operations include erase user code, program user
code, program security bits, etc.

A Chip-Erase operation can be performed using a commercially available parallel


programer. This operation will erase the contents of this Boot Block and it will be
necessary for the user to reprogram this Boot Block (Block 1) with the
Philips-provided ISP/IAP code in order to use the ISP or IAP capabilities of this
device.

In-System Programming (ISP)

In-System Programming is performed without removing the microcontroller from


the system. The In-System Programming facility consists of a series of internal
hardware resources coupled with internal firmware to facilitate remote
programming of the P89V51RB2/RC2/RD2 through the serial port. This firmware
is provided by Philips and embedded within each P89V51RB2/RC2/RD2 device.
The Philips In-System Programming facility has made in-circuit programming in
an embedded application possible with a minimum of additional expense in
components and circuit board area.
The ISP function uses five pins (VDD, VSS, TxD, RxD, and RST). Only a small
connector needs to be available to interface your application to an external circuit
in order to use this feature.

Using the In-System Programming

The ISP feature allows for a wide range of baud rates to be used in your application,
independent of the oscillator frequency. It is also adaptable to a wide range of
oscillator frequencies. This is accomplished by measuring the bit-time of a single bit
in a received character. This information is then used to program the baud rate in
terms of timer counts based on the oscillator frequency. The ISP feature requires that
an initial character (an uppercase U) be sent to the P89V51RB2/RC2/RD2 to
establish the baud rate. The ISP firmware provides auto-echo of received characters.
Once baud rate initialization has been performed, the ISP firmware will only accept
Intel Hex-type records. Intel Hex records consist of ASCII characters used to
represent hexadecimal values and are summarized below:
:NNAAAARRDD..DDCC<crlf>
In the Intel Hex record, the ‘NN’ represents the number of data bytes in the record.
The P89V51RB2/RC2/RD2 will accept up to 32 data bytes. The ‘AAAA’ string
represents the address of the first byte in the record. If there are zero bytes in the
record, this field is often set to 0000. The ‘RR’ string indicates the record type. A
record type of ‘00’ is a data record. A record type of ‘01’ indicates the end-of-file
mark. In this application, additional record types will be added to indicate either
commands or data for the ISP facility.
The maximum number of data bytes in a record is limited to 32 (decimal). ISP
commands are summarized in Table given below.. As a record is received by the
P89V51RB2/RC2/RD2, the information in the record is stored internally and a
checksum calculation is performed. The operation indicated by the record type is not
performed until the entire record has been received. Should an error occur in the
checksum, the P89V51RB2/RC2/RD2 will send an ‘X’ out the serial port indicating a
checksum error. If the checksum calculation is found to match the checksum in the
record, then the command will be executed. In most cases, successful reception of
the record will be indicated by transmitting a ‘.’ character out the serial port.

In-System Programming (ISP) hex record formats


In-System Programming (ISP) hex record formats …continued
In-System Programming (ISP) hex record formats …continued
In-System Programming (ISP) hex record formats …continued
Using the serial number

This device has the option of storing a 31-byte serial number along with the length of
the serial number (for a total of 32 bytes) in a non-volatile memory space. When ISP
mode is entered, the serial number length is evaluated to determine if the serial
number is in use. If the length of the serial number is programmed to either 00H or
FFH, the serial number is considered not in use. If the serial number is in use,
reading, programming, or erasing of the user code memory or the serial number is
blocked until the user transmits a ‘verify serial number’ record containing a serial
number and length that matches the serial number and length previously stored in the
device. The user can reset the serial number to all zeros and set the length to zero by
sending the ‘reset serial number' record. In addition, the ‘reset serial number’ record
will also erase all user code.

In-Application Programming method

Several In-Application Programming (IAP) calls are available for use by an application
program to permit selective erasing, reading and programming of Flash sectors,
security bit, configuration bytes, and device id. All calls are made through a common
interface, PGM_MTP. The programming functions are selected by setting up the
microcontroller’s registers before making a call to PGM_MTP at 1FF0H. The IAP calls
are shown in Table below.
IAP function calls
IAP function calls …continued

Timers/counters 0 and 1

The two 16-bit Timer/Counter registers: Timer 0 and Timer 1 can be configured to
operate either as timers or event counters (see Tables below).
In the ‘Timer’ function, the register is incremented every machine cycle. Thus, one
can think of it as counting machine cycles. Since a machine cycle consists of six
oscillator periods, the count rate is 1⁄ 6 of the oscillator frequency.
In the ‘Counter’ function, the register is incremented in response to a 1-to-0 transition
at its corresponding external input pin, T0 or T1. In this function, the external input is
sampled once every machine cycle.
When the samples show a high in one cycle and a low in the next cycle, the count is
incremented. The new count value appears in the register in the machine cycle
following the one in which the transition was detected. Since it takes two machine
cycles (12 oscillator periods) for 1-to-0 transition to be recognized, the maximum
count rate is 1⁄ 12 of the oscillator frequency. There are no restrictions on the duty cycle
of the external input signal, but to ensure that a given level is sampled at least once
before it changes, it should be held for at least one full machine cycle. In addition to
the ‘Timer’ or ‘Counter’ selection, Timer 0 and Timer 1 have four operating modes
from which to select.
The ‘Timer’ or ‘Counter’ function is selected by control bits C/T in the Special
Function Register TMOD. These two Timer/Counters have four operating modes,
which are selected by bit-pairs (M1, M0) in TMOD. Modes 0, 1, and 2 are the same
for both Timers/Counters. Mode 3 is different. The four operating modes are
described in the following text.

TMOD - Timer/Counter mode control register (address 89H) bit allocation


Not bit addressable; Reset value: 00000000B; Reset source(s): any source

TMOD - Timer/Counter mode control register (address 89H) bit description

TMOD - Timer/Counter mode control register (address 89H) M1/M0


operating mode
TCON - Timer/Counter control register (address 88H) bit allocation

Bit addressable; Reset value: 00000000B; Reset source(s): any reset

TCON - Timer/Counter control register (address 88H) bit description

TCON - Timer/Counter control register (address 88H) bit description


Mode 0

Putting either Timer into Mode 0 makes it look like an 8048 Timer, which is an 8-bit
Counter with a fixed divide-by-32 prescaler. Figure below shows Mode 0 operation.

Timer/Counter 0 or 1 in Mode 0 (13-bit counter).

In this mode, the Timer register is configured as a 13-bit register. As the count rolls
over from all 1s to all 0s, it sets the Timer interrupt flag TFn. The count input is
enabled to the Timer when TRn = 1 and either GATE = 0 or INTn = 1. (Setting
GATE = 1 allows the Timer to be controlled by external input INTn, to facilitate pulse
width measurements). TRn is a control bit in the Special Function Register TCON
(Figure). The GATE bit is in the TMOD register.
The 13-bit register consists of all 8 bits of THn and the lower 5 bits of TLn. The upper
3 bits of TLn are indeterminate and should be ignored. Setting the run flag (TRn)
does not clear the registers.
Mode 0 operation is the same for Timer 0 and Timer 1 (see Figure). There are two
different GATE bits, one for Timer 1 (TMOD.7) and one for Timer 0 (TMOD.3).

Mode 1

Mode 1 is the same as Mode 0, except that all 16 bits of the timer register (THn and
TLn) are used. See Figure.

Timer/Counter 0 or 1 in Mode 1 (16-bit counter).


Mode 2
Mode 2 configures the Timer register as an 8-bit Counter (TLn) with automatic reload,
as shown in Figure . Overflow from TLn not only sets TFn, but also reloads TLn
with the contents of THn, which must be preset by software. The reload leaves THn
unchanged. Mode 2 operation is the same for Timer 0 and Timer 1.

Timer/Counter 0 or 1 in Mode 2 (8-bit auto-reload).

Mode 3

When timer 1 is in Mode 3 it is stopped (holds its count). The effect is the same as
setting TR1 = 0.
Timer 0 in Mode 3 establishes TL0 and TH0 as two separate 8-bit counters. The logic
for Mode 3 and Timer 0 is shown in Figure . TL0 uses the Timer 0 control bits:
T0C/T, T0GATE, TR0, INT0, and TF0. TH0 is locked into a timer function (counting
machine cycles) and takes over the use of TR1 and TF1 from Timer 1. Thus, TH0
now controls the ‘Timer 1’ interrupt.
Mode 3 is provided for applications that require an extra 8-bit timer. With Timer 0 in
Mode 3, the P89V51RB2/RC2/RD2 can look like it has an additional Timer.
Note: When Timer 0 is in Mode 3, Timer 1 can be turned on and off by switching it
into and out of its own Mode 3. It can still be used by the serial port as a baud rate
generator, or in any application not requiring an interrupt.

Timer/Counter 0 Mode 3 (two 8-bit counters).

Timer 2
Timer 2 is a 16-bit Timer/Counter which can operate as either an event timer or an
event counter, as selected by C/T2 in the special function register T2CON. Timer 2
has four operating modes: Capture, Auto-reload (up or down counting), Clock-out,
and Baud Rate Generator which are selected according to Table given below using T2CON
(Tables below ) and T2MOD (Tables below ).

Timer 2 operating mode

T2CON - Timer/Counter 2 control register (address C8H) bit allocation

Bit addressable; Reset value: 00H


T2CON - Timer/Counter 2 control register (address C8H) bit description

T2MOD - Timer 2 mode control register (address C9H) bit allocation

Not bit addressable; Reset value: XX000000B

T2MOD - Timer 2 mode control register (address C9H) bit description


Capture mode

In the Capture Mode there are two options which are selected by bit EXEN2 in
T2CON. If EXEN2 = 0 Timer 2 is a 16-bit timer or counter (as selected by C/T2 in
T2CON) which upon overflowing sets bit TF2, the Timer 2 overflow bit.

The capture mode is illustrated in Figure below.

Timer 2 in Capture Mode.

This bit can be used to generate an interrupt (by enabling the Timer 2 interrupt bit in
the IEN0 register). If EXEN2 = 1, Timer 2 operates as described above, but with the
added feature that a 1- to -0 transition at external input T2EX causes the current
value in the Timer 2 registers, TL2 and TH2, to be captured into registers RCAP2L
and RCAP2H, respectively.

In addition, the transition at T2EX causes bit EXF2 in T2CON to be set, and EXF2 like
TF2 can generate an interrupt (which vectors to the same location as Timer 2
overflow interrupt). The Timer 2 interrupt service routine can interrogate TF2 and
EXF2 to determine which event caused the interrupt.

There is no reload value for TL2 and TH2 in this mode. Even when a capture event
occurs from T2EX, the counter keeps on counting T2 pin transitions or fosc/6 pulses.
Since once loaded contents of RCAP2L and RCAP2H registers are not protected,
once Timer2 interrupt is signalled it has to be serviced before new capture event on
T2EX pin occurs. Otherwise, the next falling edge on T2EX pin will initiate reload of
the current value from TL2 and TH2 to RCAP2L and RCAP2H and consequently
corrupt their content related to previously reported interrupt.

Auto-reload mode (up or down counter)

In the 16-bit auto-reload mode, Timer 2 can be configured as either a timer or counter
(via C/T2 in T2CON), then programmed to count up or down. The counting direction
is determined by bit DCEN (Down Counter Enable) which is located in the T2MOD
register (see respective tables). When reset is applied, DCEN = 0 and Timer 2
will default to counting up. If the DCEN bit is set, Timer 2 can count up or down
depending on the value of the T2EX pin.

Below figure shows Timer 2 counting up automatically (DCEN = 0).

Timer 2 in auto-reload mode (DCEN = 0)

In this mode, there are two options selected by bit EXEN2 in T2CON register. If
EXEN2 = 0, then Timer 2 counts up to 0FFFFH and sets the TF2 (Overflow Flag) bit
upon overflow. This causes the Timer 2 registers to be reloaded with the 16-bit value
in RCAP2L and RCAP2H. The values in RCAP2L and RCAP2H are preset by
software means.

If EXEN2 = 1, a 16-bit reload can be triggered either by an overflow or by a 1-to-0


transition at input T2EX. This transition also sets the EXF2 bit. The Timer 2 interrupt,
if enabled, can be generated when either TF2 or EXF2 is ‘1’.

Microcontroller’s hardware will need three consecutive machine cycles in order to


recognize falling edge on T2EX and set EXF2 = 1: in the first machine cycle pin T2EX
has to be sampled as ‘1’; in the second machine cycle it has to be sampled as ‘0’, and
in the third machine cycle EXF2 will be set to ‘1’.

In the below Figure , DCEN = 1 and Timer 2 is enabled to count up or down. This mode
allows pin T2EX to control the direction of count. When a logic ‘1’ is applied at pin
T2EX Timer 2 will count up. Timer 2 will overflow at 0FFFFH and set the TF2 flag,
which can then generate an interrupt, if the interrupt is enabled. This timer overflow
also causes the 16-bit value in RCAP2L and RCAP2H to be reloaded into the timer
registers TL2 and TH2.
When a logic 0 is applied at pin T2EX this causes Timer 2 to count down. The timer
will underflow when TL2 and TH2 become equal to the value stored in RCAP2L and
RCAP2H. Timer 2 underflow sets the TF2 flag and causes 0FFFFH to be reloaded
into the timer registers TL2 and TH2. The external flag EXF2 toggles when Timer 2
underflows or overflows. This EXF2 bit can be used as a 17th bit of resolution if
needed.

Programmable clock-out

A 50 % duty cycle clock can be programmed to come out on pin T2 (P1.0). This pin,
besides being a regular I/O pin, has two additional functions. It can be programmed:
1. To input the external clock for Timer/Counter 2, or
2. To output a 50 % duty cycle clock ranging from 122 Hz to 8 MHz at a 16 MHz
operating frequency.
To configure the Timer/Counter 2 as a clock generator, bit C/T2 (in T2CON) must be
cleared and bit T20E in T2MOD must be set. Bit TR2 (T2CON.2) also must be set to
start the timer.

In the Clock-Out mode Timer 2 roll-overs will not generate an interrupt. This is similar
to when it is used as a baud-rate generator.

Baud rate generator mode

Bits TCLK and/or RCLK in T2CON allow the UART) transmit and receive baud rates
to be derived from either Timer 1 or Timer 2 (See next Section “UARTs” on ). When TCLK = 0,
Timer 1 is used as the UART transmit baud rate generator.

When TCLK = 1, Timer 2 is used as the UART transmit baud rate generator. RCLK
has the same effect for the UART receive baud rate. With these two bits, the serial
port can have different receive and transmit baud rates – Timer 1 or Timer 2.
Figure below shows Timer 2 in baud rate generator mode:

Timer 2 in Baud Rate Generator mode.

The baud rate generation mode is like the auto-reload mode, when a rollover in TH2
causes the Timer 2 registers to be reloaded with the 16-bit value in registers
RCAP2H and RCAP2L, which are preset by software.

The baud rates in modes 1 and 3 are determined by Timer 2’s overflow rate given
below:

Modes 1 and 3 Baud Rates = Timer 2 Overflow Rate/16


The timer can be configured for either ‘timer’ or ‘counter’ operation. In many
applications, it is configured for ‘timer' operation (C/T2 = 0). Timer operation is
different for Timer 2 when it is being used as a baud rate generator.

The Timer 2 as a baud rate generator mode is valid only if RCLK and/or TCLK = 1 in
T2CON register. Note that a rollover in TH2 does not set TF2, and will not generate
an interrupt. Thus, the Timer 2 interrupt does not have to be disabled when Timer 2 is
in the baud rate generator mode. Also if the EXEN2 (T2 external enable flag) is set, a
1-to-0 transition in T2EX (Timer/counter 2 trigger input) will set EXF2 (T2 external
flag) but will not cause a reload from (RCAP2H, RCAP2L) to (TH2,TL2). Therefore
when Timer 2 is in use as a baud rate generator, T2EX can be used as an additional
external interrupt, if needed.

When Timer 2 is in the baud rate generator mode, one should not try to read or write
TH2 and TL2. Under these conditions, a read or write of TH2 or TL2 may not be
accurate. The RCAP2 registers may be read, but should not be written to, because a
write might overlap a reload and cause write and/or reload errors. The timer should
be turned off (clear TR2) before accessing the Timer 2 or RCAP2 registers. Table below
shows commonly used baud rates and how they can be obtained from Timer 2.

Summary of baud rate equations

Timer 2 is in baud rate generating mode. If Timer 2 is being clocked through pin
T2(P1.0) the baud rate is:

Baud rate = Timer 2 overflow rate / 16

If Timer 2 is being clocked internally, the baud rate is:

Baud rate = fosc / (16 × (65536 − (RCAP2H, RCAP2L)))

Where fosc = oscillator frequency

To obtain the reload value for RCAP2H and RCAP2L, the above equation can be
rewritten as:

RCAP2H, RCAP2L = 65536 − fosc / (16 × baud rate)

Timer 2 generated commonly used baud rates

UARTs

The UART operates in all standard modes. Enhancements over the standard 80C51
UART include Framing Error detection, and automatic address recognition.

Mode 0

Serial data enters and exits through RxD and TxD outputs the shift clock. Only 8 bits
are transmitted or received, LSB first. The baud rate is fixed at 1⁄ 6 of the CPU clock
frequency. UART configured to operate in this mode outputs serial clock on TxD line
no matter whether it sends or receives data on RxD line.

Mode 1

10 bits are transmitted (through TxD) or received (through RxD): a start bit (logical 0),
8 data bits (LSB first), and a stop bit (logical 1). When data is received, the stop bit is
stored in RB8 in Special Function Register SCON. The baud rate is variable and is
determined by the Timer 1⁄ 2 overflow rate.

Mode 2

11 bits are transmitted (through TxD) or received (through RxD): start bit (logical 0), 8
data bits (LSB first), a programmable 9th data bit, and a stop bit (logical 1). When
data is transmitted, the 9th data bit (TB8 in SCON) can be assigned the value of 0 or
(e.g. the parity bit (P, in the PSW) could be moved into TB8). When data is received,
the 9th data bit goes into RB8 in Special Function Register SCON, while the stop bit
is ignored. The baud rate is programmable to either 1⁄ 16 or 1⁄ 32 of the CPU clock
frequency, as determined by the SMOD1 bit in PCON.

Mode 3

11 bits are transmitted (through TxD) or received (through RxD): a start bit (logical 0),
8 data bits (LSB first), a programmable 9th data bit, and a stop bit (logical 1). In fact,
Mode 3 is the same as Mode 2 in all respects except baud rate. The baud rate in
Mode 3 is variable and is determined by the Timer 1⁄ 2 overflow rate.

SCON - Serial port control register (address 98H) bit allocation

Bit addressable; Reset value: 00H

SCON - Serial port control register (address 98H) bit description


SCON - Serial port control register (address 98H) SM0/SM1 mode definition

Framing error

Framing error (FE) is reported in the SCON.7 bit if SMOD0 (PCON.6) = 1. If


SMOD0 = 0, SCON.7 is the SM0 bit for the UART, it is recommended that SM0 is set
up before SMOD0 is set to ‘1’.

More about UART mode 1

Reception is initiated by a detected 1-to-0 transition at RxD. For this purpose RxD is
sampled at a rate of 16 times whatever baud rate has been established. When a
transition is detected, the divide-by-16 counter is immediately reset to align its
rollovers with the boundaries of the incoming bit times.
The 16 states of the counter divide each bit time into 16ths. At the 7th, 8th, and 9th
counter states of each bit time, the bit detector samples the value of RxD. The value
accepted is the value that was seen in at least 2 of the 3 samples. This is done for
noise rejection. If the value accepted during the first bit time is not 0, the receive
circuits are reset and the unit goes back to looking for another 1-to-0 transition. This
is to provide rejection of false start bits. If the start bit proves valid, it is shifted into the
input shift register, and reception of the rest of the frame will proceed.
The signal to load SBUF and RB8, and to set RI, will be generated if, and only if, the
following conditions are met at the time the final shift pulse is generated: (a) RI = 0,
and (b) Either SM2 = 0, or the received stop bit = 1.
If either of these two conditions is not met, the received frame is irretrievably lost. If
both conditions are met, the stop bit goes into RB8, the 8 data bits go into SBUF, and
RI is activated.
More about UART modes 2 and 3

Reception is performed in the same manner as in mode 1.


The signal to load SBUF and RB8, and to set RI, will be generated if, and only if, the
following conditions are met at the time the final shift pulse is generated: (a) RI = 0,
and (b) Either SM2 = 0, or the received 9th data bit = 1.
If either of these conditions is not met, the received frame is irretrievably lost, and RI
is not set. If both conditions are met, the received 9th data bit goes into RB8, and the
first 8 data bits go into SBUF.

Multiprocessor communications

UART modes 2 and 3 have a special provision for multiprocessor communications. In


these modes, 9 data bits are received or transmitted. When data is received, the 9th
bit is stored in RB8. The UART can be programmed so that when the stop bit is
received, the serial port interrupt will be activated only if RB8 = 1. This feature is
enabled by setting bit SM2 in SCON. One way to use this feature in multiprocessor
systems is as follows:

When the master processor wants to transmit a block of data to one of several slaves,
it first sends out an address byte which identifies the target slave. An address byte
differs from a data byte in a way that the 9th bit is ‘1’ in an address byte and ‘0’ in the
data byte. With SM2 = 1, no slave will be interrupted by a data byte, i.e. the received
9th bit is ‘0’. However, an address byte having the 9th bit set to ‘1’ will interrupt all
slaves, so that each slave can examine the received byte and see if it is being
addressed or not. The addressed slave will clear its SM2 bit and prepare to receive
the data (still 9 bits long) that follow. The slaves that weren’t being addressed leave
their SM2 bits set and go on about their business, ignoring the subsequent data
bytes.

SM2 has no effect in Mode 0, and in Mode 1 can be used to check the validity of the
stop bit, although this is better done with the Framing Error flag. When UART receives
data in mode 1 and SM2 = 1, the receive interrupt will not be activated unless a valid
stop bit is received.

Automatic address recognition

Automatic Address Recognition is a feature which allows the UART to recognize


certain addresses in the serial bit stream by using hardware to make the
comparisons. This feature saves a great deal of software overhead by eliminating the
need for the software to examine every serial address which passes by the serial
port. This feature is enabled for the UART by setting the SM2 bit in SCON. In the 9 bit
UART modes, mode 2 and mode 3, the Receive Interrupt flag (RI) will be
automatically set when the received byte contains either the ‘Given’ address or the
‘Broadcast' address. The 9 bit mode requires that the 9th information bit is a ‘1’ to
indicate that the received information is an address and not data.
Using the Automatic Address Recognition feature allows a master to selectively
communicate with one or more slaves by invoking the Given slave address or
addresses. All of the slaves may be contacted by using the Broadcast address. Two
Special Function Registers are used to define the slave’s address, SADDR, and the
address mask, SADEN. SADEN is used to define which bits in the SADDR are to be
used and which bits are ‘don’t care’. The SADEN mask can be logically ANDed with
the SADDR to create the ‘Given’ address which the master will use for addressing
each of the slaves. Use of the Given address allows multiple slaves to be recognized
while excluding others.
This device uses the methods presented in below Figure to determine if a ‘Given’ or
‘Broadcast’ address has been received or not.

Schemes used by the UART to detect ‘given’ and ‘broadcast’ addresses when multiprocessor
communications is enabled

Serial peripheral interface

SPI features

• Master or slave operation


• 10 MHz bit frequency (max)
• LSB first or MSB first data transfer
• Four programmable bit rates
• End of transmission (SPIF)
• Write collision flag protection (WCOL)
• Wake-up from idle mode (slave mode only)
SPI description

The serial peripheral interface (SPI) allows high-speed synchronous data transfer
between the P89V51RB2/RC2/RD2 and peripheral devices or between several
P89V51RB2/RC2/RD2 devices. Figure below shows the correspondence between
master and slave SPI devices. The SCK pin is the clock output and input for the
master and slave modes, respectively. The SPI clock generator will start following a
write to the master devices SPI data register. The written data is then shifted out of
the MOSI pin on the master device into the MOSI pin of the slave device. Following a
complete transmission of one byte of data, the SPI clock generator is stopped and the
SPIF flag is set. An SPI interrupt request will be generated if the SPI Interrupt Enable
bit (SPIE) and the Serial Port Interrupt Enable bit (ES) are both set.
An external master drives the Slave Select input pin, SS/P1[4], low to select the SPI
module as a slave. If SS/P1[4] has not been driven low, then the slave SPI unit is not
active and the MOSI/P1[5] port can also be used as an input port pin.
CPHA and CPOL control the phase and polarity of the SPI clock. Figures below and
show the four possible combinations of these two bits.

SPI master-slave interconnection.

SPCR - SPI control register (address D5H) bit allocation

Bit addressable; Reset source(s): any reset; Reset value: 00000000B

SPCR - SPI control register (address D5H) bit description


SPSR - SPI status register (address AAH) bit allocation

Bit addressable; Reset source(s): any reset; Reset value: 00000000B


SPSR - SPI status register (address AAH) bit description

SPI transfer format with CPHA = 0.


SPI transfer format with CPHA = 1.
Watchdog timer
The device offers a programmable Watchdog Timer (WDT) for fail safe protection
against software deadlock and automatic recovery.

To protect the system against software deadlock, the user software must refresh the
WDT within a user-defined time period. If the software fails to do this periodical
refresh, an internal hardware reset will be initiated if enabled (WDRE = 1). The
software can be designed such that the WDT times out if the program does not work
properly.
The WDT in the device uses the system clock (XTAL1) as its time base. So strictly
speaking, it is a Watchdog counter rather than a Watchdog timer. The WDT register
will increment every 344,064 crystal clocks. The upper 8-bits of the time base register
(WDTD) are used as the reload register of the WDT.
The WDTS flag bit is set by WDT overflow and is not changed by WDT reset. User
software can clear WDTS by writing ‘1' to it.

Programmable Counter Array (PCA)

The PCA includes a special 16-bit Timer that has five 16-bit capture/compare
modules associated with it. Each of the modules can be programmed to operate in
one of four modes: rising and/or falling edge capture, software timer, high-speed
output, or pulse width modulator. Each module has a pin associated with it in port 1.
Module 0 is connected to P1.3 (CEX0), module 1 to P1.4 (CEX1), etc. Registers CH
and CL contain current value of the free running up counting 16-bit PCA timer. The
PCA timer is a common time base for all five modules and can be programmed to run
at: 1⁄6 the oscillator frequency, 1⁄2 the oscillator frequency, the Timer 0 overflow, or the
input on the ECI pin (P1.2). The timer count source is determined from the CPS1 and
CPS0 bits in the CMOD SFR

Security Bit

The Security Bit protects against software piracy and prevents the contents of the
flash from being read by unauthorized parties in Parallel Programmer Mode. It also
protects against code corruption resulting from accidental erasing and programming
to the internal flash memory.
When the Security Bit is activated all parallel programming commands except for
Chip-Erase are ignored (thus the device cannot be read). However, ISP reading,
writing, or erasing of the user’s code can still be performed if the serial number and
length has not been programmed. Therefore, when a user requests to program
the Security Bit, the programmer should prompt the user and program a serial
number into the device.

Interrupt priority and polling sequence

The device supports eight interrupt sources under a four level priority scheme.
Table below summarizes the polling sequence of the supported interrupts. Note that the
SPI serial interface and the UART share the same interrupt vector.

Interrupt polling sequence

Power-saving modes
The device provides two power saving modes of operation for applications where power
consumption is critical. The two modes are idle and Power-down, see Table 58.

Idle mode

Idle mode is entered setting the IDL bit in the PCON register. In idle mode, the program
counter (PC) is stopped. The system clock continues to run and all interrupts and peripherals
remain active. The on-chip RAM and the special function registers hold their data during this
mode.

The device exits idle mode through either a system interrupt or a hardware reset. Exiting idle
mode via system interrupt, the start of the interrupt clears the IDL bit and exits idle mode.
After exit the Interrupt Service Routine, the interrupted program resumes execution
beginning at the instruction immediately following the instruction which invoked the idle
mode. A hardware reset starts the device similar to a power-on reset.

Power-down mode

The Power-down mode is entered by setting the PD bit in the PCON register. In the
Power-down mode, the clock is stopped and external interrupts are active for level
sensitive interrupts only. SRAM contents are retained during Power-down, the
minimum VDD level is 2.0 V.

The device exits Power-down mode through either an enabled external level sensitive
interrupt or a hardware reset. The start of the interrupt clears the PD bit and exits
Power-down. Holding the external interrupt pin low restarts the oscillator, the signal
must hold low at least 1024 clock cycles before bringing back high to complete the
exit. Upon interrupt signal restored to logic VIH, the interrupt service routine program
execution resumes beginning at the instruction immediately following the instruction
which invoked Power-down mode. A hardware reset starts the device similar to
power-on reset.

To exit properly out of Power-down, the reset or external interrupt should not be
executed before the VDD line is restored to its normal operating voltage. Be sure to
hold VDD voltage long enough at its normal operating level for the oscillator to restart
and stabilize (normally less than 10 ms).

Power-saving modes
SERIAL COMMUNICATION

Micro-controllers are useful to the extent that they communicate with other
devices, such as sensors, motors, switches, keypads, displays, memory and even other
micro-controllers. Many interface methods have been developed over the years to solve
the complex problem of balancing circuit design criteria such as features, cost, size,
weight, power consumption, reliability, availability, rnanufacturability. Many
microcontroller designs typically mix multiple interfacing methods. In a very simplistic
form, a micro-controller system can be viewed as a system that reads from (monitors)
inputs, performs processing and writes to (controls) outputs.

Microcontroller interfaces

Digital Analog

On/off Parallel Serial Voltage Current

Asynchronous Synchronous

1-wire 2-wire (I2c)


RS232/RS485 4-wire (SPI, Micro wire)
Ethernet

Most of devices are parallel in nature. These devices transfer the data simultaneously on
data lines but parallel data transfer process is very complicated and expensive. Hence in
some situations the serial input output mode is used where one hit is transferred over a
single line at a time.

Serial communication is a popular means of transmitting data between a Microcontroller


and a peripheral device such as a programmable instrument (Here Smart Card Reader).
Serial communication uses a transmitter to send data, one bit at a time, over a single
communication line to a receiver. You can use this method when data transfer rates are
low or you must transfer data over long distances. Serial communication is popular
because no extra hardware is needed other than a cable to connect the instrument to the
Microcontroller.

The data can be transmitted by taking various parameters into considerations such as
synchronous or asynchronous, direction of data flow speed, errors, medium of data
transmission etc.. .in synchronous transmission both transmitter and receiver operate, in
synchronization. Synchronization used for high speed operations. In asynchronous data
transmission data is transmitted between start and stop bit with logic 1as mark logic 0 as
space. In asynchronous we get around 11 bits for data transmission one start, 8 bits of
data, 2 stop bits. A synchronous data transmission is used for less than 20 kb/sec
transmission.

Advantages with Asynchronous communications:

• Popular interface with many examples


• Many compatible legacy devices
• Relatively long distance, 50 feet maximum for low baud rates although longer distances
work in practice, with low baud rates and error correction
• Immune to noise due to +/5 Volts or higher voltage
• levels for logic “0” and “1”
• Implemented in hardware or software
• Ease to implement.
Introduction to RS-232:

RS denotes “Recommended Standard” and refers to official standards of Electronics


Industries Association. RS-232 is the most known serial port used in transmitting the data
in communication and interface. Even though serial port is harder to program than the
parallel port, this is the most effective method in which the data transmission requires
less
that yields to the less cost. Serial RS-232 communication works with voltages (-15V ...
-3V for high [sic]) and +3V ... +15V for low [sic]) which are not compatible with normal
computer logic voltages. On the other hand, classic TTL computer logic operates between
0V and 5V (roughly OV ... +O.8V for low, +2V ... +5V for high). Modern low-power
logic operates in the range of OV ... +3.3V or even lower.

So, the maximum RS-232 signal levels are far too high for computer logic electronics,
and the negative RS-232 voltage for high cant be applicable at all by computer logic.
Therefore, to receive serial data from an RS-232 interface the voltage has to be reduced,
and the low and high voltage level inverted. In the other direction (sending data from
some logic over RS-232) the low logic voltage has to be bumped up”, and a negative
voltage has to be generated, too.
All this can be done with conventional analog electronics, e.g. a particular power supply
and a couple of transistors or the once popular 1488 (transmitter) and 1489 (receiver) ICs.
However, since more than a decade it has become standard in amateur electronics to do
the necessary signal level conversion with an integrated circuit (IC) from the MAX232
family (typically a MAX232A or some clone).

The MAX232 from Maxim was the first IC which in one package contains the necessary
drivers (two) and receivers (also two), to adapt the RS-232 signal voltage levels to TTL
logic. It became popular, because it just needs one voltage (+5V) and generates the
necessary RS-232 voltage levels (approx. -1OV and +IOV) internally. This greatly
simplified the design of circuitry. Circuitry designers no longer need to design and build
a power supply with three voltages (e.g. -12V, +5V, and +12V), but could just provide
one +5V power supply, e.g. with the help of a simple 78x05 voltage converter.

It should be noted that the MAX232 (A) is just a driver/receiver. It does not generate the
necessary RS-232 sequence of marks and spaces with the right timing, it does not decode
the RS-232 signal, it does not provide a serial/parallel conversion. All it does is to
convert signal voltage levels. Generating serial data with the right timing and decoding
serial data has to be done by additional circuitry, e.g. by a 16550 UART or one of these
small micro controllers (e.g. Atmel AVR, Microchip PlC) getting more and more
popular.

MAX232 (A) DIP


Package
+---v---+
C1+ -|1 16|- Vcc
V+ -| |- GND
C1- -| |- T1out
C2+ -| |- R1in
C2- -| |- R1out
V- -| |- T1in
T2out -| |- T2in
R2in -|8 9|- R2out
+-------+

MAX232(A) DIP Package Pin Layout


Capacitor Capacitor
Num Name Purpose Signal Voltage Value Value
MAX232 MAX232A
+ connector for capacitor should
1 C1+ 1µF 100Nf
capacitor C1 stand at least 16V
+10V, capacitor
output of
2 V+ should stand at 1µF to VCC 100nF to VCC
voltage pump
least 16V
- connector for capacitor should
3 C1- 1µF 100nF
capacitor C1 stand at least 16V
+ connector for capacitor should
4 C2+ 1µF 100nF
capacitor C2 stand at least 16V
- connector for capacitor should
5 C2- 1µF 100nF
capacitor C2 stand at least 16V
output of -10V, capacitor
6 V- voltage pump / should stand at 1µF to GND 100nF to GND
inverter least 16V
7 T2out Driver 2 output RS-232
Receiver 2
8 R2in RS-232
input
Receiver 2
9 R2out TTL
output
10 T2in Driver 2 input TTL
11 T1in Driver 1 input TTL
Receiver 1
12 R1out TTL
output
Receiver 1
13 R1in RS-232
input
14 T1out Driver 1 output RS-232
15 GND Ground 0V 1µF to VCC 100nF to VCC
16 VCC Power supply +5V see above see above

The MAX232 (A) has two receivers (converts from RS-232 to TTL voltage levels) and
two drivers (converts from TTL logic to RS-232 voltage levels). This means only two of
the RS-232 signals can be converted in each direction.

Typically a pair of a driver/receiver of the MAX232 is used for

• TX and RX

And the second one for

• CTS and RTS.

There are not enough drivers/receivers in the MAX232 to also connect the DTR, DSR,
and LUD signals. Usually these signals can be omitted when e.g. communicating with a
PC’s serial interface. If the DTE really requires these signals either a second MAX232 is
needed, or some other IC from the MAX232 family can be used (if it can be found in
consumer electronic shops at all). An alternative for DTRJDSR is also given below.

Maxim’s data sheet explains the MAX232 family in great detail, including the pin
configuration and how to connect such an IC to external circuitry. This information can
be used as-is in own design to get a working RS-232 interface. Maxim’s data just misses
one critical piece of information: How exactly to connect the RS-232 signals to the IC. So
here is one possible example:

In addition one can directly wire DTR (DB9 pin 4) to DSR (DB9 pin 6) without going
through any circuitry. This gives automatic (brain dead) DSR acknowledgment of an
incoming DTR signal.

Sometimes pin 6 of the MAX232 is hard wired to DCD (DB9 pin 1). This is not
recommended. pin 6 is the raw output of the voltage pump and inverter for the -IOV
voltage. Drawing currents from the pin leads to a rapid breakdown of the voltage, and as
a consequence to a breakdown of the output voltage of the two RS-232 drivers. It is better
to use software which doesn’t care about DC I), hut does hardware-handshaking via
CTSIRTS only.

The circuitry is completed by connecting five capacitors to the IC as it follows. The


MAX232 needs 1.0µF capacitors, the MAX232A needs 0.1 1.tF capacitors. MAX232
clones show similar differences. It is recommended to consult the corresponding data
sheet. At least 1 6V capacitor types should be used. If electrolytic or tantalic capacitors
are used, the polarity has to be observed. The first pin as listed in the following table is
always where the plus pole of the capacitor should be connected to the 5V power supply
is connected Pin 16.

CAPACITANCE (µF)
DEVICE C1 C2 C3 C4 C5
MAX232 1.0 1.0 1.0 1.0 1.0
MAX232A 0.1 0.1 0.1 0.1 0.1

B) RS-232

RS-232 is simple, universal, well understood and supported but it has some serious
shortcomings as a data interface. The standards to 256kbps or less and line lengths of I
5M (50 ft) or less but today we see high speed ports on our home PC running very high
speeds and with high quality cable maxim distance has increased greatly. The rule of
thumb for the length a data cable depends on speed of the data, quality of the cable.

Electronic data communications between elements will generally fall into two broad
categories: single-ended and differential. RS232 (single-ended) was introduced in 1962,
and despite rumors for its early demise, has remained widely used through the industry.

Independent channels are established for two-way (full-duplex) communications.


The RS232 signals are represented by voltage levels with respect to a system common
(power I logic ground). The “idle” state (MARK) has the signal level negative with
respect to common, and the “active” state (SPACE) has the signal level positive with
respect to common. RS232 has numerous handshaking lines (primarily used with
modems), and also specifies a communications protocol.

The RS-232 interface presupposes a common ground between the DTE and DCE. This is
a reasonable assumption when a short cable connects the DTE to the DCE, but with
longer lines and connections between devices that may be on different electrical busses
with different grounds, this may not be true.

RS232 data is bi-polar.... +3 TO +12 volts indicate an “ON or 0-state (SPACE)


condition’s while A -3 to -12 volts indicates an “OFF” 1-state (MARK) condition....
Modern computer equipment ignores the negative level and accepts a zero voltage level
as the “OFF” state. In fact, the “ON” state may be achieved with lesser positive potential.
This means circuits powered by 5 VDC are capable of driving RS232 circuits directly;
however, the overall range that the RS232 signal may be transmitted / received may be
dramatically reduced.

The output signal level usually swings between +12V and -12V. The “dead area”
between +3v and -3v is designed to absorb line noise. In the various RS-232-like
definitions this dead area may vary. For instance, the definition for V.10 has a dead area
from +0.3’s to -0.3v. Many receivers designed for RS-232 are sensitive to differentials of
1v or less.
This can cause problems when using pin powered widgets - line drivers, converters,
modems etc. These types of units need enough voltage & current to power them self’s up.
Typical URART (the RS-232 I/O chip) allows up to 5Oma per output pin - so if the
device needs 7Oma to run we would need to use at least 2 pins for power. Some devices
are very efficient and only require one pin (some times the Transmit or DTR pin) to be
high - in the “SPACE” state while idle.

An RS-232 port can supply only limited power to another device. The number of output
lines, the type of interface driver IC, and the state of the output lines are important
considerations.

The types of driver ICs used in serial ports can be divided into three general categories:

• Drivers which require plus (+) and minus (-) voltage power supplies such as the 1488
series of interface integrated circuits. (Most desktop and tower PCs use this type of
driver.)

• Low power drivers which require one +5 volt power supply. This type of driver has an
internal charge pump for voltage conversion. (Many industrial microprocessor controls
use this type of driver.)

• Low voltage (3.3 v) and low power drivers which meet the EIA-562 Standard. (Used on
notebooks and laptops.)

Data is transmitted and received on pins 2 and 3 respectively. Data Set Ready (DSR) is
an indication from the Data Set (i.e., the modem or DSU/CSU) that it is on. Similarly,
DTR indicates to the Data Set that the DTE is on. Data Carrier Detect (DCD) indicates
that a good carrier is being received from the remote modem.
Pins 4 RTS (Request to Send - from the transmitting computer) and 5 CTS (Clear to Send
- from the Data set) are used to control. In most Asynchronous situations, RTS and CTS
are constantly on throughout the communication session. However where the DTE is
connected to a multipoint line. RTS is used to turn carrier on the modem on and off. On a
multipoint line, it’s imperative that only one station is transmitting at a time (because
they share the return phone pair). When a station wants to transmit, it raises RTS. The
modem turns on carrier, typically waits a few milliseconds for carrier to stabilize, and
then raises CTS. The DTE transmits when it sees CTS up. When the station has finished
its transmission, it drops RTS and the modem drops CTS and carrier together.

Clock signals (pins 15, 17, & 24) are only used for synchronous communications. The
modem or DSU extracts the clock from the data stream and provides a steady clock
signal to the DTE. Note that the transmit and receive clock signals do not have to be the
same, or even at the same baud rate.

Note: Transmit and receive leads (2 or 3) can be reversed depending on the use of the
equipment
- DCE Data Communications Equipment or a DTE Data Terminal Equipment.

Glossary of Abbreviations etc.

CTS Clear To Send [DCE --> DTE]

DCD Data Carrier Detected (Tone from a modem) [DCE --> DTEI

DCE Data Communications Equipment e.g. Modem

DSR Data Set Ready [DCE --> DTEJ

DSRS Data Signal Rate Selector [DCE —> DTE] (Not commonly used)

DTE Data Terminal Equipment e.g. computer, printer

DTR Data Terminal Ready [DTE —> DCE]

FG Frame Ground (screen or chassis)


NC No Connection

RCK Receiver (external) Clock input

RI Ring Indicator (ringing tone detected)

RTS Ready to Send [DTE --> DCEI

RXD Received Data [DCE --> DTE]

SG Signal Ground

SCTS Secondary Clear To Send [DCE --> DTE]

SDCD Secondary Data Carrier Detected (Tone from a modem) [DCE —> DTE]

SRTS Secondary Ready to Send [DTE —> DCE]

SRXD Secondary Received Data [DCE —> DTE]

STXD Secondary Transmitted Data [DTE --> DTEI

TXD Transmitted Data [DTE --> DTE]

You might also like