Você está na página 1de 85

8051

Difference between Microprocessor


and Microcontroller
The term microprocessor and microcontroller have always been
confused with each other. Both of them have been designed for real time
application. They share many common features and at the same time
they have significant differences. Both the ICs i.e., the microprocessor
and microcontroller cannot be distinguished by looking at them. They
are available in different version starting from 6 pin to as high as 80 to
100 pins or even higher depending on the features.

Difference between
and microcontroller

microprocessor

Microprocessor is an IC which has only the CPU inside them i.e. only
the processing powers such as Intels Pentium 1,2,3,4, core 2 duo, i3, i5
etc. These microprocessors dont have RAM, ROM, and other peripheral
on the chip. A system designer has to add them externally to make them
functional. Application of microprocessor includes Desktop PCs,
Laptops, notepads etc.
But this is not the case with Microcontrollers. Microcontroller has a
CPU, in addition with a fixed amount of RAM, ROM and other
peripherals all embedded on a single chip. At times it is also termed as a
mini computer or a computer on a single chip. Today different
manufacturers produce microcontrollers with a wide range of features
available in different versions. Some manufacturers are ATMEL,
Microchip, TI, Freescale, Philips, Motorola etc.

Microcontrollers are designed to perform specific tasks. Specific means


applications where the relationship of input and output is defined.
Depending on the input, some processing needs to be done and output is
delivered. For example, keyboards, mouse, washing machine, digicam,
pendrive, remote, microwave, cars, bikes, telephone, mobiles, watches,
etc. Since the applications are very specific, they need small resources
like RAM, ROM, I/O ports etc and hence can be embedded on a single
chip. This in turn reduces the size and the cost.
Microprocessor find applications where tasks are unspecific like
developing software, games, websites, photo editing, creating documents
etc. In such cases the relationship between input and output is not
defined. They need high amount of resources like RAM, ROM, I/O ports
etc.
The clock speed of the Microprocessor is quite high as compared to the
microcontroller. Whereas the microcontrollers operate from a few MHz
to 30 to 50 MHz, todays microprocessor operate above 1GHz as they
perform complex tasks. Read more about what is microcontroller.
Comparing microcontroller and microprocessor in terms of cost is not
justified. Undoubtedly a microcontroller is far cheaper than a
microprocessor. However microcontroller cannot be used in place of
microprocessor and using a microprocessor is not advised in place of a
microcontroller as it makes the application quite costly. Microprocessor
cannot be used stand alone. They need other peripherals like RAM,
ROM, buffer, I/O ports etc and hence a system designed around a
microprocessor is quite costly.

BLOCK DIAGRAM OR ARCHITECTURE :

What is 8051 Microcontroller?


8051 is an 8-bit family of microcontroller developed by Intel in the year
1981. This is one of the most popular family of microcontroller being
used all across the world. This microcontroller was also referred as
system on a chip because it has 128 bytes of RAM, 4Kbytes of ROM,
2 Timers, 1 Serial port, and four ports on a single chip. The CPU can
work for only 8bits of data at a time because 8051 is an 8-bit
processor. In case the data is larger than 8 bits then it has to be broken
into parts so that the CPU can process conveniently. Most manufacturers
have put 4Kbytes of ROM even though the quantity of ROM can be
exceeded up to 64 K bytes.
The 8051 has been in use in a wide number of devices, mainly because it
is easy to integrate into a project or build a device around. The following
are the main areas of focus:
i.

Energy Management:Efficient metering systems help in


controlling energy usage in homes and industrial
applications. These metering systems are made capable by
incorporating microcontrollers.

ii.

Touch screens:A high number of microcontroller providers


incorporate touch-sensing capabilities in their designs.
Portable electronics such as cell phones, media players and
gaming devices are examples of microcontroller-based touch
screens.

iii.

Automobiles: The 8051 finds wide acceptance in providing


automobile solutions. They are widely used in hybrid
vehicles to manage engine variants. Additionally, functions
such as cruise control and anti-brake system have been made
more efficient with the use of microcontrollers.

iv.
Medical Devices:Portable medical devices such as blood
pressure and glucose monitors use microcontrollers will to display data,
thus providing higher reliability in providing medical results.

FEATURES OF 8051
8051 have 128 bytes of RAM
8051 have 128 user defined flags
It consist of 16 bit address bus
It consist of 3 internal and two external interrupts
less power usage in 8051 with respect to other microcontroller
It consist of 16-bit program counter and data pointer
8051 can process 1 million one-cycle instructions per
second
It consist of 32 general purpose registers each of 8 bits
ROM on 8051 is 4 Kbytes in size
It also consist of Two 16 bit Timer/ Counter
We can connect 64 kb of external RAM

SFRSS

What Are SFRs?


The 8051 is a flexible microcontroller with a relatively large number of
modes of operations. Your program may inspect and/or change the
operating mode of the 8051 by manipulating the values of the 8051's
Special Function Registers (SFRs).
SFRs are accessed as if they were normal Internal RAM. The only
difference is that Internal RAM is from address 00h through 7Fh
whereas SFR registers exist in the address range of 80h through FFh.
Each SFR has an address (80h through FFh) and a name. The following
chart provides a graphical presentation of the 8051's SFRs, their names,
and their address.

As you can see, although the address range of 80h through FFh offer 128
possible addresses, there are only 21 SFRs in a standard 8051. All other
addresses in the SFR range (80h through FFh) are considered invalid.

Writing to or reading from these registers may produce undefined


values or behavior.
// Programming Tip: It is recommended that you not read or write to
SFR addresses that have not been assigned to an SFR. Doing so may
provoke undefined behavior and may cause your program to be
incompatible with other 8051-derivatives that use the given SFR for
some other purpose.

SFR Types
As mentioned in the chart itself, the SFRs that have a blue background
are SFRs related to the I/O ports. The 8051 has four I/O ports of 8 bits,
for a total of 32 I/O lines. Whether a given I/O line is high or low and
the value read from the line are controlled by the SFRs in green.
The SFRs with yellow backgrouns are SFRs which in some way control
the operation or the configuration of some aspect of the 8051. For
example, TCON controls the timers, SCON controls the serial port.
The remaining SFRs, with green backgrounds, are "other SFRs." These
SFRs can be thought of as auxillary SFRs in the sense that they don't
directly configure the 8051 but obviously the 8051 cannot operate
without them. For example, once the serial port has been configured
using SCON, the program may read or write to the serial port using the
SBUF register.
// Programming Tip: The SFRs whose names appear in red in the chart
above are SFRs that may be accessed via bit operations (i.e., using the
SETB and CLR instructions). The other SFRs cannot be accessed using
bit operations. As you can see, all SFRs that whose addresses are
divisible by 8 can be accessed with bit operations.

SFR Descriptions
This section will endeavor to quickly overview each of the standard
SFRs found in the above SFR chart map. It is not the intention of this
section to fully explain the functionality of each SFR--this information
will be covered in separate chapters of the tutorial. This section is to just
give you a general idea of what each SFR does.

P0 (Port 0, Address 80h, Bit-Addressable): This is input/output port 0.


Each bit of this SFR corresponds to one of the pins on the
microcontroller. For example, bit 0 of port 0 is pin P0.0, bit 7 is pin P0.7.
Writing a value of 1 to a bit of this SFR will send a high level on the
corresponding I/O pin whereas a value of 0 will bring it to a low level.
// Programming Tip: While the 8051 has four I/O port (P0, P1, P2, and
P3), if your hardware uses external RAM or external code memory (i.e.,
your program is stored in an external ROM or EPROM chip or if you are
using external RAM chips) you may not use P0 or P2. This is because
the 8051 uses ports P0 and P2 to address the external memory. Thus if
you are using external RAM or code memory you may only use ports P1
and P3 for your own use.
SP (Stack Pointer, Address 81h): This is the stack pointer of the
microcontroller. This SFR indicates where the next value to be taken
from the stack will be read from in Internal RAM. If you push a value
onto the stack, the value will be written to the address of SP + 1. That is
to say, if SP holds the value 07h, a PUSH instruction will push the value
onto the stack at address 08h. This SFR is modified by all instructions
which modify the stack, such as PUSH, POP, LCALL, RET, RETI, and
whenever interrupts are provoked by the microcontroller.

// Programming Tip: The SP SFR, on startup, is initialized to 07h. This


means the stack will start at 08h and start expanding upward in internal
RAM. Since alternate register banks 1, 2, and 3 as well as the user bit
variables occupy internal RAM from addresses 08h through 2Fh, it is
necessary to initialize SP in your program to some other value if you
will be using the alternate register banks and/or bit memory. It's not a
bad idea to initialize SP to 2Fh as the first instruction of every one of
your programs unless you are 100% sure you will not be using the
register banks and bit variables.

DPL/DPH (Data Pointer Low/High, Addresses 82h/83h): The SFRs


DPL and DPH work together to represent a 16-bit value called the Data
Pointer. The data pointer is used in operations regarding external RAM
and some instructions involving code memory. Since it is an unsigned
two-byte integer value, it can represent values from 0000h to FFFFh (0
through 65,535 decimal).
// Programming Tip: DPTR is really DPH and DPL taken together as a
16-bit value. In reality, you almost always have to deal with DPTR one
byte at a time. For example, to push DPTR onto the stack you must first
push DPL and then DPH. You can't simply plush DPTR onto the stack.
Additionally, there is an instruction to "increment DPTR." When you
execute this instruction, the two bytes are operated upon as a 16-bit
value. However, there is no instruction that decrements DPTR. If you
wish to decrement the value of DPTR, you must write your own code to
do so.
PCON (Power Control, Addresses 87h): The Power Control SFR is
used to control the 8051's power control modes. Certain operation
modes of the 8051 allow the 8051 to go into a type of "sleep" mode

which requires much less power. These modes of operation are


controlled through PCON. Additionally, one of the bits in PCON is used
to double the effective baud rate of the 8051's serial port.
TCON (Timer Control, Addresses 88h, Bit-Addressable): The Timer
Control SFR is used to configure and modify the way in which the
8051's two timers operate. This SFR controls whether each of the two
timers is running or stopped and contains a flag to indicate that each
timer has overflowed. Additionally, some non-timer related bits are
located in the TCON SFR. These bits are used to configure the way in
which the external interrupts are activated and also contain the external
interrupt flags which are set when an external interrupt has occured.

TMOD (Timer Mode, Addresses 89h): The Timer Mode SFR is used
to configure the mode of operation of each of the two timers. Using this
SFR your program may configure each timer to be a 16-bit timer, an 8bit autoreload timer, a 13-bit timer, or two separate timers. Additionally,
you may configure the timers to only count when an external pin is
activated or to count "events" that are indicated on an external pin.
TL0/TH0 (Timer 0 Low/High, Addresses 8Ah/8Ch): These two SFRs,
taken together, represent timer 0. Their exact behavior depends on how
the timer is configured in the TMOD SFR; however, these timers always
count up. What is configurable is how and when they increment in value.
TL1/TH1 (Timer 1 Low/High, Addresses 8Bh/8Dh): These two SFRs,
taken together, represent timer 1. Their exact behavior depends on how
the timer is configured in the TMOD SFR; however, these timers always
count up. What is configurable is how and when they increment in value.

P1 (Port 1, Address 90h, Bit-Addressable): This is input/output port 1.


Each bit of this SFR corresponds to one of the pins on the
microcontroller. For example, bit 0 of port 1 is pin P1.0, bit 7 is pin P1.7.
Writing a value of 1 to a bit of this SFR will send a high level on the
corresponding I/O pin whereas a value of 0 will bring it to a low level.
SCON (Serial Control, Addresses 98h, Bit-Addressable): The Serial
Control SFR is used to configure the behavior of the 8051's on-board
serial port. This SFR controls the baud rate of the serial port, whether the
serial port is activated to receive data, and also contains flags that are set
when a byte is successfully sent or received.
// Programming Tip: To use the 8051's on-board serial port, it is
generally necessary to initialize the following SFRs: SCON, TCON, and
TMOD. This is because SCON controls the serial port. However, in
most cases the program will wish to use one of the timers to establish the
serial port's baud rate. In this case, it is necessary to configure timer 1 by
initializing TCON and TMOD.

SBUF (Serial Control, Addresses 99h): The Serial Buffer SFR is used
to send and receive data via the on-board serial port. Any value written
to SBUF will be sent out the serial port's TXD pin. Likewise, any value
which the 8051 receives via the serial port's RXD pin will be delivered
to the user program via SBUF. In other words, SBUF serves as the
output port when written to and as an input port when read from.
P2 (Port 2, Address A0h, Bit-Addressable): This is input/output port 2.
Each bit of this SFR corresponds to one of the pins on the
microcontroller. For example, bit 0 of port 2 is pin P2.0, bit 7 is pin P2.7.
Writing a value of 1 to a bit of this SFR will send a high level on the
corresponding I/O pin whereas a value of 0 will bring it to a low level.

// Programming Tip: While the 8051 has four I/O port (P0, P1, P2, and
P3), if your hardware uses external RAM or external code memory (i.e.,
your program is stored in an external ROM or EPROM chip or if you are
using external RAM chips) you may not use P0 or P2. This is because
the 8051 uses ports P0 and P2 to address the external memory. Thus if
you are using external RAM or code memory you may only use ports P1
and P3 for your own use.

IE (Interrupt Enable, Addresses A8h): The Interrupt Enable SFR is


used to enable and disable specific interrupts. The low 7 bits of the SFR
are used to enable/disable the specific interrupts, where as the highest bit
is used to enable or disable ALL interrupts. Thus, if the high bit of IE is
0 all interrupts are disabled regardless of whether an individual interrupt
is enabled by setting a lower bit.
P3 (Port 3, Address B0h, Bit-Addressable): This is input/output port 3.
Each bit of this SFR corresponds to one of the pins on the
microcontroller. For example, bit 0 of port 3 is pin P3.0, bit 7 is pin P3.7.
Writing a value of 1 to a bit of this SFR will send a high level on the
corresponding I/O pin whereas a value of 0 will bring it to a low level.
IP (Interrupt Priority, Addresses B8h, Bit-Addressable): The
Interrupt Priority SFR is used to specify the relative priority of each
interrupt. On the 8051, an interrupt may either be of low (0) priority or
high (1) priority. An interrupt may only interrupt interrupts of lower
priority. For example, if we configure the 8051 so that all interrupts are
of low priority except the serial interrupt, the serial interrupt will always
be able to interrupt the system, even if another interrupt is currently
executing. However, if a serial interrupt is executing no other interrupt

will be able to interrupt the serial interrupt routine since the serial
interrupt routine has the highest priority.
PSW (Program Status Word, Addresses D0h, Bit-Addressable): The
Program Status Word is used to store a number of important bits that are
set and cleared by 8051 instructions. The PSW SFR contains the carry
flag, the auxiliary carry flag, the overflow flag, and the parity flag.
Additionally, the PSW register contains the register bank select flags
which are used to select which of the "R" register banks are currently
selected.
// Programming Tip: If you write an interrupt handler routine, it is a very
good idea to always save the PSW SFR on the stack and restore it when
your interrupt is complete. Many 8051 instructions modify the bits of
PSW. If your interrupt routine does not guarantee that PSW is the same
upon exit as it was upon entry, your program is bound to behave rather
erradically and unpredictably--and it will be tricky to debug since the
behavior will tend not to make any sense.
ACC (Accumulator, Addresses E0h, Bit-Addressable): The
Accumulator is one of the most-used SFRs on the 8051 since it is
involved in so many instructions. The Accumulator resides as an SFR at
E0h, which means the instruction MOV A,#20h is really the same as
MOV E0h,#20h. However, it is a good idea to use the first method since
it only requires two bytes whereas the second option requires three
bytes.
B (B Register, Addresses F0h, Bit-Addressable): The "B" register is
used in two instructions: the multiply and divide operations. The B
register is also commonly used by programmers as an auxiliary register
to temporarily store values.
Other SFRs

The chart above is a summary of all the SFRs that exist in a standard
8051. All derivative microcontrollers of the 8051 must support these
basic SFRs in order to maintain compatability with the underlying
MSCS51 standard.
A common practice when semiconductor firms wish to develop a new
8051 derivative is to add additional SFRs to support new functions that
exist in the new chip. For example, the Dallas Semiconductor
DS80C320 is upwards compatible with the 8051. This means that any
program that runs on a standard 8051 should run without modification
on the DS80C320. This means that all the SFRs defined above also
apply to the Dallas component.
However, since the DS80C320 provides many new features that the
standard 8051 does not, there must be some way to control and
configure these new features. This is accomplished by adding additional
SFRs to those listed here. For example, since the DS80C320 supports
two serial ports (as opposed to just one on the 8051), the SFRs SBUF2
and SCON2 have been added. In addition to all the SFRs listed above,
the DS80C320 also recognizes these two new SFRs as valid and uses
their values to determine the mode of operation of the secondary serial
port. Obviously, these new SFRs have been assigned to SFR addresses
that were unused in the original 8051. In this manner, new 8051
derivative chips may be developed which will run existing 8051
programs.
// Programming Tip: If you write a program that utilizes new SFRs that
are specific to a given derivative chip and not included in the above SFR
list, your program will not run properly on a standard 8051 where that
SFR does not exist. Thus, only use non-standard SFRs if you are sure
that your program wil only have to run on that specific microcontroller.
Likewise, if you write code that uses non-standard SFRs and

subsequently share it with a third-party, be sure to let that party know


that your code is using non-standard SFRs to save them the headache of
realizing that due to strange behavior at run-time.

TIMERS
What is a Timer

Timer is a clock that controls the sequence of an event while counting in


fixed intervals of time. A Timer is used for producing precise time delay.
Secondly, it can be used to repeat or initiate an action after/at a known
period of time. This feature is very commonly used in several
applications. An example could be setting up an alarm which triggers at
a point of time or after a period of time.
Timers in a controller: Why to use them
Most of the microcontrollers have inbuilt Timers. Timers in a controller
not only generate time delays but they can also be used as counters.
They are used to count an action or event. The value of counter increases
by one, every time its corresponding action or event occurs. Timers in a
controller are inbuilt chips that are controlled by special function
registers (SFRs) assigned for Timer operations. These SFRs are used to
configure Timers in different modes of operations.
While working with microcontrollers, it is more than often required to
generate time delays. There are two possible ways of generating time
delays. First is by using the code, like using for or while loops in a C
program. However, the delays provided by the software are not very
precise. The other method is to use Timers. Timers provide time
delays that are very precise and accurate.

8051 Timers and registers


AT89C51 microcontroller has two Timers designated as Timer0 and
Timer1. Each of these timers is assigned a 16-bit register. The value of a
Timer register increases by one every time a timer counts. Timer takes a
time period of one machine cycle to count one. (Machine cycle is a unit
that refers to the time required by the microcontroller to execute
instructions.) This means that the maximum number of times a timer can
count without repeating is 216, i.e., 65536. So the maximum allowed

counts in value of Timer registers can be from 0000H to FFFFH.


Since 8051 is an 8 bit controller, the registers of 8051 Timers are
accessed as two different registers; one for lower byte and other for
higher byte. For example, register of Timer0 is accessed as TL0 for
lower byte and TH0 for higher byte. Similarly TL1and TH1 are registers
assigned to Timer 1.
When the Timer reaches FFFFH, it reloads to 0000H. This roll over is
communicated to the controller by raising a flag corresponding to that
Timer, i.e., a flag bit is raised (set high) when the timer starts counting
from 0000H again. TF0 and TF1 are the Timer flags corresponding to
Timers 0 and 1. These flags must be cleared (set low) by software every
time they are raised. The Timer may terminate updating register values
after a roll over or continue with its operation.

Starting or stopping a Timer


For every Timer, there is a corresponding Timer control bit which can be
set or cleared by the program to start or stop the Timer. TR0 andTR1 are
the control bits for Timers 0 and 1 respectively. Setting the control bit
would start the Timer.
TR0 = 1;
starts Timer 0
TR1 = 1;
starts Timer 1
Clearing the control bit would stop the Timer.
TR0 = 0;
stops Timer 0
TR1 = 0;
stops Timer1

8051 Timer Issues


While using 8051 Timers certain factors need to be considered, like
whether the Timer is to be used for time keeping or for counting;
whether the source for time generation is external clock or the controller
itself; how many bits of Timer register are to be used or left unused.
If C/T is low, Timer is used for time keeping, i.e., Timer updates its
value automatically corresponding to 8051 clock source. When C/T is
high, Timer is used as counter, i.e., it updates its value when it receives
pulse from outside the 8051 controller.
M1 and M0 bits decide the Timer modes. There are four Timer modes
designated as Modes 0, 1, 2 and 3.
Modes 1 and 2 are most commonly used while working with Timers.
TMOD = 0x01;
sets the mode1 of Timer0 used for timing
TMOD = 0x20;
sets the mode2 of Timer1 used for timing
How a Timer functions
The registers of Timers are loaded with some initial value. The value of
a Timer register increases by one after every machine cycle. One
machine cycle duration is the 1/12th of the frequency of the crystal
attached to the controller.
For example, if the frequency of the crystal is 12 MHz, then the
frequency for Timer will be 1MHz (1/12 of crystal frequency) and hence
the time (T = 1/f) taken by the Timer to count by one
is 1s (1/1MHz). Similarly if an 11.0592 MHz crystal is used, operating
frequency of Timer is 921.6 KHz and the time period is 1.085 s.
If no value is loaded into the Timer, it starts counting from 0000H.

Configuring a Timer
A register called TMOD is used for configuring the Timers for the
desired operation. TMOD is an 8-bit register with following bit
configuration:

The lower four bits (TMOD.0 TMOD.3) are used to configure Timer 0
while the higher four bits (TMOD.4 TMOD.7) are for Timer 1. When
GATE is high, the corresponding Timer is enabled only when there is an
interrupt at corresponding INTx pin of AT89C51 controller and Timer
control bit is high. Otherwise only setting Timer control bit is sufficient
to start the Timer.
Programming 8051 Timers
The programming of 8051 Timers can be done by using either polling
method or by using interrupt. In polling, the microcontroller keeps
monitoring the status of Timer flag. While doing so, it does no other
operation and consumes all its processing time in checking the Timer
flag until it is raised on a rollover. In interrupt method controller

responds to only when the Timer flag is raised. The interrupt method
prevents the wastage of controllers processing time unlike polling
method.
Polling is mostly used for time delay generation and interrupt method is
more useful when waveforms are to be generated or some action has to
be repeated in fixed delays.
(i) Polling Method
The polling method involves the following algorithm:
1.
Configure the Timer mode by passing a hex value into the TMOD
register. This will tell the controller about which Timer is be used; the
mode of Timer; operation (to be used as timer or counter); and whether
external interrupt is required to start Timer.
2.
Load the initial values in the Timer low TLx and high THx byte. (x
= 0/1)
3.
Start the Timer by setting TRx bit.
4. Wait while the Timer flag TFx is raised.
5.
Clear the Timer flag. The Timer flag is raised when Timer rolls
over from FFFFH to 0000H. If the Timer is not stopped, it will start
updating from 0000H in case of modes 0 & 1 while with initial value in
case of mode 2. If TFx is not cleared, controller will not be able to detect
next rollover.
6.
Stop the Timer by clearing TRx bit. If TRx bit is not cleared the
Timer will restart updating from 0000H after the rollover in case of
modes 0 and 1 while with initial value in case of mode 2.
(ii) Interrupt Method
The interrupt method makes use of a register called Interrupt Enable (IE)
register. An 8051 microcontroller has 6 hardware interrupts. The
interrupts refer to a notification, communicated to the controller, by a
hardware device or software, on receipt of which controller skips
temporarily whatsoever it was doing and responds to the interrupt.

The controller starts the execution of an Interrupt Service Routine (ISR)


or Interrupt Handler which is a piece of code that tells the processor or
controller what to do on receipt of an interrupt. After the execution of
ISR, controller returns to whatever it was doing earlier (before the
interrupt was received).
The Interrupt Enable register has the following bits which enable or
disable the hardware interrupts of 8051 mi crocontroller

When EA (IE.7) is set (=1), interrupts are enabled. When clear (EA=0),
interrupts are disabled and controller does not respond to any interrupts.
ET0, ET1 & ET2 (IE.3, IE.4 & IE.5) are Timer interrupt bits. When set
(high) the timer are enabled and when cleared (low) they are disabled.
(8052 controllers have three Timers, so ET2 is its Timer 2 interrupt bit.)
The ISR corresponding to these interrupts are executed when the TFx
flags of respective Timers are raised. For more details on other IE
register bits, refer Interrupts with 8051.
Note that IE register is bit addressable.
Timer programming using Timer interrupts involves following
algorithm.
1.
Configure the Timer mode by passing a hex value to TMOD
register.
2.
Load the initial values in the Timer low TLx and high THx byte.
3.
Enable the Timer interrupt by passing hex value to IE register or
setting required bits of IE register. For example,
IE = 0x82;
IE = 0x88;
or

enables Timer 0 interrupt


enables Timer 1 interrupt

EA = 1;
ET0 = 1;

enables Timer 0 interrupt

IE^7 = 1;
IE^3 = 1;

enables Timer 1 interrupt

4.
Start the Timer by setting TRx bit.
5.
Write Interrupt Service Routine (ISR) for the Timer interrupt. For
example,
ISR definition for Timer 0 :
void ISR_Timer0(void) interrupt 1
{
<Body of ISR>
}
ISR definition for Timer 1 :
void ISR_Timer1(void) interrupt 3
{
<Body of ISR>
}
6.
If the Timer has to be stopped after once the interrupt has occurred,
the ISR must contain the statement to stop the Timer.
For example,
void ISR_Timer1(void) interrupt 3
{
<Body of ISR>
TR1 =0;
}
7.
If a routine written for Timer interrupt has to be repeated again and
again, the Timer run bit need not be cleared. But it should be kept in
mind that Timer will start updating from 0000H and not the initial values
in case of mode 0 and 1. So the initial values must be reloaded in the
interrupt service routine.
For example,
void ISR_Timer1(void) interrupt 3

{
<Body of ISR>
TH1 =0XFF;
TL1 = 0xFC;
}

//load with initial values if in mode 0 or 1

Different modes of a Timer


There are four Timer modes designated as Modes 0, 1, 2 and 3. A
particular mode is selected by configuring the M1 & M0 bits of TMOD
register.
Mode
M1
M0
Operation
Mode 0
0
0
13-bit Timer
Mode 1
0
1
16-bit Timer
Mode 2
1
0
8-bit Auto Reload
Mode 3
1
1
Split Timer Mode
(i) Mode 0 : 13-bit Timer
Mode 0 is a 13 bit Timer mode and uses 8 bits of high byte and 5 bit
prescaler of low byte. The value that the Timer can update in mode0 is
from 0000H to 1FFFH. The 5 bits of lower byte append with the bits of
higher byte. The Timer rolls over from 1FFFH to 0000H to raise the
Timer flag.
(ii) Mode 1 : 16-bit Timer
Mode1 is one of the most commonly used Timer modes. It allows all 16
bits to be used for the Timer and so it allows values to vary from 0000H
to FFFFH.
If a value, say YYXXH, is loaded into the Timer bytes, then the delay
produced by the Timer will be equal to the product :
[ ( FFFFH YYXXH +1 ) x ( period of one timer clock ) ].
It can also be considered as follows: convert YYXXH into decimal, say
NNNNN, then delay will be equal to the product :

[ ( 65536-NNNNN ) x ( period of one timer clock ) ].


The period of one timer clock is 1.085 s for a crystal of 11.0592 MHz
frequency as discussed above.
Now to produce a desired delay, divide the required delay by the Timer
clock period. Assume that the division yields a number NNNNN. This is
the number of times Timer must be updated before it stops. Subtract this
number from 65536 (binary equivalent of FFFFH) and convert the
difference into hex. This will be the initial value to be loaded into the
Timer to get the desired delay.
The calculator application in Windows can be a handy tool to carry out
these calculations.
Example code
Time delay in Mode1 using polling method
// Use of Timer mode 1 for blinking LED using polling method
// XTAL frequency 11.0592MHz
#include<reg51.h>
sbit led = P1^0;
// LED connected to 1st pin of port P1
void delay();
main()
{
unsigned int i;
while(1)
{
led=~led;
for(i=0;i<1000;i++)
delay();
}
}
void delay()
mode 1
{

// Toggle LED
// Call delay

// Delay generation using Timer 0

TMOD = 0x01;
TH0= 0xFC;
1millisecond delay
TL0 = 0x66;
TR0 = 1;
while(TF0 == 0);
TR0 = 0;
TF0 = 0;
}

// Mode1 of Timer0
// FC66 evaluated hex value for
// Start Timer
// Using polling method
// Stop Timer
// Clear flag

Example code
Time delay in Mode1 using interrupt method
// Use of Timer mode 1 for blinking LED with interrupt method
// XTAL frequency 11.0592MHz
#include<reg51.h>
sbit LED = P1^0;
// LED connected to 1st pin of
port P1
void Timer(void) interrupt 1
// Interrupt No.1 for Timer
0
{
led=~led;
// Toggle LED on interrupt
}
main()
{
TMOD = 0x01;
TH0=0x00;
TL0=0x00;
IE = 0x82;
TR0=1;
while(1);
}

// Mode1 of Timer0
// Initial values loaded to Timer
// Enable interrupt
// Start Timer
// Do nothing

(iii) Mode 2 : 8-bit Auto Reload


Mode 2 is an 8 bit mode. The initial value is loaded into the higher byte.
A copy of the same is passed to the lower byte. The Timer can update
from 00H to FFH. The Timer rolls over from FFH to initial value
automatically.
Mode 2 is commonly used for setting baud rates for serial
communication.
Example code
Time delay in Mode2 using polling method
// Use of Timer mode 2 for blinking LED with polling method
// XTAL frequency 11.0592MHz
#include<reg51.h>
sbit led = P1^0;
// LED connected to 1st pin of port
P1void delay();
main()
{
unsigned int i;
while(1)
{
led=~led;
// Toggle LED
for(i=0;i<1000;i++)
delay();
// Call delay
}
}
void delay()
{
TMOD = 0x02;
TH0= 0xA2;
TR0 = 1;
while(TF0 == 0);
TR0 = 0;
TF0 = 0;

// Mode1 of Timer0
// Initial value loaded to Timer
// Start Timer
// Polling for flag bit
// Stop Timer
// Clear flag

}
(iv) Mode 3 : Split Timer
In mode 3, also known as split mode, the Timer breaks into two 8-bit
Timers that can count from 00H up to FFH. The initial values are loaded
into the higher byte and lower byte of the Timer. In this case the start
and flag bits associated with the other Timer are now associated with
high byte Timer. So one cannot start or stop the other Timer. The other
Timer can be used in modes 0, 1 or 2 and is updated automatically for
every machine cycle.
For example, if Timer0 is used in split mode, TH0 and TL0 will become
separate Timers. The start and flag bits associated with Timer1 will now
be associated with the TH0. Timer 1 cannot be stopped or started, but
will be updated for every machine cycle.
Split mode is useful when two Timers are required in addition to a baud
rate generator.

INTERRUPTS
Interrupt is one of the most important and powerful concepts and
features in microcontroller/processor applications. Almost all the real
world and real time systems built around microcontrollers and
microprocessors make use of interrupts.
What is Interrupt

The interrupts refer to a notification, communicated to the controller, by


a hardware device or software, on receipt of which controller
momentarily stops and responds to the interrupt. Whenever an interrupt
occurs the controller completes the execution of the current instruction
and starts the execution of an Interrupt Service Routine (ISR) or
Interrupt Handler. ISR is a piece of code that tells the processor or
controller what to do when the interrupt occurs. After the execution of
ISR, controller returns back to the instruction it has jumped from (before
the interrupt was received). The interrupts can be either hardware
interrupts or software interrupts.
Why need interrupts
An application built around microcontrollers generally has the following
structure. It takes input from devices like keypad, ADC etc; processes
the input using certain algorithm; and generates an output which is either
displayed using devices like seven segment, LCD or used further to
operate other devices like motors etc. In such designs, controllers
interact with the inbuilt devices like timers and other interfaced
peripherals like sensors, serial port etc. The programmer needs to
monitor their status regularly like whether the sensor is giving output,
whether a signal has been received or transmitted, whether timer has
finished counting, or if an interfaced device needs service from the
controller, and so on. This state of continuous monitoring is known as
polling.
In polling, the microcontroller keeps checking the status of other
devices; and while doing so it does no other operation and consumes
all its processing time for monitoring. This problem can be
addressed by using interrupts. In interrupt method, the controller
responds to only when an interruption occurs. Thus in interrupt
method, controller is not required to regularly monitor the status
(flags, signals etc.) of interfaced and inbuilt devices.

To understand the difference better, consider the following. The polling


method is very much similar to a salesperson. The salesman goes doorto-door requesting to buy its product or service. Like controller keeps
monitoring the flags or signals one by one for all devices and caters to
whichever needs its service. Interrupt, on the other hand, is very similar
to a shopkeeper. Whosoever needs a service or product goes to him and
apprises him of his/her needs. In our case, when the flags or signals are
received, they notify the controller that they need its service.
Hardware and Software interrupt
The interrupts in a controller can be either hardware or software. If the
interrupts are generated by the controllers inbuilt devices, like timer
interrupts; or by the interfaced devices, they are called the hardware
interrupts. If the interrupts are generated by a piece of code, they are
termed as software interrupts.
Multiple interrupts
What would happen if multiple interrupts are received by a
microcontroller at the same instant? In such a case, the controller assigns
priorities to the interrupts. Thus the interrupt with the highest priority is
served first. However the priority of interrupts can be changed
configuring the appropriate registers in the code.
8051 Interrupts
The 8051 controller has six hardware interrupts of which five are
available to the programmer. These are as follows:

1. RESET interrupt - This is also known as Power on Reset (POR).


When the RESET interrupt is received, the controller restarts executing
code from 0000H location. This is an interrupt which is not available to
or, better to say, need not be available to the programmer.
2. Timer interrupts - Each Timer is associated with a Timer interrupt. A
timer interrupt notifies the microcontroller that the corresponding Timer
has finished counting.
3. External interrupts - There are two external interrupts EX0 and EX1
to serve external devices. Both these interrupts are active low.
InAT89C51, P3.2 (INT0) and P3.3 (INT1) pins are available for external
interrupts 0 and 1 respectively. An external interrupt notifies the
microcontroller that an external device needs its service.
4. Serial interrupt - This interrupt is used for serial communication.
When enabled, it notifies the controller whether a byte has been received
or transmitted.
How is an interrupt serviced?
Every interrupt is assigned a fixed memory area inside the
processor/controller. The Interrupt Vector Table (IVT) holds the starting
address of the memory area assigned to it (corresponding to every
interrupt).

The interrupt vector table (IVT) for AT89C51 interrupts is as follows :


Interrupt
Reset
External interrupt 0
Timer interrupt 0
External interrupt 1
Timer interrupt 1
Serial COM interrupt

ROM Location (Hex)


0000
0003
000B
0013
001B
0023

Pin
9
12
13
-

Flag clearing
Auto
Auto
Auto
Auto
Auto
Programmer clears it

When an interrupt is received, the controller stops after executing the


current instruction. It transfers the content of program counter into stack.
It also stores the current status of the interrupts internally but not on
stack. After this, it jumps to the memory location specified byInterrupt
Vector Table (IVT). After that the code written on that memory area gets
executed. This code is known as the Interrupt Service Routine (ISR) or
interrupt handler. ISR is a code written by the programmer to handle or
service the interrupt.
Programming Interrupts:
While programming interrupts, first thing to do is to specify the
microcontroller which interrupts must be served. This is done by
configuring the Interrupt Enable (IE) register which enables or disables
the various available interrupts. The Interrupt Enable register has
following bits to enable/disable the hardware interrupts of the 8051
controller.

To enable any of the interrupts, first the EA bit must be set to 1. After
that the bits corresponding to the desired interrupts are enabled. ET0,
ET1 and ET2 bits are used to enable the Timer Interrupts 0, 1 and 2,
respectively. In AT89C51, there are only two timers, so ET2 is not used.
EX0 and EX1 are used to enable the external interrupts 0 and 1. ES is
used for serial interrupt.

EA bit acts as a lock bit. If any of the interrupt bits are enabled but
EA bit is not set, the interrupt will not function. By default all the
interrupts are in disabled mode.
Note that the IE register is bit addressable and individual interrupt bits
can also be accessed.
For example
IE = 0x81; enables External Interrupt0 (EX0)
IE = 0x88; enables Serial Interrupt
Setting the bits of IE register is necessary and sufficient to enable the
interrupts. Next step is to specify the controller what to do when an
interrupt occurs. This is done by writing a subroutine or function for the
interrupt. This is the ISR and gets automatically called when an interrupt
occurs. It is not required to call the Interrupt Subroutine explicitly in the
code.
An important thing is that the definition of a subroutine must have the
keyword interrupt followed by the interrupt number. A subroutine for a
particular interrupt is identified by this number. These subroutine
numbers corresponding to different interrupts are tabulated below.
Number
0
1
2
3
4
5

Interrupt
External0
Timer0
External1
Timer1
Serial
Timer2

Symbol
EX0
IT0
EX1
IT1
ES
ET2

For example : Interrupt routine for Timer1


void ISR_timer1(void) interrupt 3
{
<Body of ISR>
}
For example : Interrupt routine for External Interrupt0 (EX0)
void ISR_ex0(void) interrupt 0
{

<Body of ISR>
}
Note that the interrupt subroutines always have void return type. They
never return a value.
1. Programming Timer Interrupts
The timer interrupts IT0 and IT1 are related to Timers 0 and 1,
respectively. (Please refer 8051 Timers for details on Timer registers and
modes.) The interrupt programming for timers involves following steps :
1.
Configure TMOD register to select timer(s) and its/their
mode.
2.
Load initial values in THx and TLx for mode 0 and 1; or in
THx only for mode 2.
3.
Enable Timer Interrupt by configuring bits of IE register.
4.
Start timer by setting timer run bit TRx.
5.
Write subroutine for Timer Interrupt. The interrupt number
is 1 for Timer0 and 3 for Timer1.
Note that it is not required to clear timer flag TFx.
6.
To stop the timer, clear TRx in the end of subroutine.
Otherwise it will restart from 0000H in case of modes 0 or 1 and from
initial values in case of mode 2.
7.
If the Timer has to run again and again, it is required to
reload initial values within the routine itself (in case of mode 0 and 1).
Otherwise after one cycle timer will start counting from 0000H.
Example code :
Timer interrupt to blink an LED; Time delay in mode1 using interrupt
method
// Use of Timer mode0 for blinking LED using interrupt method
// XTAL frequency 11.0592MHz
#include<reg51.h>
sbit LED = P1^0;
//LED connected to D0 of port 1

void timer(void) interrupt 1


//interrupt no. 1 for Timer 0
{
led=~led;
//toggle LED on interrupt
TH0=0xFC;
// initial values loaded to timer
TL0=0x66;
}
main()
{
TMOD = 0x01;
// mode1 of Timer0
TH0 = 0xFC;
// initial values loaded to timer
TL0 = 0x66;
IE = 0x82;
// enable interrupt
TR0 = 1;
//start timer
while(1);
// do nothing
}
2. Programming External Interrupts
The external interrupts are the interrupts received from the (external)
devices interfaced with the microcontroller. They are received at INTx
pins of the controller. These can be level triggered or edge triggered. In
level triggered, interrupt is enabled for a low at INTx pin; while in
case of edge triggering, interrupt is enabled for a high to low
transition at INTx pin. The edge or level trigger is decided by the
TCON register. The TCON register has following bits:

Setting the IT0 and IT1 bits make the external interrupt 0 and 1 edge
triggered respectively. By default these bits are cleared and so external
interrupt is level triggered.
Note : For a level trigger interrupt, the INTx pin must remain low until
the start of the ISR and should return to high before the end of ISR. If

the low at INTx pin goes high before the start of ISR, interrupt will not
be generated. Also if the INTx pin remains low even after the end of
ISR, the interrupt will be generated once again. This is the reason why
level trigger interrupt (low) at INTx pin must be four machine cycles
long and not greater than or smaller than this.
Following are the steps for using external interrupt :
1.
Enable external interrupt by configuring IE register.
2.
Write routine for external interrupt. The interrupt number is 0 for
EX0 and 2 for EX1 respectively.
Example code
//Level trigger external interrupt
void main()
{
IE = 0x81;
while(1);
}
void ISR_ex0(void) interrupt 0
{
<body of interrupt>
}
Example code
//Edge trigger external interrupt
void main()
{
IE = 0x84;
IT1 = 1;
while(1);
}
void ISR_ex1(void) interrupt 2
{
<body of interrupt>
}

3. Programming Serial Interrupt


To use the serial interrupt the ES bit along with the EA bit is set.
Whenever one byte of data is sent or received, the serial interrupt is
generated and the TI or RI flag goes high. Here, the TI or RI flag needs
to be cleared explicitly in the interrupt routine (written for the Serial
Interrupt).
The programming of the Serial Interrupt involves the following steps:
1.
Enable the Serial Interrupt (configure the IE register).
2.
Configure SCON register.
3.
Write routine or function for the Serial Interrupt. The interrupt
number is 4.
4.
Clear the RI or TI flag within the routine.
Example code
Send A from serial port with the use of interrupt
// Sending A through serial port with interrupt
// XTAL frequency 11.0592MHz
void main()
{
TMOD = 0x20;
TH1 = -1;
SCON = 0x50;
TR1 = 1;
IE = 0x90;
while(1);
}
void ISR_sc(void) interrupt 4
{
if(TI==1)
{
SBUF = A;

TI = 0;
}
else
RI = 0;
}
Example code
// Receive data from serial port through interrupt
// XTAL frequency 11.0592MHz
void main()
{
TMOD = 0x20;
TH1 = -1;
SCON = 0x50;
TR1 = 1;
IE = 0x90;
while(1);
}
void ISR_sc(void) interrupt 4
{
unsigned char val;
if(TI==1)
{
TI = 0;
}
else
{
val = SBUF;
RI = 0;
}
}

Programming multiple interrupts

Multiple interrupts can be enabled by setting more than one interrupts in


the IE register. If more than one interrupts occur at the same time, the
interrupts will be serviced in order of their priority. By default the
interrupts have the following priorities in descending order:
Interrupt
External0
Timer0
External1
Timer1
Serial
Timer2

Default priority order of Interrupts


Symbol
EX0
ET0
EX1
ET1
ES
ET2

The priority of the interrupts can be changed by programming the bits of


Interrupt Priority (IP) register. The IP register has the following bit
configuration:

First two MSBs are reserved. The remaining bits are the priority bits for
the available interrupts.
Bit
PX0
PT0
PX1
PT1
PS
PT2

Interrupt
External0
Timer0
External1
Timer1
Serial
Timer2

Symbol
EX0
ET0
EX1
ET1
ES
ET2

Setting a particular bit in IP register makes the corresponding interrupt


of the higher priority.
For example, IP = 0x08; will make Timer1 priority higher. So the
interrupt priority order will change as follows (in descending order):
Default Priority
EX0
ET0

IP = 0x08
Changed Priority
ET1
EX0

EX1
ET1
ES
ET2

ET0
EX1
ES
ET2

More than one bit in IP register can also be set. In such a case, the higher
priority interrupts will follow the sequence as they follow in default
case.
For example, IP = 0x0A; will make Timer0 and Timer1 priorities higher.
So the interrupt priority order will change as follows (in descending
order):
Default Priority
EX0
ET0
EX1
ET1
ES
ET2

IP = 0x0A
Changed Priority
ET0
ET1
EX0
EX1
ES
ET2

Note that the Timer 0 and 1 have been assigned higher priorities in the
same sequence as they follow in default case.
Example code
// Toggle LEDs by Timer and External Interrupt
#include<reg51.h>
sbit led_timercontrol = P1^0;
sbit led_externalcontrol = P1^0;
void external(void) interrupt 0
{
led_externalcontrol = ~ led_externalcontrol;
}
void timer(void) interrupt 1
{
led_timercontrol = ~ led_timercontrol;
}

main()
{
TMOD = 0x01;
TH0 = 0x00;
TL0 = 0x00;
IE = 0x83;
TR0 = 1;
while(1);
}

SERIAL
COMMUNICATION
Serial Communication is a form of I/O in which the bits of a byte being
transferred appear one after other in a timed sequence on a single wire.
Serial Communication uses two methods, asynchronous and

synchronous. The Synchronous method transfers a block of data at a


time, while the asynchronous method transfers a single byte at a
time. In Synchronous Communication the data get transferred
based on a common clock signal. But in Asynchronous
communication, in addition to the data bit, one start bit and one
stop bit is added. These start and stop bits are the parity bits to identify
the data present between the start and stop bits.
The 8051 has two pins that are used specifically for transferring and
receiving data serially. These two pins are called TXD and RXD and are
part of the Port-3 group (Port-3.0 and Port-3.1). Pin 11 of the 8051 is
assigned to TXD and pin 10 is designated as RXD. These pins are TTL
compatible; therefore they require a line driver to make them RS232
compatible. The line driver chip is MAX232. The MAX232 uses +5v
power source, which is same as the source voltage for 8051.
The 8051 transfers and receives data serially at different baud rates. The
baud rate of the 8051 is programmed into the timers.
Generally Null Modem Connections are used for Data transfer between
two device serially.

SCON (Serial Control Register) is responsible for all serial

communication related settings in 8051.

Calculating Baud Rates


As we know that 8051 microcontrollers takes 12 clock cycles to
complete one machine cycle.
So our effective Instruction execution frequency is Fosc/12. If we are
using a crystal of 11.0592MHz; our efeective frequency is somewhere
around Feffective= 11.0592/12 MHz => 921.6 KHz.
8051 UART or serial communication block further divide this frequency
(921.6 KHz) by 32 to generate its baud rate.
Therefore Effective frequency available to generate Baud rates is 921.6
KHz/32 = 28800 Hz.

So for different standard baud rates the values of TH1 will be


Baud Rate 9600 -- TH1=0xFD --- because 28800/9600 = 3
Serial Buffer Register (SBUF): SBUF is an 8-bit register used for
serial communication specific programs. For a byte to to be transferred
via TxD line, it must be placed in the SBUF register. Similarly SBUF
holds the byte of data when it is received by 8051's receive line. SBUF
can be accessed similar to any other register in 8051, but it is not bit
addressable.
Hardware Connections: As explained above We need a RS232-TTL
level converter to enable 8051 communicate serially with other RS232
compatible devices. Here is the connection schematic...

///////////////////////////////////////
Setting the Serial Port Baud Rate
Once the Serial Port Mode has been configured, as explained above, the program
must configure the serial ports baud rate. This only applies to Serial Port modes 1 and
3. The Baud Rate is determined based on the oscillators frequency when in mode 0
and 2. In mode 0, the baud rate is always the oscillator frequency divided by 12. This
means if youre crystal is 11.059Mhz, mode 0 baud rate will always be 921,583 baud.
In mode 2 the baud rate is always the oscillator frequency divided by 64, so a
11.059Mhz crystal speed will yield a baud rate of 172,797.
In modes 1 and 3, the baud rate is determined by how frequently timer 1 overflows.
The more frequently timer 1 overflows, the higher the baud rate. There are many
ways one can cause timer 1 to overflow at a rate that determines a baud rate, but the
most common method is to put timer 1 in 8-bit auto-reload mode (timer mode 2) and

set a reload value (TH1) that causes Timer 1 to overflow at a frequency appropriate to
generate a baud rate.
To determine the value that must be placed in TH1 to generate a given baud rate, we
may use the following equation (assuming PCON.7 is clear).
TH1 = 256 - ((Crystal / 384) / Baud)
If PCON.7 is set then the baud rate is effectively doubled, thus the equation becomes:
TH1 = 256 - ((Crystal / 192) / Baud)
For example, if we have an 11.059Mhz crystal and we want to configure the serial
port to 19,200 baud we try plugging it in the first equation:
TH1 = 256 - ((Crystal / 384) / Baud)
TH1 = 256 - ((11059000 / 384) / 19200 )
TH1 = 256 - ((28,799) / 19200)
TH1 = 256 - 1.5 = 254.5
As you can see, to obtain 19,200 baud on a 11.059Mhz crystal wed have to set TH1 to
254.5. If we set it to 254 we will have achieved 14,400 baud and if we set it to 255 we
will have achieved 28,800 baud. Thus were stuck...
But not quite... to achieve 19,200 baud we simply need to set PCON.7 (SMOD).
When we do this we double the baud rate and utilize the second equation mentioned
above. Thus we have:
TH1 = 256 - ((Crystal / 192) / Baud)
TH1 = 256 - ((11059000 / 192) / 19200)
TH1 = 256 - ((57699) / 19200)
TH1 = 256 - 3 = 253
Here we are able to calculate a nice, even TH1 value. Therefore, to obtain 19,200
baud with an 11.059MHz crystal we must:
1. Configure Serial Port mode 1 or 3.
2. Configure Timer 1 to timer mode 2 (8-bit auto-reload).
3. Set TH1 to 253 to reflect the correct frequency for 19,200 baud.
4. Set PCON.7 (SMOD) to double the baud rate.

Final Schematic Diagram -

/
**********************************************************
**********
>Example program to send some characters serially at 9600 bps.
>Make all connection according to the schematic given above.
>Serial port Mode 1 is used with 8bit data, 1 stop bit, 1 start bit
>One important thing is that all calulations for baud rate generation
using Timer1 are made for Timer1 8 bit auto reload mode
**********************************************************
**********/
#include>at89x52.h<
void main(void)
{

TMOD=0x20; // Timer1 Mode2 8 bit auto reload


TH1=0xFD; // 9600 bps
SCON=0x50; // 8 Data bit, 1 start bit, 1 stop bit
TR1=1; // Timer1 ON
while(1==1)
{
SBUF='S';
while(TI==0); // Pole TI flag for complete transmission
TI=0;
SBUF='A';
while(TI==0);
TI=0;
SBUF='M';
while(TI==0);
TI=0;
}
}

/*********************************************************
***********
>Example program to send a string serially at 9600 bps.
>Make all connection according to the schematic given above.
>Serial port Mode 1 is used with 8bit data, 1 stop bit, 1 start bit
>One important thing is that all calulations for baud rate generation
using Timer1 are made for Timer1 8 bit auto reload mode
**********************************************************
**********/
#include>at89x52.h<
void serial(unsigned char x)

{
SBUF=x;
while(TI==0);
TI=0;
}
void rs_puts(char *aaa)
{
unsigned int i;
for(i=0;aaa[i]!=0;i++)
{
serial(aaa[i]);
}
}
void main(void)
{
TMOD=0x20; // Timer1 Mode2 8 bit auto reload
TH1=0xFD; // 9600 bps
SCON=0x50; // 8 Data bit, 1 start bit, 1 stop bit
TR1=1; // Timer1 ON
while(1==1)
{
rs_puts("www.electrroons.com\n\r");
}
}
Now its your turn to make a program to receive data from UART and
show it on LCD. Poll RI (Receive Flag) and as RI goes 1; retrive your
data from serial buffer, and call lcd_data(c=SBUF); .

LCD
Interfacing 162 LCD with 8051
In this discussion we are going to see how to interface 162 LCD
module to AT89C51which is a 8051 family microcontroller. We use
LCD display for the messages for more interactive way to operate the
system or displaying error messages etc. interfacing LCD to
microcontroller is very easy if you understanding the working of LCD,
in this session I will not only give the information of LCD and also
provide the code in C language which is working fine without any
errors.
Also get an idea about Interfacing LEDs with 8051 Mirocontroller
Interfacing 162 LCD with 8051 Circuit Diagram:

Interfacing LCD to AT89C51:


LCD: 162 Liquid Crystal Display which will display the 32 characters
at a time in two rows (16 characters in one row). Each character in the
display of size 57 pixel matrix, Although this matrix differs for
different 162 LCD modules if you take JHD162A this matrix goes to
58. This matrix will not be same for all the 162 LCD modules. There
are 16 pins in the LCD module, the pin configuration us given below

PI
N
NO

NAME

VSS

Ground pin

VCC

Power supply pin of 5V

VEE

Used for adjusting the contrast commonly attached to the potentiometer.

RS

RS is the register select pin used to write display data to the LCD (characters), this pin has
to be high when writing the data to the LCD. During the initializing sequence and other
commands this pin should low.

R/W

Reading and writing data to the LCD for reading the data R/W pin should be high (R/W=1)
to write the data to LCD R/W pin should be low (R/W=0)

Enable pin is for starting or enabling the module. A high to low pulse of about 450ns pulse
is given to this pin.

DB0

DB1

DB2

10

DB3

11

DB4

12

DB5

13

DB6

14

DB7

15

LED+

Back light of the LCD which should be connected to Vcc

16

LED-

Back light of LCD which should be connected to ground.

FUNCTION

DB0-DB7 Data pins for giving data(normal data like numbers characters or command
data) which is meant to be displayed

So by reading the above table you can get a brief idea how to display a
character. For displaying a character you should enable the enable pin
(pin 6) by giving a pulse of 450ns, after enabling the pin6 you should

select the register select pin (pin4) in write mode. To select the register
select pin in write mode you have to make this pin high (RS=1), after
selecting the register select you have to configure the R/W to write mode
that is R/W should be low (R/W=0).
Follow these simple steps for displaying a character or data

E=1; enable pin should be high

RS=1; Register select should be high

R/W=0; Read/Write pin should be low.


To send a command to the LCD just follows these steps:

E=1; enable pin should be high

RS=0; Register select should be low

R/W=1; Read/Write pin should be high.


Commands: There are some preset commands which will do a specific
task in the LCD. These commands are very important for displaying data
in LCD. The list of commands given below:
Command

Function

0F

For switching on LCD, blinking the cursor.

Clearing the screen

Return home.

Decrement cursor

Increment cursor

Display on and also cursor on

80

Force cursor to beginning of the first line

C0

Force cursor to beginning of second line

38

Use two lines and 5x7 matrix

83

Cursor line 1 position 3

Command

Function

3C

Activate second line

0C3

Jump to second line position 3

0C1

Jump to second line position1

To get the detailed information, Click Here and Download the Datasheet
Circuit Explanation:
The crystal oscillator is connected to XTAL1 and XTAL2 which will
provide the system clock to the microcontroller the data pins and
remaining pins are connected to the microcontroller as shown in the
circuit. The potentiometer is used to adjust the contrast of the LCD. You
can connect data pins to any port. If you are connecting to port0 then
you have to use pull up registers. The enable, R/W and RS pins are
should be connected to the 10, 11 and 16 (P3.3, P3.4 and P3.5).
Programming LCD to 8051:
Coming to the programming you should follow these steps:

STEP1: Initialization of LCD.

STEP2: Sending command to LCD.

STEP3: Writing the data to LCD.


Initializing LCD: To initialize LCD to the 8051 the following instruction
and commands are to be embed in to the functions

0x38 is used for 8-bit data initialization.

0xFH for making LCD on and initializing the cursor.

0X6H for incrementing the cursor which will help to display


another character in the LCD

0x1H for clearing the LCD.


Sending Data to the LCD:

E=1; enable pin should be high

RS=1; Register select should be high for writing the data

Placing the data on the data registers

R/W=0; Read/Write pin should be low for writing the data.


Important Post Interfacing 7 Segment Display with 8051
Microcontroller

The program given below will use above functions and display the
complete string which is given by the programmer to display the data.
You have provided two demo codes working properly and easy to
understand.

#include <REGX51.H>
#include <string.h>
#include <stdio.h>
sfr LCD=0xa0;
sbit EN=P3^6;
sbit RS=P3^7;
voidnop(void);
void delay_1s(unsigned char t);
voidinitial_lcd(void);
void delay(void);
voidstring_to_lcd(unsigned char *s);
voidwrite_lcd(unsigned char dat,unsignedint com);
void delay_50ms(unsigned char x);
void main()
{
P0=0xff;
P1=0xff;
P3=0xff;
delay_50ms(4);
initial_lcd();
write_lcd(0x80,0);
string_to_lcd( WELCOME TO );
write_lcd(0xc0,0);
string_to_lcd(INNOVATE ENG SOL);
}
voidnop(void)
{
unsigned char n;

for(n=0;n<20;n++);
}
/delay routine..//
void delay_1s(unsigned char t)
{
unsigned char i,j;
for(i=0;i<t;i++)
{
for(j=0;j<20;j++)
{
TMOD=0x01;
TH0=0x3c;
//for 12MHz (12/12MHZ)=1u>per cycle operation
TL0=0xb0;
//50ms delay get (50m/1u)=50000;
TR0=1;
//Load value is =65536-50000=15536(=3cb0H)
while(TF0!=1); //wait for overflow flag
TF0=0;
}
}
}
voidinitial_lcd(void)
{
write_lcd(0x38,0);
write_lcd(0x0c,0);
write_lcd(0x01,0);
}
voidwrite_lcd(unsigned char dat,unsignedint com)
{
RS=com;
LCD=dat;nop();
EN=1;nop();
EN=0;
nop();
}
voidstring_to_lcd(unsigned char *s)
{

unsigned char i,l;


l=strlen(s);
for(i=0;i<l;i++)
{
write_lcd(*s,1);delay_50ms(1);
s++;
}
}
void delay_50ms(unsigned char x)
{
unsigned char i;
for(i=0;i<x;i++)
{
TMOD=0x01;
TH0=0x3c;
TL0=0xb0;
TR0=1;
while(!TF0);
TF0=0;
TR0=0;
}
}
********************************
SECOND
DEMO
CODE*****************************
#include<reg51.h>
#define cmdport P3
#define dataport P2
#define q 100
sbitrs = cmdport^0;
//register select pin
sbitrw = cmdport^1;
//read write pin
sbit e = cmdport^6;
//enable pin
void delay(unsigned intmsec)
//Function to provide time delay in
msec.
{
inti,j ;

for(i=0;i<msec;i++)
for(j=0;j<1275;j++);
}
voidlcdcmd(unsigned char item) //Function to send command to LCD
{
dataport = item;
rs= 0;
rw=0;
e=1;
delay(1);
e=0;
}
voidlcddata(unsigned char item) //Function to send data to LCD
{
dataport = item;
rs= 1;
rw=0;
e=1;
delay(1);
e=0;
}
void main()
{
lcdcmd(0x38); //for using 8-bit 2 row mode of LCD
delay(100);
lcdcmd(0x0E); //turn display ON for cursor blinking
delay(100);
lcdcmd(0x01); //clear screen
delay(100);
lcdcmd(0x06); //display ON
delay(100);
lcdcmd(0x86); //bring cursor to position 6 of line 1
delay(100);
lcddata(A);
}

KEYPAD
NXPs 8051 (AT89V51RD2), 8051 Slicker Kit is proposed to smooth
the progress of developing and debugging of various designs
encompassing of speed 8-bit Microcontrollers.
Keypad
A keypad is a set of buttons arranged in a block or "pad" which usually
bear digits, symbols and usually a complete set of alphabetical letters. If
it mostly contains numbers then it can also be called a numeric keypad.
Here we are using 4 X 4 matrix keypad.
Interfacing keypad
Fig. 1 shows how to interface the 4 X 4 matrix keypad to two ports in
microcontroller. The rows are connected to an output port and the
columns are connected to an input port.
To detect a pressed key, the microcontroller grounds all rows by
providing 0 to the output latch, and then it reads the columns. If the data

read from the columns is D3-D0=1111, no key has been pressed and the
process continues until a key press is detected. However, if one of the
column bits has a zero, this means that a key press has occurred. For
example, if D3-D0=1101, this means that a key in the D1 column has
been pressed.
After a key press is detected, the microcontroller will go through the
process of identifying the key. Starting with the top row, the
microcontroller grounds it by providing a low to row D0 only; then it
reads the columns.
If the data read is all 1s, no key in that row is activated and the process is
moved to the next row. It grounds the next row, reads the columns, and
checks for any zero. This process continues until the row is identified.
After identification of the row in which the key has been pressed, the
next task is to find out which column the pressed key belongs to.

Fig. 1 Interfacing keypad to Microcontroller

Interfacing keypad with 8051


We now want to scan a keypad in 8051 Slicker Board. In case of 4X4
matrix Keypad both the ends of switches are connected to the port pin
i.e. four rows and four columns. So in all sixteen switches have been
interfaced using just eight lines.
1Keypads arranged by matrix format, each row and column section
pulled by high or low by selection J5, all row lines(P2.4 P2.7) and
column lines(P2.0 to P2.3) connected directly by the port pins.

Pin Assignment with 8051

4x4
Lines

ROW

COLUM
N

Matrix
8051 Lines

ROW-0

P2.0

ROW-1

P2.1

ROW-2

P2.2

ROW-4

P2.3

COLUMN-0

P2.4

COLUMN-1

P2.5

COLUMN-2

P2.6

COLUMN-3

P2.7

Circuit Diagram to Interface keypad with 8051

4x4 Matrix Keypad

Source Code

The Interfacing keypad with 8051 program is very simple and straight
forward that scan akeypad rows and columns. When the rows and
columns are detected then it will display in PC through UART0. The C
programs are developed in Keil software.
C Program to 4 X 4 matrix keypad using 8051
**********************************************************
Title : Program to keypad interfacing
**********************************************************
#include <stdio.h>
Functions

//Define I/O

#include <reg51.h>
Registers

//Define 8051

#define DATA P1
Port1

//Define DATA to

void lcd_init(void);

//LCD Initialization

void lcd_cmd(unsigned char);

//LCD Command Function

void lcd_display(unsigned char);

//LCD Display Function

void Key_Scan(void);

//KeyScan Function

void DelayMs(int);

//DelayMs Function

sbit RS

//Register Select

= P3^5;

sbit RW = P3^6;

//LCD Read/Write

sbit lcd_e = P3^7;

//LCD Enable

unsigned char R,C,ch,d=0x81;


unsigned int i=0;
unsigned char Key[4][4] =
Character

{'C','D','E','F',

'8','9','A','B',

//Matrix Keypad
//Initialization
'4','5','6','7',
'0','1','2','3',};

code unsigned char msg[] = ("KEYPAD TEST PGM ");


the Message

//Display

code unsigned char msg1[] = ("PRES ANY KEY... ");

//in LCD

//------------------------------//

Main Program

//------------------------------void main()
{
lcd_init();
DelayMs(20);
lcd_cmd(0x01);
lcd_e=0;
lcd_cmd(0x80);
while(1)

{
Key_Scan();
lcd_e=1;
DelayMs(5);
ch = Key[R][C];

//Assign Key

DelayMs(5);

//and Row

value to ch;
Value of Keypad
lcd_display(ch);
lcd_cmd(d++);
DelayMs(10);
P2=0xFF;
}
}
//------------------------------//

Key Scan Function

//------------------------------void Key_Scan(void)
{
unsigned int i = 0;
//Scanning for Row Value

P2 = 0x0F;

//Initialize Port2 to 0Fh

while(P2 == 0x0F);
if(P2 == 0x0E)

//Checking for Row0

R = 0;
else if(P2 == 0x0D)

//Checking for Row1

R = 1;
else if(P2 == 0x0B)

//Checking for Row2

R = 2;
else if(P2 == 0x07)
R = 3;
P2 = 0xF0;

//Checking for Row3


//Scanning for Column Value
//Initialize Port2 to F0h

while(P2 == 0xF0);
if(P2 == 0xE0)

//Checking for Column0

C = 0;
else if(P2 == 0xD0)

//Checking for Column1

C = 1;
else if(P2 == 0xB0)

//Checking for Column2

C = 2;
else if(P2 == 0x70)
C = 3;

//Checking for Column3

DelayMs(20);
}
//------------------------------//

LCD command Function

//------------------------------void lcd_cmd(unsigned char cmnd)


{
DATA = cmnd;
RS = 0;
//RS:Register Select
RW = 0;
//RW:Read/Write
lcd_e = 1;
DelayMs(15);
lcd_e = 0;
}
//------------------------------//

LCD Data Function

//------------------------------void lcd_display(unsigned char dat)


{

//LCD Enable

DATA = dat;
RS = 1;

//RS:Register Select

RW = 0;

//RW:Read/Write

lcd_e = 1;
DelayMs(15);
lcd_e = 0;
}
//------------------------------//

LCD Initialization

//------------------------------void lcd_init(void)
{
unsigned char i;
lcd_cmd(0x38);

//2x16 Character 5x7

dot
DelayMs(15);
lcd_cmd(0x0c);

//matrix LCD,8-bit format


//Display On, cursor off

DelayMs(15);
lcd_cmd(0x06);

//Shift Cursor to right

DelayMs(15);
lcd_cmd(0x01);

//Clear display screen

DelayMs(15);
//-----------------------------------//

First Line Message Display

//-----------------------------------lcd_cmd(0x80);

//First Line Initialization

DelayMs(15);
i=0;
while(msg[i]!='\0')
{
lcd_display(msg[i]);
i++;
}
DelayMs(20);
//-----------------------------------// Second Line Message Display
//-----------------------------------lcd_cmd(0xc0);
DelayMs(15);
i=0;

//Second Line Initialization

while(msg1[i]!='\0')
{
lcd_display(msg1[i]);
i++;
}
DelayMs(30);
}
//-------------------------//

DelayMs Function

//-------------------------void DelayMs(int k)
{
unsigned int a,b;
for(a=0;a<=k;a++)
for(b=0;b<1275;b++);
}

ADC
Introduction

ADC0808 is one of the useful chips from National Semiconductor. See


in figure given aside. In lot of embedded systems micro controllers
needs to take analog input. Most of the sensors AND transducers such as
temperature, humidity, pressure, are analog. For interfacing these
sensors to micro controllers we require to convert the analog output of
these sensors to digital so that the controller can read it. Some micro
controllers have built in Analog to Digital Converter (ADC) so there is
no
need of external ADC. For controllers that dont have internal
ADC external ADC is used.
One of the most commonly used ADC is ADC0808. ADC 0808 is a
Successive approximation type with 8 channels i.e. it can directly access
8 single ended analog signals. ADC0808 has an 8-bit data output just
like the ADC804. The 8 analog input channels are multiplexed and
selected according to table given below I/O pins using three address pins
A, B, and C.
In the ADC0808, Vref(+) and Vref(-) set the reference voltage. If
Vref(-)=Gnd and Vref(+)=5V, the step size is 5V/256 = 19.53mV.
Therefore, to get a 10mV step size we need to set Vref(+)=2.56V and
Vref(-)=Gnd. From figure given below of ADC0808, notice the ALE
pins. We use A, B, and C addresses to select IN0 IN7, and activate
ALE to latch in the address. SC is for the start conversion. SC is same as
the WR pin in other ADC chips. EOC is for end-of-conversion, and OE

is for output enable (READ). The EOC and OE are the same as the
INTR and RD pins respectively.
Features of ADC 0808
1.
Inbuilt 8 analog channels with multiplexer
2.
Zero or full scale adjustment is not required
3.
0 to 5V input voltage range with a single polarity 5V supply
4.
Output is TTL compatible
5.
High speed
6.
Low conversion time (100micro second)
7.
High accuracy
8.
8-bit resolution
9.
Low power consumption (less than 15mW)
10.
Easy to interface with all microprocessor
11.
Minimum temperature dependence
Pin Configuration of ADC 0808

I/O Pins (Analog channel selection)

Description

ADC devices - Analog-to-digital converters are among the most


widely used devices for data acquisition. Digital computers use binary
(discrete) values, but in the physical world everything is analog.
Temperature, pressure, humidity and velocity are a few examples of
physical quantities that we deal with everyday. A physical quantity can
be converted into electrical signals using a device called as transducer.
Transducers are also referred to as sensors. We need an analog to digital
converter to translate he analog signals to digital numbers so that
the microcontroller can read and process them. An ADC has n-bit
resolution where n can be 8, 10, 12, 16 or even 24 bits. The highestresolution ADC size, where step size is the smallest change that can be
discerned by an ADC.

CS - Chip select is an active low input used to activate the


ADC0808 chip. To access the ADC0804, this pin must be low.
.
RD (read) - This is an input signal and is active low. The ADC
converts the analog input to its binary equivalent and holds it in an

internal register. RD is used to get the converted data out of the


ADC0808 chip. When CS=0, if a high-to-low pulse is applied to the RD
pin, the 8-bit digital output shows up at the D0 D7 data pins. The RD
pin is also referred to as output enable (OE).

WR (write; start conversion) - This is an active low input used to


inform the ADC0808 to start the conversion process. If CS=0 when WR
makes a low-to-high transition, the ADC0808 starts converting the
analog input value of Vin to an 8-bit digital number. The amount of time
it takes to convert varies depending on the CLK IN and CLK R values
explained below. When the data conversion is complete, the INTR pin is
forced low by the ADC0808.

ADDRESS LINE A, B, C - The device contains 8-channels. A


particular channel is selected by using the address decoder line. The
TABLE 1 shows the input states for address lines to select any channel.

Address Latch Enable (ALE) - The address is latched on the Low


High transition of ALE.

START - The ADCs Successive Approximation Register (SAR)


is reset on the positive edge i.e. Low- High of the Start Conversion
pulse. Whereas the conversion is begun on the falling edge i.e. High
Low of the pulse.

Output Enable - Whenever data has to be read from the ADC,


Output Enable pin has to be pulled high thus enabling the TRI-STATE
outputs, allowing data to be read from the data pins D0-D7.

End of Conversion (EOC) - This pin becomes High when the


conversion has ended, so the controller comes to know that the data can
now be read from the data pins.

Clock - External clock pulses are to be given to the ADC; this can
be given either from LM 555 in Astable mode or the controller can also
be used to give the pulses.


D0 D7 - D0- D7 are the digital data output pins since ADC0808
is a parallel ADC chip. These are tri state buffered and the converted
data is accessed only when CS=0 and RD is forced low. To calculate the
output voltage, we can use following formula
Dout = Vin / step size
Where Dout = digital data output, Vin = analog input voltage, and step
size is the smallest input change.

ALGORITHM :

1.
2.

Start.
Select the channel.

3.
A Low High transition on ALE to latch in the address.
4.
A Low High transition on Start to reset the ADCs SAR.
5.
A High Low transition on ALE.
6.
A High Low transition on start to start the conversion.
7.
Wait for End of cycle (EOC) pin to become high.
8.
Make Output Enable pin High.
9.
Take Data from the ADCs output
10. Make Output Enable pin Low.
11. Stop
The total numbers of lines required are:

data lines: 8

ALE: 1


START: 1

EOC:1

Output Enable:1
I.e. total 12 lines. You can directly connect the OE pin to Vcc. Moreover
instead of polling for EOC just put some delay so instead of 12 lines you
will require 10 lines.
You can also provide the clock through the controller thus eliminating
the need of external circuit for clock.
Calculating Step Size
ADC 0808 is an 8 bit ADC i.e. it divides the voltage applied at Vref+ &
Vref- into 28 i.e. 256 steps.
Step Size = (Vref+ -Vref-)/256
Suppose Vref+ is connected to Vcc i.e. 5V & Vref- is connected to the
Gnd then the step size will be
Step size= (5 - 0)/256= 19.53 mV.
Calculating Dout
The data we get at the D0 - D7 depends upon the step size & the Input
voltage i.e. Vin.
Dout = Vin /step Size.
If you want to interface sensors like LM35 which has output 10mv/C
then I would suggest that you set the Vref+ to 2.56v so that the step size
will be
Step size= (2.56 - 0)/256= 10 mV.
So now whatever reading that you get from the ADC will be equal to the
actual temperature.

Steps to program ADC 0808


The following are steps to get data from an ADC0808. Select an analog
channel by providing bits to A, B, and C addresses according to the
Table Analog channel selection.
1.
Activate the ALE (Address Latch Enable) pin. It needs an L-to-H
pulse to latch in the address. See the figure given below.
2. Activate SC (Start Conversion) by an L-to-H pulse to initiate
conversion.
3.
Monitor EOC (End of Conversion) to see whether conversion is
finished. H-to-L output indicates that he data is converted and is ready to
be picked up.
4.
Activate OE (Output Enable) to read data out of the ADC chip. An
L-to-H pulse to the OE pin will bring digital data out of the chip. OE pin
is the same as the RD pin in other ADC chips.
There is no self clocking and the clock must be provided from an
external source to the CLK pin. Although the speed of conversion also
depends on the frequency of the clock connected to the CLK pin, it
cannot be faster than 100 microseconds.

Functional block diagram of IC ADC 0808

Interfacing

channel

8-bit

ADC

to

8051

OR
In lot of embedded systems microcontrollers needs to take analog input.
Most of the sensors & transducers such as temperature, humidity,
pressure, are analog. For interfacing these sensors to microcontrollers we
require to convert the analog output of these sensors to digital so that the
controller can read it. Some microcontrollers have built in Analog to
Digital Convertor (ADC) so there is no need of external ADC. For
microcontrollers that dont have internal ADC external ADC is used.
One of the most commonly used ADC is ADC0808. ADC 0808 is a
Successive approximation type with 8 channels i.e. it can directly access
8 single ended analog signals.
I/O Pins
ADDRESS LINE A, B, C

The device contains 8-channels. A particular channel is selected by using


the address decoder line. The TABLE 1 shows the input states for
address lines to select any channel.
channel_select_adc_1
Address Latch Enable ALE
The address is latched on the Low High transition of ALE.
START
The ADCs Successive Approximation Register (SAR) is reset on the
positive edge i.e. Low- High of the Start Conversion pulse. Whereas the
conversion is begun on the falling edge i.e. High Low of the pulse.
Output Enable
Whenever data has to be read from the ADC, Output Enable pin has to
be pulled high thus enabling the TRI-STATE outputs, allowing data to be
read from the data pins D0-D7.
End of Conversion (EOC)
This Pin becomes High when the conversion has ended, so the controller
comes to know that the data can now be read from the data pins.
Clock
External clock pulses are to be given to the ADC; this can be given
either from LM 555 in Astable mode or the controller can also be used to
give the pulses.
ALGORITHM
1. Start.
2. Select the channel.
3. A Low High transition on ALE to latch in the address.
4. A Low High transition on Start to reset the ADCs SAR.
5. A High Low transition on ALE.
6. A High Low transition on start to start the conversion.
7. Wait for End of cycle (EOC) pin to become high.
8. Make Output Enable pin High.
9. Take Data from the ADCs output
10. Make Output Enable pin Low.
11. Stop

The total numbers of lines required are:


data lines: 8
ALE: 1
START: 1
EOC:1
Output Enable:1
I.e. total 12 lines. You can directly connect the OE pin to Vcc. Moreover
instead of polling for EOC just put some delay so instead of 12 lines you
will require 10 lines.
You can also provide the clock through the controller thus eliminating
the need of external circuit for clock.
Calculating Step Size
ADC 0808 is an 8 bit ADC i.e. it divides the voltage applied at Vref+ &
Vref- into 28 i.e. 256 steps.
Step Size = (Vref+ - Vref-)/256
Suppose Vref+ is connected to Vcc i.e. 5V & Vref- is connected to the
Gnd then the step size will be
Step size= (5 - 0)/256= 19.53 mv.
Calculating Dout.
The data we get at the D0 - D7 depends upon the step size & the Input
voltage i.e. Vin.
Dout = Vin /step Size.
If you want to interface sensors like LM35 which has output 10mv/C
then I would suggest that you set the Vref+ to 2.56v so that the step size
will be
Step size= (2.56 - 0)/256= 10 mv.
So now whatever reading that you get from the ADC will be equal to the
actual temperature.

PROGRAM

Here is a program for interfacing the ADC to microcontroller, as stated


above I have assumed that the OE pin is connected to Vcc & the clock is
given by the controller.
This program selects channel 0 as input channel reads from it & saves in
the accumulator.
adc_a
adc_b
adc_c
adc_start
adc_ale
adc_clk
Org 0000h
clr ale
clr start
clr adc_a
clr adc_b
clr adc_c
call delay_small
setb adc_ale
call delay_small
setb adc_start
call delay_small
clr adc_ale
call delay_small
clr adc_start
call delay_long
mov a,P1
loop:
ajmp loop
delay_small:
mov r0,#10
l1_delay_small:
cpl adc_clk
nop

bit
bit
bit
bit
bit
bit

p2.0
p2.1
p2.2
p2.3
p2.4
P2.5

;Select Channel 0
;ale pin high
;start pin high
;ale pin low
;start pin low

nop
nop
nop
nop
djnz r0,l1_delay_small
ret
delay_long:
mov r0,#40
l1_delay_long:
cpl adc_clk
nop
nop
nop
nop
nop
djnz r0,l1_delay_long
ret
End

Você também pode gostar