Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

MC Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 105

SUBJECT NAME: 8051 MICROCONTROLLER NOTES

SUBJECT CODE: BEC405A


SEMESTER: IV

PREPARED BY
E.N. SRIVANI
ASSISTANT PROFESSOR
DEPARTMENTOF ECE
SJC INSISTITUTE OF TECHNOLOGY, CHCIKBALLAPUR
Module –
1
8051 Microcontroller

Microprocessor vs Microcontroller
• General-purpose microprocessors

• Must add RAM, ROM, I/O ports, and timers externally to make them functional

• Make the system bulkier and much more expensive

• Have the advantage of versatility on the amount of RAM, ROM, and I/O ports

• Microcontroller

• The fixed amount of on-chip ROM, RAM, and number of I/O ports makes them
ideal for many applications in which cost and space are critical

• In many applications, the space it takes, the power it consumes, and the price
per unit are much more critical considerations than the computing power

Microprocessor Microcontroller
Microprocessor contains ALU, General purpose Microcontroller contains the circuitry of microprocessor,
registers, stack pointer, program counter, clock and in addition it has built in ROM, RAM, I/O Devices,
timing circuit, interrupt circuit Timers/Counters
etc.
It has many instructions to move data between It has few instructions to move data between
memory and CPU memory and CPU
Few bit handling instruction It has many bit handling instructions
Less number of pins are multifunctional More number of pins are multifunctional
Single memory map for data and code Separate memory map for data and code
(program) (program)
Access time for memory and IO are more Less access time for built in memory and IO.
Microprocessor based system requires It requires less additional hardware
additional hardware
More flexible in the design point of view Less flexible since the additional circuits which is
residing inside the microcontroller is fixed for
a particular microcontroller
Large number of instructions with flexible Limited number of instructions with few
addressing modes addressing modes
M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

Microcontrollers for Embedded Systems


 An embedded product uses a microprocessor (or microcontroller) to do one task and one task
only
o There is only one application software that is typically burned into ROM
 A PC, in contrast with the embedded system, can be used for any number of applications
o It has RAM memory and an operating system that loads a variety of applications
into RAM and lets the CPU run them
o A PC contains or is connected to various embedded products
 Each one peripheral has a microcontroller inside it that performs only one task
Criteria for Choosing a Microcontroller
 Meeting the computing needs of the task at hand efficiently and cost effectively
o Speed
o Packaging
o Power consumption
o The amount of RAM and ROM on chip
o The number of I/O pins and the timer on chip
o How easy to upgrade to higher performance or lower power-consumption versions
o Cost per unit
 Availability of software development tools, such as compilers, assemblers, and debuggers
 Wide availability and reliable sources of the microcontroller
 The 8051 family has the largest number of diversified (multiple source) suppliers
o Intel (original)
o Atmel
o Philips/Signetics
o AMD
o Infineon (formerly Siemens)
o Matra
o Dallas Semiconductor/Maxim
Harvard and Von Neumann Architectures
• Harvard Architecture—a type of computer architecture where the instructions (program
code) and data are stored in separate memory spaces
Example: Intel 8051 architecture
• Von Neumann Architecture—another type of computer architecture where the instructions
and data are stored in the same memory space
Example: Intel x86 architecture (Intel Pentium, AMD Athlon, etc.)

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 6


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

8051 Architecture

Salient features of 8051 microcontroller are given below.


 Eight bit CPU
 On chip clock oscillator
 4Kbytes of internal program memory (code memory) [ROM]
 128 bytes of internal data memory [RAM]
 64 Kbytes of external program memory address space.
 64 Kbytes of external data memory address space.
 32 bi directional I/O lines (can be used as four 8 bit ports or 32 individually addressable
I/O lines)
 Two 16 Bit Timer/Counter :T0, T1
 Full Duplex serial data receiver/transmitter
 Four Register banks with 8 registers in each bank.
 Sixteen bit Program counter (PC) and a data pointer (DPTR)
 8 Bit Program Status Word (PSW)
 8 Bit Stack Pointer
 Five vector interrupt structure (RESET not considered as an interrupt.)
 8051 CPU consists of 8 bit ALU with associated registers like accumulator ‘A’, B register,
PSW, SP, 16 bit program counter, stack pointer.
 ALU can perform arithmetic and logic functions on 8 bit variables.
 8051 has 128 bytes of internal RAM which is divided into
o Working registers [00 – 1F]
o Bit addressable memory area [20 – 2F]
o General purpose memory area (Scratch pad memory) [30-7F]

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 7


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

8051 Microcontroller Architecture

 8051 has 4 K Bytes of internal ROM. The address space is from 0000 to 0FFFh. If the
program size is more than 4 K Bytes 8051 will fetch the code automatically from external
memory.
 Accumulator is an 8 bit register widely used for all arithmetic and logical operations. Accumulator
is also used to transfer data between external memory. B register is used along with Accumulator
for multiplication and division. A and B registers together is also called MATH registers.
 PSW (Program Status Word). This is an 8 bit register which contains the arithmetic status of ALU
and the bank select bits of register banks.
 The heart of the 8051 is the circuitry that generates the clock pulses by which all internal
operations are synchronized.
 Pins XTALI and XTAL2 are provided for connecting a resonant network to form an
oscillator.
 The 8051 requires an external oscillator circuit. The oscillator circuit usually runs
around 12MHz. the crystal generates 12M pulses in one second. The pulse is used to
synchronize the system operation in a controlled pace.
 A machine cycle is minimum amount time a simplest machine instruction must take.
 An 8051 machine cycle consists of 12 crystal pulses (ticks).
 Instruction with a memory operand needs multiple memory accesses (machine cycles).
E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 8
M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

 Typically, a quartz crystal and capacitors are employed, as shown in Figure.

A and B CPU Registers


• The 8051 contains 34 general-purpose, or working, registers. Two of these, registers A
and B.
• The other 32 are arranged as part of internal RAM in four banks, BO-B3, of eight registers
each, named RO to R7.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 9


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

• The A (accumulator) register is used for many operations, including addition,


subtraction, integer multiplication and division, and Boolean bit manipulations.
• The A register is also used for all data transfers between the 8051 and any external
memory.
• The B register is used with the A register for multiplication and division operations.

Program Counter (PC) and Data Pointer (DPTR)


• Program instruction bytes are fetched from locations in memory that are addressed by the PC.
• The PC is automatically incremented after every instruction byte is fetched and may also
be altered by certain instructions.
• The PC is the only register that does not have an internal address.
• The DPTR register is made up of two 8-bit registers, named DPH and DPL
• Are used to furnish memory addresses for internal and external code access and
external data access.
• The DPTR is under the control of program instructions
• Can be specified by its 16-bit name, DPTR, or by each individual byte name, DPH and DPL.
• DPTR does not have a single internal address; DPH and DPL are each assigned an address.

Flags and the Program Status Word (PSW)


• Flags are 1-bit registers provided to store the results of certain program instructions.
• Other instructions can test the condition of the flags and make decisions based upon the
flag states.
• The 8051 has four math flags that respond automatically to the outcomes of math
operations and three general-purpose user flags that can be set to 1 or cleared to 0 by the
programmer as desired.
• The math flags include carry (C), auxiliary carry (AC), overflow (OY), and parity (P).
• User flags are named FO, GFO, and GFI; they are general-purpose flags.
• Note that all of the flags can be set and cleared by the programmer.

7 6 5 4 3 2 1 0

CY AC F0 RS1 RS0 OV - P

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 10


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

The Stack and the Stack Pointer


• The stack refers to an area of internal RAM that is used in conjunction with certain opcodes to
store and retrieve data quickly.
• The 8-bit stack pointer (SP) register is used by the 8051 to hold an internal RAM address
that is called the "top of the stack."
• The top of the stack is the location in internal RAM where the last byte of data was
stored by a stack operation.
• The SP increments before storing data on the stack so that the stack grows up as data is
stored.
• As data is retrieved from the stack, the byte is read from the stack, and then the SP decrements
to point to the next available byte of stored data.
• The SP is set to 07h when the 8051 is reset and can be changed to any internal RAM address
by the programmer.

Special Function Registers


• The 8051 has a group of specific internal registers, each called a special-function register
(SFR), which may be addressed much like internal RAM, using addresses from 80h to FFh.
• Some SFRs (marked with an asterisk*) are also bit addressable; this feature allows the
programmer to change only what needs to be altered, leaving the remaining bits in that
SFR unchanged.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 11


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

• Not all of the addresses from 80h to FFh are used for SFRs, and attempting to use an
address that is not defined, or "empty" results in unpredictable results.
• SFRs are named in certain opcodes by their functional names, such as A or TH0, and are
referenced by other opcodes by their addresses, such as 0E0h or 8Ch.
• Note that any address used in the program must start with a number; thus address E0h for
the A SFR begins with 0.
• Failure to use this number convention will result in an assembler error when the program
is assembled.

Pin Diagram

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 12


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

Pinout Description
Pins 1-8 PORT 1. Each of these pins can be configured as an input or an output.
Pin 9 RESET. A logic one on this pin disables the microcontroller and clears the contents of most
registers. In other words, the positive voltage on this pin resets the microcontroller. By applying
logic zero to this pin, the program starts execution from
the beginning.

Pins10-17 PORT 3. Similar to port 1, each of these pins can serve as general input or output.
Besides, all of them have alternative functions
Pin 10 RXD. Serial asynchronous communication input or Serial synchronous
communication output.
Pin 11 TXD. Serial asynchronous communication output or Serial synchronous
communication clock output.
Pin 12 INT0.External Interrupt 0 input
Pin 13 INT1. External Interrupt 1 input
Pin 14 T0. Counter 0 clock input
Pin 15 T1. Counter 1 clock input
Pin 16 WR. Write to external (additional) RAM
Pin 17 RD. Read from external RAM
Pin 18, 19 XTAL2, XTAL1. Internal oscillator input and output. A quartz crystal which
specifies operating frequency is usually connected to these pins.
Pin 20 GND. Ground.
Pin 21-28 Port 2. If there is no intention to use external memory then these port pins are configured
as general inputs/outputs. In case external memory is used, the higher address byte, i.e.
addresses A8-A15 will appear on this port. Even though memory with capacity of 64Kb is
not used, which means that not all eight port bits are used for its addressing, the rest of
them are not available as
inputs/outputs.

Pin 29 PSEN. If external ROM is used for storing program then a logic zero (0)
appears on it every time the microcontroller reads a byte from memory.
Pin 30 ALE. Prior to reading from external memory, the microcontroller puts the lower address
byte (A0-A7) on P0 and activates the ALE output. After receiving signal from the ALE
pin, the external latch latches the state of P0
and uses it as a memory chip address. Immediately after that, the ALE pin is returned its
previous logic state and P0 is now used as a Data Bus.
Pin 31 EA. By applying logic zero to this pin, P2 and P3 are used for data and address transmission
with no regard to whether there is internal memory or not. It means that even there is a
program written to the microcontroller, it will not be executed. Instead, the program
written to external ROM will be executed. By applying logic one to the EA pin, the
microcontroller will use both
memories, first internal then external (if exists).

Pin 32-39 PORT 0. Similar to P2, if external memory is not used, these pins can be used as general
inputs/outputs. Otherwise, P0 is configured as address output (A0- A7) when the ALE pin
is driven high (1) or as data output (Data Bus) when
the ALE pin is driven low (0).
Pin 40 VCC. +5V power supply.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 13


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

Internal Memory organization


 A functioning computer must have
• MEMORY FOR PROGRAM CODE BYTES, COMMONLY IN ROM
• RAM MEMORY FOR VARIABLE DATA THAT CAN BE ALTERED AS
THE PROGRAM RUNS.
 Additional memory can be added externally using suitable circuits.
 8051 has a Harvard architecture, which uses the same address, in different memories,
for code and data.
• Internal circuitry accesses the correct memory based upon the nature of the operation in
progress.

Internal RAM
 Thirty-two bytes from address 00h to 1Fh that make up 32 working registers organized as four
banks of eight registers each. (Bank0- Bank3; with each bank having registers R0-R7)
 Each register can be addressed by name (when its bank is selected) or by its RAM address.
 Thus R0 of bank 3 is R0 (if bank 3 is currently selected) or address 18h (whether bank 3 is
selected or not).
 Bits RS0 and RS1 in the PSW determine which bank of registers is currently in use.
 Register banks not selected can be used as general-purpose RAM.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 14


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

 Bank 0 is selected upon reset.


 A bit-addressable area of 16 bytes occupies RAM byte addresses 20h to 2Fh, forming a
total of 128 addressable bits.
 An addressable bit may be specified by its bit address of 00h to 7Fh, or 8 bits may form any
byte address from 20h to 2Fh.
o Thus, for example, bit address 4Fh is also bit 7 of byte address 29h.
o Addressable bits are useful when the program need only remember a binary event (switch
on, light off, etc.).
 A general-purpose RAM area above the bit area, from 30h to 7Fh, addressable as bytes.
Internal ROM
 The 8051 is organized so that data memory and program code memory can be in two
entirely different physical memory entities; each has the same address ranges.
 A corresponding block of internal program code, contained in an internal ROM, occupies
code address space 0000h to 0FFFh.
 The PC is ordinarily used to address program code bytes from addresses 0000h to 0FFFh.
 Program addresses higher than 0FFFh, which exceed the internal ROM capacity, will cause the
8051 to automatically fetch code bytes from external program memory.
 Code bytes can also be fetched exclusively from an external memory, addresses 0000h to
FFFFh, by connecting the external access pin (EA pin 31 on the DIP) to ground.
 The PC does not care where the code is; the circuit designer decides whether the code is found
totally in internal ROM, totally in external ROM, or in a combination of internal and
external ROM.

Input/ Output Pins, Ports, and Circuits


 Ports can be accessed directly by instructions during program execution
 I/O ports are memory mapped, they are treated as memory locations
 All ports are bit addressable
 Each PIN consists of a D latch, I/P buffer and O/P driver
 SFRs for each port is made of 8-latches
 Accessed by SFRs address or name of that port
 The four 8-bit I/O ports P0, P1, P2 and P3 each uses 8 pins
 All the ports upon RESET are configured as output, ready to be used as output ports
o When the first 0 is written to a port, it becomes an output
o To reconfigure it as an input, a 1 must be sent to the port
 To use any of these ports as an input port, it must be programmed

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 15


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

External Memory (ROM & RAM) interfacing


Eg. Interfacing of 16 K Byte of RAM and 32 K Byte of EPROM to 8051
Number of address lines required for 16 Kbyte memory is 14 lines and that of 32Kbytes of memory is
15 lines.
The connections of external memory is shown below.

The lower order address and data bus are multiplexed. De-multiplexing is done by the latch.
Initially the address will appear in the bus and this latched at the output of latch using ALE signal.
The output of the latch is directly connected to the lower byte address lines of the memory. Later
data will be available in this bus. Still the latch output is address itself. The higher byte of address
bus is directly connected to the memory. The number of lines connected depends on the memory
size.
The RD and WR (both active low) signals are connected to RAM for reading and writing the data.
PSEN of microcontroller is connected to the output enable of the ROM to read the data from the
memory.
EA (active low) pin is always grounded if we use only external memory. Otherwise, once the program
size exceeds internal memory the microcontroller will automatically switch to external memory.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 16


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

 The number of bits that a semiconductor memory chip can store is called chip capacity
o It can be in units of Kbits (kilobits), Mbits (megabits), and so on.
 Memory chips are organized into a number of locations within the IC.
o Each location can hold 1 bit, 4 bits, 8 bits, or even 16 bits, depending on how it is
designed internally
 The number of locations within a memory IC depends on the address pins
 The number of bits that each location can hold is always equal to the
number of data pins
 A memory chip contain 2x location, where x is the number of address pins.
 Each location contains y bits, where y is the number of data pins on the chip.
 The entire chip will contain 2x X y bits

Example 1.1
A given memory chip has 12 address pins and 4 data pins. Find:
(a) The organization, and (b) the capacity.
Solution:
a) This memory chip has 4096 locations (212 = 4096), and each location can hold
4 bits of data. This gives an organization of 4096 × 4, often represented as 4K
× 4.
b) The capacity is equal to 16K bits since there is a total of 4K locations and each
location can hold 4 bits of data.

Example 1.2
A 512K memory chip has 8 pins for data. Find:
(a) The organization, and (b) the number of address pins for this memory chip.
Solution:
a) A memory chip with 8 data pins means that each location within the chip can hold
8 bits of data. To find the number of locations within this memory chip, divide the
capacity by the number of data pins. 512K/8 = 64K; therefore, the organization for
this memory chip is 64K × 8
b) The chip has 16 address lines since 216 = 64K

Memory Address Decoding


 The CPU provides the address of the data desired, but it is the job of the decoding circuitry to
locate the selected memory block
o Memory chips have one or more pins called CS (chip select), which must be
activated for the memory’s contents to be accessed.
o Sometimes the chip select is also referred to as chip enable (CE)
 In connecting a memory chip to the CPU, the following points need to be noted
o The data bus of the CPU is connected directly to the data pins of the memory chip
o Control signals RD (read) and WR (memory write) from the CPU are connected to
the OE (output enable) and WE (write enable) pins of the memory chip

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 17


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

o In the case of the address buses, while the lower bits of the address from the CPU go
directly to the memory chip address pins, the upper ones are used to activate the CS pin
of the memory chip.
 Normally memories are divided into blocks and the output of the decoder selects a given memory
block
o Using simple logic gates
o Using the 74LS138
o Using programmable logics

Simple Logic Gate Address Decoder


 The simplest way of decoding circuitry is the use of NAND or other gates.
o The fact that the output of a NAND gate is active low, and that the CS pin is also
active low makes them a perfect match

Logic Gate as
Decoder

Using 74LS138 3-8 Decoder


 This is one of the most widely used address decoders
o The 3 inputs A, B, and C generate 8 active-low outputs Y0 – Y7
o Each Y output is connected to CS of a memory chip, allowing control of 8 memory
blocks by a single 74LS138
o In the 74LS138, where A, B, and C select which output is activated, there are three
additional inputs, G2A, G2B, and G1
o G2A and G2B are both active low, and G1 is active high
o If any one of the inputs G1, G2A, or G2B is not connected to an address signal,
they must be activated permanently either by Vcc or ground, depending on the
activation level

74LS138 Decoder
E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 18
M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

74LS138 as Decoder

Example 1.3 Looking at the design in the above figure, find the address range for the
Following.
(a) Y4, (b) Y2, and (c) Y7.

Solution :
(a) The address range for Y4 is calculated as follows.
A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1
A0 01 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1

The above shows that the range for Y4 is 4000H to 4FFFH. In the above figure,
notice that A15 must be 0 for the decoder to be activated. Y4 will be selected
when A14 A13 A12 = 100 (4 in binary). The remaining A11-A0 will be 0 for the lowest
address and 1 for the highest address.

(b) The address range for Y2 is 2000H to 2FFFH.


A15 A14 A13 A12 A11 A10 A9 A8 A7 A6 A5 A4 A3 A2 A1
A0 0 0 1 0 0 0 0 0 0 0 0 0
0 0 00
0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1

(c) The address range for Y7 is 7000H to 7FFFH.


A15
0 A141 A131 A121 A11
0 A100 A90 A80 A7
0 A6
0 A5
0 A4
0 A30 A20 A1
0 A0
0
0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

External ROM (program memory) Interfacing

Interfacing of ROM/EPROM to 8051

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 19


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

Above figure shows how to access or interface ROM to 8051.


Port 0 is used as multiplexed data & address lines. It gives lower order (A7-A0) 8 bit address in initial
cycle & higher order (A8-A15) used as data bus. 8 bit address is latched using external latch &
ALE signal from 8051. Port 2 provides higher order (A15-A8) 8 bit address. PSEN' is used to
activate the output enable signal of external ROM/EPROM.

External RAM (data memory) Interfacing

Interfacing of RAM (data memory) to 8051


Above figure shows how to connect or interface external RAM (data memory) to 8051.
Port 0 is used as multiplexed data & address lines. Address lines are decoded using external latch
& ALE signal from 8051 to provide lower order (A7-A0) address lines. Port 2 gives higher order
address lines. RD' & WR' signals from 8051 selects the memory read & memory write operations
respectively.

Example 1.4: Design a controller system using 8051.Interface the external RAM of size 16k x 8.
Solution: Given, Memory size: 16k
That means we require 2n=16k :: n address lines
Here n=14 :: A0 to A13 address lines are required.
A14 and A15 are connected through OR gate to CS pin of external RAM.
When A14 and A15 both are low (logic ‘0’), external data memory (RAM) is selected.
Address Decoding (Memory Map) for 16k x 8 RAM.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 20


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

Example 1.5: Design a controller system using 8051.Interface the external ROM of size 4k x 8.
Solution: Given, Memory size: 4k
That means we require 2n=4k :: n address lines
Here n=12 :: A0 to A11 address lines are required.
Remaining lines A12, A13, A14, A15 & PSEN are connected though OR gate to CS & RD of external
ROM.
When A0 to A0 are low (logic ‘0’), only then external ROM is selected.
Address Decoding (Memory Map) for 4k x 8 RAM.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 21


M I C R O C O N T R O L L E R | M O D U L E 1: 8 0 5 1 M I C R O C O N T R O L L E R

Module –
2
8051 Instruction Set
General syntax for 8051 assembly language is as follows.
LABEL: OPCODE OPERAND ; COMMENT

LABEL: (THIS IS NOT NECESSARY UNLESS THAT SPECIFIC LINE HAS TO BE


ADDRESSED). The label is a symbolic address for the instruction. When the program is
assembled, the label will be given specific address in which that instruction is stored. Unless
that specific line of instruction is needed by a branching instruction in the program, it is not
necessary to label that line.

OPCODE: Opcode is the symbolic representation of the operation. The assembler converts
the opcode to a unique binary code (machine language).

OPERAND: While opcode specifies what operation to perform, operand specifies where to
perform that action. The operand field generally contains the source and destination of the data.
In some cases only source or destination will be available instead of both. The operand will be
either address of the data, or data itself.

COMMENT: Always comment will begin with ; or // symbol. To improve the program
quality, programmer may always use comments in the program.

Addressing Modes
The CPU can access data in various ways, which are called addressing modes

Immediate

addressing
modes Register Direct

Register
Memory indirect

Indexed

Immediate Addressing Mode


• The source operand is a constant
• The immediate data must be preceded by the pound sign, “#”
• Can load information into any registers, including 16-bit DPTR register
• DPTR can also be accessed as two 8-bit registers, the high byte DPH and low byte DPL
E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 22
MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

MOV A, #25H ;load 25H into A


MOV R4, #62 ;load 62 into R4
MOV B, #40H ;load 40H into B
MOV DPTR, #4521H ;DPTR=4512H
MOV DPL, #21H ;This is the same
MOV DPH, #45H ;as above

; Illegal!! Value > 65535 (FFFFH)


MOV DPTR, #68975

We can use EQU directive to access immediate data

We can use EQU directive to access immediate data

Register Addressing Mode


 Use registers to hold the data to be manipulated

 The source and destination registers must match in


size MOV DPTR, A will give an error

 The movement of data between Rn registers is not


allowed MOV R4,R7 is invalid

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 23


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Accessing Memory- Direct Addressing Mode


 It is most often used, the direct addressing mode, to access RAM locations 30H – 7FH
o The entire 128 bytes of RAM can be accessed
o The register bank locations are accessed by the register names

Direct
addressing mode
MOV A,4 ;is same as
MOV A,R4 ;which means copy R4 into A
Register addressing
mode

 In contrast to immediate addressing mode


o There is no “#” sign in the operand

MOV R0,40H ;save/move content of 40H in R0


MOV 56H,A ;save/move content of A in 56H

 The SFR (Special Function Register) can be accessed by their names or by their addresses

MOV 0E0H,#55H ;is the same as


MOV A,#55h ;load 55H into A
MOV 0F0H,R0 ;is the same as
MOV B,R0 ;copy R0 into B

 The SFR registers have addresses between 80H and FFH


o Not all the address space of 80 to FF is used by SFR
o The unused locations 80H to FFH are reserved and must not be used by the 8051
programmer.

Example 2-1
Write code to send 55H to ports P1 and P2, using (a) their names (b) their addresses
Solution :
(a) MOV A,#55H ;A=55H
MOV P1,A ;P1=55H
MOV P2,A ;P2=55H

(b) P1 address=90H; P2 address=A0H


MOV A,#55H ;A=55H
MOV 90H,A ;P1=55H
MOV 0A0H,A ;P2=55H

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 24


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Accessing Memory- Stack and Direct Addressing Mode


 Only direct addressing mode is allowed for pushing or popping the stack
• PUSH A is invalid
• Pushing the accumulator onto the stack must be coded as PUSH 0E0H

Example 2-2
Show the code to push R5 and A onto the stack and then pop them back them into R2 and B,
where B = A and R2 = R5
Solution:
PUSH 05 ;push R5 onto stack
PUSH 0E0H ;push register A onto stack
POP 0F0H ;pop top of stack into B
;now register B = register A
POP 02 ;pop top of stack into R2
;now R2=R6

Accessing Memory- Register-Indirect Addressing Mode


 A register is used as a pointer to the data
• Only register R0 and R1 are used for this purpose
• R2 – R7 cannot be used to hold the address of an operand located in RAM
 When R0 and R1 hold the addresses of RAM locations, they must be preceded by the “@”
sign
MOV A,@R0 ; move contents of RAM whose
; Address is held by R0 into A
MOV @R1,B ;move contents of B into RAM
; whose address is held by R1

Example 2-3
Write a program to copy the value 55H into RAM memory locations 40H to 41H using
(a) direct addressing mode, (b) register indirect addressing mode without a loop, and (c) with a loop
Solution:
(a)
MOV A,#55H ;load A with value 55H
MOV 40H,A ;copy A to RAM location 40H
MOV 41H,A ;copy A to RAM location 41H
(b)
MOV A,#55H ;load A with value 55H
MOV R0,#40H ;load the pointer. R0=40H
MOV @R0,A ;copy A to RAM R0 points to
INC R0 ;increment pointer. Now R0=41h
MOV @R0,A ;copy A to RAM R0 points to
(c)
MOV A,#55H ;A=55H
MOV R0,#40H ;load pointer.R0=40H,
MOV R2,#02 ;load counter, R2=3
AGAIN: MOV @R0,A ;copy 55 to RAM R0 points to
INC R0 ;increment R0 pointer
DJNZ R2,AGAIN ;loop until counter = zero

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 25


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

 The advantage is that it makes accessing data dynamic rather than static as in
direct addressing mode
• Looping is not possible in direct addressing mode

Example 2-4
Write a program to clear 16 RAM locations starting at RAM address 60H
Solution:
CLR A ;A=0
MOV R1,#60H ;load pointer, R1=60H
MOV R7,#16 ;load counter, R7=16
AGAIN: MOV @R1,A ;clear RAM R1 points to
INC R1 ;increment R1 pointer
DJNZ R7,AGAIN ;loop until counter=zero

Example 2-5
Write a program to copy a block of 10 bytes of data from 35H to 60H
Solution:
MOV R0,#35H ;source pointer
MOV R1,#60H ;destination pointer
MOV R3,#10 ;counter
BACK: MOV A,@R0 ;get a byte from source
MOV @R1,A ;copy it to destination
INC R0 ;increment source pointer
INC R1 ;increment destination pointer
DJNZ R3,BACK ;keep doing for ten bytes

 R0 and R1 are the only registers that can be used for pointers in register
indirect addressing mode
 Since R0 and R1 are 8 bits wide, their use is limited to access any information in the
internal RAM
 Whether accessing externally connected RAM or on-chip ROM, we need 16-bit pointer
 In such case, the DPTR register is used.

 Indexed addressing mode is widely used in accessing data elements of look-up table
entries located in the program ROM.
 The look-up table allows access to elements of a frequently used table with
minimum operations
 The instruction used for this purpose is MOVC A,@A+DPTR
• Use instruction MOVC, “C” means code
• The contents of A are added to the 16-bit register DPTR to form the 16-bit
address of the needed data

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 26


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Example 2-6
Write a program to get the x value from P1 and send x2 to P2, continuously
Solution:
ORG 0
MOV DPTR,#300H ;LOAD TABLE ADDRESS
MOV A,#0FFH ;A=FF
MOV P1,A ;CONFIGURE P1 INPUT PORT
BACK: MOV A,P1 ;GET X
MOV A,@A+DPTR ;GET X SQAURE FROM TABLE
MOV P2,A ;ISSUE IT TO P2
SJMP BACK ;KEEP DOING IT

ORG 300H
XSQR_TABLE:
DB 0,1,4,9,16,25,36,49,64,81
END

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 27


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Data Transfer instructions


 The MOV opcodes involve data transfers within the following four distinct physical parts of
8051 memory :
• Internal RAM
• Internal special. function registers
• External RAM
• Internal and external ROM
 Finally, the following five types of opcodes are used to move data:
• MOV
• MOVX
• MOVC
• PUSH and POP
• XCH

Data Transfer using immediate and register addressing modes


Mnemonic Operation

MOV A, #n Copy the immediate data byte n to the A register

MOV A, Rr Copy data from register Rr to register A

MOV Rr, A Copy data from register A to register Rr

MOV Rr, #n Copy the immediate data byte n to register Rr

MOV DPTR, #nn Copy the immediate 16-bit number nn to the DPTR register.

 A data MOV does not alter the contents of the data source address.
 A copy of the data is made from the source and moved to the destination address.
 The contents of the destination address are replaced by the source address contents.
Mnemonic Operation

MOV A,#0Flh Move the immediate data byte F1h to the A register

MOV A,R0 Copy the data in register R0 to register A

MOV DPTR,#0ABCDh Move the immediate data bytes ABCDh to the DPTR

MOV R5,A Copy the data in register A to register R5

MOV R3,#1Ch Move the immediate data byte 1Ch to register R3

 It is impossible to have immediate data as a destination.


 All numbers must start with a decimal number (0-9), or the assembler assumes the
number is a label.
 Register-to-register moves using the register addressing mode occur between registers A
and RO to R7.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 28


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Data Transfer using direct, immediate and register addressing modes

Mnemonic Operation

MOV A, addr Copy data from direct address add to register A


MOV add, A Copy data from register A to direct address addr

MOV Rr, addr Copy data from direct address add to register Rr

MOV addr, Rr Copy data from register Rr to direct address addr

MOV addr, #n Copy immediate data byte n to direct address addr

 MOV instructions that refer to direct addresses above 7Fh that are not SFRs will result
in errors.
 The SFRs are physically on the chip; all other addresses above 7Fh do not physically exist.
 Moving data to a port changes the port latch; moving data from a port gets data from the port
pins.
 Moving data from a direct address to itself is not predictable and could lead to errors.

Mnemonic Operation

MOV A, 80h Copy data from the port 0 pins to register A


MOV 80h, A Copy data from register A to the port 0 latch

MOV 3Ah, #3Ah Copy immediate data byte 3Ah to RAM location 3Ah

MOV R0, 12h Copy data from RAM location 12h to register RO

MOV 8Ch,R7 Copy data from register R 7 to timer 0 high byte

MOV 5Ch,A Copy data from register A to RAM location 5Ch

MOV 0A8h,77h Copy data from RAM location 77h to IE register

Data Transfer using register indirect addressing modes

 The indirect addressing mode uses a register to hold the actual address that will finally
be used in the data move;
 The register itself is not the address, but rather the number in the register.
 Indirect addressing for MOV opcodes uses register R0 or R1, often called "data pointers,"
to hold the address of one of the data locations, which could be a RAM or an SFR
address.
 The mnemonic symbol used for indirect addressing is the "at" sign, which is printed as @.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 29


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Mnemonic Operation

MOV @Rp, #n Copy the immediate byte n to the address in Rp


MOV @Rp, addr Copy the contents of add to the address in Rp

MOV @Rp, A Copy the data in A to the address in Rp

MOV addr, @Rp Copy the contents of the address in Rp to addr

MOV A, @Rp Copy the contents of the address in Rp to A

 The number in register Rp must be a RAM or an SFR address.


 Only registers R0 or R1 may be used for indirect addressing

Mnemonic Operation

MOV A, @R0 Copy the contents of the address in RO to the A register


MOV @R1, #35h Copy the number 35h to the address in R1

MOV addr, @R0 Copy the contents of the address in RO to addr

MOV @R1, A Copy the contents of A to the address in R1

MOV @R0, 80h Copy the contents of the port 0 pins to the address in R0

Data Transfer - External Data Moves

 Registers R0. R1, and the DPTR can be used to hold the address of the data byte
in external RAM.
 R0 and R1 are limited to external RAM address ranges of 00h to 0FFh, while the
DPTR register can address the RAM space of 0000h to 0FFFFh.
 An X is added to the MOV mnemonics to serve as a reminder that the data move is external
to the 8051

Mnemonic Operation

MOVX A, @Rp Copy the contents of the external address in Rp to A


MOVX A, @DPTR Copy the contents of the external address in DPTR to A

MOVX @Rp, A Copy data from A to the external address in Rp

MOVX @DPTR, A Copy data from A to the external address in DPTR

 All external data moves must involve the A register.


 Rp can address 256 bytes; DPTR can address 64K bytes.
 MOVX is normally used with external RAM or I/0 addresses.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 30


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Mnemonic Operation

MOVX @DPTR, A Copy data from A to the 16-bit address in DPTR


MOVX@R0, A Copy data from A to the 8-bit address in R0

MOVXA, @R1 Copy data from the 8-bit address in R1 to A

MOVX A, @DPTR Copy data from the 16-bit address in DPTR to A

Data Transfer - Code Memory Read-Only Data Moves

 Data moves between RAM locations and 8051 registers are made by using MOV and
MOVX opcodes. The data is usually of a temporary or "scratch pad" nature and
disappears when the system is powered down.
 There are times when access to a preprogrammed mass of data is needed, such as
when using tables of predefined bytes. This data must be permanent to be of repeated
use and is stored in the program ROM.
 Access to this data is made possible by using indirect addressing and the A register
in conjunction with either the PC or the DPTR.
 In both cases, the number in register A is added to the pointing register to form the address
in ROM where the desired data is to be found.
 The data is then fetched from the ROM address so formed and placed in the A register.
 The original data in A is lost, and the addressed data takes its place.

Mnemonic Operation

Copy the code byte, found at the ROM address formed by adding
MOVC A, @A+DPTR A and the DPTR, to A

Copy the code byte, found at the ROM address formed by adding
MOVC A, @A+PC A and the PC, to A

Mnemonic Operation

MOV DPTR, #1234h Copy the immediate number 1234h to the DPTR
MOV A, #56h Copy the immediate number 56h to A

MOVC A, @A+DPTR Copy the contents of address 128Ah to A

Copies the contents of address 4059h to A if the PC contained


MOVC A, @A+PC 4000h and A contained 58h when the opcode is executed

Data Transfer - External Data Moves

 The PC is incremented by one (to point to the next instruction) before it is added to A to
form the final address of the code byte.
 All data is moved from the code memory to the A register.
 MOVC is normally used with internal or external ROM and can address 4K of internal or
64K bytes of external code.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 31


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Data Transfer - PUSH and POP Opcodes

 The PUSH and POP opcodes specify the direct address of the data.
 The data moves between an area of internal RAM, known as the stack, and the specified
direct address.
 The stack pointer special-function register (SP) contains the address in RAM where data from
the source address will be PUSHed, or where data to be POPed to the destination address is
found.
 The SP register actually is used in the indirect addressing made but is not named in the mnemonic.
It is implied that the SP holds the indirect address whenever PUSHing or POPing.
 A PUSH opcode copies data from the source address to the stack.
 SP is incremented by one before the data is copied to the internal RAM location contained in SP
so that the data is stored from low addresses to high addresses in the internal RAM.
 The stack grows up in memory as it is PUSHed. Excessive PUSHing can make the stack
exceed 7Fh (the top of internal RAM), after which point data is lost.
 A POP opcode copies data from the stack to the destination address.
 SP is decremented by one after data is copied from the stack RAM address to the direct
destination to ensure that data placed on the stack is retrieved in the same order as it was
stored.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 32


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

 When the SP reaches FFh it "rolls over" to 00h (R0).


 RAM ends at address 7Fh; PUSHes above 7Fh result in errors.
 The SP is usually set at addresses above the register banks.
 The SP may be PUSHed and POPed to the stack.
 Note that direct addresses, not register names, must be used for most registers. The stack
mnemonics have no way of knowing which bank is in use.

Data Transfer - Data Exchanges

 MOV, PUSH, and POP opcodes all involve copying the data found in the source address to
the destination address; the original data in the source is not changed.
 Exchange instructions actually move data in two directions: from source to destination
and from destination to source.
 All addressing modes except immediate may be used in the XCH (exchange) opcodes

 All exchanges are internal to the 8051.


 All exchanges use register A.
 When using XCHD, the upper nibble of A and the upper nibble of the address location in
Rp do not change.

Arithmetic instructions
The 8051 can perform addition, subtraction. Multiplication and division operations on 8 bit numbers.
The 24 arithmetic opcodes are grouped into as follows
Mnemonic Operation

INC destination Increment destination by 1

DEC destination Decrement destination by 1

ADD/ ADDC destination ,source Add source to destination without/with carry (C) flag

SUBB destination, source Subtract, with carry, source from destination

MUL AB Multiply the contents of registers A and B

DlV AB Divide the contents of register A by the contents of register B

DA A Decimal Adjust the A register

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 33


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Arithmetic instructions - Addition


 All addition is done with the A register as the destination of the result.
 All addressing modes may be used for the source: an immediate number, a register, a direct
address, and an indirect address.
 Some instructions include the carry flag as an additional source of a single bit that is included
in the operation at the least significant bit position.
Mnemonic Operation

ADD A, #n Add A and the immediate number n; put the sum in A

ADD A, Rr Add A and register Rr; put the sum in A

ADD A, addr Add A and the address contents; put the sum in A

ADD A, @Rp Add A and the contents of the address in Rp; put the sum in A

These instructions affect 3 bits in PSW:


C = 1 if result of add is greater than
FF AC = 1 if there is a carry out of bit
3
OV = 1 if there is a carry out of bit 7, but not from bit 6, or vice versa.

Addition of Unsigned Numbers


ADD A, source; A = A + source
 The instruction ADD is used to add two operands
 Destination operand is always in register A
 Source operand can be a register, immediate data, or in memory
 Memory-to-memory arithmetic operations are never allowed in 8051 Assembly language

Example 2-7 CY =1, since there is


Show how the flag register is affected by the following instruction. a carry out from D7
MOV A,#0F5H ;A=F5 hex PF =1, because the
ADD A,#0BH ;A=F5+0B=00 number of 1s is zero
Solution: (an even number),
F5H 1111 0101 PF is set to 1.
+ 0BH + 0000 1011 AC =1, since there is
100H 0000 0000 a carry from D3 to
D4

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 34


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Example 2-8
Assume that RAM locations 40 – 44H have the following values.
Write a program to find the sum of the values. At the end of the program, register A
should contain the low byte and R7 the high byte.
40 = (7D) | 41 = (EB) | 42 = (C5) | 43 = (5B) | 44 = (30)
Solution:
MOV R0,#40H ;load pointer
MOV R2,#5 ;load counter
CLR A ;A=0
MOV R7,A ;clear R7
AGAIN: ADD A,@R0 ;add the byte ptr to by R0
JNC NEXT ;if CY=0 don’t add carry
INC R7 ;keep track of carry
NEXT: INC R0 ;increment pointer
DJNZ R2,AGAIN ;repeat until R2 is zero

ADDC and Addition of 16-Bit Numbers

 When adding two 16-bit


data operands, the
propagation of a carry
from lower byte to higher
byte is concerned

Example 2-9
Write a program to add two 16-bit numbers. Place the sum in R7 and
R6; R6 should have the lower byte.
Solution:
CLR C ;make CY=0
MOV A, #0E7H ;load the low byte now A=E7H
ADD A, #8DH ;add the low byte
MOV R6, A ;save the low byte sum in R6
MOV A, #3CH ;load the high byte
ADDC A, #3BH ;add with the carry
MOV R7, A ;save the high byte sum

BCD Number System

The binary representation of the digits 0 to 9 is called BCD (Binary Coded Decimal)
Unpacked BCD
 In unpacked BCD, the lower 4 bits of the number represent the BCD number, and the
rest of the bits are 0
• Ex. 00001001 and 00000101 are unpacked BCD for 9 and 5
Packed BCD
 In packed BCD, a single byte has two BCD number in it, one in the lower 4 bits, and
one in the upper 4 bits
• Ex. 0101 1001 is packed BCD for 59H

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 35


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

 Adding two BCD numbers must give a BCD result

MOV A, #17H
ADD A, #28H
The result above should have been 17 + 28 = 45 (0100 0101).
To correct this problem, the programmer must add 6 (0110) to the
low digit: 3F + 06 = 45H.

DA Instruction
 DA A ;decimal adjust for addition
 The DA instruction is provided to correct the aforementioned problem associated with
BCD addition
 The DA instruction will add 6 to the lower nibble or higher nibble if need

Example:
MOV ;A=47H first BCD operand
A,#47H ;B=25H second BCD operand
MOV ;hex(binary) addition(A=6CH)
B,#25H ;adjust for BCD addition(A=72H)
 The “DA” instruction works only on A.
 In other word, while the source can be an operand of any addressing mode, the
destination must be in register A in order for DA to work.

Summary of DA instruction
 After an ADD or ADDC instruction
 If the lower nibble (4 bits) is greater than 9, or if AC=1, add 0110 to the lower 4 bits
 If the upper nibble is greater than 9, or if CY=1, add 0110 to the upper 4 bits

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 36


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Example 2-10
Assume that 5 BCD data items are stored in RAM locations starting at 40H, as shown
below. Write a program to find the sum of all the numbers. The result must be in BCD.
40=(71) | 41=(11) | 42=(65) | 43=(59) | 44=(37)

Solution:
MOV R0,#40H ;Load pointer
MOV R2,#5 ;Load counter
CLR A ;A=0
MOV R7,A ;Clear R7
AGAIN: ADD A,@R0 ;add the byte pointer to by R0
DA A ;adjust for BCD
JNC NEXT ;if CY=0 don’t accumulate carry
INC R7 ;keep track of carries
NEXT: INC R0 ;increment pointer
DJNZ R2,AGAIN ;repeat until R2 is 0

Subtraction of Unsigned Numbers


 In many microprocessor there are two different instructions for
subtraction: SUB and SUBB (subtract with borrow)
 In the 8051 we have only SUBB
 The 8051 uses adder circuitry to perform the subtraction

SUBB A, source ; A = A – Source – CY


 To make SUB out of SUBB, we have to make CY=0 prior to the execution of the instruction
 Notice that we use the CY flag for the borrow

SUBB when CY = 0
 Take the 2’s complement of the subtrahend (source operand)
 Add it to the minuend (A)
 Invert the carry
CLR C
MOV A,#4CH ;load A with value 4CH
SUBB A,#6EH ;subtract 6E from A
JNC NEXT ;if CY=0 jump to NEXT
CPL A ;if CY=1, take 1’s complement
INC A ;and increment to get 2’s comp
NEXT: MOV R1,A ;save A in R1

Solution:
4C 0100 1100 0100 1100
- 6E 0110 1110 1001 0010
-22 01101 1110

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 37


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

SUBB when CY = 1
This instruction is used for multi-byte numbers and will take care of the borrow of the lower operand

Code to subtract 1296h from 2762h (2762H -


1296H).
CLR C ;A=62H
MOV
SUBB A,#62H
A,#96H ;62H-96H=CCH with CY=1
MOV R7,A ;save the result
MOV A,#27H ;A=27H
SUBB A,#12H ;27H-12H-1=14H
MOV R6,A ;save the result
Solution:
We have 2762H - 1296H = 14CCH.

Multiplication of Unsigned Numbers


The 8051 supports byte by byte multiplication only
 The byte are assumed to be unsigned data

MUL A B; A*B, 16-bit result in B, A

Code to multiply 25h and 65h.


MOV A,#25H ;load 25H to reg. A
MOV B,#65H ;load 65H to reg. B
MUL AB ;25H * 65H = E99 where
;B = OEH and A = 99H

Division of Unsigned Numbers


The 8051 supports byte over byte division only
 The byte are assumed to be unsigned data

DIV A B ; A/B, Result(R, Q) in B, A


Code to Divide 95 by
10.
MOV A,#95 ;load 95 to reg. A
MOV B,#10 ;load 10 to reg. B
DIV AB ;B=05(Rem)and A=09(Qou)

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 38


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Example 2-11
Write a program to get hex data in the range of 00 – FFH from port 1 and convert it
to decimal. Save it in R7, R6 and R5.
Solution:
MOV A, #0FFH
MOV P1, A ;make P1 an input port
MOV A, P1 ;read data from P1
MOV B, #10 ;B=0A hex
DIV AB ;divide by 10
MOV R7, B ;save lower digit
MOV B, #10
DIV AB ;divide by 10 once more
MOV R6, B ;save the next digit
MOV R5, A ;save the last digit

Logical instructions
 A large part of machine control concerns sensing the on-off states of external
switches, making decisions based on the switch states, and then turning external
circuits on or off.
 Sensing and control implies a need for byte and bit opcodes that operate on data
using Boolean operators.
 All 8051 RAM areas, both data and SFRs, may be manipulated using byte opcodes.
 Many of the SFRs, and a unique internal RAM area that is bit addressable, may be
operated upon at the individual bit level.
 Bit operators are notably efficient when speed of response is needed.
 Bit operators yield compact program code that enhances program execution speed.

ANL destination, source ; dest = dest AND source


 This instruction will perform a logic AND on the two operands and place the result in
the destination
• The destination is normally the accumulator
• The source operand can be a register, in memory, or immediate

MOV A,#35H ;A = 35H


ANL A,#0FH ;A = A AND 0FH

35H 00110101 ANL is often used to


0FH 00001111 mask (set to 0)
0FH 00000101 certain bits of an
operand
ORL destination, source; dest = dest OR source
 This instruction will perform a logic OR on the two operands and place the result in
the destination
• The destination is normally the accumulator
• The source operand can be a register, in memory, or immediate

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 39


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

MOV A,#04H ;A = 04H


ORL A,#68H ;A = A OR 68H=6CH

04H 00000100 ORL instruction can be


68H 0 11 0 1000 used to set certain bits of
6CH 0 11 0 1100 an operand to 1

XRL destination, source; dest = dest XOR source


 This instruction will perform a logic XOR on the two operands and place the result in
the destination
• The destination is normally the accumulator
• The source operand can be a register, in memory, or immediate

The XRL instruction can be used to clear the contents of a register by XORing it with
itself.
Show how XRL A, A clears A, assuming that AH = 45H.
45H 0100 0101
45H 0100 0101
00H 0000 0000

Example 2:12
Read and test P1 to see whether it has the value 45H. If it does, send 99H to P2;
otherwise, it stays cleared.
Solution: XRL can be used to
MOV P2,#00 ;clear P2 see if two registers
MOV P1,#0FFH ;make P1 an input port have the same value
MOV R3,#45H ;R3=45H
MOV A,P1 ;read
P1 XRL A,R3
JNZ EXIT ;jump if A is not If both registers have
0 MOV P2,#99H the same value, 00 is
EXIT: ... placed in A. JNZ and
JZ test the contents of
the accumulator.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 40


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

CPL A ; complements the register


A This is called 1’s complement
 Source and destination both will be the accumulator
 Content of A will 1’s complemented and stored back in A itself.

MOV A, #56H
CPL A ;now A=A9H
;0101 0110(56H)
;becomes 1010 1001(A9H)

 To get the 2’s complement, all we have to do is to add 1 to the 1’s complement

CJNE destination, source, Label


 The actions of comparing and jumping are combined into a single instruction called CJNE
(compare and jump if not equal)
 The CJNE instruction compares two operands, and jumps if they are not equal
 The destination operand can be in the accumulator or in one of the Rn registers
 The source operand can be in a register, in memory, or immediate
• The operands themselves remain unchanged
 It changes the CY flag to indicate if the destination operand is larger or smaller.
 Notice in the CJNE instruction that any Rn register can be compared with an immediate value
 There is no need for register A to be involved
 The compare instruction is really a subtraction, except that the operands remain unchanged
 Flags are changed according to the execution of the SUBB instruction.

Example 2 – 13
Write a program to read the temperature and test it for the value 75.
According to the test results, place the temperature value into the registers indicated
by the following.
If T = 75 then A = 75
If T < 75 then R1 = T
If T > 75 then R2 = T
Solution:
MOV P1,#0FFH ;make P1 an input port
MOV A,P1 ;read P1 port
CJNE A,#75,OVER;jump if A is not 75
SJMP EXIT ;A=75, exit
OVER: JNC NEXT ;if CY=0 then A>75
MOV R1,A ;CY=1, A<75, save in R1
SJMP EXIT ; and exit
NEXT: MOV R2,A ;A>75, save it in R2
EXIT: ...

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 41


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

RR A ; rotate right
A In rotate right
 The 8 bits of the accumulator are rotated right one bit, and
 Bit D0 exits from the LSB and enters into MSB, D7

MOV A,#36H ;A = 0011 0110


RR A ;A = 0001 1011 = 1Bh
RR A ;A = 1000 1101 = 8Dh
RL A ; rotate left RR A ;A = 1100 0110 = C6h
A In rotate left RR A ;A = 0110 0011 = 63h
 The 8 bits of the accumulator are rotated left one bit, and
 Bit D7 exits from the MSB and enters into LSB, D0

MOV A,#72H ;A = 0111 0010


RL A ;A = 1110 0100
RL A ;A = 1100 1001
RRC A ; rotate right A, through carry
 Bits are rotated from left to right
 They exit the LSB to the carry flag, and the carry flag enters the MSB

CLR C ;make CY = 0
MOV A,#26H;A = 0010 0110
RRC A ;A = 0001 0011 CY = 0
RRC A ;A = 0000 1001 CY = 1
RRC A ;A = 1000 0100 CY = 1

RLC A ; rotate left A, through carry


 Bits are rotated from left to right
 They exit the MSB to the carry flag, and the carry flag enters the LSB

Example 2- 14
Write a program that finds the number of 1s in a given
byte. MOV R1,#0
MOV R7,#8 ;count=08
MOV A,#97H
AGAIN: RLC A
JNC NEXT ;check for CY
INC R1 ;if CY=1 add to count
NEXT: DJNZ R7,AGAIN

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 42


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

SWAP A
It swaps the lower nibble and the higher nibble
 In other words, the lower 4 bits are put into the higher 4 bits and the higher 4 bits are put
into the lower 4 bits
 SWAP works only on the accumulator (A)

Example 2- 15
(a) Find the contents of register A in the following code.
(b) In the absence of a SWAP instruction, how would you exchange the nibbles?
Write a simple program to show the process.
Solution:
(a)
MOV A,#72H ;A = 72H
SWAP A ;A = 27H
(b)
MOV A,#72H ;A = 0111 0010
RL A ;A = 1110 0100
RL A ;A = 1100 1001
RL A ;A = 1001 0011
RL A ;A = 0010 0111

Example 2 - 16 Assume that register A has packed BCD, write a program to


convert packed BCD to two ASCII numbers and place them in R2 and R6.
Solution:
MOV A,#29H ;A=29H, packed BCD
MOV R2,A ;keep a copy of BCD data
ANL A,#0FH ;mask the upper nibble (A=09)
ORL A,#30H ;make it an ASCII, A=39H(‘9’)
MOV R6,A ;save it
MOV A,R2 ;A=29H, get the original data
ANL A,#0F0H ;mask the lower nibble
RR A ;rotate right
RR A ;rotate right
RR A ;rotate right SWAP A
RR A ;rotate right
ORL A,#30H ;A=32H, ASCII char. ’2’
MOV R2,A ;save ASCII char in R2

Branch instructions
 Repeating a sequence of instructions a certain number of times is called a loop.
 Loop action is performed by DJNZ reg, Label
• The register is decremented by one
• If it is not zero, it jumps to the target address referred to by the label
• Prior to the start of loop the register is loaded with the counter for the number of
repetitions
• Counter can be R0 – R7 or RAM location

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 43


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

;This program adds value 3 to the ACC ten times


MOV A,#0 A loop can
;A=0, clear ACC
MOV R2,#10 be repeated a
;load counter R2=10
AGAIN: ADD A,#03 maximum of
;add 03 to ACC
255 times, if
DJNZ R2,AGAIN ;repeat until R2=0,10 times
MOV R5,A ;save A in R5 R2 is FFH

Branch instructions – Nested loop


If we want to repeat an action more times than 256, we use a loop inside a loop, which is called
nested loop.
 We use multiple registers to hold the count

Example 2 – 17
Write a program to
(a) load the accumulator with the value 55H, and
(b) complement the ACC 700 times
MOV A,#55H ;A=55H
MOV R3,#10 ;R3=10, outer loop count
NEXT: MOV R2,#70 ;R2=70, inner loop count
AGAIN: CPL A ;complement A register
DJNZ R2,AGAIN ;repeat it 70 times
DJNZ R3,NEXT
Conditional Jumps

JZ label ; jump if

A=0
Jump only if a certain condition is met.
MOV A,R0 ;A=R0 Can be used only for
JZ OVER ;jump if A = 0 register A,
MOV A,R1 ;A=R1 not any other register
JZ OVER ;jump if A = 0
...
OVER:

Determine if R5 contains the value 0. If so, put 55H in


it. MOV A,R5 ;copy R5 to A
JNZ NEXT ;jump if A is not zero
MOV R5,#55H
NEXT: ...

JNC label ; jump if no carry, CY=0


 If CY = 0, the CPU starts to fetch and execute instruction from the address of the label
 If CY = 1, it will not jump but will execute the next instruction below JNC

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 44


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Example 2 – 18
Find the sum of the values 79H, F5H, E2H. Put the sum in registers R0 (low byte) and
R5 (high byte).
MOV A,#0 ;A=0
MOV R5,A ;clear R5
ADD A,#79H ;A=0+79H=79H
JNC N_1 ;if CY=0, add next number
INC R5 ;if CY=1, increment R5
N_1: ADD A,#0F5H ;A=79+F5=6E and CY=1
JNC N_2 ;jump if CY=0
INC R5 ;if CY=1,increment R5 (R5=1)
N_2: ADD A,#0E2H ;A=6E+E2=50 and CY=1
JNC OVER ;jump if CY=0
INC R5 ;if CY=1, increment 5
OVER: MOV R0,A ;now R0=50H, and R5=02

Example 2 – 19
Program using JNB and JBC
instructions.
LOOP: MOV A,#10h ; A = 10h
MOV R0,A ;RO = 10h
ADDA: ADD A,R0 ;add RO to A
JNC ADDA ;if the carry flag is 0, then ‘no
;carry’(NC) is true
;jump to address ADDA
;jump until A is F0h
;C flag is set on the next ADD & ‘no
;carry’(NC) is false
; do the next instruction

MOV A,#10h ;A = 10h; do program again using JNB


ADDR: ADD A,RO ;add RO to A (RO already equals 10h)
JNB OD7h,ADDR ;D7h is the bit address of the carry
;flag
JBC OD7h,LOOP ;the carry bit is 1; the jump to LOOP
;is taken, and the carry flag is
;cleared to 0

Unconditional Jumps
 The unconditional jump is a jump in which control is transferred unconditionally to the
target location.
 Unconditional jumps do not test any bit or byte to determine whether the jump should be taken.
 The jump is always taken.

LJMP (long jump)


• 3-byte instruction
• First byte is the opcode
• Second and third bytes represent the 16-bit target address (Any memory location
from 0000 to FFFFH)

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 45


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

SJMP (short jump)


• 2-byte instruction
• First byte is the opcode
• Second byte is the relative target address
• 00 to FFh (forward +127 and backward -128 bytes from the current PC)

Calculating Short Jump Address


 To calculate the target address of a short jump (SJMP, JNC, JZ, DJNZ, etc.)
• The second byte is added to the PC of the instruction immediately below the jump
 If the target address is more than -128 to +127 bytes from the address below the short jump
instruction
• The assembler will generate an error stating the jump is out of range

Bit manipulation instructions


Bit manipulation instructions will check the conditions of the bit and if condition is true, it jumps
to the address specified in the instruction. All the bit jumps are relative jumps.

Instructions that are used for signal-bit operations are


Instruction Function

SETB bit Set the bit (bit = 1)


CLR bit Clear the bit (bit = 0)

CPL bit Complement the bit (bit = NOT bit)

JB bit, target Jump to target if bit = 1 (jump if bit)

JNB bit, target Jump to target if bit = 0 (jump if no bit)

JBC bit, target Jump to target if bit = 1, clear bit (jump if bit, then clear)

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 46


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

 The JNB and JB instructions are widely used single-bit operations


• They allow you to monitor a bit and make a decision depending on whether it’s 0 or 1
• These two instructions can be used for any bits of I/O ports 0, 1, 2, and 3

Simple Assembly language program examples (without loops) to use these


instructions.

1. Write a program to add the values of locations 50H and 51H and store the result in
locations in 52h and 53H.

ORG 0000H ; Set program counter 0000H


MOV A,50H ; Load the contents of Memory location 50H into A
ADD A,51H ; Add the contents of memory 51H with CONTENTS A
MOV 52H,A ; Save the LS byte of the result in 52H
MOV A, #00 ; Load 00H into A
ADDC A, #00 ; Add the immediate data and carry to A
MOV 53H,A ; Save the MS byte of the result in location 53h
END

2. Write a program to store data FFH into RAM memory locations 50H to 58H using
direct addressing mode

ORG 0000H ; Set program counter 0000H


MOV A, #0FFH ; Load FFH into A
MOV 50H, A ; Store contents of A in location 50H
MOV 51H, A ; Store contents of A in location 5IH
MOV 52H, A ; Store contents of A in location 52H
MOV 53H, A ; Store contents of A in location 53H
MOV 54H, A ; Store contents of A in location 54H
MOV 55H, A ; Store contents of A in location 55H
MOV 56H, A ; Store contents of A in location 56H
MOV 57H, A ; Store contents of A in location 57H
MOV 58H, A ; Store contents of A in location 58H
END

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 47


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

3. Write a program to subtract a 16 bit number stored at locations 51H-52H from 55H-
56H and store the result in locations 40H and 41H. Assume that the least significant byte
of data or the result is stored in low address. If the result is positive, then store 00H, else
store 01H in 42H.

ORG 0000H ; Set program counter 0000H


MOV A, 55H ; Load the contents of memory location 55 into A
CLR C ; Clear the borrow flag
SUBB A,51H ; Sub the contents of memory 51H from contents of A
MOV 40H, A ; Save the LSByte of the result in location 40H
MOV A, 56H ; Load the contents of memory location 56H into A
SUBB A, 52H ; Subtract the content of memory 52H from the content
A MOV 41H, A ; Save the MSbyte of the result in location 415.
MOV A, #00 ; Load 005 into A
ADDC A, #00 ; Add the immediate data and the carry flag to A
MOV 42H, A ; If result is positive, store00H, else store 0lH in
42H END

4. Write a program to add two 16 bit numbers stored at locations 51H-52H and 55H-56H
and store the result in locations 40H, 41H and 42H. Assume that the least significant
byte of data and the result is stored in low address and the most significant byte of data
or the result is stored in high address.

ORG 0000H ; Set program counter 0000H


MOV A,51H ; Load the contents of memory location 51H into A
ADD A,55H ; Add the contents of 55H with contents of A
MOV 40H,A ; Save the LS byte of the result in location 40H
MOV A,52H ; Load the contents of 52H into A
ADDC A,56H ; Add the contents of 56H and CY flag with A
MOV 41H,A ; Save the second byte of the result in 41H
MOV A,#00 ; Load 00H into A
ADDC A,#00 ; Add the immediate data 00H and CY to A
MOV 42H,A ; Save the MS byte of the result in location 42H
END

5. Write a program to store data FFH into RAM memory locations 50H to 58H using
indirect addressing mode.

ORG 0000H ; Set program counter 0000H


MOV A, #0FFH ; Load FFH into A
MOV R0, #50H ; Load pointer, R0-50H
MOV R5, #08H ; Load counter, R5-08H
Start: MOV @R0, A ; Copy contents of A to RAM pointed by R0
INC R0 ; Increment pointer
DJNZ R5, start ; Repeat until R5 is
zero END

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 48


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

6. Write a program to add two Binary Coded Decimal (BCD) numbers stored at locations
60H and 61H and store the result in BCD at memory locations 52H and 53H. Assume
that the least significant byte of the result is stored in low address.

ORG 0000H ; Set program counter 00004


MOV A,60H ; Load the contents of memory location 6.0.H into A
ADD A,61H ; Add the contents of memory location 61H with contents of A
DA A ; Decimal adjustment of the sum in A
MOV 52H, A ; Save the least significant byte of the result in location 52H
MOV A,#00 ; Load 00H into .A
ADDC A,#00H ; Add the immediate data and the contents of carry flag to A
MOV 53H,A ; Save the most significant byte of the result in location 53:,
END

7. Write a program to clear 10 RAM locations starting at RAM address 1000H.

ORG 0000H ;Set program counter 0000H


MOV DPTR,#1000H ;Copy address 1000H to DPTR
CLR A ;Clear A
MOV R6, #0AH ;Load 0AH to R6
again:MOVX @DPTR,A ;Clear RAM location pointed by DPTR
INC DPTR ;Increment DPTR
DJNZ R6, again ;Loop until counter R6=0
END

8. Write a program to compute 1 + 2 + 3 + N (say N=15) and save the sum at70H

ORG 0000H ; Set program counter 0000H


N EQU 15
MOV R0,#00 ; Clear R0
CLR A ; Clear A
again: INC R0 ; Increment R0
ADD A, R0 ; Add the contents of R0 with
A CJNE R0,#N,again ; Loop until counter, R0, N
MOV 70H,A ; Save the result in location
70H END

9. Write a program to multiply two 8 bit numbers stored at locations 70H and 71H and
store the result at memory locations 52H and 53H. Assume that the least significant byte
of the result is stored in low address.

ORG 0000H ; Set program counter 00 OH


MOV A, 70H ; Load the contents of memory location 70h into A
MOV B, 71H ; Load the contents of memory location 71H into B
MUL A B ; Perform multiplication
MOV 52H,A ; Save the least significant byte of the result in location
52H MOV 53H,B ; Save the most significant byte of the result in location
53 END

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 49


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

10. Write a program to find the average of five 8 bit numbers. Store the result in 55H.
(Assume that after adding five 8 bit numbers, the result is 8 bit only).

ORG 0000H
MOV 40H,#05H
MOV 41H,#55H
MOV 42H,#06H
MOV 43H,#1AH
MOV 44H,#09H
MOV R0,#40H
MOV R5,#05H
MOV B,R5
CLR A
Loop: ADD A,@R0
INC R0
DJNZ
R5,Loop DIV
A B
MOV 55H,A
END

11. Write a program to find the cube of an 8 bit number program is as follows

ORG 0000H
MOV R1,#N
MOV A,R1
MOV B,R1
MUL A B
MOV R2, B
MOV B, R1
MUL A B
MOV 50,A
MOV 51,B
MOV A,R2
MOV B, R1
MUL AB
ADD A, 51H
MOV 51H, A
MOV 52H, B
MOV A, #00H
ADDC A, 52H
MOV 52H, A
END

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 50


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

12. Write a program to exchange the lower nibble of data present in external memory
6000H and 6001H

ORG 0000H ; Set program counter 00h


MOV DPTR, #6000H ; Copy address 6000H to DPTR
MOVX A, @DPTR ; Copy contents of 60008 to A
MOV R0, #45H ; Load pointer, R0=45H
MOV @RO, A ; Copy cont of A to RAM pointed by 80
INC DPL ; Increment pointer
MOVX A, @DPTR ; Copy contents of 60018 to A
XCHD A, @R0 ; Exchange lower nibble of A with RAM pointed by RO
MOVX @DPTR, A ; Copy contents of A to 60018
DEC DPL ; Decrement pointer
MOV A, @R0 ; Copy cont of RAM pointed by R0 to A
MOVX @DPTR, A ; Copy cont of A to RAM pointed by DPTR
END

13. Write a program to count the number of and o's of 8 bit data stored in location 6000H.

ORG 0000 ; Set program counter 00008


MOV DPTR, #6000h ; Copy address 6000H to DPTR
MOVX A, @DPTR ; Copy number to A
MOV R0,#08 ; Copy 08 in R0
MOV R2,#00 ; Copy 00 in R2
MOV R3,#00 ; Copy 00 in R3
CLR C ; Clear carry flag
BACK: RLC A ; Rotate A through carry flag
INC R2 ; If CF = 0, increment R2 AJMP NEXT2
NEXT: INC R3 ; If CF = 1, increment R3
NEXT2: DJNZ R0,BACK ; Repeat until RO is zero
END
14. Write a program to shift a 24 bit number stored at 57H-55H to the left logically four
places. Assume that the least significant byte of data is stored in lower address.

ORG 0000H ; Set program counter 0000h


MOV R1,#04 ; Set up loop count to 4
again: MOV A,55H ; Place the least significant byte of data in A
CLR C ; Clear tne carry flag
RLC A ; Rotate contents of A (55h) left through carry
MOV 55H,A
MOV A,56H
RLC A ; Rotate contents of A (56H) left through carry
MOV 56H,A
MOV A,57H
RLC A ; Rotate contents of A (57H) left through carry
MOV 57H,A
DJNZ R1,again ; Repeat until R1 is zero
END

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 51


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

15. Two 8 bit numbers are stored in location 1000h and 1001h of external data memory.
Write a program to find the GCD of the numbers and store the result in 2000h.

ALGORITHM
Step 1 :Initialize external data memory with data and DPTR with address
Step 2 :Load A and TEMP with the operands
Step 3 :Are the two operands equal? If yes, go to step 9
Step 4 :Is (A) greater than (TEMP) ? If yes, go to step 6
Step 5 :Exchange (A) with (TEMP) such that A contains the bigger number
Step 6 :Perform division operation (contents of A with contents of TEMP)
Step 7 :If the remainder is zero, go to step 9
Step 8 :Move the remainder into A and go to step 4
Step 9 :Save the contents 'of TEMP in memory and terminate the program

ORG 0000H ; Set program counter 0000H


TEMP EQU 70H
TEMPI EQU 71H
MOV DPTR, #1000H ; Copy address 100011 to DPTR
MOVX A, @DPTR ; Copy First number to A
MOV TEMP, A ; Copy First number to temp INC DPTR
MOVX A, @DPTR ; Copy Second number to A
LOOPS: CJNE A, TEMP, LOOP1 ; (A) /= (TEMP) branch to LOOP1
AJMP LOOP2 ; (A) = (TEMP) branch to L00P2
LOOP1: JNC LOOP3 ; (A) > (TEMP) branch to LOOP3
NOV TEMPI, A ; (A) < (TEMP) exchange (A) with (TEMP)
MOV A, TEMP
MOV TEMP, TEMPI
LOOP3: MOV B, TEMP
DIV AB ; Divide (A) by (TEMP)
MOV A, B ; Move remainder to A
CJNE A,#00, LOOPS ; (A)/=00 branch to LOOPS
LOOP2: MOV A, TEMP
MOV DPTR, #2000H
MOVX @DPTR, A ; Store the result in 2000H
END

****************************************************************************************

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 52


MICROCONTROLLER | MODULE2:8051 INSTRUCTION SET

Module – 3

8051 Stack, I/O Port Interfacing and Programming


8051
Stack
 The stack is a section of RAM used by the CPU to store information temporarily.
o This information could be data or an address.
 The register used to access the stack is called the SP (stack pointer) register.
o The stack pointer in the 8051 is only 8 bit wide, which means that it can take value of
00 to FFH.
o When the 8051 is powered up, the SP register contains value 07.
o RAM location 08 is the first location begin used for the stack by the 8051.
 The storing of a CPU register in the stack is called a PUSH
o SP is pointing to the last used location of the stack
o As we push data onto the stack, the SP is incremented by one
 This is different from many microprocessors
 Loading the contents of the stack back into a CPU register is called a POP
o With every pop, the top byte of the stack is copied to the register specified by
the instruction and the stack pointer is decremented once

Example 3-1
Show the stack and stack pointer from the following. Assume the default stack area.
MOV R6, #25H
MOV R1, #12H
MOV R4, #0F3H
PUSH 6
PUSH 1
PUSH 4
Solution:

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 53


MICROCONTROLLER | MODULE 3: 8051 STACK, I/O PORT INTERFACING AND PROGRAMMING

Example 3-2
Examining the stack, show the contents of the register and SP after execution of the
following instructions. All value are in hex.
POP 3 ; POP stack into R3
POP 5 ; POP stack into R5
POP 2 ; POP stack into R2
Solution:

 The CPU also uses the stack to save the address of the instruction just below the CALL
instruction
o This is how the CPU knows where to resume when it returns from the called
subroutine.
 The reason of incrementing SP after push is
o Make sure that the stack is growing toward RAM location 7FH, from lower to upper
addresses.
 If the stack pointer were decremented after push
o We would be using RAM locations 7, 6, 5, etc. which belong to R7 to R0 of bank 0,
the default register bank.
 When 8051 is powered up, register bank 1 and the stack are using the same memory space
o We can reallocate another section of RAM to the stack.

Example 3-3
Examining the stack, show the contents of the register and SP after execution of the
following instructions. All value are in hex.
MOV SP, #5FH ;make RAM location 60H, first stack location
MOV R2, #25H
MOV R1, #12H
MOV R4, #0F3H
PUSH 2
PUSH 1
PUSH 4
Solution:

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 54


.
MICROCONTROLLER | MODULE 3: 8051 STACK, I/O PORT INTERFACING AND PROGRAMMING

Stack and Subroutine instructions


CALLs and Subroutines
 Call instruction is used to call subroutine
o Subroutines are often used to perform tasks that need to be performed frequently
o This makes a program more structured in addition to saving memory space
 LCALL (long call)
o 3-byte instruction
o First byte is the opcode
o Second and third bytes are used for address of target subroutine
• Subroutine is located anywhere within 64K byte address space
 ACALL (absolute call)
o 2-byte instruction
o 11 bits are used for address within 2K-byte range
 When a subroutine is called, control is transferred to that subroutine, the processor
o Saves on the stack the address of the instruction immediately below the LCALL
o Begins to fetch instructions from the new location
 After finishing execution of the subroutine
o The instruction RET transfers control back to the caller
• Every subroutine needs RET as the last instruction

CALL Instructions- LCALL


1. A call opcode occurs in the program software, or an interrupt is generated in the hardware
circuitry.
2. The return address of the next instruction after the call instruction or interrupt is found in
the program counter.
3. The return address bytes are pushed on the stack, low byte first.
4. The stack pointer is incremented for each push on the stack.
5. The subroutine address is placed in the program counter.
6. The subroutine is executed.
7. A RET (return) opcode is encountered at the end of the subroutine.
Example 3-4 Upon executing “LCALL DELAY”,
ORG 0 the address of instruction below it,
“MOV A,#0AAH” is pushed onto
BACK: MOV A,#55H ;load A with 55H stack, and the 8051 starts to execute
MOV P1,A ;send 55H to port 1 at 300H.
LCALL DELAY ;time delay
MOV A,#0AAH ;load A with AA (in hex)
MOV P1,A ;send AAH to port 1
LCALL DELAY
SJMP BACK ;keep doing this indefinitely

;---------- this is delay subroutine ------------


ORG 300H ;put DELAY at address 300H
DELAY: MOV R5,#0FFH ;R5=255 (FF in hex), counter
AGAIN: DJNZ R5,AGAIN ;stay here until R5 become 0
RET ;return to caller (when R5 =0)
END ;end of asm file When R5 becomes 0, control falls to
the RET which pops the address
from the stack into the PC and
resumes executing the instructions

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 55


.
MICROCONTROLLER | MODULE 3: 8051 STACK, I/O PORT INTERFACING AND PROGRAMMING

CALL Instructions- ACALL


 The only difference between ACALL and LCALL is
o The target address for LCALL can be anywhere within the 64K byte address
o The target address of ACALL must be within a 2K-byte range
 The use of ACALL instead of LCALL can save a number of bytes of program ROM space.

Interrupts and Returns


 An interrupt is a hardware-generated call.
 Just as a call opcode can be located within a program to automatically access a subroutine,
certain pins on the 8051 can cause a call when external electrical signals on them go to a
low state.
 Internal operations of the timers and the serial port can also cause an interrupt call to take place.
 The subroutines called by an interrupt are located at fixed hardware addresses and are called as
Interrupt Service Routine (ISR).
 When an interrupt call takes place,
INTERRUPT ADDRESS (HEX) CALLED
 Hardware interrupt disable flip-flops are set.
 So that it prevents another interrupt of the IEO 0003
same priority level from taking place.
TFO 0008
 Disabled Hardware interrupts can be enabled
back by executing an interrupt return IEl 0013
instruction. (Generally written at the end TFl 0018
of the interrupt subroutine.)
SERIAL 0023

RETI
 Pops two bytes from the stack into the program counter (PC) and reset the interrupt enable Flip-
Flops.
 The only difference between the RET and RETI instructions is the enabling of the interrupt logic
when RETI is used.
 RET is used at the ends of subroutines called by an opcode. RETI is used by subroutines
called by an interrupt

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 56


.
MICROCONTROLLER | MODULE 3: 8051 STACK, I/O PORT INTERFACING AND PROGRAMMING

I/O Port Interfacing and Programming

 The four 8-bit I/O ports P0, P1, P2 and P3 each uses 8 pins
 All the ports upon RESET are configured as input, ready to be used as input ports
o When the first 0 is written to a port, it becomes an output
o To reconfigure it as an input, a 1 must be sent to the port
o To use any of these ports as an input port, it must be programmed

Port 0
 Port 0 can be used for input or output, each pin must
be connected externally to a 10K ohm pull-up resistor
o This is due to the fact that P0 is an open
drain, unlike P1, P2, and P3
• Open drain is a term used for MOS
chips in the same way that open
collector is used for TTL chips

Example 3-5
The following code will continuously send out to port 0 the alternating value 55H and
AAH
BACK: MOV A,#55H
MOV P0,A
ACALL DELAY
MOV A,#0AAH
MOV P0,A
ACALL DELAY
SJMP BACK

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 57


.
MICROCONTROLLER | MODULE 3: 8051 STACK, I/O PORT INTERFACING AND PROGRAMMING

 In order to make port 0 an input, the port must be programmed by writing 1 to all the bits

Example 3-6
Port 0 is configured first as an input port by writing 1s to it, and then data is received from
that port and sent to P1
MOV A,#0FFH ;A=FF hex
MOV P0,A ;make P0 an i/p port by writing it all 1s
BACK:MOV A,P0 ;get data from P0
MOV P1,A ;send it to port 1
SJMP BACK ;keep doing it

Port 1
 Port 1 can be used as input or output
o In contrast to port 0, this port does not need any pull-up resistors since it already has pull-
up resistors internally
o Upon reset, port 1 is configured as an input port
o To make port 1 an input port, it must be programmed as such by writing 1 to all its bits

Example 3-7
The following code will continuously send out to port 1 the alternating value 55H and
AAH
MOV A,#55H
BACK: MOV P1,A
ACALL DELAY
CPL A
SJMP BACK
A= 01010101(55h) =>Complementing gives 10101010(AAh)

Example 3-8
Port 1 is configured first as an input port by writing 1s to it, then data is received from
that port and saved in R7 and R5
MOV A,#0FFH ;A=FF hex
MOV P1,A ;make P1 an input port by writing it all 1s
MOV A,P1 ;get data from P1
MOV R7,A ;save it to in reg R7
ACALL DELAY ;wait
MOV A,P1 ;another data from P1
MOV R5,A ;save it to in reg R5

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 58


.
MICROCONTROLLER | MODULE 3: 8051 STACK, I/O PORT INTERFACING AND PROGRAMMING

Port 2 and Port 3


 Port 2 can be used as input or output
o Just like P1, port 2 does not need any pull-up resistors since it already has pull-up
resistors internally
o Upon reset, port 2 is configured as an input port
 To make port 2 an input port, it must be programmed as such by writing 1 to all its bits.
 Port 3 can be used as input or output
o Port 3 does not need any pull-up resistors
o Port 3 is configured as an input port upon reset.

I/O Programming- Different ways of Accessing Entire 8 Bits

The entire 8 bits of Port 1 are accessed


BACK: MOV A,#55H
MOV P1,A
ACALL DELAY
MOV A,#0AAH
MOV P1,A
ACALL DELAY
SJMP BACK

Rewrite the code in a more efficient manner


by accessing the port directly without going Another way of doing the same thing
through the accumulator MOV A,#55H
BACK: MOV P1,#55H BACK: MOV P1,A
ACALL DELAY ACALL DELAY
MOV P1,#0AAH CPL A
ACALL DELAY SJMP BACK
SJMP BACK

Example 3-9
Write a program to toggle all the bits of port1 by sending to it the values 55h and AAh
continuously. Put a time delay in between each issuing of data to port1.
ORG 0
BACK: MOV A,#55H ; Load A with 55h
MOV P1,A ; Send 55h to port1
ACALL DELAY ; Call the subroutine DELAY
MOV A,#0AAH ; Load A with AAh
MOV P1,A ; Send AAh to port1
ACALL DELAY ; Call the subroutine DELAY
SJMP BACK ; Keep doing this indefinitely
Delay Subroutine
ORG 300H
DELAY: MOV R5, #0FFH ; R5 works as counter with 256 counts
AGAIN: DJNZ R5, AGAIN ; Stay here until R5 becomes 0
RET ; Return to Called program
END

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 59


.
MICROCONTROLLER | MODULE 3: 8051 STACK, I/O PORT INTERFACING AND PROGRAMMING

Example 3-10
Rewrite the previous program efficiently.

ORG 0
MOV A,#55H ; Load A with 55h
BACK: MOV P1,A ; Send 55h to port1
ACALL DELAY ; Call the subroutine DELAY
CPL A ; Complements A, so that A becomes
SJMP BACK ;AAh
Keep doing this indefinitely
------ Delay Subroutine---------
ORG 300H
DELAY: MOV R5, #0FFH ; R5 works as counter with 256 counts
AGAIN: DJNZ R5, AGAIN ; Stay here until R5 becomes 0
RET ; Return to Called program
END

Example 3-11
Write a program to toggle the bits of port1 delay which depends on the value of a
number in R0.
ORG 0
BACK: MOV A,#0H
MOV P1,A ; Send 0h to port P1
MOV R0, #30H ; Required count value for generating
delay
ACALL DELAY; Call the subroutine
CPL A DELAY
MOV P1,A ; Complement
Send AAh toA to toggle
MOV R0, #0FFH port1 ; required count value for generating
ACALLdelay
DELAY ; Call the subroutine DELAY
SJMP BACK ; Keep doing this indefinitely
------ Delay Subroutine---------
ORG 300H
DELAY: NOP ; Do nothing
AGAIN: DJNZ R0, AGAIN ; Stay here until R0 becomes 0
RET ; Return to the Called
program

Example 3-12
Write a program to perform the following:
(a) Keep monitoring the P1.2 bit until it becomes high
(b) When P1.2 becomes high, write value 45H to port 0
(c) Send a high-to-low (H-to-L) pulse to P2.3
SETB P1.2 ;make P1.2 an input
MOV A,#45H ;A=45H
AGAIN: JNB P1.2,AGAIN ;get out when P1.2=1
MOV P0,A ;issue A to P0
SETB P2.3 ;make P2.3 high
CLR P2.3 ;make P2.3 low for H-to-
L

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 60


.
MICROCONTROLLER | MODULE 3: 8051 STACK, I/O PORT INTERFACING AND PROGRAMMING

Example 3-13
Assume that bit P2.3 is an input and represents the condition of an
oven. If it goes high, it means that the oven is hot. Monitor the bit
continuously.
Whenever it goes high, send a high-to-low pulse to port P1.5 to turn on a
HERE: JNB P2.3,HERE ;keep monitoring for high
SETB P1.5 ;set bit P1.5=1
CLR P1.5 ;make high-to-low
SJMP HERE ;keep repeating

Example 3-14
A switch is connected to pin P1.7. Write a program to check the status of SW and
perform the following:
(a) If SW=0, send letter ‘N’ to P2
(b) If SW=1, send letter ‘Y’ to P2

SETB P1.7 ;make P1.7 an input


AGAIN: JB P1.7,OVER ;jump if P1.7=1
MOV P2,#’N’ ;SW=0, issue ‘N’ to P2
SJMP AGAIN ;keep monitoring
OVER: MOV P2,#’Y’ ;SW=1, issue ‘Y’ to P2
SJMP AGAIN ;keep monitoring

SETB P1.0 ;make P1.0 an input


AGAIN: MOV C, P1.0 ;Read the switch status in to CF
MOV P2.7,C ;Send the switch status on to LED
SJMP AGAIN ;keep monitoring

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 61


.
MICROCONTROLLER | MODULE 3: 8051 STACK, I/O PORT INTERFACING AND PROGRAMMING

Module – 4
8051 Timers and Serial Port
Timers/Counters are used generally for
 Time reference
 Creating delay
 Wave form properties measurement
 Periodic interrupt generation
 The 8051 has two timers/counters, they can be used either as Timers to generate a time delay or
as Event counters to count events happening outside the microcontroller

8051 has two timers, Timer 0 and Timer 1.


 Timer 0 and Timer 1 are 16 bits.
 8051 has an 8-bit architecture, each 16-bits timer is accessed as two separate registers of low
byte and high byte.
 The low byte register is called TL0/TL1 and The high byte register is called TH0/TH1.
 Accessed like any other register.

Timer in 8051 is used as timer, counter and baud rate generator. Timer always counts up irrespective of
whether it is used as timer, counter, or baud rate generator: Timer is always incremented by the
microcontroller. The time taken to count one digit up is based on master clock frequency.

If Master CLK=12 MHz,


Timer Clock frequency = Master CLK/12 = 1 MHz
Timer Clock Period = 1micro second
This indicates that one increment in count will take 1 microsecond.
The two timers in 8051 share two SFRs (TMOD and TCON) which control the timers, and each
timer also has two SFRs dedicated solely to itself (TH0/TL0 and TH1/TL1).

The following are timer related SFRs in 8051.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 62


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

TMOD Register
 Both timers 0 and 1 use the same register, called TMOD (timer mode), to set the various
timer operation modes
 TMOD is an 8-bit register
 The lower 4 bits are for Timer 0, the upper 4 bits are for Timer 1
 In each case, the lower 2 bits are used to set the timer mode, the upper 2 bits to specify the
operation.

TCON (timer control) register

 TCON (timer control) register is an 8bit register

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 63


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

TIMER MODES
Timers can operate in four different modes. They are as follows
Timer Mode-0: In this mode, the timer is used as a 13-bit UP counter as follows.

Fig. Operation of Timer on Mode-0

The lower 5 bits of TLX and 8 bits of THX are used for the 13-bit count. Upper 3 bits of TLX
are ignored. When the counter rolls over from all 0's to all 1's, TFX flag is set and an
interrupt is generated. The input pulse is obtained from the previous stage. If TR1/0 bit is 1
and Gate bit is 0, the counter continues counting up. If TR1/0 bit is 1 and Gate bit is 1, then
the operation of the counter is controlled by input. This mode is useful to measure the width of a
given pulse fed to input.

Timer Mode-1: This mode is similar to mode-0 except for the fact that the Timer operates in 16-
bit mode.

Fig: Operation of Timer in Mode 1

Timer Mode-2: (Auto-Reload Mode): This is an 8 bit counter/timer operation. Counting is


performed in TLX while THX stores a constant value. In this mode when the timer overflows
i.e. TLX becomes FFH, it is fed with the value stored in THX. For example, if we load THX
with 50H then the timer in mode 2 will count from 50H to FFH. After that 50H is again reloaded.
This mode is useful in applications like fixed time sampling.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 64


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

Fig: Operation of Timer in Mode 2


Timer Mode-3: Timer 1 in mode-3 simply holds its count. The effect is same as setting TR1=0.
Timer0 in mode-3 establishes TL0 and TH0 as two separate counters.

Fig: Operation of Timer in Mode 3


Control bits TR1 and TF1 are used by Timer-0 (higher 8 bits) (TH0) in Mode-3 while TR0 and TF0
are available to Timer-0 lower 8 bits (TL0).

PROGRAMMING 8051 TIMERS IN ASSEMBLY


In order to program 8051 timers, it is important to know the calculation of initial count value to be
stored in the timer register. The calculations are as follows.
In any mode, Timer Clock period = 1/Timer Clock Frequency.
= 1/ (Master Clock Frequency/12)

1. Mode 1 (16 bit timer/counter)


Value to be loaded in decimal = 65536 – (Delay required/Timer clock period)
Convert the answer into hexadecimal and load onto THx and TLx register.
(65536D = FFFFH+1)

2. Mode 0 (13 bit timer/counter)


Value to be loaded in decimal = 8192 – (Delay required/Timer clock period)
Convert the answer into hexadecimal and load onto THx and TLx register.
(8192D = 1FFFH+1)

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 65


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

3. Mode 2 (8 bit auto reload)


Value to be loaded in decimal = 256 – (Delay required/Timer clock period)
Convert the answer into hexadecimal and load onto THx register. Upon starting the timer this value
from THx will be reloaded to TLx register. (256D = FFH+1)

Steps for programming timers in 8051

Mode 1:
 Load the TMOD value register indicating which timer (0 or 1) is to be used and which timer
mode is selected.
 Load registers TL and TH with initial count values.
Start the timer by the instruction “SETB TR0” for timer 0 and “SETB TR1” for timer 1.
 Keep monitoring the timer flag (TF) with the “JNB TFx, target” instruction to see if it
is raised. Get out of the loop when TF becomes high.
 Stop the timer with the instructions “CLR TR0” or “CLR TR1”, for timer 0 and timer
1, respectively.
 Clear the TF flag for the next round with the instruction “CLR TF0” or “CLR TF1”, for
timer 0 and timer 1, respectively.
 Go back to step 2 to load TH and TL again.

Mode 0:
The programming techniques mentioned here are also applicable to counter/timer mode 0. The only
difference is in the number of bits of the initialization value.

Mode 2:
 Load the TMOD value register indicating which timer (0 or 1) is to be used; select
timer mode 2.
 Load TH register with the initial count value. As it is an 8-bit timer, the valid range is
from 00 to FFH.
 Start the timer.
 Keep monitoring the timer flag (TFx) with the “JNB TFx, target” instruction to see if it
is raised. Get out of the loop when TFx goes high.
 Clear the TFx flag.
 Go back to step 4, since mode 2 is auto-reload.

Example 4-1
Indicate which mode and which timer are selected for each of the following.
(a) MOV TMOD, #01H (b) MOV TMOD, #20H (c) MOV TMOD, #12H
Solution:
We convert the value from hex to binary. From Figure 9-3 we have:
(a) TMOD = 00000001, mode 1 of timer 0 is selected.
(b) TMOD = 00100000, mode 2 of timer 1 is selected.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 66


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

(c) TMOD = 00010010, mode 2 of timer 0, and mode 1 of timer 1 are selected

Example 4-2
Find the timer’s clock frequency and its period for various 8051-based system, with the crystal
frequency 11.0592 MHz when C/T bit of TMOD is 0.

1/12 × 11.0529 MHz = 921.6 MHz;


T = 1/921.6 kHz = 1.085 us

Example 4-3
In the following program, we create a square wave of 50% duty cycle (with equal portions high and
low) on the P1.5 bit. Timer 0 is used to generate the time delay. Analyze the program

MOV TMOD,#01 ;Timer 0, mode 1(16-bit mode)


HERE: MOV TL0,#0F2H ;TL0=F2H, the low byte
MOV TH0,#0FFH ;TH0=FFH, the high byte
CPL P1.5 ;toggle P1.5
ACALL DELAY
SJMP HERE
DELAY: SETB TR0 ;start the timer 0
AGAIN: JNB TF0,AGAIN ;monitor timer flag 0 ;until it rolls over
CLR TR0 ;stop timer 0
CLR TF0 ;clear timer 0 flag
RET

In the above program notice the following step.


1. TMOD is loaded.
2. FFF2H is loaded into TH0-TL0.
3. P1.5 is toggled for the high and low portions of the pulse.
4. The DELAY subroutine using the timer is called.
5. In the DELAY subroutine, timer 0 is started by the SETB TR0 instruction.
6. Timer 0 counts up with the passing of each clock, which is provided by the crystal oscillator. As
the timer counts up, it goes through the states of FFF3,FFF4, FFF5, FFF6, FFF7, FFF8, FFF9,
FFFA, FFFB, and so on until it reaches FFFFH. One more clock rolls it to 0, raising the timer
flag (TF0=1).
At that point, the JNB instruction falls through.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 67


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

7. Timer 0 is stopped by the instruction CLR TR0. The DELAY subroutine ends, and the
process is repeated.
Notice that to repeat the process, we must reload the TL and TH registers, and start the process is
repeated

Example 4-4
In Example 9-4, calculate the amount of time delay in the DELAY subroutine generated by the timer.
Assume XTAL = 11.0592 MHz.
Solution:
The timer works with a clock frequency of 1/12 of the XTAL frequency; therefore, we have
11.0592 MHz / 12 = 921.6 kHz as the timer frequency. As a result, each clock has a
period of T
=1/921.6kHz = 1.085us. In other words, Timer 0 counts up each 1.085 us resulting in delay
= number of counts × 1.085us.
The number of counts for the roll over is FFFFH – FFF2H = 0DH (13decimal). However, we
add one to 13 because of the extra clock needed when it rolls over from FFFF to 0 and raise the
TF flag. This gives 14× 1.085us = 15.19us for half the pulse. For the entire period it is T = 2×
15.19us = 30.38us as the time delay generated by the timer.

Example 4-5
The following program generates a square wave on P1.5 continuously using timer 1 for a time delay.
Find the frequency of the square wave if XTAL = 11.0592 MHz. In your calculation do not
include the overhead due to Instructions in the loop.
MOV TMOD,#10 ;Timer 1, mod 1 (16-bitmode)
AGAIN: MOV TL1,#34H ;TL1=34H, low byte of timer
MOV TH1,#76H ;TH1=76H, high byte timer
SETB TR1 ;start the timer 1
BACK: JNB TF1,BACK ;till timer rolls
over
CLR TR1 ;stop the timer 1
CPL P1.5 ;comp. p1. to get hi, lo
CLR TF1 ;clear timer flag 1
SJMP AGAIN ;is not auto-reload
Solution:
Since FFFFH – 7634H = 89CBH + 1 = 89CCH and 89CCH = 35276 clock count and 35276
× 1.085 us = 38.274 ms for half of the square wave. The frequency = 13.064Hz. Also notice that
the high portion and low portion of the square wave pulse are equal. In the above
calculation, the overhead due to all the instruction in the loop is not included.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 68


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

Example 4-6
Write a program to continuously generate a square wave of 2 kHz frequency on pin P1.5 using timer
1. Assume the crystal oscillator frequency to be 12 MHz.

The period of the square wave is T = 1/(2 kHz) = 500 µs. Each half pulse = 250 µs.
The value n for 250 µs is: 250 µs /1 µs = 250 65536 - 250 = FF06H. TL = 06H and TH = 0FFH.

MOV TMOD,#10 ;Timer 1, mode 1


AGAIN: MOV TL1,#06H ;TL0 = 06H
MOV TH1,#0FFH ;TH0 = FFH
SETB TR1 ;Start timer 1
BACK: JNB TF1,BACK ;Stay until timer rolls over
CLR TR1 ;Stop timer 1
CPL P1.5 ;Complement P1.5 to get Hi, Lo
CLR TF1 ;Clear timer flag 1
SJMP AGAIN ;Reload timer

Example4-6
Write a program segment that uses timer 1 in mode 2 to toggle P1.0 once whenever the counter
reaches a count of 100. Assume the timer clock is taken from external source P3.5 (T1).
The TMOD value is 60H The initialization value to be loaded into TH1 is 256 - 100 = 156 = 9CH

MOV TMOD, #60h ;Counter1, mode 2, C/T’= 1


MOV TH1, #9Ch ;Counting 100 pulses
SETB P3.5 ;Make T1 input
SETB TR1 ;Start timer 1
BACK: JNB TF1, BACK ;Keep doing it if TF =
0 CPL P1.0 ;Toggle port bit
CLR TF1 ;Clear timer overflow flag
SJMP BACK ;Keep doing it

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 69


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

SERIAL COMMUNICATION
The 8051 microcontroller is parallel device that transfers eight bits of data simultaneously over eight
data lines to parallel I/O devices. Parallel data transfer over a long is very expensive. Hence, a
serial communication is widely used in long distance communication. In serial data
communication, 8-bit data is converted to serial bits using a parallel in serial out shift register and
then it is transmitted over a single data line. The data byte is always transmitted with least significant
bit first.

Basics of serial data communication

Communication Links
1. Simplex communication link: In simplex transmission, the line is dedicated for transmission.
The transmitter sends and the receiver receives the data.

2. Half duplex communication link: In half duplex, the communication link can be used for
either transmission or reception. Data is transmitted in only one direction at a time.

3. Full duplex communication link: If the data is transmitted in both ways at the same time,
it is a full duplex i.e. transmission and reception can proceed simultaneously. This
communication link requires two wires for data, one for transmission and one for reception.

Types of Serial communication:


Serial data communication uses two types of communication.
1. Synchronous serial data communication: In this transmitter and receiver are synchronized. It
uses a common clock to synchronize the receiver and the transmitter. First the synch
character is sent and then the data is transmitted. This format is generally used for high speed
transmission. In Synchronous serial data communication a block of data is transmitted at
a time.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 70


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

2. Asynchronous Serial data transmission: In this, different clock sources are used for
transmitter and receiver. In this mode, data is transmitted with start and stop bits. A
transmission begins with start bit, followed by data and then stop bit. For error
checking purpose parity bit is included just prior to stop bit. In Asynchronous serial
data communication a single byte is transmitted at a time.

Baud rate: The rate at which the data is transmitted is called baud or transfer rate. The baud rate
is the reciprocal of the time to send one bit. In asynchronous transmission, baud rate is not
equal to number of bits per second. This is because; each byte is preceded by a start bit and followed
by parity and stop bit. For example, in synchronous transmission, if data is transmitted with
9600 baud, it means that 9600 bits are transmitted in one second. For bit transmission time = 1
second/ 9600 =
0.104 ms.

8051 SERIAL COMMUNICATION


Three special function registers support serial communication.
1. SBUF Register: Serial Buffer (SBUF) register is an 8-bit register. It has separate SBUF registers
for data transmission and for data reception. For a byte of data to be transferred via the
TXD line, it must be placed in SBUF register. Similarly, SBUF holds the 8-bit data received by
the RXD pin and read to accept the received data.

2. SCON register: The contents of the Serial Control (SCON) register are shown below.
This register contains mode selection bits, serial port interrupt bit (TI and RI) and also the ninth
data bit for transmission and reception (TB8 and RB8).

SM0, SM1:They determine the framing of data by specifying the number of bits per character, and
the start and stop bits

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 71


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

SM2: This enables the multiprocessing capability of the 8051


REN (receive enable) : It is a bit-addressable register ◻ When it is high, it allows 8051 to receive
data on RxD pin ◻ If low, the receiver is disable
TI (transmit interrupt) : When 8051 finishes the transfer of 8-bit character ◻ It raises TI flag to
indicate that it is ready to transfer another byte ◻ TI bit is raised at the beginning of the stop bit ◻
RI (receive interrupt) : When 8051 receives data serially via RxD, it gets rid of the start and
stop bits and places the byte in SBUF register ◻ It raises the RI flag bit to indicate that a byte has
been received and should be picked up before it is lost ◻ RI is raised halfway through the stop bit.

3. PCON register: The SMOD bit (bit 7) of PCON register controls the baud rate in
asynchronous mode transmission

SERIAL COMMUNICATION MODES


1. Mode 0: In this mode serial port runs in synchronous mode. The data is transmitted and received
through RXD pin and TXD is used for clock output. In this mode the baud rate is 1/12 of
clock frequency.
2. Mode 1: In this mode SBUF becomes a 10 bit full duplex transceiver. The ten bits are 1 start
bit, 8 data bit and 1 stop bit. The interrupt flag TI/RI will be set once transmission or
reception is over. In this mode the baud rate is variable and is determined by the timer 1
overflow rate. Baud rate = [2smod/32] x Timer 1 overflow Rate = [2smod/32] x [Oscillator Clock
Frequency] / [12 x [256 – [TH1]]]
3. Mode 2: This is similar to mode 1 except 11 bits are transmitted or received. The 11 bits are, 1
start bit, 8 data bit, a programmable 9th data bit, 1 stop bit. Baud rate = [2smod/64] x
Oscillator Clock Frequency.
4. Mode 3: This is similar to mode 2 except baud rate is calculated as in mode 1

RS-232 standards: To allow compatibility among data communication equipment made by


various manufactures, an interfacing standard called RS232 was set by the Electronics Industries
Association (EIA) in 1960. Since the standard was set long before the advent of logic family, its
input and output voltage levels are not TTL compatible. In RS232, a logic one (1) is represented

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 72


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A
by -3 to -25V and

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 73


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

referred as MARK while logic zero (0) is represented by +3 to +25V and referred as SPACE.
For this reason to connect any RS232 to a microcontroller system we must use voltage converters
such as MAX232 to convert the TTL logic level to RS232 voltage levels and vice-versa.
MAX232 IC chips are commonly referred as line drivers. In RS232 standard we use two types
of connectors. DB9 connector or DB25 connector.

The 8051 connection to MAX232 is as follows.


The 8051 has two pins that are used specifically for transferring and receiving data serially. These two
pins are called TXD, RXD. Pin 11 of the 8051 (P3.1) assigned to TXD and pin 10 (P3.0) is
designated as RXD. These pins TTL compatible; therefore they require line driver (MAX 232)
to make them RS232 compatible. MAX 232 converts RS232 voltage levels to TTL voltage levels
and vice versa. One advantage of the MAX232 is that it uses a +5V power source which is the
same as the source voltage for the 8051. The typical connection diagram between MAX 232
and 8051 is shown below

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 74


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

SERIAL COMMUNICATION PROGRAMMING IN ASSEMBLY AND C.


Steps to programming the 8051 to transfer data serially
1. The TMOD register is loaded with the value 20H, indicating the use of the Timer 1 in mode
2 (8-bit auto reload) to set the baud rate.
2. The TH1 is loaded with one of the values in table 5.1 to set the baud rate for serial
data transfer.
3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an8-bit data
is framed with start and stop bits.
4. TR1 is set to 1 start timer 1.
5. TI is cleared by the “CLR TI” instruction.
6. The character byte to be transferred serially is written into the SBUF register.
7. The TI flag bit is monitored with the use of the instruction JNB TI, target to see if
the character has been transferred completely.
8. To transfer the next character, go to step 5.

Example 4.7
With XTAL = 11.0592 MHz, find the TH1 value needed to have thefollowing baud rates. (a) 9600
(b) 2400 (c) 1200
Solution:
The machine cycle frequency of 8051 = 11.0592 / 12 = 921.6 kHz,and 921.6 kHz / 32 = 28,800 Hz
is frequency by UART to timer 1 toset baud rate.
(a) 28,800 / 3 = 9600 where -3 = FD (hex) is loaded into TH1
(b)28,800 / 12 = 2400 where -12 = F4 (hex) is loaded into TH1
(c)28,800 / 24 = 1200 where -24 = E8 (hex) is loaded into TH1

Example 4.8
Write a program for the 8051 to transfer letter ‘A’ serially at 4800- baud rate, 8 bit data, 1 stop bit
continuously.
Solution:
MOV TMOD, #20H ;timer 1,mode 2(auto reload)
MOV TH1, #-6 ;4800 baud rate
MOV SCON, #50H ;8-bit, 1 stop, REN enabled
SETB TR1 ;start timer 1
AGAIN: MOV SBUF, #”A” ;letter “A”to transfer
HERE: JNB TI, HERE ;wait for the last bit
CLR TI ;clear TI for next char
SJMP AGAIN ;keep sending A

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 75


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

Example 4.9
Write a program for the 8051 to transfer “YES” serially at 9600 baud, 8-bit data, 1 stop bit, do this
continuously
MOV TMOD, #20H ;timer 1,mode 2(auto reload)
MOV TH1, #-3 ;9600 baud rate
MOV SCON, #50H ;8-bit, 1 stop, REN enabled
SETB TR1 ;start timer 1
AGAIN: MOV A, #”Y” ;transfer “Y”
ACALL TRANS
MOV A, #”E” ;transfer “E”
ACALL TRANS
MOV A, #”S” ;transfer “S”
ACALL TRANS
SJMP AGAIN ;keep doing it serial data transfer subroutine
TRANS: MOV SBUF,A ;load SBUF
HERE: JNB TI,HERE ;wait for the last bit
CLR TI ;get ready for next byte
RET

Example 4.10
Write a C program for 8051 to transfer the letter “A” serially at 4800 baud continuously. Use 8-bit data and 1
stop bit.
Solution:
#include
<reg51.h> void
main(void)
{
TMOD=0x20; //use Timer 1, mode 2
TH1=0xFA; //4800 baud
rate SCON=0x50;
TR1=1;
while (1) {
SBUF=‘A’; //place value in buffer
while (TI==0);
TI=0;
}
}

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 76


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

Example 4.11
Write an 8051 C program to transfer the message “YES” serially at 9600 baud, 8-bit data, 1 stop bit.
Do this continuously.
Solution:
#include <reg51.h>
void SerTx(unsigned char);
void main(void)
{
TMOD=0x20; //use Timer 1, mode
2 TH1=0xFD; //9600 baud rate
SCON=0x50;
TR1=1; //start
timer While (1) {
SerTx(‘Y’);
SerTx(‘E’);
SerTx(‘S’);
}
}
void SerTx(unsigned char x)
{
SBUF=x; //place value in
buffer While (TI==0); //wait until
transmitted TI=0;
}

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 77


.
MICROCONTROLLER | MODULE4:8051 TIMERS AND SERIAL PORT BEC405A

Module – 5
8051 Interrupts and Interfacing Applications

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 an Interrupt?
An interrupt 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.
Need of 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 door-to-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 & Software Interrupt


The interrupts in a controller can be either hardware or software. If the interrupts are generated by the
controller’s 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.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 78


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

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. In AT89C51, 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 :

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 79


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

Interrupt ROM Location (Hex) Pin Flag clearing


Reset 0000 9 Auto
External interrupt 0 0003 12 Auto
Timer interrupt 0 000B – Auto
External interrupt 1 0013 13 Auto
Timer interrupt 1 001B – Auto
Serial COM interrupt 0023 – 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 by
Interrupt 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.

Bit Values of IE Register of 8051 Microcontroller

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.
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

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 80


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

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 Interrupt Symbol

0 External0 EX0

1 Timer0 IT0

2 External1 EX1

3 Timer1 IT1
4 Serial ES

5 Timer2 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.

Programming Timer Interrupts


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.
E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 81
.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

5. Write subroutine for Timer Interrupt. The interrupt number is 1 for Timer0 and 3 for Timer1.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 82


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

6. Note that it is not required to clear timer flag TFx.


7. 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.
8. 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
}

Programming External Interrupts


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:

Bit Values of TCON Register of 8051 Microcontroller

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.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 83


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

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.
3.
Example 5.1
//Level trigger external interrupt
void main()
{
IE = 0x81;
while(1);
}
void ISR_ex0(void) interrupt 0
{
<body of interrupt>
}

Example 5.2
//Edge trigger external interrupt
void main()
{
IE = 0x84;
IT1 = 1;
while(1);
}
void ISR_ex1(void) interrupt 2
{
<body of interrupt>
}

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 84


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

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 5.3
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;
}

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 85


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

Example 5.4
// 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;
}
}

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 86


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

Stepper Motor Interfacing:


Stepper motor is a widely used device that translates electrical pulses into mechanical movement.
Stepper motor is used in applications such as; disk drives, dot matrix printer, robotics etc,. The
construction of the motor is as shown in figure below.

Figure: Structure of stepper motor

It has a permanent magnet rotor called the shaft which is surrounded by a stator. Commonly used
stepper motors have four stator windings that are paired with a center – tapped common. Such motors
are called as four-phase or unipolar stepper motor. The stator is a magnet over which the electric
coil is wound. One end of the coil are connected commonly either to ground or +5V. The other
end is provided with a fixed sequence such that the motor rotates in a particular direction. Stepper
motor shaft moves in a fixed repeatable increment, which allows one to move it to a precise
position. Direction of the rotation is dictated by the stator poles. Stator poles are determined by the
current sent through the wire coils.

Step angle: Step angle is defined as the minimum degree of rotation with a single step.
No of steps per revolution = 360° / step angle Steps per second = (rpm x steps per revolution) / 60
Example: step angle = 2° No of steps per revolution = 180

Switching Sequence of Motor: As discussed earlier the coils need to be energized for the
rotation. This can be done by sending a bits sequence to one end of the coil while the other end is
commonly connected. The bit sequence sent can make either one phase ON or two phase ON for a
full step sequence or it can be a combination of one and two phase ON for half step sequence.
Both are tabulated below.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 87


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

Full Step: Two Phase ON

Half Step (8 – sequence): The sequence is tabulated as below:

Figure: 8051 interface to stepper motor

The following example 1 to example 6 shown below will elaborate on the discussion done above:

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 88


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

Example 1: Write an ALP to rotate the stepper motor clockwise / anticlockwise continuously with full
step sequence.
Program:
MOV A, #66H
BACK: MOV P1, A
RR A
ACALL DELAY
SJMP BACK
DELAY: MOV R1, #100
UP1: MOV R2, #50
UP: DJNZ R2, UP
DJNZ R1, UP1
RET

Note: motor to rotate in anticlockwise use instruction RL A instead of RR A

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 89


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 90


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

Programming Stepper Motor with 8051 C


The following examples 5 and 6 will show the programming of stepper motor using 8051 C.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 91


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

Digital-to-Analog (DAC) converter:


The DAC is a device widely used to convert digital pulses to analog signals. In this section we
will discuss the basics of interfacing a DAC to 8051. The two method of creating a DAC is binary
weighted and R/2R ladder. The Binary Weighted DAC, which contains one resistor or current
source for each bit of the DAC connected to a summing point. These precise voltages or currents
sum to the correct output value. This is one of the fastest conversion methods but suffers from poor
accuracy because of the high precision required for each individual voltage or current. Such high-
precision resistors and current-sources are expensive, so this type of converter is usually limited to 8-
bit resolution or less.

The R-2R ladder DAC, which is a binary weighted DAC that uses a repeating cascaded structure
of resistor values R and 2R. This improves the precision due to the relative ease of producing equal
valued matched resistors (or current sources). However, wide converters perform slowly due to
increasingly large RC-constants for each added R-2R link.

The first criterion for judging a DAC is its resolution, which is a function of the number of binary
inputs. The common ones are 8, 10, and 12 bits. The number of data bit inputs decides the
resolution of the DAC since the number of analog output levels is equal to 2n, where n is the
number of data bit inputs. DAC0808: The digital inputs are converter to current Iout, and by
connecting a resistor to the Iout pin, we can convert the result to voltage. The total current Iout is a
function of the binary numbers at the D0-D7 inputs of the DAC0808 and the reference current Iref ,
and is as follows:

Usually reference current is 2mA. Ideally we connect the output pin to a resistor, convert this current
to voltage, and monitor the output on the scope. But this can cause inaccuracy; hence an opamp is
used to convert the output current to voltage. The 8051 connection to DAC0808 is as shown in
E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 92
.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

the figure below.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 93


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

Figure: 8051 connection to DAC0808

The following examples 9, 10 and 11 will show the generation of waveforms using DAC0808.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 94


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

Analog-to-digital converter (ADC) interfacing:


ADCs (analog-to-digital converters) are among the most widely used devices for data acquisition.
A physical quantity, like temperature, pressure, humidity, and velocity, etc., is converted to
electrical (voltage, current) signals using a device called a transducer, or sensor We need an
analog-to-digital converter to translate the analog signals to digital numbers, so microcontroller can
read them. ADC804 chip: ADC804 IC is an analog-to-digital converter. It works with +5 volts and
has a resolution of 8 bits. Conversion time is another major factor in judging an ADC. Conversion
time is defined as the time it takes the ADC to convert the analog input to a digital (binary) number.
In ADC804 conversion time varies depending on the clocking signals applied to CLK R and CLK
IN pins, but it cannot be faster than 110μs.

Pin Description of ADC804:

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 95


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

CLK IN and CLK R: CLK IN is an input pin connected to an external clock source. To use the
internal clock generator (also called self-clocking), CLK IN and CLK R pins are connected to a
capacitor and a resistor and the clock frequency is determined by:
Typical values are R = 10K ohms and C =150pF. We get f = 606 kHz and the conversion time is
110μs.
Vref/2 : It is used for the reference voltage. If this pin is open (not connected), the analog input voltage
is in the range of 0 to 5 volts (the same as the Vcc pin). If the analog input range needs to be 0 to
4 volts, Vref/2 is connected to 2 volts. Step size is the smallest change can be discerned by an
ADC

D0-D7: The digital data output pins. These are tri-state buffered. The converted data is accessed only
when CS =0 and RD is forced low. To calculate the output voltage, use the following formula

Dout = digital data output (in decimal),


Vin = analog voltage, and
step size (resolution) is the smallest change

Analog ground and digital ground: Analog ground is connected to the ground of the analog Vin
and digital ground is connected to the ground of the Vcc pin. To isolate the analog Vin signal from
transient voltages caused by digital switching of the output D0 – D7. This contributes to the
accuracy of the digital data output.

Vin(+) & Vin(-): Differential analog inputs where Vin = Vin (+) – Vin (-). Vin (-) is connected to
ground and Vin (+) is used as the analog input to be converted.

RD: Is “output enable” a high-to-low RD pulse is used to get the 8-bit converted data out of ADC804.

INTR: It is “end of conversion” When the conversion is finished, it goes low to signal the CPU
that the converted data is ready to be picked up.

WR: It is “start conversion” When WR makes a low-to-high transition, ADC804 starts converting the
analog input value of Vin to an 8- bit digital number.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 96


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

CS: It is an active low input used to activate ADC804.

The following steps must be followed for data conversion by the ADC804 chip:
1. Make CS= 0 and send a L-to-H pulse to pin WR to start conversion.
2. Monitor the INTR pin, if high keep polling but if low, conversion is complete, go to next step.
3. Make CS= 0 and send a H-to-L pulse to pin RD to get the data

out The following figure shows the read and write timing for

ADC804.

The following figures shows the self-clocking with the RC component for frequency and the external
frequency connected to XTAL2 of 8051.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 97


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 98


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

ADC0808/0809 chip: ADC808 has 8 analog inputs. It allows us to monitor up to 8 different


transducers using only single chip. The chip has 8-bit data output just like the ADC804. The 8 analog
input channels are multiplexed and selected according to the values given to the three address pins, A,
B, and C. that is; if CBA=000, CH0 is selected; CBA=011, CH3 is selected and so on. The pin details
of ADC0808 are as shown in the figure below. (Explanation can be done as is with ADC0804).

Steps to Program ADC0808/0809


1. Select an analog channel by providing bits to A, B, and C addresses.
2. Activate the ALE pin. It needs an L-to-H pulse to latch in the address.
3. Activate SC (start conversion) by an H-to-L pulse to initiate conversion.
4. Monitor EOC (end of conversion) to see whether conversion is finished.
5. Activate OE (output enable) to read data out of the ADC chip. An H-to-L pulse to the OE pin
will bring digital data out of the chip.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 99


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

LCD Interfacing:
LCD is finding widespread use replacing LEDs for the following reasons: The declining prices of LCD
The ability to display numbers, characters, and graphics Incorporation of a refreshing controller
into the LCD, thereby relieving the CPU of the task of refreshing the LCD Ease of programming
for characters and graphics.

Command codes

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 100


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

LCD timing diagram for reading and writing is as shown in the below figures.

Sending Data/ Commands to LCDs with Time Delay: To send any of the commands to the LCD,
make pin RS=0. For data, make RS=1. Then send a high-to-low pulse to the E pin to enable the
internal latch of the LCD.

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 101


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 102


.
MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS 18EC46

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 100


MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS 18EC46

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 101


MICROCONTROLLER | MODULE 5: 8051 INTERRUPTS AND INTERFACING APPLICATIONS 18EC46

****************************************************************************************

E N SRIVANI, ASSISTANT PROFESSOR DEPT. OF ECE, SJCIT 102

You might also like