Download as pdf or txt
Download as pdf or txt
You are on page 1of 205

1

 The Intel MCS-51 (commonly termed 8051) is a Harvard


architecture, complex instruction set
computing (CISC) Architecture, single
chip microcontroller (µC) series developed by Intel in 1980
for use in embedded systems

 In a CISC processor, each instruction performs so many


actions that it takes several clock cycles to complete.

 RISC-based machines execute one instruction per clock cycle

MODULE - 2 2
FEATURES
 8-bit CPU
 64K bytes on-chip program memory (ROM)
 128 bytes on-chip data memory (RAM)
 32 I/O pins arranged as four 8-bit ports (P0 - P3)
 32 general purpose registers each of 8-bit
 Special Function Registers (SFRs) of 128 bytes
 16-bit Program Counter
 8-bit Processor Status Word (PSW) & Stack Pointer
 Two 16-bit timer/counters : T0 and T1
 Two external and three internal vectored interrupts
 One full duplex serial I/O (UART)
MODULE - 2 3
8051 FAMILY SERIES

MODULE - 2 4
8051 FAMILY SERIES
 Although the 8051 is the most popular member of the 8051
family, you will not see “8051″ in the part number.

 This is because the 8051 is available in different memory


types, such as UV-EPROM, flash, and NV-RAM, all of which
have different part numbers.

 The UV-EPROM version of the 8051 is the 8751. The flash


ROM version is marketed by many companies including Atmel
Corp. and Dallas Semiconductor.
MODULE - 2 5
8051 FAMILY SERIES

 The Atmel Flash 8051 is called AT89C51, while Dallas


Semiconductor calls theirs DS89C4xO (DS89C420/430/440).

 The NV-RAM version of the 8051 made by Dallas


Semiconductor is called DS5000.

 There is also an OTP (one-time programmable) version of the


8051 made by various manufacturers.

MODULE - 2 6
8051 MAJOR MANUFACTURERS

 ATMEL
 ANALOG DEVICES
 ST MICROELECTRONICS
 DALLAS
 MAXIM
 SILICON LABS
 TEXAS INSTRUMENTS
 MICROCHIP
 ZILOG
MODULE - 2 7
8051 ATMEL SERIES

Part Number ROM RAM I/O pins Timer Interrupt Vcc Packaging
AT89C51 4K 128 32 2 6 5V 40
AT89C52 8K 256 32 3 8 5V 40
AT89C1051 1K 64 15 1 3 3V 20

AT89C2051 2K 128 32 3 8 3V 20
AT89LV51 4K 128 32 2 6 3V 40
AT89LV52 8K 128 32 3 8 3V 40

MODULE - 2 8
8051 PIN DETAILS
 Although 8051 family members (e.g., 8751, 89C51,
89C52, DS89C4xO) come in different packages, such DIP QFP
as DIP (dual in-line package), QFP (quad flat package),
and LLC (leadless chip carrier)

 They all have 40 pins that are dedicated to various


functions such as I/O, RD, WR, address, data, and LLC
interrupts.

 Some companies provide a 20-pin version of the 8051


with a reduced number of I/O ports for less demanding
applications.
MODULE - 2 9
8051 PIN DETAILS
 However, since the vast majority of developers
use the 40-pin chip, we will concentrate on that.
 In 40 pin package, a total of 32 pins are set
aside for the four ports PO, P1, P2, and P3,
where each port takes 8 pins.
 The rest of the pins are designated as Vcc,
GND, XTAL1, XTAL2, RST, EA, PSEN, and
ALE.

MODULE - 2 10
8051 PIN DETAILS
 Of these pins, six (Vcc, GND, XTAL1, XTAL2, RST, and EA)
are used by all members of the 8051 and 8031 families.

 In other words, they must be connected in order for the


system to work, regardless of whether the microcontroller is
of the 8051 or 8031 family.

 The other two pins, PSEN and ALE, are used mainly in 8031-
based systems.

MODULE - 2 11
8051 SCHEMATICS

MODULE - 2 12
8051 PIN DIAGRAM

MODULE - 2 13
8051 PIN DESCRIPTION

 Pin-40 : Vcc is the main power source. Usually its +5V DC.

 Pins 32-39: Port 0 (P0.0 to P0.7) – In addition to serving as


I/O port, lower order address and data bus signals are
multiplexed with this port (to serve the purpose of external
memory interfacing). This is a bi directional I/O port (the
only one in 8051) and external pull up resistors are required
to function this port as I/O.

MODULE - 2 14
 Pin-31:- ALE - Address Latch Enable. It is especially used
for 8031 IC to connect it to the external memory. It can be
used while deciding whether P0 pins will be used as Address
bus or Data bus. When ALE = 1, then the P0 pins work as
Data bus and when ALE = 0, then the P0 pins act as Address
bus.

 Pin-30:- EA - External Access input is used to enable or


disallow external memory interfacing. If there is no external
memory requirement, this pin is pulled high by connecting it
to Vcc.
MODULE - 2 15
 Pin- 29:- PSEN or Program Store Enable. This is an active
low pin, i.e., it gets activated after applying a low pulse. It
is an output pin and used along with the EA pin in 8031 based
(i.e. ROMLESS) Systems to allow storage of program code in
external ROM.

 Pins- 21-28: Port 2 (P 2.0 to P 2.7) – in addition to serving


as I/O port, higher order address bus signals are multiplexed
with this quasi bi directional port.

 Pin 20:- Vss – it represents ground (0 V) connection.


MODULE - 2 16
 Pins 18 and 19:- XTAL1 & XTAL2 Used for interfacing
an external crystal to provide system clock.

 Pins 10 – 17:- Port 3 (P 3.0 to P 3.7) It is also of 8 bits and can crystal
be used as Input/Output. This port provides some extremely
important signals.

 P3.0 and P3.1 are RxD (Receiver) and TxD (Transmitter)


respectively and are collectively used for Serial Communication.
Serial Communication.
 P3.2 and P3.3 pins are used for external interrupts. P3.4 and P3.5
are used for timers T0 and T1 respectively.

 P3.6 and P3.7 are Write (WR) and Read (RD) pins.

MODULE - 2 17
 Pin 9:- RESET pin is used to set the 8051 microcontroller to
its initial values, while the microcontroller is working or at
the initial start of application. The RESET pin must be set
high for 2 machine cycles.

 Pins 1 – 8:- Port 1 (P 1.0 to P 1.7). It is an 8-bit port (pin


1 through 8) and can be used either as input or
output. Unlike other ports, this port does not serve any
other functions. Port 1 is an internally pulled up, quasi bi
directional I/O port.

MODULE - 2 18
8051 ARCHITECTURE (Simplified)

MODULE - 2 19
CENTRAL PROCESSING UNIT (CPU)
 Central Processor Unit (CPU) is the brain of any processing
device of the microcontroller.

 It monitors and controls all operations that are performed on


the Microcontroller units.

 The User has no control over the work of the CPU directly.

 It reads program written in ROM memory and executes them


and do the expected task of that application.
MODULE - 2 21
INTERRUPT CONTROL
 There are five interrupt sources in 8051 Microcontroller and
interrupt control section control all these interrupts.

 Two external interrupts (INT0 & INT1), two timer (TF0 &
TF1) interrupts and one serial port (RI / TI) interrupt.

 The Microcontroller 8051 can be configured in such a way


that it temporarily terminates or pause the main program at
the occurrence of interrupt. When subroutine is completed
then the execution of main program starts as usual.
MODULE - 2 22
RAM & ROM
 Microcontroller 8051 has 4K of Code Memory or Program
memory that is it has 4KB ROM and RAM of 128 bytes.

 The memory which is used to store the program


of Microcontroller, is known as code memory or Program
memory . It is known as 'ROM'(Read Only Memory).

 Microcontroller also requires a memory to store data or


operands temporarily. This memory is known as Data Memory
and we use 'RAM'(Random Access Memory) for this purpose.
MODULE - 2 23
BUS CONTROL
 Bus control section of 8051 is responsible for controlling the
operation of address and data bus.
 Bus: Basically Bus is a collection of wires which work as a
communication channel or medium for transfer of Data.
 Buses are of two types:
 Address Bus: Microcontroller 8051 has a 16 bit address
bus. It used to address memory locations.
 Data Bus: Microcontroller 8051 has 8 bits data bus. It
is used to carry data.
MODULE - 2 24
CRYSTAL OSCILLATOR
 Crystal Oscillator: Since Microcontroller is a digital circuit
device, therefore it requires clock for its operation.

 For this purpose, Microcontroller 8051 has oscillator circuitry


section which works as a clock source for Central Processing
Unit.

 As the output pulses of oscillator are stable therefore it


enables synchronized work of all parts of
8051 Microcontroller.
MODULE - 2 25
I/O PORTS
 I/O Ports: To connect any external devices or peripherals we
require I/O interfacing ports in the microcontroller.

 All 8051 microcontrollers have 4 I/O ports each comprising 8


bits which can be configured as input (1) or an output (0),
depends on its logic state.

 Accordingly, in total of 32 input/output pins enabling the


microcontroller to be connected to peripheral devices are
available for use.
MODULE - 2 26
TIMERS/COUNTERS
 Timers/Counters: 8051 Microcontroller 8051 two 16-bit
timers and counters: Timer 0 and Timer 1.

 They can be used either as timers to generate a time delay


or as counters to count events happening outside the
microcontroller.

 Since the 8051 has an 8-bit architecture, each 16-bit is


accessed as two separate registers of low byte and high
byte.
MODULE - 2 27
SERIAL PORT
 Serial port: The 8051 contains one Serial port or UART
(Universal Asynchronous Receiver Transmitter)

 The serial port is full-duplex so, it can transmit and


receive simultaneously

 Two port pins are used to provide the serial interface


P3.0 is the receive pin (RXD) P3.1 is the transmit pin
(TXD)

 This serial port that can be programmed to operate in


one of four different modes and at a range of
frequencies.
MODULE - 2 28
 The 8051 has two types of memory and these are Program
Memory and Data Memory.

 Program Memory (ROM) is used to permanently save the


program being executed, while Data Memory (RAM) is used
for temporarily storing data and intermediate results created
and used during the operation of the microcontroller.

 Depending on the model in use (8051 microcontroller family in


general) at most a few Kb of ROM and 128 or 256 bytes of
RAM is used.
MODULE - 2 29
PROGRAM MEMORY (ROM)

 The 8051 has 4K (4096 locations) of internal or on-chip


ROM. And it can be expanded up to 64K.

 This is used for storing the system program. 212 = 4096,


therefore the internal ROM locations go from 0000H to
0FFFH.

 Even though such an amount of memory is sufficient for


writing most of the programs, there are situations when it is
necessary to use additional memory as well.
MODULE - 2 30
PROGRAM MEMORY (ROM)
 EA=0 In this case, the
microcontroller completely
ignores internal program
memory and executes only
the program stored in
external memory.

 EA=1 In this case, the


microcontroller executes first
the program from built-in
ROM, then the program
stored in external memory
MODULE - 2 31
DATA MEMORY (RAM)

 In the MCS-51 family, 8051 has 128 bytes of internal data


memory and it allows interfacing external data memory of
maximum size up to 64K.

 So the total size of data memory in 8051 can be upto 64K


(external) + 128 bytes (internal).

 So there are 3 separations/divisions of the data memory:-


1) Register banks
2) Bit addressable area
3) Scratch pad area
MODULE - 2 32
DATA MEMORY (RAM)

MODULE - 2 33
DATA MEMORY – REGISTER BANKS
 Registers are used to store data or operands during
executions. Register banks form the lowest 32 bytes on
internal RAM memory.

 There are 4 register banks designated bank #0,#1, #2


and #3. Each bank has 8 registers which are designated as
R0,R1…R7.

 At a time only one register bank is selected (using RS1 &


RS0 bits in PSW register) for operations and the registers
inside the selected bank are accessed using mnemonics
R0..R1.. etc.

 By default register bank #0 is selected (after a system


reset).
MODULE - 2 35
DATA MEMORY – BIT ADDRESSABLE AREA
 The 8051 supports a special feature which allows
access to bit variables. This is where individual
memory bits in Internal RAM can be set or cleared.

 The Bit Addressable area of the RAM is 16 bytes


(128 bits) next to register banks of Internal RAM
located between 20h and 2Fh. In all there are 128
bits numbered 00h to 7Fh.

 Being bit variables any one variable can have a value


0 or 1. A bit variable can be set with a command
such as SETB and cleared with a command such as
CLR.
MODULE - 2 37
DATA MEMORY – BIT ADDRESSABLE AREA
 Example instructions are
SETB 25h ; sets the bit 25h (becomes 1)
CLR 25h ; clears bit 25h (becomes 0)

 Bit addressable area is mainly used to store bit variables


from application program, like status of an output device like
LED or Motor (ON/OFF) etc.

 We need only a bit to store this status and using a complete


byte addressable area for storing this is really bad
programming practice, since it results in wastage of memory.
MODULE - 2 39
DATA MEMORY – SCRATCH PAD RAM
 These 80 bytes of Internal RAM memory scratch pad RAM
are available for general-purpose data storage.
 Scratch pad RAM is from 30H to 7FH and this includes
stack too.

 However, these 80 bytes are used by the system stack and


in practice little space is left for general storage.

 Access to this area of memory is fast compared to access to


the main memory and special instructions with single byte
operands are used.
MODULE - 2 40
DATA MEMORY – SCRATCH PAD RAM

 The scratch pad RAM can be accessed using direct or


indirect addressing modes.

 Examples of direct addressing:


MOV A, 6Ah ;reads contents of address 6Ah to accumulator

 Examples for indirect addressing (use registers R0 or R1):


MOV R1, #6Ah ; move immediate 6Ah to R1
MOV A, @R1 ; move indirect: R1 contains address of Internal
RAM which contains data that is moved to A.

MODULE - 2 41
DATA MEMORY – SFRs (Special Function
Registers)
 SFRs are accessed just like normal Internal RAM
locations.

 The SFR registers are located within the Internal


Memory in the address range 80h to FFh.

 Each SFR has a very specific function. Note some


of the SFR registers are bit addressable.

MODULE - 2 42
DATA MEMORY – SFRs

 Although 128 byes of the SFR address space is defined only


21 SFR registers are defined in the standard 8051.

 Rest of locations are intentionally left unoccupied in order to


enable the manufacturers to further develop microcontrollers
keeping them compatible with the previous versions.

 Main function of SFR is to control timers, counters, serial


I/O, port I/O, and peripherals that are present in 8051
microcontroller.
MODULE - 2 43
DATA MEMORY – SFRs

MODULE - 2 45
SFRs A- Register

 The 21 Special Function Registers of 8051 Microcontroller are


categorized in to seven groups.

1) Math or CPU Registers: A and B


2) Status Register: PSW (Program Status Word)
3) I/O Port Latches: P0 (Port 0), P1 (Port 1), P2 (Port 2) and P3 (Port 3)
4) Pointer Registers: DPTR (Data Pointer – DPL,DPH), SP (Stack Pointer)
5) Peripheral Control Registers: PCON, SCON, TCON, TMOD, IE and IP
6) Peripheral Data Registers: TL0, TH0, TL1, TH1 and SBUF

MODULE - 2 46
SFRs A- Register
 The most important of all special function register is
Accumulator which is also known as ACC or A.

 The Accumulator holds the result of most of arithmetic and logic


operations. It is also used to store 8 bit data and to hold one of
operand of ALU units during arithmetical and logical operations.

 More than half instructions used by the 8051 microcontroller use


somehow use the accumulator.

 ACC is usually accessed by direct addressing and its physical


address is E0H.
MODULE - 2 47
SFRs A- Register
 Accumulator is an 8-bit register and it is both byte and bit
addressable.

 To access the individual bits of accumulator, use the format


ACC.X in the instruction where “X” denotes bit to be accessed.

MODULE - 2 48
SFRs B- Register

 It is special 8-bit math register and it is bit and byte


accessible.

 It is used in conjunction with A register as an input operand


for ALU to perform multiplication and division operation.

 It can also be used as general purpose register to store 8-


bit data.

MODULE - 2 49
SFRs - PSW REGISTER
 It is 8 bit register and it is bit and byte accessible.

 It contains several status bits that reflects the status of the operation that is being
carried out in the processor.

 It has 4 conditional flags or math flags (CY, AC, OV, P)which sets or resets
according to condition of result.

 It has 3 control flags (F0, RS0, RS1) by setting or resetting bit required operation
or function can be achieved.
MODULE - 2 50
SFRs - PSW REGISTER
 CY, the carry flag: This flag is set whenever there is a carry out from
the D7 bit. This flag bit is affected after an 8-bit addition or
subtraction.

 AC, the auxiliary carry flag: If there is a carry from D3 to D4 during


an ADD or SUB operation, this bit is set; otherwise, it is cleared. This
flag is used by instructions that perform BCD (binary coded decimal)
arithmetic.

 F0, the Flag 0 : The PSW.5 and PSW.1 bits are general-purpose
status flag bits and can be used by the programmer for any purpose. In
other words, they are user definable.
MODULE - 2 52
SFRs - PSW REGISTER
 RS0, RS1 - Register bank select bits. These two bits are used to
select one of four register banks of RAM. By setting and clearing these
bits, registers R0-R7 are stored in one of four banks of RAM.

MODULE - 2 53
SFRs - PSW REGISTER
 OV, overflow flag:
 This flag is set whenever the result of a signed number operation
is too large, causing the high-order bit to overflow into sign bit.
 In general, the carry flag is used to detect errors in unsigned
arithmetic operations.
 The overflow flag is only used to detect errors in signed
arithmetic operations

 P, the parity flag: The parity flag reflects the number of 1 s in the A
(accumulator) register only. If the A register contains an odd number
of 1’s, then P = 1. Therefore, P = 0 if A has an even number of 1s.

MODULE - 2 54
SFRs - P0, P1, P2, P3 - Input/Output Registers
 There are 4 ports with in total of 32 input/output pins are
available for connection to peripheral environment.
 So 4 Input/Output ports named P0, P1, P2 and P3 has got
four corresponding port registers P0, P1, P2 and P3. All 4
port registers are bit as well as byte addressable.
 Data must be written into port registers first to send it out
to any other external device through ports.

 Similarly any data received through ports must be read from


port registers for performing any operation.
MODULE - 2 55
SFRs - P0, P1, P2, P3 - Input/Output Registers

MODULE - 2 56
SFRs - P0, P1, P2, P3 - Input/Output Registers

MODULE - 2 57
SFRs - P0, P1, P2, P3 - Input/Output Registers

 If a bit is cleared (0), the appropriate pin will be configured


as an output, while if it is set (1), the appropriate pin will be
configured as an input.

 Upon reset and power-on, all port bits are set (1), which
means that all appropriate pins will be configured as inputs.

MODULE - 2 58
SFRs - DPTR REGISTER
 It is a 16 bit register used to hold address of external or
internal RAM where data is stored or result is to be stored.
 It can be divided into two 8-bit registers, DPH-data pointer
higher order and DPL-data pointer lower order.
 Each register can be used as general purpose register to
store 8 bit data and can also be used to store memory
location.
 It functions as Base register in base relative addressing
mode and indirect jump.
MODULE - 2 59
SFRs - DPTR REGISTER

MODULE - 2 60
SFRs - STACK POINTER
 It is 8-bit register. It is byte addressable.

 It is used to hold the internal RAM memory


location addresses which are used as stack
memory.

 When the data is to be placed on stack by


push instruction, the content of stack pointer is
incremented by 1.

 When data is retrieved from stack, content of


stack of stack pointer is decremented by 1.
MODULE - 2 61
SFRs - STACK POINTER

 A value stored in the Stack Pointer points to the first free


stack address and permits stack availability.

 Upon any reset and power-on, the value 7 is stored in the


Stack Pointer, which means that the space of RAM reserved
for the stack starts at this location.

MODULE - 2 62
PC - PROGRAM COUNTER (not a part of SFRs)

 It is used to hold 16 bit address of internal program


memory, or external ROM locations.

 The Program Counter (PC) is a 2-byte address which tells the


8051 where the next instruction to be executed from
memory.

 When the 8051 is initialized PC always starts at 0000h and


is incremented each time an instruction is executed.

MODULE - 2 63
MACHINE CYCLES
 The CPU takes a certain number of clock cycles to execute
an instruction.

 In the 8051 family, these clock cycles are referred to


as machine cycles.

 A single machine cycle is the minimum amount of time in


which a single 8051 instruction can be executed, although
many instructions take multiple machine cycles.

MODULE - 2 64
MACHINE CYCLES
 Pulse - One complete oscillation of the clock source; State -
Two pulses;
 1 machine cycle 8051 = six states or 12 clock pulses

MODULE - 2 65
MACHINE CYCLES
 If an instruction takes one machine cycle to execute, it will
take 12 pulses of the crystal to execute.

 8051 is designed to operate between 4MHz to 40MHz and


generally operates with a crystal frequency 11.0592 MHz.

 Since we know the crystal is pulsing 11,059,000 times per


second and that one machine cycle is 12 pulses. we can
calculate how many instruction cycles the 8051 can execute
per second:
11,059,000 / 12 = 921,583 and 1/ 921,583=1.085µs
MODULE - 2 66
MACHINE CYCLES
 This means that the 8051 can execute 921,583 single-cycle
instructions per second.

 For example, if you are using exclusively 2-cycle instructions


you would find that the 8051 would execute 460,791
instructions per second.

 The 8051 also has two really slow instructions that require a
full 4 cycles to execute-those instructions you’d find
performance to be about 230,395 instructions per second.
MODULE - 2 67
EXAMPLE - 1
 Lets find the time period of the machine cycle in each case for the
following crystal frequency of different 8051 based systems: 11.0592
MHz, 16 MHz, 20 MHz.
Answer:
11.0592 MHz:
11.0592/12 = 921.6 KHz
Machine cycle = 1/921.6 KHz = 1.085us [us=microsecond]
16 MHz:
16MHz/12 = 1.333 MHz
Machine cycle = 1/1.333 MHz = 0.75us [us=microsecond]
20MHz:
20MHz/12 = 1.66 MHz
Machine Cycle = 1/1.66 MHz = 0.60us [us=microsecond]
MODULE - 2 68
EXAMPLE - 2
 Lets find how long it takes to execute each of the following
instructions, for a crystal frequency of 11.0592 MHz. The machine
cycle of a system of 11.0592.z is 1.085 us
INSTRUCTION MACHINE CYCLE TIME TO EXECUTE
MOV R2,#55H 1 1x1.085 us = 1.085 us
DEC R2 1 1x1.085 us = 1.085 us
DJNZ R2,target 2 2x1.085 us = 2.17 us
LJMP 2 2x1.085 us = 2.17 us
SJMP 2 2x1.085 us = 2.17 us
NOP 1 1x1.085 us = 1.085 us
MUL AB 4 4x1.085 us = 4.34 us

MODULE - 2 69
8051 Timers
• The 8051 comes -with two 16 bit timers, both of which may
be controlled, set, read, and configured individually. The 8051
timers have three general functions:
• Programming predefined length of time, and then issuing an
interrupt request.
• Counting the transitions on an external pin,
• Generating baud rates for the serial port.
8051 Timers
• Basically the timers are the digital counters which are
incremented at the pulses given to it. The timers can be
controlled to -function through four SFRs namely, TMOD,
TCON, TH0/TL0 and TH1/TL1.
• The timers will have overflow when it counts to full value and
resets to 0 upon next count.
• The overflow in the timers will set the two bits in the TCON
SFR. This overflow can be programmed to interrupt the
microcontroller execution and execute a predefined
subroutine.
8051 Timers
• If the timer registers are incremented by the internal clock
pulses from the microcontroller, then the operation is termed
as ‘Timing’ operation.
• Meanwhile if the timer registers get their clock pulses from
an external device through the port 3 pins of 8051, then the
operation is termed as ‘Counting’.
• Timer 0 external input pin P3.4 (T0) is used give clock input to
timer 0 to act as counter.
• Timer 1 external input pin P3.5 (T1) is used give clock input to
timer 1.
Timer SFRS
• The 8051 has two timers and each of them will have similar
operations and functions. The timer in 8051 is basically a 16-
bit register which can be incremented depending upon the
clock pulses applied to it.

• These timer registers are configured as the Special Function


Registers.
Timer SFRS
• These SFRs at any time has the timer/counter register content.
So, the timers can be stopped at any time and the contents can
be read from these registers .Since there are only two bytes
devoted to the value of each timer it is apparent that the
maximum value a timer may have is 65,535.
• If a timer contains the value 65,535 and is subsequently
incremented, it will reset to 0 with an indication of overflow.
• One timer is TIMER0 and the other is TIMER1. Each timer also
has two 8 bit SFRs namely TH0 and TL0 forming the higher and
lower order bytes of Timer0 and TH1 and TL1 forming the
higher and lower bytes of Timer1.
TMOD SFR
• The TMOD SFR -used to control the mode of operation of both
timers. Each bit of the SFR gives the micro controller specific
information -how to run a timer. The higher order four bits (bits
4 through 7) relate to Timer 1 whereas the low four bits (bits 0
through 3) perform the same functions for timer 0.
BIT Patterns for TMOD (89h) SFR
TCON SFR
• SFR that controls the two timers and provides
valuable information about them is TCON.
BIT Patterns for TCON (88h) SFR
Bit Name Bit Address Explanation of Function Timer

7 TF1 8Fh Timer 1 Overflow. The micro 1


controller sets this bit when Timer
1 overflows.
6 TR1 8Eh Timer 1 Run. When this bit is set 1
Timer 1 is turned on. When this bit
is cleared Timer 1 is off.
5 TF0 8Dh Timer 0 Overflow. The micro 0
controller sets this bit when Timer
0 overflows.
4 TR0 8Ch Timer 0 Run. When this bit is set 0
Timer 0 is turned on. When this bit
is cleared Timer 0 is off.
TCON SFR
• Only 4 of the 8 bits of the TCON SFR is defined. the other 4 bits
of the SFR don’t have anything to do with timers. They are
related with Interrupts and they will be discussed in the
chapter that addresses interrupts.

• Note that the individual bits of TCON register can be addressed


separately by their bit addresses. This allows the programmer
to run the timers using bit addressable instructions and check
the overflow independently.
Timer Operating Modes

• The two 16 bit timers of 8051 can be operated in any


one of the four modes. The mode selection can be
done by the setting the proper bits in the TMOD SFR.
Operating Modes of 8051
Mode 0 - 13-bit Timer Mode
• Timer mode "0" is a 13-bit timer. Out of 16 bits of Timers, only 13bits
are used. The 5 bits of lower order byte is used and 8 bits of the
higher order byte of the timers are used in Mode0. Lower order byte
TL0/1 will count from 0 to 31.
• When TL0/1 is incremented from 31, it will "reset" to 0 and
increment TH0/1. So, the timer can only contain 8192 values from 0
to 8192.
• The timer can be operated as timer with internal clock pulses or as a
counter with external clock pulses.
• This selection is done by D2 bits of TMOD for Timer 0 and D6 bit of
TMOD for Timer1
TCON SFR
• The clock pulses selected by D2 and D6 bits of TMOD is then
controlled by programmer setting and connected to the Timer
registers. The control is by three different means.

• First is the Timer Run control bits D4 and D6 of TCON register.


The timer will run only when Timer run control bits are set to 1.
TCON SFR
• The other controls for the timers are through the GATE control
bits D4 and D7 of TMOD and the External inputs for timer.
Setting GATE to 1 allows the timer to count only if the external
control input INT0 or INT1 is set to 1. Setting Gate to 0 will
disable the corresponding external timer control inputs INT0
and INT1.

• Setting Timer to mode 0 will overflow back to zero after 8192


counts. This will set the TF1 and TF0 bits for timer 1 and timer 0
respectively.
Mode 0 Operation of Timer 1 of
8051
Mode 1 – 16-bit Timer Mode
• In timer Mode 1 of 8051, each timer is operated as a 16-bit
timer. It functions just like mode 0 except that all 16 bits are
used.
• TL0/1 bits are incremented from 0 to 255. When TL0/1 is
incremented from 255, it resets to 0 and causes TH0/1 to be
incremented by 1. Since this is a full 16-bit timer, the timer may
contain -65536 distinct values.
• The control of gating and running the timer in mode 1 is similar
to that of mode 0
Mode 1 Operation of Timer 1 of
8051
Mode 2 – 8-bit Timer Auto Reload
Mode
• Only 4 of the 8 bits of the TCON SFR is defined. the other 4 bits
of the SFR don’t have anything to do with timers. They are
related with Interrupts and they will be discussed in the
chapter that addresses interrupts.

• Note that the individual bits of TCON register can be addressed


separately by their bit addresses. This allows the programmer
to run the timers using bit addressable instructions and check
the overflow independently.
Mode 2 – 8-bit Timer Auto Reload
Mode
• For example, let’s say TH0 holds the value FDh and TL0 holds
the value FEh. Then at the next counting pulse, TL0 will be
incremented to FFh. Then for the next pulse, the TL0 will
overflow and should have become 00.

• But, as it is reload mode, the TL0 will be loaded with TH0 i.e.,
FDh. The value of TH0 will never be changed. TH0/1 is set to a
known value and TL0/1 is the SFR that is constantly
incremented.
Mode 2 – 8-bit Timer Auto
Reload Mode
• The auto-reload mode is very commonly used for
establishing a baud rate for Serial Communications.

• The control of gating and running the timer in mode 2


is similar to that of mode 0
Mode 2 Operating of Timer 1 of
8051
Mode 3 – Split Timer Mode
• Mode "3" of 8051 timer is a split-timer mode and is applicable
only for Timer 0. When Timer 0 is placed in mode 3, it
essentially becomes two separate 8-bit timers. That is, Timer 0
is TL0 and Timer 1 is TH0.

• Both timers count from 0 to 255 and overflow back to 0.

• In mode 3, all the bits that are related to Real Timer 1 will
simply hold its count and will not run and the situation is
similar to keeping TR1=0.
Mode 3 – Split Timer Mode
• In Split Timer mode of Timer 0, the real Timer 1 (i.e. TH1
and TL1) can not be started or stopped since the bits that
do that are now linked to TH0. The real timer 1, in this
case, will be incremented every machine cycle no matter
what.

• When two separate timers in addition to a baud rate


generator is required in an application, then real Timer 1
can be used as a baud rate generator and TH0/TL0 can be
used as two separate timers in mode 3.
Mode 3 Operation of Timer 0 of
8051
Timer Control and Operation
• For timer operation (C/T = 0 in TMOD), the timer register
counts the divided-down clock. The timer register is
incremented once every (FOSC / 12) in standard mode. If the
clock frequency is 11,059,000KHz, then the counter will be
incremented at the rate of (11,059,000KHz/12) = 921,583 KHz.

• This means the counter will be incremented 921,583 times in a


second. Thus to have delay of say 0.1 seconds, then the
counter must be initialized to the count value of (0.1*921,583)
= 92158.
Timer Control and Operation
Following steps are the program steps to initialize and use a
timer in 8051
• Decide what mode the timer to be in.
• Initialize the TMOD SFR.
• Write the timer value to Timer register
• Start the timer running by setting the TR0/1 bit in TCON
register
• Check for TF0/1 bit or program to handle timer overflow
as interrupt and execute interrupt subroutine.
Steps in Timer Control
Write TMOD

Write TCON

Write timer register

Start timer

Program Required Operation

Continue
Timer Control and Operation

• To set the bit TR1 of TCON (D6 bit), any one of the following
two commands can be used -MOV TCON, #40h OR SETB TR1

• As, TR1 is a bit addressable location, SETB instruction is used


and this has the benefit of setting the TR1 bit of TCON without
changing the value of any of the other bits of the SFR.
Reading Value of 16-bit Timer
• There are two common ways of reading the value of a 16-bit
timer;
1. Read the actual value of the timer as a 16-bit number from
TH0/TL0 or TH1/TL1.
2. Detect when the timer has overflowed from the TF0/1 bits of
TCON. If TF0 is set, it means that timer 0 has overflowed; if
TF1 is set, it means that timer 1 has overflowed. This overflow
can act as an interrupt and can directly run an Interrupt
service routine, if enabled properly.
Using Timers and Counters

• Timers in 8051 can be programmed to count pulses from


external devices. For example, a sensor placed along a
conveyor belt can give one pulse for every object moving on
the conveyor.

• This pulse can be counted by the 8051 timer in counter mode.


The pulses from the sensor can be given as an external input to
a timer and programmed to count.
Using Timers and Counters
• The timer can be programmed to give an interrupt after a
predefined count value. For example, after counting 12 objects
in the conveyor or after counting 12 pulses in the timer, an
interrupt may be given to the 8051 system to give signal to
some other action like packing the 12 items
• It is important to note that the 8051 checks the P3.4 line each
instruction cycle (12 clock cycles). This means that if P3.4 is low,
goes high, and goes back low in 6 clock cycles it will not be
detected by the 8051.
• This also means the 8051 event counter is only capable of
counting events that occur at a maximum of 1/24th the rate of
the crystal frequency.
Using Timers and Counters
• That is to say, if the crystal frequency is 12 MHz, it can count a
maximum of 500,000 events per second (12.000 MHz * 1/24 =
500,000).

• If the event being counted occurs more than 500,000 times per
second, it will not be able accurately counted by the 8051.
Interrupt Sources and Interrupt
Vector Addresses
• 8051 basically has following five interrupt sources so
that any of the following events will make 8051 to
execute an interrupt service routine.
• Timer 0 Overflow.
• Timer 1 Overflow.
• Reception/Transmission of Serial Character.
• External hardware interrupt 0.
• External hardware interrupt 1.
Interrupt Sources and Interrupt
Vector Addresses
• Different interrupt sources have to be distinguished
and 8051 must execute different subroutines
depending –interrupt triggered. This is accomplished
by jumping or calling to a fixed address when
interrupt occurs.
• These addresses are called interrupt vector addresses
or interrupt handler addresses.
Interrupt Sources and Interrupt
Vector Addresses
Interrupt Flag Interrupt Vector Address

External 0 IE0 0003h

Timer 0 TF0 000Bh

External 1 IE1 0013h

Timer 1 TF1 001Bh

Serial RI/TI 0023h


Interrupt Sources and Interrupt
Vector Addresses
• Whenever Timer 0 overflows (i.e., the TF0 bit is set), the main
program will be temporarily suspended and control will jump
to 000BH.

• It is assumed that service routine at address 0003H handles the


situation of Timer 0 overflowing.
Enabling and Disabling Interrupts
• By default at power up, all interrupts are disabled. This means
that even if, for example, the TF0 bit is set, the 8051 will not
execute the interrupt. Programming must be done specifically
to enable interrupts.

• Interrupt Enable Special Function Register IE SFR at the address


A8h is used to enable and disable interrupts by modifying its
bits.

• The interrupts enabling can be handled individually by - bit


addresses for the individual bits of IE register.
Bit Patterns for the IE SFR (A8H)
Bit D7 D6 D5 D4 D3 D2 D1 D0
position

Bit AF AC AB AA A9 A8
Address

Name EA - - ES ET1 EX1 ET0 EX0


Explana
tion
Global
Enable Enable Enable Enable Enable
Interrupt Undefi Undefin
Serial Timer 1 External 1 Timer 0 External 0
Enable/ ned ed
Interrupt Interrupt Interrupt Interrupt Interrupt
Disable
Bit Patterns for the IE SFR (A8H)
• Each of the 8051’s interrupts has its own bit in the IE SFR. A
particular interrupt can be enabled by -corresponding bit. For
example, to enable Timer 1 Interrupt, the one of the following
instructions can be executed.

• MOV IE, #08h OR SETB ET1


Bit Patterns for the IE SFR (A8H)
• However, before Timer 1 Interrupt (or any other interrupt) is
truly enabled, bit 7 of IE SFR must also be set. Bit 7, the Global
Interrupt Enable/Disable, enables or disables all interrupts
simultaneously.

• That is, if bit 7 is cleared then no interrupts will occur, even if


all the other bits of IE are set. Setting bit 7 will enable all the
interrupts -selected by setting other bits in IE.
Interrupt Priorities and Polling
Sequence
• The 8051 automatically evaluates whether an interrupt occurs
after every instruction. When checking for interrupt conditions,
it checks them in the following order:
• External 0 Interrupt
• Timer 0 Interrupt
• External 1 Interrupt
• Timer 1 Interrupt
• Serial Interrupt
Interrupt Priorities and Polling
Sequence
• The above list -gives the interrupt priority.
• So, whenever the External 0 interrupt and Timer 1 interrupt
occurs at the same instant, then 8051 microcontroller executes
the interrupt service routine corresponding to External 0
interrupt first.
• Then 8051 microcontroller will return to the main program,
execute one instruction and then execute the interrupt service
routine corresponding to Timer 1 Interrupt.
Interrupt Priorities and Polling
Sequence
• If a Serial Interrupt occurs at the exact same instant that an External 0
Interrupt occurs, the External 0 Interrupt will be executed first and the
Serial Interrupt will be executed once the External 0 Interrupt has
completed.
• The 8051 offers two levels of interrupt priority: high and low. By using
interrupt priorities, the above interrupts can be divided into two
separate interrupt priorities. So, the five interrupts can be again
prioritized.
• Interrupt priorities are controlled by the IP SFR (B8h). For example, if
the Serial Interrupt is much more important than the Timer 0 interrupt,
then the Interrupt Priority register IP SFR at the address B8h can be
properly programmed to set the priority.
Interrupt Priorities and Polling
Sequence
• This is done by assigning a high priority to the Serial Interrupt
and a low priority to the Timer 0 Interrupt. By setting the D4 bit
to 1, the serial interrupt will be set to higher priority and
making D1 bit to 0, the Timer 0 interrupt will be set to lower
priority.
• Note that the priority can be set individually by using the bit
addresses of the IP register. For example, the timer 0 interrupt
priority can be made high by setting the D1 bit of IP SFR. So,
the following instructions can be used for the same.
• SETB PT0 (or) SETB B9H (or) MOV IP, #82H
Bit Patterns for the IP SFR

Bit position D7 D6 D5 D4 D3 D2 D1 D0

Bit Address
BC BB BA B9 B8
Name - - PS PT1 PX1 PT0 PX0
-
Explanation

Serial Timer 1 External 1 Timer 0 External 0


Undef Undefin
Undefined Interrupt Interrupt Interrupt Interrupt Interrupt
ined ed
Priority Priority Priority Priority Priority
Interrupt Priorities and Polling
Sequence
When considering interrupt priorities, the following rules apply:
• Nothing can interrupt a high-priority interrupt--not even
another high priority interrupt.
• A high-priority interrupt may interrupt a low-priority interrupt.
• A low-priority interrupt may only occur if no other interrupt is
already executing.
• If two interrupts occur at the same time, the interrupt with
higher priority will execute first. If both interrupts are of the
same priority the interrupt which is serviced first by polling
sequence will be executed first.
Interrupt Priorities and Polling
Sequence
• The complete structure of the 8051 interrupts can be well
understood -figure 11.16. The five interrupt sources are passed
first - IE register, which decides the enabling and disabling of
interrupts. The global interrupt enable -shown -figure.

• The IP register - set two priority levels among the available


interrupts. This is shown in the figure as high priority and low
priority blocks. The bits IT0 and IT1 can be set by TCON special
function register and this is used to select whether the
hardware interrupt is level triggered or edge triggered.
Structure of 8051 Interrupts
IE IP High
register register priority
1 interrupt
INT0 IT0 IE0
0 Low
priority
interrupt
TF0

1
IT1 IE1
INT1 Interrupt
0 polling
sequence
TF1

RI

TI

Interrupt
enables

Global
Enable Interrupt
enabled
Timing of Interrupts
• 8051 micro-controller samples the hardware signal level on its pins once in
every machine cycle. A machine cycle is the time taken by the controller to
access one memory location or I/O device.
• As 8051 takes 12 clock cycles to complete one machine cycle, the interrupt
signal applied at the pins of 8051 must be available for at least 12 clock
periods.
• External interrupts are applied at the pins INT0 and INT1. The sensing of
voltage level applied to this pin can also programmed in 8051. The interrupts
can be either level triggered or edge triggered as set by the IT0 and IT1 bits of
the SFR TCON
• A ‘0’ on these bit positions will make both the hardware interrupts to be level
triggered. Level triggered means a low level voltage on the interrupt pins will
activate the interrupts.
Bit Patterns for the TCON SFR
Bit position D7 D6 D5 D4 D3 D2 D1 D0

Bit Address 8F 8E 8D 8C 8B 8A 89 88
Name TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Interrupt 0
Interrupt 1 type
Timer 0
Timer 1 Extern type control. control. Set
run
run al Set to 1 by External to 1 by
Timer control
Timer 1 control Interru software for Interrupt software
0 bit. Set
Explanation Overflow bit. Set to pt 1 edge 0 edge for edge
Overflo to 1 by
flag 1 by edge triggering detect triggering
w flag softwar
software detect and cleared bit and
e to
to run. bit for level cleared for
run.
triggering level
triggering
Bit Address 8F 8E 8D 8C 8B 8A 89 88
Interrupt Priorities and Polling
Sequence
• A ‘1’ on the IT0 and IT1 bits of the SFR TCON will program the
hardware interrupts as edge triggered. Edge triggering means
the change of voltage from high state to low state will activate
the interrupt.
• When an interrupt is triggered, the micro controller takes the
following actions automatically:
• The current Program Counter is saved on the stack, low-byte
first.
• Interrupts of the same and lower priority are blocked.
• In the case of Timer and External interrupts, the corresponding
interrupt flag is cleared.
Interrupt Priorities and Polling
Sequence
• Program execution transfers to the corresponding interrupt
handler vector address.
• The Interrupt Handler Routine executes.
• An interrupt ends when your program executes the RETI
(Return from Interrupt) instruction. When the RETI instruction
is executed the micro controller takes the following actions:
• Two bytes are popped off the stack into the Program Counter
to restore normal program execution.
• Interrupt status is restored to its pre-interrupt status.
Interrupt Priorities and Polling Sequence
• The internal architecture of 8051 is such that the external
hardware interrupts will be cleared automatically when the
interrupt service routine is executed only if is programmed to be
edge or transition triggered.

• If the interrupts are level triggered, then the programmer will


have to reset the interrupt enable corresponding to this interrupt
using IP SFR.

• If the interrupt being handled is a Timer or External interrupt, the


micro controller automatically clears the interrupt flag before
passing control to interrupt handler routine. This means it is not
necessary to clear the bit in the program.
8051 Serial Ports
• One of the 8051’s many powerful features is its integrated Universal
Asynchronous Receiver Transmitter (UART), otherwise known as a serial
port. With integrated serial port of 8051, data can be transmitted and
received easily by reading and writing the data to the serial port registers.
The features of the 8051 serial ports are
• Full duplex operation.
• Receive Buffered.
• Access using single double buffered Register SBUF.
• Four different modes of operation.
• Option to use fixed baud rate or programmable baud rate.
8051 Serial Ports
• Full Duplex serial port means that it can transmit and receive
data simultaneously. It is also receive-buffered, meaning it can
commence reception of a second byte before a previously
received byte has been read from the SBUF register.

• However, if the first byte still hasn’t been read by the time
reception of the second byte is complete, one of the bytes will
be lost. The serial port receive and transmit registers are both
accessed at Special Function Register SBUF.
8051 Serial Ports
• Data to be transmitted are written to the register SBUF and
the data received by the serial port are read from the register
SBUF. Physically reading and writing SBUF actually accesses
two separate registers.

• This technique of having same address for two different


registers is called double buffering.
SERIAL PORT CONTROL SFRS
• The serial port of 8051 is controlled by two registers in SFR area of
8051 as shown in Table
• The two registers are Serial Port control registers; SCON and serial
port buffer register SBUF.

SFR Name Description SFR Address


Serial port control
SCON 98h
register
Serial port buffer
SBUF 99h
register
SERIAL PORT CONTROL SFRS
• In addition to the above two registers, the MSB of PCON register
named as SMOD bit is used to double the baud rate of serial
transmission and reception.
• If SMOD bit is set to 1, then the baud rate is doubled.
• The individual bits of SCON have the functions as shown in Table .
As the SCON register has many individual status bits, the
individual bits of this register are bit addressable. The bit address
is also given in Table .
• The programmer can use these bit addresses to check the status
of the serial port and set the mode individually.
Bit patterns for SCON (98h) SFR

Bit Name Bit Address Explanation of Function


D7 SM0 9Fh
Serial port mode select bits
D6 SM1 9Eh
D5 SM2 9Dh Multiprocessor Communications Enable bit
Receiver Enable. This bit must be set in order to receive
D4 REN 9Ch
characters.
D3 TB8 9Bh Transmit bit 8. The 9th bit to transmit in mode 2 and 3.
D2 RB8 9Ah Receive bit 8. The 9th bit received in mode 2 and 3.
Transmit Interrupt Flag. Set when a byte has been
D1 TI 99h
completely transmitted.
Receive Interrupt Flag. Set when a byte has been completely
D0 RI 98h
received.
Bit Pattern - Description
• D7 and D6 bits of the SCON register define the operation
modes of the serial port and the basic operating modes
are given in Table.

• The SM0 and SM1 bits can select any one of the four
operating modes described in the next section.
Definition of Bits SM0 and SM1 in
SCON SFR
Bit Pattern - Description
• The next bit, SM2, is a flag used for enabling "Multiprocessor
communication" in modes 2 and 3. If SM2 is set to 1 in modes 2
and 3, the “Receive Interrupt” RI flag will not be activated if the
received 9th data bit is 0. If SM2 is set in Mode1, then “Receive
Interrupt” RI flag will not be activated if valid stop bit is not
received.

• This can be useful in certain advanced serial applications. It can


be now assumed that SM2 bit has to be cleared so that RI flag
will be set when any character is received.
Bit Pattern - Description
• The next bit, REN, is "Receiver Enable." This bit is set in order to
receive the characters from the receive data line of the serial
port.

• The TB8 bit is used in modes 2 and 3. In modes 2 and 3, a total of


nine data bits are transmitted. The first 8 bits are the 8 bits of the
data to be transmitted, and the ninth bit is taken from TB8. The
RB8 also operates in modes 2 and 3 on the reception side.
Bit Pattern - Description
• When a byte is received in modes 2 or 3, a total of nine bits
are received. In this case, the first eight bits received are the
data of the serial byte received and the value of the ninth bit
received will be placed in RB8.

• TI means "Transmit Interrupt." When a program writes a data


to the serial port buffer SBUF, then the serial port will start
shifting this data in the serial transmit line bit by bit at the
predefined clock speed or baud rate. 8051 will give TI signal to
the programmer after sending the data completely.
Bit Pattern - Description
• Upon sensing the TI bit set to 1, the programmer can then write
the next data for transmission. When the TI bit is set, the
programmer may assume that the serial port is "free" and ready
to send the next byte.

• Finally, the RI bit means "Receive Interrupt." Whenever a data is


received on the receive data line of the serial port, this serial data
will be shifted in to a buffer and then stored in the SBUF register.

• Setting of RI bit indicates that a byte has been received. Upon


sensing the RI bit set to 1, the programmer may read the data
from the SBUF.
OPERATING MODES
• Bits SM0 and SM1 are used to set the serial mode to a value
between 0 and 3.

• Selecting the Serial Mode selects the mode of operation (8-bit/9-


bit, UART or Shift Register) and also determines how the baud
rate will be calculated.

• In modes 0 and 2 the baud rate is fixed based on the oscillator’s


frequency. In modes 1 and 3 the baud rate is variable based on
Timer 1 overflows.
Block Diagram of the serial port of
8051
SBUF
• SBUF is physically two registers with the same address.
• When data to be transmitted is written to the SBUF register, then
it will be shifted bit by bit into the TXD line of 8051. The port 3 pin
3.1 acts as the TXD line. The shifting is done by the transmit clock
which determines the baud rate.
• Similarly, when the data bits are received on the RXD line (Pin 3.0
of port 3), the bits are shifted serially into the shift register
according to the Receive clock.
• After the reception is complete, the data received will be placed
on SBUF from where it can be read by the programmer through
the internal bus.
Reception / Transmission
• Mode 0: In this mode serial data is entering and exiting through RxD pin. So, in
mode 0, Full duplex is not possible – meaning that both transmission and
reception cannot take place simultaneously. TxD pin outputs the shift clock. 8
bits are transmitted/received (LSB first). The baud rate is fixed at 1/12 the
oscillator frequency. Transmission is started by writing a data byte to the SBUF
register and once the transmission is complete, TI flag is set.

• The reception is started by enabling REN in SCON register. Once the data
reception is complete, the RI flag is set.

• The baud rate in Mode 0 is fixed at one twelfth of the clock frequency. Baud
rate= (Clock frequency/12)
Signal Transmission / Reception
pattern
Reception / Transmission

• Mode 1: In this mode, 10 bits are transmitted through TxD and


simultaneously 10 bits can be received through RxD. The 10
bits are made up of a start bit (0), 8 data bits (LSB first), and a
stop bit (1). On completion of reception, the stop bit goes into
RB8 in Special Function Register SCON. The baud rate is
variable and is set by the Timer 1 overflow rate. The baud rate
for mode 1 is fixed at the following rate.
Reception / Transmission
• Baud rate= (Timer 1 overflow rate /16) if SMOD bit in PCON
SFR is set to 1.

• Baud rate= (Timer 1 overflow rate /32) if SMOD bit in PCON


SFR is set to 0.

• Note that PCON is a special Function Register described in


chapter 25. The MSB of PCON register can be set or reset by
the programmer. The baud rate can be doubled by setting
the MSB of PCON.
Reception / Transmission
• In order to generate the baud rate clock from timer 1, Timer 1
can be configured to act as timer in auto reload mode with the
timer 1 interrupt disabled.

• As in mode 0, the transmission is initiated by writing a data to


SBUF register. Reception is initiated by a 1 to 0 transition that is
the start bit received and also when REN of SCON SFR is 1.
Reception / Transmission
• Mode 2: In this mode, 11 bits are transmitted through TxD or received
through RxD. The 11 bits are made up of one start bit (always 0), 8 data bits
(LSB first), a programmable 9th data bit, and a stop bit (always 1). The 9th
data bit transmitted is same as TB8 bit in SCON special function register. It
can be assigned the value of 0 or 1 by the programmer. Or, for example, the
parity bit (P, in the PSW) could be moved into TB8.
• On reception, the 9th data bit goes into RB8 in Special Function Register
SCON, while the stop bit is ignored. The baud rate is programmable to either
1/32 or 1/64 of the oscillator clock frequency.
• Baud rate= (Clock frequency /32) if SMOD bit in PCON SFR is set to 1.
• Baud rate= (Clock frequency /64) if SMOD bit in PCON SFR is set to 0.
Reception / Transmission
• Mode 3: In this mode, 11 bits are transmitted through TxD and
simultaneously 11 bits are received through RxD. The 11bits are
made up of a start bit (0), 8 data bits (LSB first), a programmable
9th data bit, and a stop bit (1). In fact, Mode 3 is the same as
Mode 2 in all respects except baud rate. The baud rate in Mode 3
is variable.
• The baud rate for mode 3 is fixed at the following rate similar to
mode1.
• Baud rate= (Timer 1 overflow rate /16) if SMOD bit in PCON SFR is
set to 1.
• Baud rate= (Timer 1 overflow rate /32) if SMOD bit in PCON SFR is
set to 0.
Reception / Transmission
• In all four modes, transmission is initiated by any
instruction that uses SBUF as a destination register.
Reception is initiated in Mode 0 by the condition RI = 0
and REN = 1. Reception is initiated in the other modes
by the incoming start bit when REN = 1.
• The flow chart 11.20 shows the steps in programming
the serial port of 8051. These steps are detailed in the
following sections and also in the example programs.
Programming the Serial Port
Initializing Serial Port
• Once the Serial Port Mode has been selected, then the programmer
must configure the serial port’s baud rate. Only serial port modes 1
and 3, the baud rates are programmable.

• The Baud Rate is determined based on the oscillator’s frequency


when in mode 0 and 2. In mode 0, the baud rate is always the
oscillator frequency divided by 12. This means if the crystal is 11.059
MHz, mode 0 baud rate will always be 921,583 baud.

• In mode 2 the baud rate is always the oscillator frequency divided by


64, so an 11.059 MHz crystal speed will yield a baud rate of 172,797.
Initializing Serial Port
• In modes 1 and 3, the baud rate is determined by how frequently timer 1
overflows. The most common method is to put timer 1 in 8-bit auto-reload mode
(timer mode 2) and set a reload value (TH1) that causes Timer 1 to overflow at a
frequency appropriate to generate a baud rate.
• To determine the value that must be placed in TH1 to generate a given baud
rate, the following equation is used.
• TH1 = 256 - ((Clock frequency / 384) / Baud) if SMOD in PCON SFR is 0.
• TH1 = 256 - ((Clock frequency / 192) / Baud) if SMOD in PCON SFR is 1.
• The following table gives the commonly used baud rates and the corresponding
reload for the timer in mode 2 assuming the clock frequency of 11.059 MHz and
SMOD is reset.
Commonly used baud rates

Baud Rate Timer value TH1

300 A0h

1200 D0h

2400 FAh

9600 FDh
Baud Rate
Following set of instructions will set the timer for the baud
rate of 9600.
– MOV TMOD, #00100000B ;timer/counter 1 set for mode 2, 8-
bit TIMER
– ;operation
– MOV TH1, #0FDh ; timer/counter 1 is timed
for 9600 baud
– SETB TR1 ; timer/counter 1 is
enabled for free run
• For initializing the serial port for mode 3 operation, the
following instruction can be used.
– MOV SCON, #11010000B
Transmitting and Receiving Data
Using Serial Port
• Once the Serial Port has been properly configured as explained
above, the serial port is ready to be used to send data and
receive data.

• To write a byte to the serial port one must simply write the
value to be transmitted to the SBUF (99h) SFR. For example, to
send the letter "A" to the serial port, the following instruction
can be written.
MOV SBUF, #’A’
Transmitting and Receiving Data
Using Serial Port
• Upon execution of the above instruction the 8051 will begin
transmitting the character via the serial port. Once the transmission is
complete, the serial port transmit interrupt flag TI is set. Since the 8051
does not have a serial output buffer, a character can not be written to
SBUF before the previous written character is completely transmitted.
This can be accomplished by checking the TI flag.

• Reading data received by the serial port is equally easy. To read a byte
from the serial port one just needs to read the value stored in the SBUF
(99h) SFR after the 8051 has automatically set the RI flag in SCON.
8051 Interface Examples
Interfacing 8255 to 8051
• When the 8051 is connected to external memory, port 0 (P0) is used for the
lower-order address and data bus and port 2 (P2) is used for the higher-order
address bus.
• Since the port 3 pins have an alternative function, the net result is that only
P1 is left for input and output operation.
• One way to expand the number of I/O ports is to connect the 8255
programmable peripheral interface with the 8051.
• The interfacing of the 8255 with the 8051 is done assuming the 8255 as a
memory location, because the 8051 supports only memory-mapped I/O.
• For accessing the external memory in the 8051, the MOVX instruction is
used.
• The lower-order address bus and the data bus are multiplexed and are
available in the port 0 pins.
• This is de-multiplexed using a latch and the ALE signal.
Learning Outcomes

• After studying this chapter, you will be able to understand


the following:
• Interfacing of the programmable interface IC 8255 and
switches and LEDs with the 8051
• Interfacing of analog-to-digital and digital-to-analog
converters
• Interfacing of LCD interface, Matrix keyboard and motors
• 8051 application examples
Interfacing 8255 with 8051
Interfacing 8255 to 8051
• The first step in the general interfacing method is to decide the
addresses for the port.
• The 8051 uses 16-bit addresses and the most significant address
lines are used for decoding and selecting the device.
• Here, the higher-order address bus from port 2 is given to a decoder
logic circuit.
• From the decoder, the 8255 chip select signal is generated.
• The 8255 needs four addresses for interfacing with any processor—
three for the ports A, B, and C and one for the control register.
• The lower-order address lines A0 and A1 are connected to select
one of these four registers. The read and write control signals are
available from the port 3 pins P3.7 and P3.6.
Interfacing of Push button switches & LEDs
• The simplest input and output device that can be interfaced to any
microprocessor is the push button switches and Light Emitting Diodes
(LEDs).

• The example here is considering 4 push button switches interfaced to one


port of 8051 and four LEDs connected to another port.

• The switches are connected in such a way that when it is open, it connects
a logic 0 i.e. 0Volts to the port and when it is closed, it connects logic 1 i.e.
5Volts to the port pins.
Interfacing of switches to port pins
Interfacing of Push button switches & LEDs

• The circuit connections are shown in Figure are such that the port is not
damaged and also the port is not sourcing over current. This ensures safe
operation of the ports and switches.

• An LED gives out light illuminating when it is forward biased and has enough
current flowing through it. LED indicators are easy to interface with the
microcontrollers as output device.

• LEDs can be driven with a minimum current of about 10mA. A driver IC can be
used for illuminating LEDs.
Interfacing LED with driver to port pins
• Figure shows a method of using an inverter driver for connecting ports to LEDs.
Description

• When logic 1 is given out on the port pin, it will be


inverted by the inverter and will connect ground
(logic 0) to the cathode of LED. This will forward
bias the LED and light will be given by LED.
Interfacing of 4 switches and 4 LEDs
• Figure shows the interfacing of 4 Switches to port 3 pins and 4 LEDs to Port1 pins of 8051.
• The inverter driver IC 74240 is used to drive the LEDs. Even though only 4 LEDs are
shown connected in Figure 12.4, we can connect 8 LEDs as 74240 has eight inverter
drivers.
• The program to display the contents of 4 switches on to the LEDs is as followed.
Description

– Start: MOV A, P3
– MOV P1, A

• When logic 1 is sensed on port 3 line, the


same data is given as output on port 1 lines.
When logic 0 is sensed, the same is given on
port 1lines. The LEDs will not be illuminated
now as the LEDs are not forward biased.
Interfacing of Seven Segment Displays
• Seven segment displays consist of seven LED segments. The seven segments are
arranged in the form as shown in figure and the display of various digits is also
shown in the same figure.
• Seven segment displays are available in a single dual line in package.
• There are each pin for each segment and these pins are named from a to f and
another LED is available for decimal point.
• In addition to these eight pins, the seven segment displays have one more pin
for power supply.
• Seven segment displays come in two types either in common anode or common
cathode.
Interfacing of Seven Segment Displays

• In common anode display, the anode of all segment LEDs are tied
together and taken out.
• So, to illuminate a segment, the common anode is connected to
the supply and then the segment input i.e. a to f is connected to a
low level logic 0.
• In common cathode display, the cathodes of all the LEDs are
connected together and taken out.
• So, to illuminate a segment, the corresponding segment input is
connected to the high level voltage or logic 1 and the common
cathode is connected to the ground. This will forward bias the LEDs
and illuminate them.
Seven Segment Display
Interfacing Description
• Interfacing of Seven segment displays to 8051 microcontroller needs a driver
as shown in Figure. Here 74240 TTL inverter driver IC is used for driving the
seven segment displays.

• Also the seven segment display is assumed to be common anode type. The
common anode is connected to the supply +5V.

• The interfacing diagram for displaying the BCD code obtained from key
connected to port3 and displaying the same in seven segment display
connected to port 1
Interfacing Switches and seven segment
display to 8051
Interfacing Description
• The segments can be illuminated
if the segments pins are
connected to the low level of
supply or to ground.
• This is done by connecting the
segment inputs of logic 0 through
74240. The 74240 IC will invert the
inputs applied to it. So, if we want
to illuminate a particular segment,
the corresponding output for that
segment has to be logic 1.
• The data output for displaying
decimal digits 0 to 9
8051 Programming in C
Number System
Exercise - I

Number
system 10 16 32 127 255 512 1023
Decimal
Binary 1010 ? ? ? ? ? ?
Base 2
Octal 12 ? ? ? ? ? ?
(Base 8)
Hexadeci A ? ? ? ? ? ?
mal
(Base 16)
Answer

Number
system 10 16 32 127 255 512 1023
Decimal
Binary 1010 10000 100000 1111111 11111111 1000000000 1111111111
Base 2
Octal 12 20 40 177 377 1000 1777
(Base 8)
Hexadecimal A 10 20 7F FF 200 3FF
(Base 16)
sbit, sfr, and bit

#include<reg51.h>
sbit inbit = P1^0;
//sbit datatype and inbit variable
sbit outbit = P2^7;
bit membit =27H;
//bit addresable memory for store the single bit
void main(void){
while(1){
membit= inbit;
// read the single bit data from port
outbit = membit;
// out the single bit data to port
}
}
sbit, sfr, and bit.
#include<reg51.h>
sbit sw = P1^7
void main(void)
{ 1
while(1){
if(sw == 1)
{
P0 = 0x55; }
else
{P2 = 0XAA;
}}}
/* Switch variable corresponds to PORT 1 Pin7. It is
used as an input. We put 0x55 on P0 if the P1.7 status
is 1 else we put 0xAA on P2*/
Producing delay using loops
#include <reg51.h>
void main(void)
{
unsigned int x;
for (;;) //repeat forever
{
p1=0x55;
for (x=0;x<40000;x++); //delay size unknown
p1=0xAA;
for (x=0;x<40000;x++);
}
}
Programs on logic operations
Bitwise Operations

There are two bit-wise shift operators in C:


shift right ( »), and shift left («)
Logical operations example code
#include <reg51.h>
void main(void)
{
P0=0x35 & 0x0F; //ANDing
P1=0x04 | 0x68; //ORing
P2=0x54 ^ 0x78; //XORing
P0=~0x55; //inverting
P1=0x9A >> 3; //shifting right 3 0001 1101
P2=0x77 >> 4; //shifting right 4
P0=0x6 << 4; //shifting left 4
}
Write an 8051 C program to get bit P1.0 and
send it to P2.7 after inverting it.
#include <reg51.h>
sbit inbit=P1^0;
sbit outbit=P2^7;
bit membit;
void main(void)
{
while (1)
{
membit=inbit; //get a bit from P1.0
outbit=~membit; //invert it and send it to P2.7
}
• }
Embedded C Program for generating the LED output sequence as shown below:
00000001
00000010
00000100.....
.... And so on up to 10000000.
1.#include<reg51.h>
2.void main() {
3.unsigned int k;
4.unsigned char l,b;
5.while(1) {
6.P0=0x01;
7.b=P0;
8.for(l=0;l<3000;l++);
9.for(k=0;k<8;k++) {
10.b=b<<1;
11.P0=b;
12.} }}
• }
Data conversion
BCD 0 0000

1 0001
• BCD is a form of binary encoding method
• Each digit in a decimal number is represented in the form of binary 2 0010
bits.
• Encoding can be done in either 4-bit or 8-bit (usually 4-bit is preferred). 3 0011
• Generally used in digital displays, calculators do all their calculations in
BCD 4 0100
• RTC provides the time of day
5 0101
• Saves storage space compared to binary representations
• Ease of use in coding, fewer computations and less computational 6 0110
errors.
7 0111

8 1000

9 1001
ASCII
• ASCII code is an alphanumeric code used for data communication in
digital computers.
• it uses eight bits to represent a letter or a punctuation mark.
• keyboard, printers, and monitors all use ASCII
• On ASCII keyboards, when press the key “0″ - 30H (011 0000) is
forward to CPU, Similarly, 31H (011 0001) is provided for the key “1″
Data conversion
Decimal number into BCD
Packed BCD to ASCII conversion
ASCII to packed BCD conversion
Binary to decimal and ASCII conversion in C
Checksum byte in ROM
Convert 29 into ASCII character 32 and 39 for
display in LCD
#include <reg51.h>
void main(void)
{
unsigned char x,y,z;
unsigned char mybyte=0x29;
x=mybyte&0x0F;  X=09
P1=x|0x30;  P=39
y=mybyte&0xF0;  X=20
y=y>>4;  Y=02 shift right
P1=y|0x30;  P1 = 32
}
write a C program to convert 8 bit BCD number
(29) into ASCII Code
#include <reg51.h> unsigned char x,y,z;
void main() { unsigned char mybyte=0x29;
unsigned char bcdNumber = 0x29; // 8-bit BCD number
x=mybyte&0x0F;  X=09
P1=x|0x30;  P=39
unsigned char tensDigit, onesDigit;
y=mybyte&0xF0;  X=20
// Extract tens digit y=y>>4;  Y=02 shift right
tensDigit = (bcdNumber >> 4) & 0x0F; //02 P1=y|0x30;  P1 = 32
// Extract ones digit
onesDigit = bcdNumber & 0x0F; //09
// Convert BCD digits to their ASCII representation
tensDigit += '0’; //32
onesDigit += '0’; //39
// Output the ASCII representation on Port 1
P1 = (tensDigit << 4) | onesDigit; //outputs 39
// Infinite loop
while(1);
}
Write an 8051 C program to convert ASCII digits of ‘4’ and ‘7’ to
packed BCD and display them on P1.
#include <reg51.h>

void main() {
unsigned char bcd4, bcd7;

// Convert ASCII digits '4' and '7' to BCD


bcd4 = '4' - '0'; // Convert ASCII '4' to BCD
bcd7 = '7' - '0'; // Convert ASCII '7' to BCD

// Pack the BCD digits


unsigned char packedBCD = (bcd4 << 4) | bcd7;

// Output packed BCD on P1


P1 = packedBCD;

// Infinite loop
while(1);
}
Write an 8051 C program to convert ASCII digits of ‘4’ and ‘7’ to
packed BCD and display them on P1.

#include <reg51.h>
void main(void)
{
unsigned char bcdbyte;
unsigned char w=‘4’;  34
unsigned char z=‘7’;  37
w=w&0x0F;  04
w=w<<4; 40
z=z&0x0F;  07
bcdbyte=w|z;  47
P1=bcdbyte;
}
Write an 8051 C program to convert 11111101 (FD hex) to
decimal and display the digits on P0, P1 and P2.
#include <reg51.h>
void main() {
unsigned char binaryNumber = 0xFD; // Binary number 11111101
unsigned char decimalNumber = 0;
unsigned char digit;
// Convert binary number to decimal
decimalNumber = 0;
for(int i = 0; i < 8; i++) {
digit = (binaryNumber >> i) & 0x01;
decimalNumber += digit << i;
}
// Display decimal digits on P0, P1, and P2
P0 = decimalNumber % 10; // Least significant digit on P0
P1 = (decimalNumber / 10) % 10; // Tens digit on P1
P2 = (decimalNumber / 100) % 10; // Hundreds digit on P2
// Infinite loop
while(1);
}
Write an 8051 C program to convert hexadecimal
value FF into decimal, BCD and ASCII format
Write an 8051 C program to calculate the checksum byte for
the data 25H, 62H, 3FH, and 52H.
Steps to calculate Checksum byte in ROM are:
1. Add the bytes together and drop carries.
2. Take the 2’s complement (invert and then add 1) of the total sum. This is
the Checksum byte, which becomes the last byte of the series.
Data serialization with I/O ports.
• Serializing data is a way of sending a byte of data one bit at a time
through a single pin of microcontroller.
• There are two ways to transfer a byte of data serially:
• Serializing data and transfer data the one bit a time through bit
wise data transfer method
• Using the serial port
Write A C Program To Send Out The Value 44H Serially
One Bit At A Time Via P1.0. The LSB Should Go Out First.
• #include <reg51.h>
• sbit P1b0 = P1^0;
• sbit regALSB = ACC^0;
• void main(void) {
• unsigned char conbyte = 0x44;
• unsigned char x;
• ACC = conbyte;
• for (x=0; x<8; x++) {
• P1b0 = regALSB;
• ACC = ACC >> 1; }
• }
Program 1---16 bit timer in mode1

Assume that XTAL = 11.0592 MHz, write a C program continuously gets a single bit
of data from PI. 7 and sends it to P1.0, Simultaneously generate a square wave of 2 kHz
frequency on pin P1.5. Crystal frequency is 11.0592MHz.

(a) T = 1 / f = 1 / 2 kHz = 500 us the period of square wave.

(b) 1 / 2 of it for the high and low portion of the pulse is 250 us.

(c) 250 us / 1.085 us = 230 and 65536 – 230 = 65306 which in hex FF1AH.

(d) TL = 1A and TH = FF, all in hex.

#include <reg51.h>
sbit SW =P1^7;
sbit IND =P1^0;
sbit WAVE =P1^5;

void timer0(void) interrupt 1


{
WAVE=~WAVE; //toggle pin
}
void main()
{

SW=1; //make switch input


TMOD=0x01;
TL0=0xFF;
TH0=0x1A; //for delay
IE=0x82; //enable interrupt for timer 0
TR0=1;

while (1)
{
IND=SW; //send switch to LED
}
}

Program 2—8 bit autoreload--

Write a C program that continuously gets a single bit of data from PI. 7 and sends it to P1.0,
while simultaneously creating a square wave of 200us (as period) on pin P1.5. Use timer 0 in
mode 2 to create the square wave. Assume that XTAL = 11.0592 MHz.

#include <reg51.h>

sbit SW =P1^7;

sbit IND =P1^0;

sbit WAVE =P1^5;

void timer0(void) interrupt 1

WAVE=~WAVE; //toggle pin

void main()

SW=1; //make switch input

TMOD=0x02;

TH0=0xA4; //TH0=-92

IE=0x82; //enable interrupt for timer 0

TR0=1;

while (1)

IND=SW; //send switch to LED


}

Program 3

A switch is connected to pin P3.2. When switch is pressed the corresponding line goes low Display 0A at
port0. Write a C program to blink alternate LEDS connected to Port 1 Simultaneously.

#include <reg51.h>

sbit SW =P3^2;

unsigned int i;

void extint0() interrupt 0

P0=0x0A;

//void delay_ms(unsigned int j);

void main()

//unsigned int i;

SW=1;

IE=0x81;

while(1)

P1=0x00;

for(i=250;i>0;i--)

{}
P1=0xAA;

for(i=250;i>0;i--)

{}

Program 4(timer 0 interrupt and external interrupt1)

Write a C program using interrupts to do the following:

(a) Generate a 10 KHz frequency on P2.1 using T0 8-bit auto-reload

(b) Assume that the clock pulse is connected to external interrupt1 EX1. Count the pulses and
display it on P0. Assume that XTAL = 11.0592 MHz. Set the baud rate at 9600.

#include <reg51.h>

sbit WAVE =P2^1;

unsigned char cnt;

void timer0() interrupt 1

WAVE=~WAVE; //toggle pin

//void timer1() interrupt 3

void extint1() interrupt 2

cnt++; //increment counter

P0=cnt; //display value on pins


}

void main()

cnt=0; //set counter to 0

TMOD=0x02;

TH0=0x46; //10 KHz

IE=0x86; //enable interrupts

TR0=1; //start timer 0

while (1); //wait until interrupted

Changed priority example for above program

#include <reg51.h>

// Define global variables

sbit WAVE =P2^1;

unsigned char cnt;

// Timer 0 ISR for generating a 10 KHz frequency on P2.1

void timer0_ISR() interrupt 1

WAVE=~WAVE;

// External Interrupt 0 ISR for counting pulses and displaying on P0

void extint0_ISR() interrupt 0


{

// Increment the counter

cnt++;

// Display the value on P0

P0 = cnt;

void main()

// Initialize the counter

cnt = 0;

// Configure Timer 0 in mode 2 (8-bit auto-reload) for generating a 10 KHz frequency

TMOD |= 0x02;

TH0 = 0x46; // 10 KHz frequency at 11.0592 MHz crystal frequency

// Enable Timer 0 interrupt (high priority)

ET0 = 1;

PT0 = 1; // Set high priority for Timer 0 interrupt (or IP=0x02)

TR0 = 1;

// Configure External Interrupt 0 for counting pulses

IT0 = 1; // Edge-triggered

EX0 = 1; // Enable External Interrupt 0

// Enable interrupts globally

EA = 1;

// Main loop
while (1) {

Let’s program the external interrupt such that, when falling edge is detected on the INT0 pin then
the microcontroller will toggle the P1.0 pin.

Programming steps

1. Enable global interrupt i.e. EA = 1


2. Enable external interrupt i.e. EX0 = 1
3. Enable interrupt trigger mode i.e. whether interrupt is edge triggered or level triggered,
here we will use falling edge trigger interrupt, so make IT0 = 1.

/*

* 8051_External_Interrupt

*/

#include <reg51.h> /* Include x51 header file */

sbit LED = P1^0; /* set LED on port1 */

void Ext_int_Init()

EA = 1; /* Enable global interrupt */

EX0 = 1; /* Enable Ext. interrupt0 */

IT0 = 1; /* Select Ext. interrupt0 on falling edge */

}
void External0_ISR() interrupt 0

LED = ~LED; /* Toggle pin on falling edge on INT0 pin */

void main()

Ext_int_Init(); /* Call Ext. interrupt initialize */

while(1);

You might also like