UNIT-1-8051 Architecture
8051 Microcontroller Hardware
Addressing Modes
Instruction Set
External Memory
Counters and Timers - Modes of Operation
Serial Data Input/Output
Interrupt
8051 Microcontroller Hardware
• Features of microcontroller
• 8051 block diagram
• 8051 programming model
• Pin diagram description
• Registers(PC,DPTR,PSW,SFR)
• Internal memory(RAM,ROM)
Addressing Modes
• Immediate AM (Mov A,#xx)
• Register AM(Mov A,Rr)
• Direct AM(Mov p1,#0a5h)
• Indirect AM(Mov A,@R0)
• External data moves(MOVX,MOVC)
• Push and pop opcodes(SP)
Instruction Set
• Data Transfer Instructions
• Arithmetic
• Logical
• Control Instructions
• Branch Instructions
• Bit-Related Instructions
External Memory
Connecting External Memory
Counters and Timers
Counter Registers(TMOD,TCON,TL,TH)
Timer modes of operation(Mode 0,1,2,3)
Serial Data Input/Output
Serial registers
Serial data transmission modes( mode0,1,2,3)
Interrupt
Interrupt Registers
Timer interrupts serial port interrupts
External interrupts
General-purpose microprocessor
• CPU for Computers
• No RAM, ROM, I/O on CPU chip itself
• Example : Intel’s x86, Motorola’s 680x0
Many chips on mother’s board
Data Bus
CPU
General-
Serial
Purpose RAM ROM I/O Timer COM
Micro- Port
Port
processor
Address Bus
General-Purpose Microprocessor System
Microcontroller
• A smaller computer
• On-chip RAM, ROM, I/O ports...
• Example : Motorola’s 6811, Intel’s 8051, Zilog’s Z8 and PIC 16X
CPU RAM ROM
A single chip
Serial
I/O Timer COM
Port
Port
Microcontroller
Microprocessor vs. Microcontroller
Microprocessor Microcontroller
• CPU is stand-alone, RAM, • CPU, RAM, ROM, I/O and
ROM, I/O, and timer are timer are all on a single chip
separate • fixed amount of on-chip
• The designer can decide on ROM, RAM, I/O ports
the amount of ROM, RAM, and
I/O ports.
• for applications in which
• Expensive cost, power and space are
• General-purpose critical
• 1 • Single-purpose
Microprocessor vs. Microcontroller
Aspect Microprocessor Microcontroller
Purpose General-purpose tasks and Specific, dedicated tasks within an
complex computations. embedded system.
Used in computers,
Used in home appliances,
smartphones, and gaming
automotive systems, and toys.
consoles.
Integrat Integrates CPU, memory (RAM
ion Requires external components
and ROM), and I/O peripherals on
(RAM, ROM, I/O ports).
a single chip.
Acts as the central unit
Self-contained unit that can
needing support from other
operate independently.
chips.
Complex More complex, with higher Simpler, optimized for specific
ity processing power and
control tasks.
flexibility.
Suitable for running operating
Typically runs a single program
systems and multiple
repeatedly.
applications.
Power Generally consumes more power Designed to be power-efficient,
Consum due to higher computational suitable for battery-operated
ption demands. devices.
Requires cooling solutions like Often used in applications where
fans or heat sinks. low power consumption is critical.
Cost More expensive due to complexity
Generally cheaper as it integrates
and need for additional
multiple functions on one chip.
components.
Cost varies based on processing Cost-effective solution for specific
power and features. control tasks.
Applica Personal computers, laptops, Home appliances (washing
tions servers. machines, microwaves).
Automotive control systems (engine
Smartphones, tablets.
control units, airbag systems).
High-performance gaming Consumer electronics (remote
consoles and workstations. controls, toys).
IoT devices (smart home gadgets,
wearables).
Embedded System
• Embedded system means the processor is embedded into
that application.
• An embedded product uses a microprocessor or
microcontroller to do one task only.
• In an embedded system, there is only one application
software that is typically burned into ROM.
• Example : printer, keyboard, video game player
Three criteria in Choosing a Microcontroller
• Meeting the computing needs of the task efficiently and cost-effectively
• speed, the amount of ROM and RAM, the number of I/O ports and
timers, size, packaging, power consumption
• easy to upgrade
• cost per unit
• Availability of software development tools
• assemblers, debuggers, C compilers, emulator, simulator, technical
support.
• Wide availability and reliable sources of microcontrollers.
Block Diagram
External interrupts
On-chip Timer/Counter
Interrupt ROM for
On-chip Timer 1 Counter
Control program
RAM Timer 0 Inputs
code
CPU
Bus Serial
4 I/O Ports
OSC Control Port
P0 P1 P2 P3 TxD RxD
Address/Data
Comparison of the 8051 Family Members
Feature 8051 8052 8031
ROM (program space in bytes) 4K 8K 0K
RAM (bytes) 128 256 128
Timers 2 3 2
I/O pins 32 32 32
Serial port 1 1 1
Interrupt sources 6 8 6
Features of 8051
• 8-bit CPU with registers A and B
•8-bit data bus and 16-bit address bus
• 16- bit program counter(PC) and data pointer(DPTR)
• 8 -bit program status word(PSW)
• 8-bit stack pointer
• Internal ROM of 0(8031) to 4KB(8051), 4KB bytes on-chip program
memory (ROM)
• Internal RAM of 128 Bytes
• 4 Register banks 00-1F
• 16 bytes(bit addressable) 20-2F
• 80 bytes of general-purpose data memory 30-7F
• 32 I/O pins arranged as four 8-bit ports (P0 - P3)
• Two 16-bit timer/counters: T0 and T1
• Full duplex serial data receiver/transmitter: SBUF
• Control registers: TCON, TMOD, SCON, PCON, IP and IE
• 2 external and 3 internal interrupt sources
• Oscillator and clock circuits(12MHz frequency)
•It has 111 instructions, 64 instructions are of single cycle
•It has 11 special function registers of 128 bytes.
Pin Description of the 8051
P1.0 1 40 Vcc
P1.1 2 39 P0.0(AD0
P1.2 3 38 P
) 0.1(AD1)
P1.3
P1.4
4
5
8051 37
36
P0.2(AD2
P
) 0.3(AD3)
P1.5 6 (8031) 35 P0.4(AD4)
P1.6 7 34 P0.5(AD5)
P1.7 8 33 P0.6(AD6)
RST 9 32 P0.7(AD7)
(RXD)P3.0 10 31 EA/VPP
(TXD)P3.1 11 30 ALE/PROG
(INT0)P3.2 12 29 PSEN
(INT1)P3.3 13 28 P2.7(A15)
(T0)P3.4 14 27 P2.6(A14
(T1)P3.5 15 26 )P2.5(A13
(WR)P3.6 16 25 )P2.4(A12
(RD)P3.7 17 24 P
) 2.3(A11
XTAL2 18 23 P ) 2.2(A10)
XTAL1 19 22 P2.1(A9)
GND 20 21 P2.0(A8)
Mahdi Hassanpour Wednesda
y, Decem
ber 10, 20
Mahdi Hassanpour Wednesda
y, Decem
ber 10, 20
Mahdi Hassanpour
Pins of 8051
• Vcc ( pin 40 ):
- Vcc provides supply voltage to the chip.
- The voltage source is +5V.
• GND ( pin 20 ): ground
• XTAL1 and XTAL2 ( pins 19,18 ):
- These 2 pins provide external clock.
- Way 1 : using a quartz crystal oscillator
- Way 2 : using a TTL oscillator
XTAL Connection to 8051
• Using a quartz crystal oscillator
• We can observe the frequency on the XTAL2 pin.
C2
XTAL2
30pF
C1
XTAL1
30pF
GND
Find the machine cycle for
(a) XTAL = 11.0592 MHz
(b) XTAL = 16 MHz.
Solution:
(a) 11.0592 MHz / 12 = 921.6 kHz;
machine cycle = 1 / 921.6 kHz = 1.085 s
(b) 16 MHz / 12 = 1.333 MHz;
machine cycle = 1 / 1.333 MHz = 0.75 s
Pins of 8051
• RST ( pin 9 ): reset
- It is an input pin and is active high ( normally low ) .
- The high pulse must be high at least 2 machine cycles.
- It is a power-on reset.
- Upon applying a high pulse to RST, the microcontroller will
reset and all values in registers will be lost.
RESET Value of Some 8051 Registers:
Register Reset Value
PC 0000
ACC 0000
B 0000
PSW 0000
SP 0007
DPTR 0000
RAM are all zero.
Mahdi Hassanpour
Mahdi Hassanpour
Pins of 8051
• /EA ( pin 31 ): external access
- There is no on-chip ROM in 8031 and 8032 .
- /EA pin is active low and is connected to GND to indicate the code is stored
externally.
- For 8051, /EA pin is connected to Vcc.
• /PSEN ( pin 29 ): Program Store Enable
- This is an output pin and is connected to the OE pin of the ROM in 8031
based systems
Pins of 8051
• ALE ( pin 30 ): Address Latch Enable
- It is an output pin and is active high.
- 8051 port 0 provides both address and data.
- The ALE pin is used for de-multiplexing the address and data by
connecting to the G pin of the 74LS373 latch.
• I/O port pins
- 8051 has four ports P0, P1, P2, and P3.
- Each port uses 8 pins.
- All I/O pins are bi-directional.
Mahdi Hassanpour Wednesda
y, Decem
ber 10, 20
Mahdi Hassanpour Wednesda
y, Decem
ber 10, 20
Mahdi Hassanpour Wednesda
y, Decem
ber 10, 20
Mahdi Hassanpour
Registers:
•8051 is a CISC based with Harvard architecture
•Databus is of 8-bit wide
•Address bus is 0f 16-bit
CPU:
•A, B,PSW, SP, 16-bit PC&DPTR
•11 special function Registers
•ALU is of 8-bit so it Perform arithmetic and logic
functions on 8-bit variables, data.
A (Accumulator)
B
PSW (Program Status Word)
SP (Stack Pointer)
PC (Program Counter)
DPTR (Data Pointer)
Registers
A
R0
DPTR DPH DPL
R1
R2 PC PC
R3
R4 Some 8051 16-bit Registers
R5
R6
R7
Some 8-bit Registers of
the 8051
8051 Flag bits and the PSW register
• PSW Register
CY AC F0 RS1 RS0 OV -- P
Carry flag PSW.7 CY
Auxiliary carry flag PSW.6 AC
Available to the user for general purpose PSW.5 --
Register Bank selector bit 1 PSW.4 RS1
Register Bank selector bit 0 PSW.3 RS0
Overflow flag PSW.2 OV
User define bit PSW.1 --
Parity flag Set/Reset odd/even parity PSW.0 P
RS1 RS0 Register Bank Address
0 0 0 00H-07H
0 1 1 08H-0FH
1 0 2 10H-17H
1 1 3 18H-1FH
Memory Organization
8051 supports two types of memories.
•1. Internal Memory
•2. External Memory
Internal Memory:
Internal memory means on chip memory, this is the memory, which is inbuilt
into a microcontroller. 8051 microcontroller has separate on-chip program
memory and data memory. Internal memories supported by 8051 are grouped
as:
128 bytes RAM
4K bytes ROM
Internal RAM:
The 128 bytes of Internal RAM is grouped as
follows and is shown in the figure below:
•1. Register Bank
•2. Bit addressable Area
•3. Scratch Pad Area
Mahdi Hassanpour
Internal RAM organization
Internal RAM of 8051 it is divided into 3 main sections:
1. Register Banks
8051 Internal RAM(00H-1FH)
•There are 32 8-bit registers arranged in 4 groups. These are used as
general-purpose registers.
2. Bit Addressable RAM (20H-2FH)
•8051 has 16 bytes of RAM, which is bit addressable. It is grouped as 16,
8-byte arrays and any of the 128 bits can also be set/cleared individually.
3. Scratch PAD RAM (30H-7FH)
•The third group of registers occupy addresses 30h-7Fh, i.e. 80 locations,
and does not have any special functions or features. Scratch pad RAM is
used by the ALU , while fetching, decoding and executing the instructions
during the operation of the microcontroller
2F 7F 78 • 20h–2Fh (16 locations x 8-bits
2E = 128 bits)
2D • As internal RAM is in short
2C supply, why use a byte when
2B bit is required?
2A • Addressable bits are useful for
29 a binary event like switching a
28 fan on turning a light off
27
26
25 Bit addressing:
24 mov C, 1Ah
23 1A or
22 10 mov C, 23h.2
21 0F 08
20 07 06 05 04 03 02 01 00
Special Function Registers(SFRs)
• CPU Registers: A and B
• Status Register: PSW (Program Status Word)
• Pointer Registers: DPTR (Data Pointer – DPL, DPH) and SP
(Stack Pointer)
• I/O Port Latches: P0 (Port 0), P1 (Port 1), P2 (Port 2) and
P3 (Port 3)
• Peripheral Control Registers: PCON, SCON, TCON, TMOD,
IE and IP
• Peripheral Data Registers: TL0, TH0, TL1, TH1 and SBUF
Special Function Registers(SFRs)
• All the 21 8051 Microcontroller Special Function Registers
(SFRs) along with their functions and Internal RAM Address
is given in the following table.
Mahdi Hassanpour
Internal ROM of 4K Bytes
•8051 microcontroller supports 4K Internal ROM
for program. Setting EA pin to high level (Vcc) can
access this internal ROM.
External Memory
•8051 supports external memory of 64K Bytes of data
memory and 64K Bytes of program memory (total 128K
Bytes).
Data Memory:
•8051 supports 64K Bytes of external data memory in
addition to 128 Bytes of internal RAM. The external data
memory is accessed using 16-bit address lines and its
address varies from 0000H to FFFFH.
Program Memory:
8051 supports 64K Bytes of program memory.
This 64K Bytes of program memory is organized
as follows:
•4k Internal + 60K External
•64K External
Mahdi Hassanpour Wednesda
y, Decem
ber 10, 20
• Figure 5.6.1 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 T 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.
Mahdi Hassanpour Wednesda
y, Decem
ber 10, 20
• Figure 5.6.2 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:
MOV R6,#25H
MOV R1,#12H
MOV R4,#0F3H
PUSH 6
PUSH 1
PUSH 4
0BH 0BH 0BH 0BH
0AH 0AH 0AH 0AH F3
09H 09H 09H 12 09H 12
08H 08H 25 08H 25 08H 25
Start SP=07H SP=08H SP=09H SP=0AH
Addressing Modes
Every instruction of a program has to operate on a data. The
method of specifying the data to be operated by the instruction is
called addressing.
8051 provides five distinct addressing modes
•Immediate
•Register
•Direct
•Register Indirect
•Indexed
Immediate Addressing Mode
In immediate addressing mode, an 8/16 bit immediate data / constant is
specified in the instruction itself
In this mode, source operand is constant and comes immediately after the
Opcode preceded by ‘# ‘ sign. Loads data into any register including DPTR.
MOV A, #65H
MOV A, #’A’
MOV R6, #65H
MOV DPTR,#2343H
MOV P1,#65H
Example :
Num EQU 30
…
MOV R0,Num
MOV DPTR,#data1
…
ORG 100H
data1: db “IRAN”
Register Addressing Mode
Involves the use of registers to hold the data to be manipulated. Source and
destination register must match in size.
Movement of data between Rn registers is not valid.
MOV Rn, A ;n=0,..,7
ADD A, Rn
MOV DPL, R6
MOV DPTR, A
MOV Rm, Rn
Direct Addressing Mode
In direct addressing mode, the address of the data is directly specified in the instruction.
The direct address can be the address of an internal data RAM location (00H to 7FH) or
address of special function register (80H to FFH).
Although the entire of 128 bytes of RAM can be accessed using direct addressing mode, it is
most often used to access RAM loc. 30 – 7FH. This is because register bank locations are
accessed by names R0-R7.
MOV R0, 40H
MOV 56H, A
MOV A, 4 ; ≡ MOV A, R4
MOV 6, 2 ; copy R2 to R6
; MOV R6, R2 is invalid !
SFR register and their address
MOV 0E0H, #66H ; ≡ MOV A,#66H
MOV 0F0H, R2 ; ≡ MOV B, R2
MOV 80H,A ; ≡ MOV P1,A
Register Indirect Addressing Mode
• In this mode, the instruction specifies the name of the register in which the
address of the data is available. The internal data RAM locations (00H to 7FH)
can be addressed indirectly through registers R1 and R0. The external RAM can
be addressed indirectly through DPTR.
• MOV A, @Ri; move content of RAM loc. Where address is held by Ri into A ( i=0 or 1 )
MOV @R1, B
Example:
Write a program to copy a block of 10 bytes from RAM location starting at 37h
to RAM location starting at 59h.
Solution:
MOV R0,37h ; source pointer
MOV R1,59h ; dest pointer
MOV R2,10 ; counter
L1: MOV A,@R0
MOV @R1,A
INC R0
INC R1
DJNZ R2,L1
Indexed Addressing Mode And On-Chip ROM Access
• In this mode the 16-bit address in a base register is added to a positive
offset to form an effective address for the jump indirect instruction JMP
@A+DPTR, and the two move code byte instructions MOVC A,@A+DPTR
and MOVC A,@A+PC.
• The base register in the jump instruction is the data pointer and the
positive offset is held in the accumulator. For the move instructions the
base register can either be the data pointer or the program counter, and
again the positive offset is in the accumulator.
JMP @A+DPTR
¨ (A) +(DPTR)
MOVC A,@A+DPTR (A) ¨ ((A) + (DPTR))
MOVC A,@A+PC (PC)
¨ (PC) + 1 (A) ¨
((A) + (PC))
Indexed Addressing Mode And On-Chip ROM Access
• This mode is widely used in accessing data elements of look-up table entries located
in the program (code) space ROM at the 8051.
MOVC A, @A+DPTR/PC; A= content of address (A +DPTR) or (A+PC) from ROM
Note:
Because the data elements are stored in the program space of 8051, it uses the
instruction MOVC instead of MOV. “C” means code.
8051 has 64KB external memory exclusively set aside for data storage that is
accessed using MOVX instruction. It transfers data between external memory and A.
MOVX A, @DPTR / MOVX @DPTR, A
MOVX A, @Ri / MOV @Ri , A
Instruction set
8051 instructions are divided into five functional groups:
• Arithmetic operations
• Logical operations
• Data transfer operations
• Boolean variable operations
• Program branching operations
Arithmetic Operations
• This group of operators perform arithmetic operations. Arithmetic operations effect the flags such as Carry Flag
(CY), Overflow Flag (OV) etc, in the PSW register
ADD A, Source ;A=A+SOURCE (data, Rn , direct, @Ri )
ADDA,#6 ;A=A+6
ADDA,R6 ;A=A+R6
ADD A,6 ;A=A+[6] or A=A+R6
ADDA,0F3H ;A=A+[0F3H]
ADDC A, source ;A=A+ source+ CY (data, Rn , direct, @Ri )
SETB C ;CY=1
ADC A,R5 ;A=A+R5+1
DA A ; Decimal-adjust Accumulator for Addition
It adjusts 8-bit value in Accumulator resulting from the earlier addition of two variables (each in packed-BCD
format), producing two four-bit digits.
SUBB A, source ;A=A-source-CY(data, Rn , direct, @Ri)
SETB C ;CY=1
SUBB A,R5 ;A=A-R5-1
INC byte ;byte=byte+1(A, Rn , direct, @Ri)
INC R7 R7=R7+1
DEC byte ;byte=byte-1 (A, Rn , direct, @Ri)
DEC A ;A=A-1
DEC 40H ; [40]=[40]-1
MUL AB ; A=lower order byte, B=higher order byte
MOVA,#25H
MOV B,#65H
MUL AB ;25H*65H=0E99 ;B=0EH, A=99H
DIV AB ;A = A/B, A= Quotient, B=Remainder
MOV A,#25
MOV B,#10
DIV AB ;A=2, B=5
Logical operations
Perform standard Boolean operations such as AND, OR, XOR, NOT
(compliment). Other logical operations are clear accumulator, rotate
accumulator left and right, and swap nibbles in accumulator.
ANL / ORL / XRL dest, src ; (A, Rn , direct, @Ri , data)
When the destination is A, source can use register, direct, register-indirect,
or immediate addressing; when destination is a direct address, source can
be A or immediate data
Ex: MOV A,#89H
ANL A,#08H
RR / RL / RRC / RLC A
Ex: RR A
CLRA ;A=0
CPL A ;1’s complement
Ex: MOV A,#55H ;A=01010101 B
L01: CPL A
MOV P1,A
ACALL DELAY
SJMP L01
SWAP A ; Swap nibbles within the Accumulator
Swaps bits 0-3 with bits 4-7 of Accumulator. This instruction is identical to
executing "RR A" or "RL A" four times.
Data Transfer Instructions
MOV dest, source ; dest = source
MOV A, #72H ;A=72H
MOV A, #’r’ ;A=‘r’ OR 72H
MOV R4, #62H ;R4=62H
MOV B, 0F9H ;B=the content of F9’th byte of RAM
MOV DPTR, #7634H
MOV DPL, #34H
MOV DPH, #76H
MOV P1, A ;move A to port 1
Note 1:
MOV A, #72H ≠ MOV A, 72H
After instruction “MOV A, 72H ” content of 72’th byte of RAM will replace in A.
8086 8051
MOV AL,72H MOV A, #72H
MOV AL, ’r’ MOV A, #’r’
MOV BX,72H
MOV AL,[BX] MOV A, 72H
Note 2: MOV A, R3 ≡ MOV A, 3
MOVX @DPTR, A ;External[@DPTR] = A
MOVX @Ri, A ;External[@Ri] = A
MOVX A,@DPTR ;A = Data byte from external ram [@DPTR]
MOVX A, @Ri ;A = Data byte from external ram [@Ri]
MOVC A,@A+PC ;A = Code byte from [@A+PC]
MOVC A,@A+DPTR ;A = Code byte from [@A+DPTR]
PUSH direct ; Push value of RAM address onto stack
SP is incremented by one. Contents of the indicated variable is then copied into internal RAM location
addressed by SP
POP direct ; Pop value of RAM address onto stack
Contents of internal RAM location addressed by SP is read and SP is decremented by one. The value
read is then transferred to the directly addressed byte indicated.
XCH A, src ; Exchanges value of A with value contained in register.
(Rn, direct, @Ri)
XCHD A,[@R0/@R1] ; Exchanges bits 0-3 of Accumulator with bits 0-3 of
the internal RAM address pointed to indirectly by R0 or R1. Bits 4-7 of each
register are unaffected.
Boolean variable operations
CLR C ;Clear Carry flag
CLR bit ;clear direct bit
SETB bit ; bit=1
CPL bit ;Complement direct bit
ANL C, bit / ANL C, /bit ; AND bit with C/ AND NOT bit with C
ORL C, bit / ORL C, /bit ; OR bit with C/ OR NOT bit with C
MOV C, bit / MOV bit, C
JC/JNC bit, addr. ; Jump if carry/ Jump if no carry
JB/JNB bit, addr. ; Jump if bit set/ Jump if bit not set
JBC bit, addr. ; If specified bit is set, clear and jump
Program Branching Instructions
ACALL addr11 ; absolute call that unconditionally calls a subroutine indicated
by address. The subroutine called must start within the same 2 KB block of the
program memory.
Ex: ACALL LOC_SUB
LCALL addr16 ; calls a subroutine located at the indicated address. Since it is a
Long call, the subroutine may therefore begin anywhere in the full 64KB program
memory address space
Ex: LCALL LOC_SUB
RET ; returns program from a subroutine. It pops high byte & low byte
address of PC from stack and decrements the SP by 2. The execution of
the instruction will result in the program to resume from the location
just after the “call” instruction
RETI ; returns program from ISR. Pops high byte and low byte address
of PC from stack and restores interrupt logic to accept additional
interrupts. SP decrements by 2
After RETI, program execution will resume immediately after the point
at which the interrupt is detected.
AJMP addr11 ; 2-byte instruction. Transfers program execution to a 11-bit destination address
which is located at the absolute short range distance i.e., within the same 2 KB block of program
memory
Ex: AJMP NEAR
LJMP addr16 ; 3-byte instruction. transfers program execution to 16-bit destination address
which is located at the absolute long range distance i.e., anywhere in the full 64 KB program
memory address space.
Ex: LJMP FAR_ADR
SJMP rel ; 2-byte instruction. It uses 8 bit address. short jump instruction adds the signed 8-bit
relative value to the PC. This will be the new address where the program would branch to
unconditionally. Range of destination -128 to +127 bytes from the instruction.
Ex: SJMP RELSRT
JZ/JNZ rel ; branches to the destination address if ACC=zero/no-
zero;
Ex: SUBB A,#20H DEC A
JZ LABEL1 JNZ LABEL2
DJNZ byte, rel ; ”decrement and jump if not zero”
It decrements the contents of the destination location and if the
resulting value is not 0, branches to the address indicated by the
source operand.
Ex: Write a program to clear ACC, then add 3 to the accumulator ten
times
MOV A,#0;
MOV R2,#10
AGAIN: ADD A,#03
DJNZ R2,AGAING ;repeat until R2=0 (10 times)
MOV R5,A
CJNE dest, src, rel; compares the magnitude of the dest-byte and
the source-byte and jumps if their values are not equal.
CY is set if the unsigned dest-byte is less than the unsigned integer
source-byte; otherwise cleared. Neither of the operands is affected.
CJNE R3,#50H,NEQU • CJNE A, direct,
… … ; R3 = 50H
rel
NEQU: JC LOC1 ;If R3 < 50H … … • CJNE A, #data,
;R3 > 50H
rel
LOC1: … … ;R3 < 50H • CJNE Rn,
#data, rel
NOP ; no operation instruction that takes one machine cycle
• CJNE @Ri,
operation time. #data, rel
CLR P1.2
NOP
NOP
NOP
SETB P1.2
Structure of Assembly language and Running an
8051 program
ORG 0H EDITOR
PROGRAM
MOV R5,#25H
[Link]
MOV R7,#34H ASSEMBLER
PROGRAM
MOV A,#0
[Link]
Other obj file
ADD A,R5 [Link]
ADD A,#12H LINKER
PROGRAM
HERE: SJMP HERE
[Link]
END
OH
PROGRAM
[Link]
Assuming that ROM space starting at 250h contains “Hello.”, write a program
to transfer the bytes into RAM locations starting at 40h.
ORG 0
MOVDPTR,#MYDATA
MOVR0,#40H
L1: CLR A
MOVC A,@A+DPTR
JZ L2
MOV @R0,A
INC DPTR
INC R0
SJMP L1
L2: SJMP L2
;-------------------------------------
ORG 250H
MYDATA: DB “Hello”,0
END
Notice the NULL character ‘0’, as end of string and how we use the JZ instruction to detect
that.
Pins of I/O Ports
• The 8051 has four I/O ports
• Port 0 ( pins 32-39 ): P0 ( P0.0 ~ P0.7 )
• Port 1 ( pins 1-8 ) : P1 ( P1.0 ~ P1.7 )
• Port 2 ( pins 21-28 ): P2 ( P2.0 ~ P2.7 )
• Port 3 ( pins 10-17 ): P3 ( P3.0 ~ P3.7 )
• Each port has 8 pins.
• Named P0.X ( X=0,1,...,7 ) , P1.X, P2.X, P3.X
• Ex : P0.0 is the bit 0 ( LSB ) of P0 , P0.7 is the bit 7 ( MSB ) of P0
• These 8 bits form a byte.
• Each port can be used as input or output (bi-direction). When a ‘1’ is sent it acts as input line and when ‘0’ is
sent it acts as output line.
• Each port has a D-latch for each pin. SFR for each port is made up of these 8 latches which can be addressed
at that SFR address for that port. Data on latches need not be the same as the port pin.
I/O Port Programming
• Upon reset all ports are configured as output ports. To configure it as input
port, a ‘1’ is written to port.
• Port 1 is denoted by P1.
• P1.0 ~ P1.7
• P1 is used as example to show the operations on ports.
• P1 as an output port (i.e., write CPU data to the external pin)
• P1 as an input port (i.e., read pin data into CPU bus)
Hardware Structure of I/O Pin
• Each pin of I/O ports
• Internal CPU bus : communicate with CPU
• A D- latch stores the value of this pin
• D latch is controlled by “Write to latch”
- Write to latch = 1 : write data into the D latch
• 2 Tri-state buffer :
• TB1: controlled by “Read pin”
- Read pin = 1 : really read the data present at the pin
• TB2: controlled by “Read latch”
- Read latch = 1 : read value from internal latch
• A transistor M1 gate
• Gate=0: open; Gate=1: close
A Pin of Port 1
Read latch Vcc
TB2
Load(L1)
Internal CPU D Q P1.X
bus P1.X pin
Write to latch Clk Q M1
TB1
Read pin
Writing “1” to Output Pin P1.X
Read latch Vcc
TB2
Load(L1) 2. output pin is
1. write a 1 to the pin Vcc
Internal CPU D Q 1 P1.X
bus P1.X pin
0 M1
output 1
Write to latch Clk Q
TB1
Read pin
Writing “0” to Output Pin P1.X
Read latch Vcc
TB2
Load(L1) 2. output pin is
1. write a 0 to the pin ground
Internal CPU D Q 0 P1.X
bus P1.X pin
1 M1
output 0
Write to latch Clk Q
TB1
Read pin
Port 1 as Output ( Write to a Port )
• Send data to Port 1 :
MOV A,#55H
BACK: MOV P1,A
ACALL DELAY
CPL A
SJMP BACK
Reading “High” at Input Pin
Read latch Vcc 2. MOV A,P1
TB2 external pin=High
1. write a 1 to the pin MOV Load(L1)
P1,#0FFH
1 1 P1.X pin
Internal CPU bus D Q
P1.X
0 M1
Write to latch Clk Q
TB1
Read pin
3. Read pin=1 Read latch=0
Write to latch=1
Reading “Low” at Input Pin
Read latch Vcc 2. MOV A,P1
TB2
1. write a 1 to the pin Load(L1) external pin=Low
MOV P1,#0FFH
1 0 P1.X pin
Internal CPU bus D Q
P1.X
0 M1
Write to latch Clk Q
TB1
Read pin
3. Read pin=1 Read latch=0
Write to latch=1
Port 1 as Input ( Read from Port )
• In order to make P1 an input, the port must be programmed by writing 1 to all the
bits.
MOV A,#0FFH ;A=11111111B
MOV P1,A ;make P1 an input port
BACK: MOV A,P1 ;get data from P1
MOV P2,A ;send data to P2
SJMP BACK
• To be an input port, P0, P1, P2 and P3 have similar methods.
Instructions For Reading an Input Port
• Following are instructions for reading external pins of ports:
Mnemonics Examples Description
Bring into A the data at P2
MOV A,PX MOV A, P2
pins
JNB PX.Y,.. JNB P2.1, TARGET Jump if pin P2.1 is low
JB PX.Y,.. JB P1.3, TARGET Jump if pin P1.3 is high
MOV C,PX.Y MOV C, P2.4 Copy status of pin P2.4 to CY
Other Pins
• P1, P2, and P3 have internal pull-up resisters.
• P1, P2, and P3 are not open drain.
• P0 has no internal pull-up resistors and does not connects to Vcc
inside the 8051.
• P0 is open drain.
• Compare the figures of P1.X and P0.X.
• All the ports upon RESET are configured as output.
A Pin of Port 0
Read latch
TB2
Internal CPU D Q P0.X
bus P1.X pin
Write to latch Clk Q M1
TB1
Read pin
Port 0 ( pins 32-39 )
• P0 is an open drain.
• Open drain is a term used for MOS chips in the same way that
open collector is used for TTL chips.
• When P0 is used for simple data I/O we must connect it to external
pull-up resistors.
• Each pin of P0 must be connected externally to a 10K ohm pull-
up resistor.
• With external pull-up resistors connected upon reset, port 0 is
configured as an output port.
Port 0 with Pull-Up Resistors
Vcc
10 K
P0.0
DS5000 P0.1
Port 0
P0.2
8751 P0.3
8951 P0.4
P0.5
P0.6
P0.7
Dual Role of Port 0
• When connecting an 8051/8031 to an external memory, the 8051 uses
ports to send addresses and read instructions.
• 8031 is capable of accessing 64K bytes of external memory.
• 16-bit address : P0 provides both address A0-A7, P2 provides
address A8-A15.
• Also, P0 provides data lines D0-D7.
• When P0 is used for address/data multiplexing, it is connected to the
74LS373 to latch the address.
ALE Pin
• The ALE pin is used for de-multiplexing the address and data by
connecting to the G pin of the 74LS373 latch.
• When ALE=0, P0 provides data D0-D7.
• When ALE=1, P0 provides address A0-A7.
• The reason is to allow P0 to multiplex address and data.
Port 2 ( pins 21-28 )
• Port 2 does not need any pull-up resistors since it already
has pull-up resistors internally.
• In an 8031-based system, P2 are used to provide address
A8-A15.
Port 3 ( pins 10-17 )
• Port 3 does not need any pull-up resistors since it already has pull-up
resistors internally.
• Although port 3 is configured as an output port upon reset, this is not
the way it is most commonly used.
• Port 3 has the additional function of providing signals.
• Serial communications signal : RxD, TxD
• External interrupt : INT0, INT1
• Timer/counter : T0, T1
• External memory accesses in 8031-based system : WR, RD
Port 3 Alternate Functions
P3 Bit Function Pin
P3.0 RxD 10
P3.1 TxD 11
P3.2 INT0 12
P3.3 INT1 13
P3.4 T0 14
P3.5 T1 15
P3.6 WR 16
P3.7 RD 17
Programming 8051 Timers
Timer 0 registers
TL0 ( timer 0 low byte )
TH0 ( timer 0 high byte )
Timer 1 registers
TL1 ( timer 1 low byte )
TH1 ( timer 1 high byte )
TMOD (Timer mode) register
TCON register
TF0/TF1: Timer0/1 overflow flag is set when the timer counter
overflows, reset by program
TR0/TR1: Timer0/1 run control bit is set to start, reset to stop
the timer0/1
IE0/IE1: External interrupt 9/1 edge detected flag1 is set when a
falling edge interrupt on the external port
0/1, reset(cleared) by hardware itself for falling
edge transition-activated INT; Reset by code for
low level INT.
IT0/IT1 External interrupt type (1: falling edge triggered, 0 low
level triggered)
Mode 0 Programming
Works like mode 1
13-bit timer instead of 16-bit that hold values 0000 to 1FFFH
When the timer reaches its maximum of 1FFFH, it rolls over to
0000, and TF is set
Lower byte(TL0/TL1) + 5 bits of upper byte(TH0/TH1)
Mode 1 programming
• 16-bit timer, values of 0000 to FFFFH
• TH and TL are loaded with a 16-bit initial value
• Timer started by "SETB TR0" for Timer 0 and "SETB TR1" for
Timer l
• Timer count ups until it reaches its limit of FFFFH and rolls over
to 0000H
• Sets TF (timer flag)
• When TF is raised, timer can be stopped with "CLR TR0" or "CLR
TR1”
• After the timer reaches its limit and rolls over, TH and TL must be
reloaded with original value and TF must be reset to 0
Steps to program in mode 1
• Set timer mode 1 or 2
• Set TL0 and TH0 (for mode-1 16-bit mode)
• Set TH0 only (for mode 2 8-bit auto reload mode)
• Run the timer
• Monitor the timer flag bit
Finding the values to be loaded into timer
(FFFF-n+1)X machine cycle time period = Delay (required)
In Decimal: (65536-n)X machine cycle = Delay
Assume: XTAL = 11.0592 MHz (12MHz)
Machine cycle frequency =11.0592 MHz /12 = 921.6 KHz
Machine cycle time period = 1/921.6 kHZ =1.085 us
(65536-n)X machine cycle = Delay
65536-n = required delay
Machine cycle time period
divide the desired time delay by 1.085us (1ms) to get n
65536 – n = N
n=65536-N
convert n to hex yyxx
set TL = xx and TH = yy
Assuming XTAL = 11.0592MHz, Write a program to generate a square
wave of 50 Hz frequency on pin P2.3.
T = 1/50 Hz = 20ms
1/2 of it for the high and low portions of the pulse = 10 ms
10 ms / 1.085 us = 9216(n)
65536 - 9216 = 56320(N)
In decimal = DC00H
TL = 00 and TH = DCH
The calculation for 12MHz crystal uses the same steps
Create a square wave of 50% duty cycle (with equal portions of high
and low) on P1.5 bit. Timer 0 is used to generate the time delay
Mode 2(Auto reload)programming
• 8-bit timer, allows values of 00 to FFH
• TH is loaded with the 8-bit value and a copy is given to TL
• Timer is started by ,"SETB TR0" or "SETB TR1“
• Starts to count up by incrementing the TL register
• Counts up until it reaches its limit of FFH
• When it rolls over from FFH to 00, it sets TF high
• TL is reloaded automatically with the value in TH
• To repeat, clear TF
Steps to program in mode 2
• Load TMOD, select mode 2
• Load the TH and Start timer
• Monitor the timer flag (TF) with "JNB”
• Get out of the loop when TF=1
• Clear TF
• Go back to Step 4 since mode 2 is auto-reload
Assuming that XTAL = 11.0592 MHz, find (a) the frequency of the square
wave generated on pin P1.0 and (b) the smallest frequency achievable in
this program, and the TH value to do that.
Mode 3 – Split Timer mode
• Splits Timer 0 into two 8-bit timers
• TL0 sets TF0
• TL1 sets TF1
• Timer 1 is available for other 3 modes but TF1 is not
available
Timer /counter
Serial Communication
Serial versus Parallel Data Transfer
Serial Communication
• Serial communication uses single data line making it much cheaper
• Enables two computers in different cities to communicate over the
telephone
• Byte of data must be converted to serial bits using a parallel-in-serial-
out shift register and transmitted over a single data line
• Receiving end there must be a serial-in-parallel-out shift register
• If transferred on the telephone line, it must be converted to audio
tones by modem
• For short distance the signal can be transferred using wire
• Ex: PC keyboards transfer data to the motherboard
Serial Communication
• Two methods - Asynchronous and Synchronous
• Synchronous method transfers a block of data (characters) at a time
• Asynchronous method transfers a single byte at a time
• Uses special ICs called UART (Universal Asynchronous Receiver
Transmitter) and USART (Universal Synchronous Asynchronous
Receiver Transmitter)
• 8051 chip has a built-in UART
Serial Communication
Basics Of Serial Communication
Half- and full-duplex transmission
• Simplex transmissions the computer only sends data
• If the data can be transmitted and received, it is a duplex
transmission
• Duplex transmissions can be half or full duplex
• Depends on whether or not the data transfer can be simultaneous
• If one way at a time, it is half duplex
• If can go both ways at the same time, it is full duplex
• Full duplex requires two wire conductors for the data lines (in
addition to the signal ground)
Basics Of Serial Communication
Asynchronous serial communication and data framing
• Data coming in 0s and 1s
• To make sense of the data, sender and receiver agree on a set of rules
• Protocol
• How the data is packed
• How many bits/character
• When the data begins and ends
Asynchronous Serial Communication
Start and stop bits
• In asynchronous method, each character is placed between
start and stop bits called Framing
• Start bit is always one bit
• Stop bit can be one or two bits
• Start bit is always a 0 (low)
• Stop bit(s) is 1 (high)
• LSB is sent out first
Asynchronous Serial Communication
Framing ASCII “A” (41H)
Asynchronous Serial Communication
Data transfer rate
• Rate of data transfer measured in bps (bits per second)
• Widely used terminology for bps is baud rate
• Baud and bps rates are not necessarily equal
• Baud rate is defined as the number of signal changes per second
8051 Connection To RS232
RxD and TxD pins in 8051
• 8051 has two pins used for transferring and receiving data serially
• TxD and RxD are part of the port 3 group
• Pin 11 (P3.1) is assigned to TxD
• Pin 10 (P3.0) is designated as RxD
• These pins are TTL compatible & require a line driver to make
them RS232 compatible
• Driver is the MAX232 chip
8051 Serial Port Programming
• Baud rate in 8051 is programmable
• Baud rates supported by 8051 (unit: bps): 9600, 4800, 2400, 1200
• It can be set via timer 1 in mode 2 (8-bit auto-reload) - (XTAL/12)/32
• Crystal frequency & baud rate - 8051 divides crystal frequency by 12
to get machine cycle frequency.
• XTAL = 11.0592 MHz, machine cycle frequency is 921.6 KHz
• 8051's UART divides machine cycle frequency(921.6 KHz) by 32 once
more before it is used by timer 1 to set the baud rate
• 921.6 KHz / 32 gives 28,800 Hz
With XTAL = 11.0592 MHz, find the TH1 value needed to have the
following baud rates.(a) 9600 (b) 2400 (c) 1200
• Machine cycle frequency
= 11.0592 mhz / 12 = 921.6 khz
• Timer 1 frequency provided by 8051 UART
= 921.6 khz / 32 = 28,800 hz
(a) 28,800 / 3 = 9600 where -3 = FD (hex)
(b) 28,800 / 12 = 2400 where -12 = F4 (hex)
(c) 28,800 / 24 = 1200 where -24 = E8 (hex)
8051 Serial Port Programming
Timer 1 TH1 Register Values for Various Baud Rates
8051 Serial Port Programming
SBUF (Serial Buffer) – 8 bit register that holds data to be transferred or
received from serial port
•A byte of data to be transferred via TxD line must be placed in SBUF register
•Also, SBUF holds the byte of data when it is received by the RxD line
•Can be accessed like any other register
MOV SBUF,#'D' ;load SBUF=44H, ASCII for 'D‘
MOV SBUF,A ;copy accumulator into SBUF
MOV A,SBUF ;copy SBUF into accumulator
•When a byte is written, it is framed with the start and stop bits and transferred
serially via TxD pin
•When the bits are received serially via RxD, it is deframed by eliminating the stop
and start bits, making a byte out of the data received and then placing it in the SBUF
8051 Serial Port Programming
SCON (Serial Control) bit addressable register - 8-bit register used
to program start bit, stop bit and data bits of data framing and some
other serial related processing
8051 Serial Port Programming
SM0 and SM1 determine the mode
•(SM0, SM1) = (0,1)
• Mode 1: 8-bit data, 1 start bit, 1 stop bit, variable baud set by timer.
Most commonly used
•The other three modes are rarely used (not required for this
course)
– (SM0, SM1) = (0,0), Mode 0: fixed baud = XTAL/12
– (SM0, SM1) = (1,0), Mode 2: 9-bit data, fixed baud
– (SM0, SM1) = (1, 1), Mode 3: 9-bit data, variable baud
•SM2 = 0: single processor
•SM2 = 1: multiprocessor communication (not required for this
course)
8051 Serial Port Programming
• REN (receive enable) = 1, allows 8051 to receive data on the RxD
• REN=0, the receiver is disabled
• If 8051 is to both transfer and receive data, REN must be set to 1
• SETB SCON.4 / CLR SCON.4
• TB8 & RB8
• Used by modes 2 and 3 for the transmission and reception of bit 8
• RB8 is used by mode 1 to store the stop bit, CLR TB8 in mode 1
8051 Serial Port Programming
TI (transmit interrupt)
• When 8051 finishes the transfer of the 8-bit character, it raises the TI flag to
indicate that it is ready to transfer another byte
RI (receive interrupt)
• When the 8051 receives data serially via RxD, it places the byte in the SBUF
register
• Then raises the RI flag bit to indicate that a byte has been received and
should be picked up before it is lost
Interrupt-based data transfer
• It is a waste of the microcontroller's time to poll the TI and RI flags
• To avoid wasting time, use interrupts instead of polling
8051 Serial Port Programming
Program to transfer data serially
1. TMOD register is loaded with the value 20H
2. TH1 is loaded with value to set the baud rate
3. SCON register is loaded with the value 50H
4. TR1 is set to 1 to start Timer1
5. TI is cleared by the "CLR TI" instruction
6. Transmit character byte is written into the SBUF register
7. TI flag bit is monitored to see if the character has been transferred
completely
8. To transfer the next character, go to Step 5.
Write a program to transfer letter "A" serially at 4800 baud, continuously.
Write a program to transfer message "YES" serially at 9600 baud, 8-bit
data, 1 stop bit. Do this continuously.
8051 Serial Port Programming
Importance of the TI flag
• Checking TI flag bit, we know whether we can transfer
another byte
• It is raised by the 8051 and cleared by the programmer
• Writing a byte into SBUF before the TI flag bit is raised, may
lead to loss of a portion of the byte being transferred
8051 Serial Port Programming
Program to receive data serially
1. TMOD register is loaded with the value 20H
2. TH1 is loaded with value set the baud rate
3. SCON register is loaded with the value 50H
4. TR1 is set to 1 to start Timer 1
5. RI is cleared with the "CLR RI" instruction
6. RI flag bit is monitored to see if an entire character has been received
7. When RI=1, SBUF has the byte and its contents are moved into a safe
place
8. To receive the next character, go to Step 5
Program the 8051 to receive bytes of data serially, and put them in P1.
Set the baud rate at 4800, 8-bit data, and 1 stop bit.
8051 Serial Port Programming
Importance of the RI flag bit
1. It receives the start bit, next bit is the first bit of the character
2. When the last bit is received, a byte is formed and placed in
SBUF
3. When stop bit is received, makes RI = 1
4. When RI=1, received byte is in the SBUF register, copy SBUF
contents to a safe place
5. After the SBUF contents are copied the RI flag bit must be
cleared to 0
8051 Serial Port Programming
Doubling the baud rate in the 8051
• Two ways to increase the baud rate
1. Use a higher-frequency crystal
2. Change a bit in the PCON register
Baud Rate Comparison for SMOD = 0 and SMOD = 1
Interrupts Programming
• An interrupt is an external or internal event that interrupts the
microcontroller to inform it that a device needs its service.
• A single microcontroller can serve several devices.
• There are two ways to do that:
• INTERRUPTS - Whenever any device needs its service, the device
notifies the microcontroller by sending it an interrupt signal
• Upon receiving an interrupt signal, the microcontroller interrupts
whatever it is doing and serves the device
• POLLING - microcontroller continuously monitors the status of a
given device.
• When the condition is met, it performs the service. After that, it
moves on to monitor the next device until all devices are serviced
• The program which is associated with the interrupt is called Interrupt
Service Routine (ISR) Or Interrupt Handler.
• Each devices can get the attention of the microcontroller based on
the assigned priority
• For the polling method, it is not possible to assign priority since it
checks all devices in a round-robin fashion.
Steps in executing an interrupt
• Finish executing current instruction and save the PC on stack.
• Jumps to a fixed location in memory depending on type of interrupt
• Starts to execute the interrupt service routine until RETI
• Upon executing RETI, microcontroller returns to the place where it
was interrupted. Pops PC from stack
Interrupt Sources
Original 8051 has 6 sources of interrupts
• Reset
• Timer 0 overflow
• Timer 1 overflow
• External Interrupt 0
• External Interrupt 1
• Serial Port (buffer full, buffer empty)
Interrupt Vectors
• Each interrupt has a specific place in code memory where program
execution (interrupt service routine) begins. The group of memory
locations set aside to hold the addresses of ISRs is called Interrupt
Vector Table
Reset: 0000h
External Interrupt 0(INTO): 0003h
Timer 0 overflow(TF0): 000Bh
External Interrupt 1(INT1): 0013h
Timer 1 overflow(TF1): 001Bh
Serial : 0023h
Note: There are only 8 memory locations between vectors.
ISRs and Main Program in 8051
SJMP main
ORG 03H
LJMP int0sr
ORG 0BH
LJMP t0sr
ORG 13H
LJMP int1sr
ORG 1BH
LJMP t1sr
ORG 23H
LJMP serialsr
ORG 30H
main:
…
END
• Upon reset, all interrupts are disabled (masked), meaning that none
will be responded to by the microcontroller if they are activated
• The interrupts must be enabled by software in order for the
microcontroller to respond to them.
• There is a register called IE (interrupt enable) that is responsible for
enabling (unmasking) and disabling (masking) the interrupts
Interrupt Enable (IE) register
• All interrupt are disabled after reset
• We can enable and disable them by IE
Enabling and disabling an interrupt
• By bit operation
• Recommended in the middle of program
SETB EASETB IE.7 ;Enable All
SETB ET0 SETB IE.1 ;Enable Timer0 overflow
SETB ET1 SETB IE.3 ;Enable Timer1 overflow
SETB EX0 SETB IE.0 ;Enable INT0
SETB EX1 SETB IE.2 ;Enable INT1
SETB ES SETB ;Enable Serial port
IE.4
• By MOV instruction
• Recommended in the first of program
MOV IE, #10010110B
• Write a program to generate a square wave of 50Hz frequency on pin P1.2 using interrupt
method. Use timer 0. Assume that XTAL=11.0592 MHz
0RG 0
LJMP MAIN
ORG 000BH ;ISR for Timer 0
CPL P1.2
MOV TL0,#00
MOV TH0,#0DCH
RETI
ORG 30H
;--------main program for initialization
MAIN:MOV TM0D,#01H ;Timer 0, Mode 1
MOV TL0,#00
MOV TH0,#0DCH
MOV IE,#82H ;enable Timer 0 interrupt
SETB TR0
HERE:SJMP HERE
END
Write a program that continuously get 8-bit data from P0 and sends it to P1 while simultaneously creating a square wave of 200μs period on pin
P2.1. Use timer 0 to create the square wave. Assume that XTAL = 11.0592 MHz.
ORG 0000H
LJMP MAIN ;by-pass interrupt vector table
;ISR for timer 0 to generate square wave
ORG 000BH ;Timer 0 interrupt vector table
CPL P2.1 ;toggle P2.1 pin
RETI ;return from ISR
Main program
ORG 30H ;after vector table space
MAIN: MOV TMOD,#02H ;Timer 0, mode 2
MOV P0,#0FFH ;make P0 an input port
MOV TH0,#-92 ;TH0=A4H for -92
MOV IE,#82H ;IE=10000010 (bin) enable Timer 0
SETB TR0 ;Start Timer 0
BACK: MOV A,P0 ;get data from P0
MOV P1,A ;issue it to P1
SJMP BACK ;keep doing the loop unless interrupted by TF0
END
• Assume that INT1 pin is connected to a switch that is normally high.
Whenever it goes low, it should turn ON an LED. LED is connected to P1.3
and is normally OFF. When it is turned ON, it should stay ON for a fraction of
a second. As long as the switch is pressed low, the LED should stay ON.
ORG 0H
LJMP MAIN ;by-pass interrupt vector table
;ISR for INT1 to turn on LED
ORG 0013H ;INT1 ISR
SETB P1.3 ;turn ON LED
MOV R3,#255
BACK: DJNZ R3,BACK ;keep LED ON for a while
CLR P1.3 ;turn OFF the LED
RETI ;return from ISR
;--MAIN program for initialization
ORG 30H
MAIN: MOV IE,#10000100B ;enable external INT 1
HERE: SJMP HERE ;stay here until get interrupted
END
• Write a program using interrupts to simultaneously create 7 kHz
and 500 Hz square waves on P1.7 and P1.6.
8051 143s
71s
P1.7
2ms
P1.6 1ms
Solution
ORG 0
LJMP MAIN
ORG 000BH 8051 143s
LJMP T0ISR 71s
ORG 001BH P1.7
LJMP T1ISR
ORG 0030H
MAIN: MOV TMOD,#12H
MOV TH0,#-71
SETB TR0 2ms
SETB TR1
P1.6 1ms
MOV IE,#8AH
MOV IE,#8AH
SJMP $
T0ISR: CPL P1.7
RETI
T1ISR: CLR TR1
MOV TH1,#HIGH
MOV TL1,#LOW
SETB TR1
CPL P1.6
RETI
END
Timer ISR
• Notice that
• There is no need for a “CLR TFx” instruction in timer ISR
• 8051 clears the TF internally upon jumping to ISR
• Notice that
• We must reload timer in mode 1
• There is no need on mode 2 (timer auto reload)
External interrupt type control
• By low nibble of Timer control register TCON
• IE0 (IE1): External interrupt 0(1) edge flag.
• set by CPU when external interrupt edge (H-to-L) is detected.
• Not affected by H-to-L while ISR is executed
• Cleared by CPU when RETI executed.
• IT0 (IT1): interrupt 0 (1) type control bit.
• Set/cleared by software
• IT=1 edge trigger
• IT=0 low-level trigger
(MSB) (LSB)
TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
Timer 1 Timer0 for Interrupt
External Interrupts
Level-triggered (default)
INT0
)Pin 3.2( 0
IT0 0003
12 IE0 (TCON.3)
Edge-triggered
Level-triggered (default)
INT0
)Pin 3.3( 0
IT1 0013
13 IE1 (TCON.3)
Edge-triggered
Example of external interrupt
ORG 0000H
LJMP MAIN
;ISR for hardware external interrupt INT1
ORG 0013H
SETB P1.1
MOV R0,#200
WAIT:DJNZ R0,WAIT
CLR P1.1
RETI
;main program for initialization
ORG 30H
MAIN: SETB IT1 ;on negative edge of INT1
MOV IE,#10000100B
WAIT2: SJMP WAIT2
END
Interrupt Priorities
• What if two interrupt sources interrupt at the same time?
• The interrupt with the highest PRIORITY gets serviced first.
• All interrupts have a power on default priority order.
1. External interrupt 0 (INT0)
2. Timer interrupt0 (TF0)
3. External interrupt 1 (INT1)
4. Timer interrupt1 (TF1)
5. Serial communication (RI+TI)
• Priority can also be set to “high” or “low” by IP reg.
Interrupt Priorities (IP) Register
--- --- PT2 PS PT1 PX1 PT0 PX0
IP.7: Reserved
IP.6: Reserved
IP.5: Timer 2 interrupt priority bit(8052 only)
IP.4: Serial port interrupt priority bit
IP.3: Timer 1 interrupt priority bit
IP.2: External interrupt 1 priority bit
IP.1: Timer 0 interrupt priority bit
IP.0: External interrupt 0 priority bit
Interrupt Priorities Example
--- --- PT2 PS PT1 PX1 PT0 PX0
• MOV IP , #00000100B or SETB IP.2 gives priority order
1. Int1
2. Int0
3. Timer0
4. Timer1
5. Serial
• MOV IP , #00001100B gives priority order
1. Int1
2. Timer1
3. Int0
4. Timer0
5. Serial
Interrupt inside an interrupt
--- --- PT2 PS PT1 PX1 PT0 PX0
A high-priority interrupt can interrupt a low-priority interrupt
All interrupt are latched internally
Low-priority interrupt wait until 8051 has finished servicing the high-
priority interrupt