You are on page 1of 228

CHƯƠNG 2.

VI ĐIỀU KHIỂN MCS51


• 2.1 Kiến trúc trong
• 2.2 Tổ chức bộ nhớ
• 2.3 Chế độ truy nhập địa chỉ
• 2.4 Tập lệnh Mcs 51
• 2.5 Cấu trúc ngắt Mcs 51
( Microprocessor vs Microcontroller)
• So sánh Vi xử lý ( Microprocessor ) và Vi điều khiển( Microcontroller)
Microprocessor ( Vi xử lý )

3
Microprocessor (Cont…)

4
Microcontroller ( Vi điều khiển )

5
Microcontroller (Cont…)

6
Chương 2. Vi điều khiển MCS 8051
2.1 Kiến trúc trong RAR
128x8
RAM
4Kx8
ROM
PCH DPH P2 LATCH

PCL DPL PORT2

2.1.1 Sơ đồ khối và các chân RAM SENSE


P0 LATCH

BUFFER AM PS
Đặc điểm Vi điêu khiển 8051 :

INTERNAL BUS
P2 LATCH

CPU 8 bit với : PORT2


ALU
A IR

5 vectơ ngắt với 6 nguồn ngắt :


ROM
PLA

2 ngắt ngoài , 2 mức ưu tiên TM P2 TM P1 B

2 Bộ đếm/ định thời 16 bít PSW SP


CONTROL
ALU

1 cổng truyền tin nối tiếp song công


4 cổng vào ra song song ( 32 đường ) P0 LATCH SCON TCON IE P3 LATCH

RAM : 128 bytes /64k bytes PORT0 SBUF(REC)

SBUF(XM IT)
TM OD

TL0
IP

INTERRUPT
PORT3

CONTROL

ROM/EPROM : 4 K byte /64 kbytes SERIAL


PORT
TH0

TL1

TH1

TIM ER
CONTROL
Sơ đồ khối 8051Microcontroller
Oscillator 4096 Bytes 128 Bytes Two 16 Bit
and timing Program Data Timer/Event
Memory Memory Counters

Internal data bus


8051
CPU

64 K Byte Bus Programmable Programmable


Expansion I/O Serial Port Full
Control Duplex UART
Synchronous Shifter
subsystem interrupts

Control Parallel ports Serial Output


External interrupts Address Data Bus Serial Input
TxD
INT0, INT1 I/O pins RxD
Chương 2
Intel 8051: Mô tả các chân tín hiệu
VSS - Ground: 0V
VCC VSS
VCC - Power Supply
X T AL 1
P0.0-P0.7 - Port 0, Đặc điểm :

PORT 0
AD D R E S S AN D
-Open drain ( Cực máng để hở) D AT A B U S

cổng vào/ra 2 chiều X T AL 2

RST
-Muốn sử dụng như đầu vào Trở

PORT 1
E A/V p p
kháng cao thì trước tiên phải viết 1 ra PSEN
AL E /P R O G
-Là Tín hiệu dồn kênh Data/Address

SECONDARY FUNCTIONS
R xD

( D0-D7/A0-A7) khi truy cập bộ nhớ T xD

PORT 3

PORT 2
IN T 0
ngoài ( external program and data IN T 1
AD D R E S S B U S

memory) T0
T1
WR
RD
Intel 8051: Mô tả các chân tín hiệu Chương 2
P2.0-P2.7 - Port 2 • Port 3 gồm các tín hiệu:
- Cổng vào/ ra song song 2 chiều, có điện • RxD - Serial input port
trở treo bên trong • TxD - Serial output port
- Muốn sử dụng như đầu vào Trở kháng • INT0 - External interrupt
cao thì trước tiên phải viết 1 ra
• INT1 - External interrupt
- Sử dụng như Address bus ( A8-A15 ) Khi
truy cập bộ nhớ ngoài (external program
• T0 - Timer 0 external input
and data memory ) • T1 - Timer 1 external input
P3.0-P3.7 - Port 3 • WR - External data memory
- Cổng vào/ ra song song 2 chiều, có điện write strobe
trở treo bên trong • RD - External data memory
- Muốn sử dụng như đầu vào Trở kháng read strobe
cao thì trước tiên phải viết 1 ra.
Intel 8051: Mô tả các chân tín hiệu Chương 2
• RST - Reset • EA - External Access Enable
• Mức cao ở chân RESET trong 2 • EA : Để truy cập được bộ nhớ
chu kỳ máy sẽ RESET 8051 chương trình ngoài thì EA=0.
• ALE - Address Latch Enable • XTAL1 - Crystal 1
• Tín hiệu điều khiển chốt 8 bit địa chỉ Chân dao động thạch anh 1
thấp A0-A7 khi truy cập bộ nhớ • XTAL2 - Crystal 2
ngoài • Chân dao động thạch anh 2
• PSEN - Program Store Enable
• Tín hiệu điều khiển đọc bộ nhớ
chương trình ngoài

11/175
Chương 2
Intel 8051: Cấu hình
chân 44 34
P 1 .0
P 1 .1
1

2
40

39
Vcc
P 0 .0 /A D 0
P 1 .2 3 38 P 0 .1 /A D 1
1 33
P 1 .3 4 37 P 0 .2 /A D 2
P 1 .4 5 36 P 0 .3 /A D 3
PLCC P 1 .5 6 35 P 0 .4 /A D 4
P 1 .6 7 34 P 0 .5 /A D 5
11 23 P 1 .7 8 33 P 0 .6 /A D 6
RST 9 32 P 0 .6 /A D 6
R x D /P 3 .0 10 31 EA
12 22 T xD/ 11 30 ALE
1 P1.5 16 VSS 31 P0.6/AD6 P 3 .1
2 P1.6 17 NIC 32 P0.5/AD5 IN T 0 /P 3 .2 12 29 PSEN
3 P1.7 18 P2.0/A8 33 P0.4/AD4
4 RST 19 P2.1/A9 34 P0.3/AD3 IN T 1 /P 3 .3 13 28 P 2 .7 /A 1 5
5 P3.0/RxD 20 P2.2/A10 35 P0.2/AD2 T 0 /P 3 .4 14 27 P 2 .6 /A 1 4
6 NIC 21 P2.3/A11 36 P0.1/AD1
7 P3.1/TxD 22 P2.4/A12 37 P0.0/AD0 T 1 /P 3 .5 15 26 P 2 .5 /A 1 3
8 P3.2/INT0 23 P2.5/A13 38 VCC W R /P 3 .6 16 25 P 2 .4 /A 1 2
9 P3.3/INT1 24 P2.6/A14 39 NIC
10 P3.4/T0 25 P2.7/A15 40 P1.0 R D /P 3 .7 17 24 P 2 .3 /A 1 1
11 P3.5/T1 26 PSEN 41 P1.1 XT AL2 18 23 P 2 .2 /A 1 0
12 P3.6/WR 27 ALE 42 P1.2
13 P3.4/RD 28 NIC 43 P1.3 XT AL1 19 22 P 2 .1 /A 9
14 XTAL2 29 EA 44 P1.4
Vss 20 21 P 2 .0 /A 8
15 XTAL1 30 P0.7/AD7
12/
175
Intel 8051: Chương 2
• CPU ( Central Processing Unit )CPU
gồm :
• 8 bit ALU ( Ảrithmetic and Logic RAR
128x8
RAM
4Kx8
ROM
PCH

PCL
DPH

DPL
P2 LATCH

PORT2

Unit ) : Đơn vị xử lý số học logic. P0 LATCH

+,-*/ , AND, OR , NOT với thanh RAM


BUFFER
SENSE
AM PS

chứa A, thanh ghi B, Thanh ghi

INTERNAL BUS
P2 LATCH

từ trạng thái PSW và con trỏ PORT2


ALU

ngăn xếp SP
A IR
ROM
PLA

• 16 –bit Program Counter (PC)- TM P2 TM P1 B

Bộ đếm chương trình 16 bit, PCH PSW SP


CONTROL

và PCL
ALU

• Thanh ghi con trỏ dữ liệu DPTR


P0 LATCH SCON TCON IE P3 LATCH

( Data Pointer ) 16 bit, chia thành PORT0 SBUF(REC) TM OD IP PORT3

DPH và DPL SBUF(XM IT)

SERIAL
TL0

TH0
INTERRUPT
CONTROL

PORT
TL1

TH1

TIM ER
CONTROL
Intel 8051: CPU Chương 2

• Khối xử lý số học logic ALU có thể thao tác với toán hạng 1 bit hoặc 8 bit
• Đặc điểm này khiến cho 8051 phù hợp với các ứng dụng điều khiển
• Có tất cả 51 tác vụ riêng biệt ( Move and manipulate ) với 3 kiểu dữ liệu :
• Boolean (1-bit)
• Byte (8-bits)
• Address (16-bits)
Chương 2
Intel 8051: CPU
• Instruction types ( Các kiểu lệnh ) :
• Arithmetic Operations ( Lệnh số học )
• Logic Operations for Byte Variables ( Lệnh Logic với biến byte)
• Data Transfer Instructions ( Lệnh chuyển số liệu )
• Boolean Variable Manipulation ( Lệnh logic với biến bit )
• Program Branching and Machine Control( Rẽ nhánh chương trình
và điều khiển máy )
Chương 2
Power and Ground
• Power (Nguồn cung cấp ) :
Vcc(bipolar,c="collector"), Sử dụng transistor BJT
Vdd (FET, d = drain), sử dụng MOSFET
• 5V cho TTL ( Vcc)
• 1.9V to 3.3V cho (CMOS) ( Vdd)

• GND: ground (0V)


Chương 2
Các loại nguồn Pin cho Vcc:
• Pin khô : 1.5V, 3.0V, 4.5V, ... 9V

• Nạp được : 1.2V, 2.4V, ...

• Lithium Ion: 3.7-4.2 V

• Coin cell: 3V
Chương 2
Intel 8051: The On-Chip
•Oscillator
Intel 8051 microcontrollers have
an on-chip oscillator Q U AR TZ C R YS TAL O R 8051
C E R AM IC R E S O N ATO R
• resonators are connected
between XTAL1 and XTAL2 pins
C1
XTAL2
• external oscillators (HMOS or
CMOS)
C2
XTAL1
VSS

18/175
Chương 2
Intel 8051: Reset

• Chân RESET là chân RST , có đầu vào là Schmitt Trigger


• Bằng cách giữ chân RST ở mức cao trong 2 chu kỳ máy – tức 24 chu kỳ dao
động (two machine cycles -24 oscillator periods) trong khi mạch dao động
đang chạy
(while the oscillator is running)
• Chân RST được lấy mẫu trong S5P2 của mỗi chu kỳ máy .
• Khi chân RST ở mức cao thì các chân ALE và PSEN được treo lên mức cao
• Nếu điều khiển chân ALE và PSEN xuống thấp trong khi chân RST đang tích
cực có thể làm cho 8051 đi vào trạng thái không xác định.
Chương 2
Intel 8051: Reset
S5 S6 S1 S2 S3 S4 S5 S6 S1 S2 S3 S4 S5 S6 S1 S2 S3

RST
IN T E R N AL R E S E T S IG N AL
S AM P L E S AM P L E
RST RST

AL E

PSEN

P0 IN IN IN IN IN IN
S. A0-A7 S. A0-A7 S. A0-A7 S. A0-A7 S. A0-A7 S.
IN IN IN IN IN IN

11 O S C . P E R IO D S 19 O S C . P E R IO D S
Chương 2
Intel 8051: Power On Reset (Cold Reset )
• Chân RST phải giữ ở mức cao đủ lâu ( tối thiểu lớn hơn thời gian
Mạch dao động khởi động + 2 chu kỳ máy ( 24 chu kỳ clock))
• Thời gian khởi động oscillator phụ thuộc vào tần số oscillator
• Các chân cổng (Port pins ) sẽ ở trạng thái ngẫu nhiên trong khi
oscillator khởi động cho đến khi thuật toán RESET bên trong ghi giá
trị 1 ra các cổng ra Từ P0 đến P3. Muốn các cổng này về mức 0 thì ở
đầu chương trình phải có các câu lệnh xóa các cổng này về 0.
• Cấp nguồn cho 8051 với tín hiệu RST không chuẩn sẽ khiến CPU thực
hiện chương trình ở địa chỉ không xác định ( PC không nạp được
RESET vector )

21/175
Chương 2
Reset (RST)
• “RESET cứng"(Giữ chân RST cao trong 2 chu kỳ máy)
• Nạp PC= 0000h (Rsset vector), Xóa các thanh ghi,
, Set các port ( P0-P3) =11111111... , SP=07 h
• Hai tình huống
• Power-on reset (Khi mới bật nguồn )

• Sử dụng phím RESET (Nếu


Chương 2
Power on Reset and Reset switch

reset
How Power-on Reset works
Vcap+
Vcap-

Vcap+
5V
Vcap-
Reset switch (Warm Re
Vcap+

Vcap-
Chương 2
Power-up Reset Values
• PC: 0000H • DPTR: 0000H
• ACC, B: 00H • PSW: 00H
• SP: 07H • P0..P3: FFH
Chương 2
EA: External Access
• Đầu vào: Phải nối với GND hoặc Vcc
• Tích cực thấp
• EA nối GND: Sử dụng ROM ngoài chứa chương trình

• EA nối Vcc : Sử dụng ROM trong chứa chương trình

• Không được để hở chân EA


Chương 2

PSEN: program store enable


• Tín hiệu ra , "output enable" cho ROM , Tích cực thấp

• PSEN = 0 (nối GND): Cho phép ROM đưa dữ liệu ra

• PSEN =1(nối Vcc): đầu ra ROM Cao trở ( HiZ )


Chương 2

ALE: Address latch enable


• Đầu ra, tích cực cao

• Mục đích : Tín hiệu ra để điều khiển “address latch"

• “address latch" là thanh ghi chứa 8 bít địa chỉ thấp

A0-A7 khi truy cập bộ nhớ ngoài


• Tại sao ? Vì cổng P0 là tín hiệu dồn kênh địa chỉ / dữ

liệu ( AD0 – AD7) nên địa chỉ phải được chốt


Chương 2
Schematic for ALE
Chương 2
2.1.2 Các thanh ghi và SFR
Chương 2
2.1.2. ( Các thanh ghi trong 8051)

Các thanh ghi trong 8051 gồm :


Chương 2
PC ( Progam Counter )
• PC là Bộ đếm chương trình 16 bít
• PC là thanh ghi duy nhất không có địa chỉ trong
• PC chứa địa chỉ ô nhớ của câu lệnh sẽ thực hiện
• Bộ nhớ chương trình ROM trong ở địa chỉ 0000H đến 0FFF H ( 4 kbytes),
ROM ngoài từ địa chỉ trên 0FFFH
• Bộ nhớ chương trình có thể là toàn bộ ROM ngoài từ địa chỉ 0000H đến
FFFFH
• PC tự động tăng lên 1 sau khi thực hiện xong 1 lệnh
‰PC trỏ đến địa chỉ của câu lệnh tiếp theo
PROGRAM
COUNTER AND
mà Vi xử lý sẽ thực hiện
ROM SPACE ¾ Sau khi CPU nạp lệnh từ bộ nhớ chương trình ROM
PC sẽ tự động tăng lên 1 để trỏ đến câu lệnh tiếp theo
Program
Counter
‰ PC dài 16 bits
 Điều đó có nghĩa nó có thể truy cập bộ nhớ
Chương trình có dung lượng tối đa 64Kbytes có
địa chỉ từ 0000 đến FFFFH,
Chương 2
‰ Với 8051 sau khi RESET thì PC = 0000H
PROGRAM
COUNTER AND
ROM SPACE ¾ Program Counter PC = 0000H

Power up ¾ Do đó câu lệnh đầu tiên phải được


nạp vào bộ nhớ ROM ở địa chỉ 0000H,

¾ Chúng ta đạt được điều này bằng cách


sử dụng lệnh giả ORG 0h (Directive)
trong chương trình chính
‰ Ví dụ file listing chương trình bố trí
PROGRAM Trong bộ nhớ ROM
COUNTER AND 1 0000 ORG 0H ;start (origin) at 0

ROM SPACE 2
3
0000
0002
7D25
7F34
MOV
MOV
R5,#25H
R7,#34H
;load 25H into R5
;load 34H into R7
4 0004 7400 MOV A,#0 ;load 0 into A
5 0006 2D ADD A,R5 ;add contents of R5 to A
Placing Code in ;now A = A + R5
6 0007 2F ADD A,R7 ;add contents of R7 to A
ROM ;now A = A + R7
7 0008 2412 ADD A,#12H ;add to A value 12H
;now A = A + 12H
8 000A 80EF HERE: SJMP HERE ;stay in this loop
9 000C END ;end of asm source file

ROM Address Machine Language Assembly Language


0000 7D25 MOV R5, #25H
0002 7F34 MOV R7, #34H
0004 7400 MOV A, #0
0006 2D ADD A, R5
0007 2F ADD A, R7
0008 2412 ADD A, #12H
000A 80EF HERE: SJMP HERE
Sau khi chương trình được nạp vào ROM,
‰
PROGRAM
COUNTER AND
Mã lệnh và toán hạng được sắp xếp trong
ROM SPACE Bộ nhớ ROM từ địa chỉ 0000H
ROM contents
Address Code
Placing Code in
0000 7D
ROM 0001 25
(cont’) 0002 7F
0003 34
0004 74
0005 00
0006 2D
0007 2F
0008 24
0009 12
000A 80
000B FE
‰ Mô tả từng bước thực hiện chương
PROGRAM
COUNTER AND
Trình của 8051 sau khi bật nguồn
ROM SPACE
1. Khi 8051 được cấp nguồn lần đầu , PC nạp
Executing 0000h và bắt đầu nạp câu lệnh ở địa chỉ
Program 0000h trong bộ nhớ chương trình ROM
 Khi thực hiện mã lệnh 7D, CPU đọc giá trị 25 và
nạp nó vào thanh ghi R5
 Câu lệnh kết thúc, và sau đó PC tăng lên 1 để trỏ
đến địa chỉ 0002, tại đó chứa mã lệnh 7F

2. Khi thực hiện mã lệnh 7F, giá trị 34H được


chuyển vào thanh ghi R7
ƒ Sau đó nội dung PC tăng lên 0004
(tiếp theo )

PROGRAM 3. Câu lệnh ở địa chỉ 0004 sẽ được thực hiện


COUNTER AND và bây giờ PC = 0006
ROM SPACE 4. Tương tự với các câu lệnh tiếp theo
Executing
Program
(cont’)
Thanh chứa A và thanh ghi B
• Thanh chứa A là thanh ghi quan trọng nhất trong CPU, được sử
dụng trong hầu hết các thao tác và chỉ định bắt buộc sử dụng
trong các câu lệnh hợp ngữ sau :
• Các lệnh thực hiện phép tính số học : cộng, trừ, nhân chia nguyên,
phép tính thao tác bit
• Trong các lệnh vào/ra dữ liệu với bộ nhớ dữ liệu RAM ngoài
• ( MOVX A,@DPTR hoặc MOVX @DPTR,A)

• Thanh ghi B sử dụng với thanh ghi A trong các phép tính nhân
và chia nguyên, ngoài ra còn sử dụng như 1 thanh ghi chứa dữ
liệu
‰ Program status word (PSW)
FLAG BITS AND
PSW REGISTER Thanh ghi từ trạng thái, còn gọi là thanh ghi cờ
, là thanh ghi 8 bit
Program Status ¾Chỉ sử dụng 6 bit
Word ƒ Cờ nhớ CY (carry), Cờ nhớ phụ AC (auxiliary carry),
Cờ chẵn lẻ P (parity), và cờ tràn OV (overflow)
- Đây gọi là các cờ trạng thái , tức là nó phản ánh các trạng
thái của kết quả phép tính khi thực hiện xong câu lệnh
ƒ Bít PSW3 and PSW4 được sử dụng làm bít RS0 và
RS1, để chọn bank thanh ghi R0 – R7 ( Bank 0 – Bank 3)
CY AC F0 RS1 RS0 OV -- P
FLAG BITS AND Nhớ từ bit D3 to D4
CY PSW.7 Carry flag.
PSW REGISTER
AC PSW.6 Auxiliary carry flag. Nhớ từ bit D7
-- PSW.5 Available to the user for general purpose
Program Status RS1 PSW.4 Register Bank selector bit 1.
Word (cont’) RS0 PSW.3 Register Bank selector bit 0.
OV PSW.2 Overflow flag.
Phản ánh số bit bằng 1
Kết quả khi thực -- PSW.1 User definable bit.
Trong thanh ghi A
Hiện phép tính P PSW.0 Parity flag. Cờ chẵn lẻ, thay đổi sau mỗi phép tính
Với số có dấu Chỉ ra tổng số bit bằng 1 trong thanh chứa A
Quá lớn là một số chẵn hay lẻ .
Làm cho bit cao
Nhất tràn sang RS1 RS0 Register Bank Address
Bit dấu
0 0 0 00H - 07H
0 1 1 08H - 0FH
1 0 2 10H - 17H
1 1 3 18H - 1FH
Intel 8051: PSW
7 6 5 4 3 2 1 0
PSW CY AC F0 RS1 RS0 OV - P

Carry flag Parity flag


Auxiliary Carry flag Overflow flag
Flag 0 Registar Bank
Registar Bank Select bit 1
Select bit 1

• Auxiliary Carry flag : (AC) Cờ nhớ phụ sử dụng khi thực hiện phép tính với số BCD
• CY : Cờ nhớ ; Cờ CY =1 khi có nhớ từ bit D7 sang
• P : Cờ chẵn lẻ ; PY = 1 khi tổng số bit bằng 1 trong thanh chứa A là 1 số chắn, ngược lại P=0
• OV : Cờ tràn ;
• Flag 0 ( F0) : Dành cho người sử dụng
• Nội dung (RS1, RS0) để chọn Bank thanh ghi Ro-R7 như sau : 00 - Bank 0 [0x00-0x07], 01 - Bank 1
[0x08-0x0f], 10 - Bank 2 [ 0x10-0x17], 11 - Bank 3 [0x18-0x1F]
Câu lệnh tác động đến cờ
FLAG BITS AND Instruction CY OV AC
PSW REGISTER ADD X X X
ADDC X X X

ADD SUBB X X X
MUL 0 X
Instruction And DIV 0 X
PSW DA X
RPC X
PLC X
SETB C 1
CLR C 0
CPL C X
ANL C, bit X
ANL C, /bit X
ORL C, bit X
ORL C, /bit X
MOV C, bit X
CJNE X
‰ 8051 có 128 bytes RAM trong
REGISTER ¾ được gán địa chỉ từ 00 đến 7FH
BANKS AND
STACK ‰ 128 bytes được chia thành các nhóm:

RAM Memory 1) 32 bytes từ địa chỉ 00h đến 1Fh là cho 4 bank
Space
Allocation Thanh ghi R0- R7 và Stack

2) 16 bytes tiếp theo từ địa chỉ 20H đến 2FH là


vùng định địa chỉ bit có thể đọc/ ghi

3) Còn 80 bytes từ địa chỉ 30H đến 7FH sử


dụng để chứa dự liệu đọc/ ghi được
RAM Allocation in 8051

8051 7F

REGISTER Scratch pad RAM

BANKS AND 30
STACK 2F
Bit-Addressable RAM

RAM Memory 20
Space 1F
Register Bank 3
Allocation
18
(cont’) 17 Register Bank 2
10
0F
Register Bank 1 (stack)
08
07
Register Bank 0

00
‰ 32 bytes RAM trong được chia thành 4
8051
Bank thanh ghi, mỗi bank có 8 thanh ghi
REGISTER
BANKS AND Ký hiệu R0-R7
STACK ¾Các ô nhớ RAM có địa chỉ từ 0 to 7 là cho bank 0
Của R0-R7, Với Bank 0 thì R0 là ô nhớ RAM có địa chỉ 0,
Register Banks Tương tự R7 là ô nhớ RAM có địa chỉ 7.
 Việc sử dụng thanh ghi R0, R1, sẽ thuận tiện hơn
việc sử dụng các ô nhớ RAM với địa chỉ 0,1

‰ Sau khi RESET 8051 mặc định chọn Bank 0


8051 Các bank thanh ghi và địa chỉ RAM
REGISTER
Bank 0 Bank 1 Bank 2 Bank 3
BANKS AND
STACK 7 R7 F R7 17 R7 1F R7

6 R6 E R6 16 R6 1E R6

Register Banks 5 R5 D R5 15 R5 1D R5

(cont’) 4 R4 C R4 14 R4 1C R4

3 R3 B R3 13 R3 1B R3

2 R2 A R2 12 R2 1A R2
1 R1 9 R1 11 R1 19 R1

0 R0 8 R0 10 R0 18 R0
‰ Chúng ta có thể chọn bank thanh ghi bằng
8051
REGISTER
Cách lập trình birt RS0 và RS1 trong PSW
BANKS AND ¾ Bit D4 và D3 trong PSW được sử dụng để lập trình
STACK Chọn bank thanh ghi từ bank 0 đến bank 3
¾ Sử dụng câu lệnh SETB và CLR
Register Banks Để thay đổi bit PSW.4 và PSW.3
(cont’)
PSW bank selection
RS1(PSW.4) RS0(PSW.3)
Bank 0 0 0
Bank 1 0 1
Bank 2 1 0
Bank 3 1 1
Example 2-5
8051
MOV R0, #99H ;load R0 with 99H
REGISTER MOV R1, #85H ;load R1 with 85H
BANKS AND
STACK
Example 2-6

Register Banks MOV 00, #99H ;RAM location 00H has 99H
MOV 01, #85H ;RAM location 01H has 85H
(cont’)

Example 2-7
SETB PSW.4 ;select bank 2
MOV R0, #99H ;RAM location 10H has 99H
MOV R1, #85H ;RAM location 11H has 85H
 Ngăn xếp ( Stack) là một phần của
8051 bộ nhớ RAM được CPU sử dụng để
REGISTER chứa thông tin tạm thời
BANKS AND
¾ Thông tin này có thể là dữ liệu hoặc địa chỉ
STACK

Stack ‰ Thanh ghi sử dụng để truy cập stack


Gọi là SP (stack pointer)
¾ Thanh ghi SP trong 8051 dài 8 bit, như
vậy có thể nhận giá trị từ 00 đến FFH

¾ Sau khi RESET 8051 thì SP = 07

ƒ Như vậy ô nhớ RAM có địa chỉ bằng 08 là vị trí đầu


tiên được 8051 sử dụng làm Stack
‰ Để cất vào ngăn xếp 1 thanh ghi, ô nhớ
8051
Ta sử dụng lệnh PUSH
REGISTER
BANKS AND ¾ SP luôn trỏ đến đỉnh của ngăn xếp
STACK Lệnh PUSH chỉ sử dụng chế độ địa chỉ trực tiếp
¾ Ví dụ lệnh PUSH 40h ; SP sẽ tăng lên 1, sau đó
Stack Nội dung ô nhớ ở địa chỉ 40h sẽ cất vào ngăn xếp
(cont’)
ƒ Để lấy dữ liệu từ ngăn xếp vào 1 ô nhớ
trong CPU ta sử dụng lệnh POP
 Lệnh POP chỉ sử dụng chế độ địa chỉ trực tiếp
Ví dụ : Lệnh POP 40h ; Nội dung ô nhớ trỏ bới SP
được nạp vào ô nhớ có địa chỉ 40h, sau đó SP
giảm đi 1.
Example 2-8
8051
Show the stack and stack pointer from the following. Assume the
REGISTER default stack area.
BANKS AND MOV R6, #25H
STACK MOV R1, #12H
MOV R4, #0F3H
PUSH 6
Pushing onto PUSH 1
Stack PUSH 4
Solution:
After PUSH 6 After PUSH 1 After PUSH 4
0B 0B 0B 0B
0A 0A 0A 0A F3
09 09 09 12 09 12
08 08 25 08 25 08 25
Start SP = 07 SP = 08 SP = 09 SP = 0A
Example 2-9
8051
Examining the stack, show the contents of the register and SP after
REGISTER execution of the following instructions. All value are in hex.
BANKS AND POP 3 ; POP stack into R3
STACK POP 5 ; POP stack into R5
POP 2 ; POP stack into R2

Popping From Solution:


Stack
After POP 3 After POP 5 After POP 2
0B 54 0B 0B 0B
0A F9 0A F9 0A 0A
09 76 09 76 09 76 09
08 6C 08 6C 08 6C 08 6C
Start SP = 0B SP = 0A SP = 09 SP = 08
Because locations 20-2FH of RAM are reserved
for bit-addressable memory, so we can change the
SP to other RAM location by using the instruction
“MOV SP, #XX”
‰ CPU sử dụng Stack để cất địa chỉ của câu
8051
REGISTER lệnh nằm ngay sau lệnh CALL
BANKS AND
STACK CPU sẽ khôi phục lại địa chỉ này từ ngăn xếp khi
¾
gặp câu lệnh RET và tiếp tục thực hiện chương trình
CALL
Instruction And
Stack
 Sau khi Reset 8051 thì SP = 7, vậy các
8051 thanh ghi R0- R7 của Bank 1( có địa chỉ
REGISTER từ 8 – 15 ) có cùng địa chỉ với ngăn xếp
BANKS AND trỏ bởi SP.
STACK  Để tránh trùng địa chỉ chúng ta có thể
thay đổi SP trỏ sang địa chỉ khác.
Stack and Bank  Sau đây là một chương trình ví dụ sẽ nạp
1 Conflict  SP giá trị 5Fh; Vậy địa chỉ ô nhớ đầu tiên
 Sử dụng làm ngăn xếp là 60h
Example 2-10
8051 Examining the stack, show the contents of the register and SP after
REGISTER execution of the following instructions. All value are in hex.
BANKS AND MOV SP, #5FH ;make RAM location 60H
;first stack location
STACK MOV R2, #25H
MOV R1, #12H
MOV R4, #0F3H
Stack And Bank PUSH 2
1 Conflict PUSH 1
PUSH 4
(cont’)
Solution:
After PUSH 2 After PUSH 1 After PUSH 4
63 63 63 63
62 62 62 62 F3
61 61 61 12 61 12
60 60 25 60 25 60 25
Start SP = 5F SP = 60 SP = 61 SP = 62
DPTR
SFR
Intel 8051: SFR ( Thanh ghi chức năng đặc biệt )

• SFRs được truy cập như là 1 phần bộ nhớ RAM trong


• SFR chiếm các địa chỉ trong khoảng từ 80h đến FFh
• Mỗi thanh ghi SFR có địa chỉ và tên
• 8051 có 21 SFRs , vậy không phải tất cả các địa chỉ từ 80h
đến FFh được sử dụng cho SFR
• Việc sử dụng các địa chỉ khong dùng cho SFR sẽ gây kết quả
không mong muốn.
SFR
Intel 8051: SFR
0 1 2 3 4 5 6 7
F8 FF
F0 B F7
E8 EF
E0 ACC E7
D8 DF
D0 PSW D7
C8 CF
C0 C7
B8 IP BF
B0 P3 B7
A8 IE AF
A0 P2 A7
98 SCON SBUF 9F
90 T1 97
88 TCON TMOD TL0 TL1 TH0 TH1 8F
80 T0 SP DPL DPH PCON 87
Intel 8051: SFR
• Accumulator (A) • The Stack Pointer is initialized on
• Accumulator register 0x07after a reset, and this causes
stack to begin at location 0x08
• B Register (B)
• Used during multiply and • Data Pointer(DPTR)
divide operations • Consist high byte (DPH) and low
byte (DPL)
• PSW
• It may be manipulated as a 16-bit
• Contains program status register or as two independent 8-
information bit registers
• Stack Pointer (SP)
• Eight bits wide
• Stack may reside anywhere
in on chip RAM
2.2 Tổ chức bộ nhớ 8051

Bộ nhớ chương trình ( Program Memory) tách biệt với bộ nhớ dữ liệu
Mỗi loại bộ nhớ có cơ chế định địa chỉ riêng,có tín hiệu điều khiển
khác nhau, và chức năng khác nhau
Kiến trúc hỗ trợ những loại bộ nhớ sau ở mức phần cứng :
On - chip program memory ( Bộ nhớ chương trình On-chip)
On - chip data memory ( Bộ nhỡ dữ liệu On-chip)
Off - chip program memory ( Bộ nhớ chương trình ngoài chip)
Off - chip data memory ( Bộ nhỡ dữ liệu ngoài chip)
On chip special function registers - Thanh ghi chức năng On –chip
Intel 8051: Memory Organization
• Program (Code) memory : Bộ nhớ chương trình
• Chứa chương trình mà 8051 sẽ thực hiện
• Giới hạn dung lựợng 64K
• on-chip có thể ROM hoặc EPROM
• Bộ nhớ chương trình ngoài có thể sử dụng ROM hoặc EPROM
• Có thể sử dụng Flash RAM để chứa chương trình
• Có thể sử dụng kết hợp cả bộ nhớ trong và bộ nhớ ngoài
• (e.g. 4 K on-chip and 64 KB off-chip)
Intel 8051: Memory Organization
• On-chip Data memory ( Bộ nhớ dữ liệu On – chip)
• Có 2 loại :
• RAM trong 128 byte ;và
• Special Function Register (SFR) – Thanh ghi chức năng đặc biệt
• RAM trong on-chip có tốc độ cao nhất
• Khi 8051 Reset thì nội dung RAM trong sẽ bị xóa hết
• Special Function Registers (SFRs) là miền bộ nhớ kiểm soát các chức
năng đặc biệt của 8051. SFR có tên và có địa chỉ trong RAM.
• Bộ nhớ dữ liệu RAM ngoài : Có dung lượng tối đa 64 k bytes
Intel 8051: Memory Access ( Truy cập bộ nhớ )
• PORT 2 : Byte cao địa chỉ EA
PORT2 A8-A15 A8-A15 A8-A15
( A8-A15)
PORT0 AD0-AD7 A0-A7 A0-A7 A0-A7

• PORT 0 : Dồn kênh địa chỉ/ LATCH

Static RAM

ROM
"0" CS
RD "0" CS
dữ liệu ( A0-A7/D0-D7) theo ALE LE WR OE

thời gian 8051


D0-D7

• Signal ALE: Điều khiển chốt


byte thấp địa chỉ ( A0-A7)
vào bộ chốt bên ngoài
PSEN
RD
WR

64 Kbytes - Program memory (external)


64 Kbytes - Data Memory
Intel 8051: Memory Access ( Timming)

Đọc bộ nhớ chương trình Đọc bộ nhớ dữ liệu


S T AG E 1 S T AG E 2 S T AG E 3 S T AG E 4 S T AG E 5 S T AG E 6 ST AG E 4 ST AG E 5 ST AG E 6 ST AG E 1 ST AG E 2 ST AG E 3
P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2

X T AL 1 XT AL1

AL E ALE

PSEN RD

IN S . IN S . IN S . FLO AT d ata FLO AT


A0-A7 A0-A7 A 0-A 7
P0 IN IN IN P0 in

A8-A15 A8-A15 A 8-A 15 A 8-A 15


P2 P2
Intel 8051: Program Memory
PROGRAM M EM ORY
• Dung lượng tối đa 64K bytes
0xFFFF
• PSEN: Tín hiệu điều khiển đọc bộ nhớ chương
trình ngoài

EXTERNAL
• PSEN: Không tích cực nếu đọc từ bộ nhớ chương
trình bên trong
• EA = 1 : Truy cập Bộ nhớ ROM trong/ EA=0 truy
cập bộ nhớ ROM ngoài
• ROM trong chiếm địa chỉ từ 0000h đến 0FFFh
• Chương trình có địa chỉ cao hơn 0FFFh sẽ tự
động được đọc từ ROM ngoài EA = 0 EA = 1

0x0000

PSEN
Intel 8051: Program Memory
• Reset Vector - 0000h LOW ER PART OF PROGRAM MEMORY

• Mỗi ngắt được gán một địa chỉ cố định


trong bộ nhớ chương trình ( gọi là
Interrupt Vector )
0x0028
• Nếu ngắt không sử dụng thì phần
không gian bộ nhớ này có thể chứa 0x0023
chương trình.
0x0018
INTERRPUT
LOCATIONS
0x0013
8 BYTES
0x0008

0x0003

RESET 0x0000
Intel 8051: Data Memory
DAT A MEMO RY
• Bộ nhớ dữ liệu ngoài có dung lượng 64K
0xFFFF
• Truy cập sử dụng tín hiệu điều khiển RD và WR

EXTERNAL
IN T E R N A L

0xFF

0x00 0x0000

RD WR
Intel 8051: Data Memory
• 128 byte thấp ( 0x00-0x7F) : Truy cập trực INTERNAL
tiếp và gián tiếp 0xFF

• 128 byte cao : gồm 2 vùng riêng biệt :


ACCESSIBLE ACCESSIBLE
• Vùng nhớ RAM : Truy cập gián tiếp UPPER BY INDIRECT BY DIRECT
128 ADDRESSING ADDRESSING
• Vùng các thanh ghi SFR : Truy cập trực tiếp ONLY ONLY
• Nếu viết nhầm chế độ địa chỉ có thể dẫn
đến truy cập nhầm thanh ghi.
0x7F
SPECIAL
PORTS
FUNCTION
STATUS BITS
ACCESSIBLE REGISTERS
CONTOL BITS
LOWER BY DIRECT
TIMER REGISTERS
128 AND INDIRECT
STACK POINTER
ADDRESSING
ACCUMULATOR
(ETC.)

0x00
Intel 8051: Data Memory
• The lowest 32 bytes are grouped LOWER 128 BYTES OF
INTERNAL RAM
into 4 banks of 8 registers 0x7F
• Program instructions call out
these registers R0 through R7
• Two bits in the PSW
0x2F
selects register bank
BANK SELECT BITS BIT ADDRESSABLE SPACE
• Register instructions are shorter IN PSW (BIT ADDRESSES 0-7F)
• The next 16 bytes form a 0x20
block of bit-addressable space 0x1F
11
0x18
0x17 4 BANKS OF
10 8 REGISTERS
0x10 R0-R7
0x0F
01
0x08
0x07 RESET VALUE OF
00 STACK POINTER
0x00
Intel 8051: CPU Timing

S5 S6 S1 S2 S3 S4 S5 S6 S1 S2 S3 S4 S5
P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2 P1 P2

ALE
• The internal clock generator defines
the sequence of states that make up a machine cycle
• A machine cycle consists of 6 states, numbered S1 through S6
• Each state time lasts for two oscillator periods
• Each state is then divided into a Phase 1 and Phase 2 half
Cách tính thời gian thực hiện 1 lệnh
2.3. Chế độ truy nhập địa chỉ
‰ CPU có thể truy cập dữ liệu theo nhiều cách khác nhau
, gọi là chế độ địa chỉ ( addressing mode)

 Immediate : Chế độ tức thì


¾ Register : Chế độ thanh ghi

¾ Direct : Chế độ trực tiếp


¾ Register indirect : Chế độ gián tiếp thanh ghi

¾ Indexed : Chế độ chỉ số


‰ Chế độ tức thì :Toán hạng nguồn là 1 hằng số
IMMEDIATE
ADDRESSING ¾ Hằng số tức thì phải đặt sau dấu “#”
MODE
¾ Có thể nạp giá trị vào bất kỳ thanh ghi nào,
kể cả DPTR
ƒ DPTR có thể truy cập như 2 thanh ghi 8 bit là DPH ( byte cao )
và DPL ( byte thấp )

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


MOV R4,#62 ;load 62 into R4
MOV B,#40H ;load 40H into B
MOV DPTR,#4521H ;DPTR=4512H
MOV DPL,#21H ;This is the same
MOV DPH,#45H ;as above
;Không hợp lệ !! Value > 65535
(FFFFH) MOV DPTR,#68975
‰ Chúng ta có thể sử dụng EQU directive
IMMEDIATE để truy cập dữ liệu như 1 hằng số có tên
ADDRESSING
MODE Count EQU 30
(cont’)
MOV R4,#COUNT ;R4=1EH
MOV DPTR,#MYDATA ;DPTR=200H

ORG 200H
MYDATA: DB “America”

‰ Có thể sử dụng immediate addressing mode


để gửi dữ liệu ra cổng ra 8051
MOV P1,#55H
‰ Chế độ địa chỉ thanh ghi
REGISTER
ADDRESSING MOV A,R0 ;copy contents of R0 into A
MOV R2,A ;copy contents of A into R2
MODE ADD A,R5 ;add contents of R5 to A
ADD A,R7 ;add contents of R7 to A
MOV R6,A ;save accumulator in R6

‰ Thanh ghi Nguồn và đích phải cùng độ dài


¾ MOV DPTR,A Sẽ báo lỗi

MOV DPTR,#25F5H
MOV R7,DPL
MOV R6,DPH

‰ Không cho phép chuyển giữa các thanh


ghi Rn
¾ MOV R4,R7 Sẽ báo lỗi
‰ Chế độ địa chỉ trực tiếp
ACCESSING
MEMORY
Thường sử dụng để truy cập bộ nhớ RAM
trong có địa chỉ từ 30 - 7FH
Direct ¾ Toàn bộ 128 bytes RAM trong có thể truy cập
Addressing Trực tiếp Direct addressing mode
Mode ¾ Các thanh ghi R0 – R7 truy cập bằng tên

MOV A,4 ; cũng có kết quả như


MOV A,R4 ;Copy nội dung R4 vào A

‰Ngược lại với immediate


addressing mode Register addressing mode

¾ Không có dấu “#” đứng trước operand


MOV R0,40H ;save content of 40H in R0
MOV 56H,A ;save content of A in 56H
‰ SFR (Special Function Register)
ACCESSING
MEMORY
Có thể truy cập trực tiếp bằng tên
Hoặc địa chỉ của nó
SFR Registers MOV 0E0H,#55H ;cũng giống như
and Their MOV A,#55h ;Nạp 55H vào A
Addresses MOV 0F0H,R0 ;cũng giống như
MOV B,R0 ;copy R0 vào B

‰ SFR registers có địa chỉ từ 80H đến FFH


¾ Không phải tất cả địa chỉ từ 80h đến FFh được
sử dụng cho SFR

¾ Các địa chỉ không sử dụng trong vùng 80H đến


FFH là dự trữ và người lập trình 8051 không
được sử dụng
Special Function Register (SFR) Addresses
Symbol Name Address
ACCESSING ACC* Accumulator 0E0H
MEMORY B* B register 0F0H
PSW* Program status word 0D0H
SFR Registers SP Stack pointer 81H
and Their DPTR Data pointer 2 bytes

Addresses DPL Low byte 82H

(cont’) DPH High byte 83H


P0* Port 0 80H
P1* Port 1 90H
P2* Port 2 0A0H
P3* Port 3 0B0H
IP* Interrupt priority control 0B8H
IE* Interrupt enable control 0A8H
… … …
Special Function Register (SFR) Addresses
Symbol Name Address
ACCESSING TMOD Timer/counter mode control 89H
MEMORY TCON* Timer/counter control 88H

T2CON* Timer/counter 2 control 0C8H


SFR Registers T2MOD Timer/counter mode control OC9H
and Their TH0 Timer/counter 0 high byte 8CH
Addresses TL0 Timer/counter 0 low byte 8AH
(cont’) TH1 Timer/counter 1 high byte 8DH
TL1 Timer/counter 1 low byte 8BH
TH2 Timer/counter 2 high byte 0CDH
TL2 Timer/counter 2 low byte 0CCH
RCAP2H T/C 2 capture register high byte 0CBH
RCAP2L T/C 2 capture register low byte 0CAH
SCON* Serial control 98H
SBUF Serial data buffer 99H
PCON Power ontrol 87H

* Bit addressable
Example 2-3-1
ACCESSING
Write code to send 55H to ports P1 and P2, using
MEMORY
(a) their names (b) their addresses

SFR Registers Solution :


(a) MOV A,#55H ;A=55H
and Their
MOV P1,A ;P1=55H
Addresses MOV P2,A ;P2=55H
(cont’)
(b) From Table 5-1, P1 address=80H; P2 address=A0H
MOV A,#55H ;A=55H
MOV 90H,A ;P1=55H
MOV 0A0H,A ;P2=55H
‰ Để truy cập Stack bằng lệnh PUSH hoặc POP
ACCESSING
Chỉ được dùng chế độ địa chỉ trực tiếp
MEMORY
¾ PUSH A Là sai
Stack and ¾ Muốn cất ACC vào Stack phải sử dụng
Direct PUSH 0E0H
Addressing Example 2-3-2
Mode Show the code to push R5 and A onto the stack and then pop them
back them into R2 and B, where B = A and R2 = R5

Solution:
PUSH 05 ;push R5 onto stack
PUSH 0E0H ;push register A onto stack
POP 0F0H ;pop top of stack into B
;now register B = register A
POP 02 ;pop top of stack into R2
;now R2=R5
Chế độ địa chỉ gián tiếp thanh ghi
ACCESSING
‰ Thanh ghi được dùng để chứa địa chỉ
MEMORY
của ô nhớ tại đó chứa dữ liệu
Register ¾ Chỉ có thanh ghi R0 and R1 được sử dụng
Indirect ¾ Thanh ghi R2 - R7 không được sử dụng trong
Addressing Chế độ địa chỉ này
Mode
‰ Khi sử dụng R0 and R1 để chứa địa
chỉ của ô nhớ RAM, cần phải có ký tự
“@” ở trước
MOV A,@R0; chuyển nội dung ô nhớ RAM;có
địa chỉ chứa trong R0 vào A
MOV @R1,B ;chuyển nội dung B vào RAM
;mà địa chỉ của nó chưa trong R1
Example 2-3-3
Write a program to copy the value 55H into RAM memory locations
ACCESSING 40H to 41H using
MEMORY (a) direct addressing mode, (b) register indirect addressing mode
without a loop, and (c) with a loop

Register Solution:
(a)
Indirect MOV A,#55H ;load A with value 55H
MOV 40H,A ;copy A to RAM location 40H
Addressing MOV 41H.A ;copy A to RAM location 41H
Mode (b)
MOV A,#55H ;load A with value 55H
(cont’) MOV R0,#40H ;load the pointer. R0=40H
MOV @R0,A ;copy A to RAM R0 points to
INC R0 ;increment pointer. Now R0=41h
MOV @R0,A ;copy A to RAM R0 points to
(c)
MOV A,#55H ;A=55H
MOV R0,#40H ;load pointer.R0=40H,
MOV R2,#02 ;load counter, R2=3
AGAIN: MOV @R0,A ;copy 55 to RAM R0 points to
INC R0 ;increment R0 pointer
DJNZ R2,AGAIN ;loop until counter = zero
‰ The advantage is that it makes
ACCESSING
MEMORY
accessing data dynamic rather than
static as in direct addressing mode
Register ¾ Không thể thực hiện vòng lặp nếu không sử dụng
Indirect Chế độ địa chỉ Gián tiếp thanh ghi
Addressing Example 2-3-4
Mode Write a program to clear 16 RAM locations starting at RAM address
(cont’) 60H
Solution:
CLR A ;A=0
MOV R1,#60H ;load pointer. R1=60H
MOV R7,#16 ;load counter, R7=16
AGAIN: MOV @R1,A ;clear RAM R1 points to
INC R1 ;increment R1 pointer
DJNZ R7,AGAIN ;loop until counter=zero
Example 2-3-5
ACCESSING
Write a program to copy a block of 10 bytes of data from 35H to 60H
MEMORY
Solution:
Register MOV R0,#35H;source pointer
MOV R1,#60H ;destination pointer
Indirect MOV R3,#10 ;counter
Addressing BACK: MOV A,@R0 ;get a byte from source
Mode MOV @R1,A ;copy it to destination
(cont’) INC R0 ;increment source pointer
INC R1 ;increment destination pointer
DJNZ R3,BACK ;keep doing for ten bytes
‰ R0 and R1 are the only registers that
ACCESSING
MEMORY
can be used for pointers in register
indirect addressing mode
Register ‰ Since R0 and R1 are 8 bits wide, their
Indirect use is limited to access any
Addressing
information in the internal RAM
Mode
(cont’) ‰ Whether accessing externally
connected RAM or on-chip ROM,
we need 16-bit pointer
¾ In such case, the DPTR register is used
‰ Indexed addressing mode is widely
ACCESSING
MEMORY
used in accessing data elements of
look-up table entries located in
Indexed the program ROM
Addressing ‰ The instruction used for this purpose is
Mode and MOVC A,@A+DPTR
On-chip ROM
¾ Use instruction MOVC, “C” means code
Access
¾ The contents of A are added to the 16-bit
register DPTR to form the 16-bit address
of the needed data
Example 2-3-6

ACCESSING In this program, assume that the word “USA” is burned into ROM
locations starting at 200H. And that the program is burned into ROM
MEMORY locations starting at 0. Analyze how the program works and state
chip ROM where “USA” is stored after this program is run.
Indexed Solution:
ORG 0000H ;burn into ROM starting at 0
DPTR=200H, A=0 MOV DPTR,#200H ;DPTR=200H look-up table addr
CLR A ;clear A(A=0)
R=200H, A=55H MOVC A,@A+DPTR ;get the char from code space
MOV R0,A ;save it in R0
DPTR=201H, A=55H INC DPTR ;DPTR=201 point to next char
CLR A ;clear A(A=0)
DPTR=201H, A=0 MOVC A,@A+DPTR ;get the next char R0=55H
MOV R1,A ;save it in R1
DPTR=201H, A=53H INC DPTR ;DPTR=202 point to next char
CLR A ;clear A(A=0)
DPTR=202H, A=53H MOVC A,@A+DPTR ;get the next char R1=53H
MOV R2,A ;save it in R2
Here: SJMP HERE ;stay here
;Data is burned into code space starting at 200H
202 A
201 S ORG 200H R2=41H
MYDATA:DB “USA”
200 U END ;end of program
‰ The look-up table allows access to
ACCESSING
elements of a frequently used table
MEMORY
with minimum operations
Look-up Table Example 2-3-7
Write a program to get the x value from P1 and send x 2 to P2,
(cont’)
continuously
Solution:
ORG 0
MOV DPTR,#300H ;LOAD TABLE ADDRESS
MOV A,#0FFH ;A=FF
MOV P1,A ;CONFIGURE P1 INPUT PORT
BACK:MOV A,P1 ;GET X
MOVC A,@A+DPTR ;GET X SQAURE FROM TABLE
MOV P2,A ;ISSUE IT TO P2
SJMP BACK ;KEEP DOING IT
ORG 300H
XSQR_TABLE:
DB 0,1,4,9,16,25,36,49,64,81
END
‰ Many microprocessors allow program
BIT to access registers and I/O ports in
ADDRESSES byte size only
¾ However, in many applications we need to
check a single bit
‰ One unique and powerful feature
of the 8051 is single-bit operation
¾ Single-bit instructions allow the
programmer to set, clear, move, and
complement individual bits of a port,
memory, or register
¾ It is registers, RAM, and I/O ports that
need to be bit-addressable
ƒ ROM, holding program code for execution, is not
bit-addressable
‰ The bit-addressable RAM location are
BIT 20H to 2FH
ADDRESSES ¾ These 16 bytes provide 128 bits of RAM
bit-addressability, since 16 × 8 = 128
Bit- ƒ 0 to 127 (in decimal) or 00 to 7FH
Addressable ¾ The first byte of internal RAM location 20H
RAM has bit address 0 to 7H
¾ The last byte of 2FH has bit address 78H
to 7FH
‰ Internal RAM locations 20-2FH
are both byte-addressable and
bit- addressable
¾ Bit address 00-7FH belong to RAM byte
addresses 20-2FH
¾ Bit address 80-F7H belong to SFR P0,
P1, …
7F

General purpose RAM


30

BIT 2F 7F 7E 7D 7C 7B 7A 79 78
2E 77 76 75 74 73 72 71 70
ADDRESSES 2D 6F 6E 6D 6C 6B 6A 69 68
2C 67 66 65 64 63 62 61 60

Bit-addressable 2B 5F 5E 5D 5C 5B 5A 59 58
Bit- locations 2A 57 56 55 54 53 52 51 50

Addressable 29
28
4F
47
4E
46
4D
45
4C
44
4B
43
4A
42
49
41
48
40
RAM 27 3F 3E 3D 3C 3B 3A 39 38

(cont’) Byte address 26 37 36 35 34 33 32 31 30


25 2F 2E 2D 2C 2B 2A 29 28
24 27 26 25 24 23 22 21 20
23 1F 1E 1D 1C 1B 1A 19 18
22 17 16 15 14 13 12 11 10
21 0F 0E 0D 0C 0B 0A 09 08
20 07 06 05 04 03 02 01 00
1F
18
Bank 3
17
10
Bank 2
0F
08
Bank 1
07
00
Default register bank for R0-R7
Example 2-3-8
BIT Find out to which by each of the following bits belongs. Give the
ADDRESSES address of the RAM byte in hex
(a) SETB 42H, (b) CLR 67H, (c) CLR 0FH
(d) SETB 28H, (e) CLR 12, (f) SETB 05
Bit- Solution:
D7 D6 D5 D4 D3 D2 D1 D0

Addressable
2F 7F 7E 7D 7C 7B 7A 79 78
2E 77 76 75 74 73 72 71 70

RAM (a) D2 of RAM location 28H 2D 6F 6E 6D 6C 6B 6A 69 68


2C 67 66 65 64 63 62 61 60
(cont’) (b) D7 of RAM location 2CH 2B 5F 5E 5D 5C 5B 5A 59 58
2A 57 56 55 54 53 52 51 50

(c) D7 of RAM location 21H 29 4F 4E 4D 4C 4B 4A 49 48


28 47 46 45 44 43 42 41 40

(d) D0 of RAM location 25H 27 3F 3E 3D 3C 3B 3A 39 38


26 37 36 35 34 33 32 31 30
25 2F 2E 2D 2C 2B 2A 29 28
(e) D4 of RAM location 21H
24 27 26 25 24 23 22 21 20
23 1F 1E 1D 1C 1B 1A 19 18
(f) D5 of RAM location 20H
22 17 16 15 14 13 12 11 10
21 0F 0E 0D 0C 0B 0A 09 08
20 07 06 05 04 03 02 01 00
‰ To avoid confusion regarding the
BIT
ADDRESSES
addresses 00 - 7FH
¾ The 128 bytes of RAM have the byte
Bit- addresses of 00 - 7FH can be accessed in
Addressable byte size using various addressing modes
RAM ƒ Direct and register-indirect
(cont’) ¾ The 16 bytes of RAM locations 20 - 2FH
have bit address of 00 - 7FH
ƒ We can use only the single-bit instructions and
these instructions use only direct addressing mode
‰ Các lệnh thao tác bít
BIT
ADDRESSES
Single-Bit Instructions
Bit- Instruction Function
Addressable SETB bit Set the bit (bit = 1)
RAM CLR bit Clear the bit (bit = 0)
(cont’)
CPL bit Complement the bit (bit = NOT bit)
JB bit, target Jump to target if bit = 1 (jump if bit)
JNB bit, target Jump to target if bit = 0 (jump if no bit)
JBC bit, target Jump to target if bit = 1, clear bit
(jump if bit, then clear)
‰ While all of the SFR registers are byte-
BIT addressable, some of them are also bit-
ADDRESSES addressable
¾ The P0 - P3 are bit addressable
I/O Port
Bit Addresses ‰ We can access either the entire 8 bits
or any single bit of I/O ports P0, P1, P2,
and P3 without altering the rest ‰ When
accessing a port in a single-bit manner,
we use the syntax SETB X.Y
¾ X is the port number P0, P1, P2, or P3 ¾ Y
is the desired bit number from 0 to 7 for
data bits D0 to D7
¾ ex. SETB P1.5 sets bit 5 of port 1 high
‰ Notice that when code such as
BIT SETB P1.0 is assembled, it becomes
ADDRESSES SETB 90H
¾ The bit address for I/O ports
I/O Port ƒ P0 are 80H to 87H
Bit Addresses ƒ P1 are 90H to 97H
(cont’) ƒ P2 are A0H to A7H
ƒ P3 are B0H to B7H

Single-Bit Addressability of Ports


P0 P1 P2 P3 Port Bit
P0.0 (80) P1.0 (90) P2.0 (A0) P3.0 (B0) D0
P0.1 P1.1 P2.1 P3.1 D1
P0.2 P1.2 P2.2 P3.2 D2
P0.3 P1.3 P2.3 P3.3 D3
P0.4 P1.4 P2.4 P3.4 D4
P0.5 P1.5 P2.5 P3.5 D5
P0.6 P1.6 P2.6 P3.6 D6
P0.7 (87) P1.7 (97) P2.7 (A7) P3.7 (B7) D7
Example 2-3-9
BIT Write a program to see if the RAM location 37H contains an even
ADDRESSES value. If so, send it to P2. If not, make it even and then send it to P2.
Solution:
MOV A,37H ;load RAM 37H into ACC
Registers JNB ACC.0,YES ;if D0 of ACC 0? If so jump
Bit- INC A ;it’s odd, make it even
YES: MOV P2,A ;send it to P2
Addressability
Example 2-3-10
(cont’)
The status of bits P1.2 and P1.3 of I/O port P1 must be saved before
they are changed. Write a program to save the status of P1.2 in bit
location 06 and the status of P1.3 in bit location 07
Solution:
CLR 06 ;clear bit addr. 06
CLR 07 ;clear bit addr. 07
JNB P1.2,OVER ;check P1.2, if 0 then jump
SETB 06 ;if P1.2=1,set bit 06 to 1
OVER: JNB P1.3,NEXT ;check P1.3, if 0 then jump
SETB 07 ;if P1.3=1,set bit 07 to 1
NEXT: ...
‰ The BIT directive is a widely used
BIT
ADDRESSES
directive to assign the bit-addressable
I/O and RAM locations
Using BIT ¾ Allow a program to assign the I/O or RAM
bit at the beginning of the program,
making it easier to modify them
Example 2-3-11
A switch is connected to pin P1.7 and an LED to pin P2.0. Write a
program to get the status of the switch and send it to the LED.
Solution:
LED BIT P1.7 ;assign bit
SW BIT P2.0 ;assign bit
HERE: MOV C,SW ;get the bit from the port
MOV LED,C ;send the bit to the port
SJMP HERE ;repeat forever
2.4. Lập trình hợp ngữ
2.4 TẬP LỆNH 8051 VÀ
LẬP TRÌNH HỢP NGỮ
‰ Câu lệnh hợp ngữ
8051 ( Asembler
¾ Lệnh gợi )gồm :
nhớ (Mnemonic), sẽ được dịch ra mã máy
ASSEMBLY ƒ Lệnh bảo CPU phải làm gì
PROGRAMMING
¾ Theo sau là 1 hoặc 2 toán hạng ( Operand)
Structure of ƒ Toán hạng là dữ liệu cần phải xử lý
Assembly ‰Chương trình hợp ngữ là tập hợp các dòng lệnh
Language
Có 2 loại lệnh
¾ Câu lệnh thật
ƒ Bảo CPU phải làm gì

¾ Directives (lệnh giả - Pseudo Code)


ƒ Chỉ dẫn cho chương trình dịch
‰ Câu lệnh hợp ngữ gồm 4 trường ( field)
8051
ASSEMBLY :
PROGRAMMING [Tên :] Mã lệnh [Toán hạng] [;chú thích ]

ORG 0H ;start(origin) at location 0


Structure of MOV R5, #25H ;load 25H into R5
Assembly MOV R7, #34H ;load 34H i ORG là Directives
Language MOV A, #0 ;load 0 int Không dịch ra mã máy
ADD A, R5 ;add conten Mà chỉ dẫn cho
;now A = A Trình dịch assembler
Lệnh gợi nhớ ADD A, R7 ;add contents of R7 to A
;now A = A + R7
Tạo ra mã lệnh ADD A, #12H ;add to A value 12H
;now A = A + 12H
HERE: SJMP HERE ;stay in this loop
END ;en Chú thích, bắt đầu bằng dấu ;
Trường tên, kết thúc : Ở cuối dòng lệnh hoặc đứng riêng
Giúp chương trình tham Trình dịch bỏ qua chú thích
Chiếu đến dòng lệnh
Các bước lập trình ngôn ngữ Assembly
ASSEMBLING
AND RUNNING
bao gồm các bước sau :
AN 8051 1) Bước 1 : Sử dụng 1 chương trình soạn thảo (editor )
PROGRAM Để viết chương trình dưới dạng file.asm
Có rất nhiều chương trình soạn thảo có
thể làm việc này
ƒ Chú ý : Chương trình editor cần phải tạo file ASCII

ƒ File có phần mở rộng *.asm“ hoặc *.src tùy thuộc


vào trình dịch assebler mà bạn sử dụng

11
2) Chương trình nguồn *.asm” được tạo ở
ASSEMBLING bước 1 sẽ được đưa vào chương trình
AND RUNNING dịch 8051 assembler program
AN 8051 ƒ Trình dịch assembler sẽ dịch các câu lệnh hợp ngữ
Thành mã máy
PROGRAM
(cont’) ƒ Trình dịch assembler sẽ tạo ra 1 file object và 1 líst file

ƒ Object file có phần mở rộng là *.obj, còn list file là *.lst

3) Assembler thực hiện liên kết (linker Prog. )


ƒ Chương trình linker sẽ lấy thêm 1 số object code files và
tạo thành absolute object file với phần mở rộng là *.abs

4) Bước 4 : File *.abs sẽ được OH program


Đổi Thành file dạng *.hex ( file hexa)
Và sẵn sàng để nạp vào bộ nhớ ROM
EDITOR
PROGRAM
ASSEMBLING myfile.asm
AND RUNNING
AN 8051 ASSEMBLER
PROGRAM PROGRAM
myfile.lst
Other obj files
Steps to Create myfile.obj

a Program LINKER
PROGRAM

myfile.abs

OH
PROGRAM

myfile.hex
‰ File *.lst (list) file, là tùy chọn,
ASSEMBLING
Nó rất hiệu quả với người lập trình
AND RUNNING
AN 8051 ¾ It lists all the opcodes and addresses as
PROGRAM well as errors that the assembler detected
¾ The programmer uses the lst file to find
lst File the syntax errors or debug
1 0000 ORG 0H ;start (origin) at 0
2 0000 7D25 MOV R5,#25H ;load 25H into R5
3 0002 7F34 MOV R7,#34H ;load 34H into R7
4 0004 7400 MOV A,#0 ;load 0 into A
5 0006 2D ADD A,R5 ;add contents of R5 to A
;now A = A + R5
6 0007 2F ADD A,R7 ;add contents of R7 to A
;now A = A + R7
7 0008 2412 ADD A,#12H ;add to A value 12H
;now A = A + 12H
8 000A 80EF HERE: SJMP HERE;stay in this loop
9 000C END ;end of asm source file
address
15
‰ 8051 microcontroller has only one data
8051 DATA
TYPES AND
type - 8 bits
DIRECTIVES ¾ The size of each register is also 8 bits
¾ It is the job of the programmer to break
Data Type down data larger than 8 bits (00 to FFH,
or 0 to 255 in decimal)
¾ The data types can be positive or negative
‰ DB ( Define a Byte ) directive
8051 DATA
TYPES AND ¾ DB dùng để định nghĩa 8-bit data ( khai báo
DIRECTIVES biến 1 byte )
¾ Khi sử dụng DB để khai báo dữ liệu, nó có thể
Assembler Là thập phân, nhị phân, hexa hoặc ASCII
The “D” after the decimal
Directives number is optional, but using
“B” (binary) and “H”
ORG 500H (hexadecimal) for the others is
required
DATA1: DB 28 ;DECIMAL (1C in Hex)
DATA2: DB 00110101B ;BINARY (35 in Hex)
DATA3: DB 39H ;HEX
The Assembler will ORG 510H Place ASCII in quotation marks
convert the numbers DATA4: DB “2591” The Assembler will assign ASCII
into hex code for the numbers or characters
ORG 518H
DATA6: DB “My name is Joe”
Define ASCII strings larger ;ASCII CHARACTERS
than two characters

24
‰ ORG (origin)
8051 DATA ¾ The ORG directive is used to indicate the
TYPES AND beginning of the address
DIRECTIVES
¾ The number that comes after ORG can be
either in hex and decimal
Assembler ƒ If the number is not followed by H, it is decimal
Directives and the assembler will convert it to hex
(cont’) ‰ END
¾ This indicates to the assembler the end of
the source (asm) file
¾ The END directive is the last line of an
8051 program
ƒ Mean that in the code anything after the END
directive is ignored by the assembler

25
‰ EQU (equate) : Khai báo hằng có tên
8051 DATA
TYPES AND ¾ This is used to define a constant without
DIRECTIVES occupying a memory location
¾ The EQU directive does not set aside
Assembler storage for a data item but associates
directives a
constant value with a data label
(cont’) ƒ When the label appears in the program, its
constant value will be substituted for the label

26
‰ EQU (equate) (cont’)
8051 DATA
¾ Assume that there is a constant used in
TYPES AND any different places in the program, and
DIRECTIVES the programmer wants to change its value
Assembler throughout
ƒ By the use of EQU, one can change it once and
directives
the assembler will change all of its occurrences
(cont’)
Use EQU for the
counter constant

COUNT EQU 25

MOV R3, #COUNT

The constant is used to


load the R3 register

27
Intel 8051: Instruction Set

Arithmetic Operations
ADD Addition
ADDC Addition with Carry Flag
SUBB Subtraction
INC Increment
DEC Decrement
MUL Multiply
DIV Divide
DA Decimal Adjust Accumulator
Intel 8051: Instruction Set
Logical Operations
AND And
ORL Or
XRL Exclusive-Or
CLR A Clear (Accumulator)
CPL A Complement
RL A Rotate Left
RLC A Rotate Left through Carry Flag
RR A Rotate Right
RLC A Rotate Right through Carry Flag
SWAP A Swap nibbles within Accumulator
Intel 8051: Instruction Set
Data Transfer
MOV Move
MOVC Move Code byte
MOVX Move External RAM byte/word
PUSH Push direct byte on stack
POP Pop direct byte from stack
XCH Exchange
XCHD Exchange low order Digit
Intel 8051: Instruction Set
Boolean Variable Manipulation
CLR Clear bit/flag
SET Set bit/flag
CPL Complement bit/flag
ANL AND bit and flag
ORL OR bit and flag
MOV Move bit
Intel 8051: Instruction Set
Program and Machine Control #1
ACALL Absolute Subroutine Call
LCALL Long Subroutine Call
RET Return from Subroutine
RETI Return from interrupt
AJMP Absolute Jump
LJMP Long Jump
SJMP Short (Relative) Jump
JMP @A+DPTR Jump indirect relative to the DPTR
Intel 8051: Instruction Set
Program and Machine Control #2
JZ Jump if Accumulator is Zero
JNZ Jump if Accumulator is Not Zero
JC Jump if Carry flag is set
JNC Jump if No Carry flag
JB Jump if Bit set
JNB Jump if Bit Not set
JBC Jump if Bit set & Clear bit
CJNE Compare and Jump if Not Zero
DJNZ Decrement and Jump if Not Zero
NOP No Operation
Intel 8051: Instruction Set

Instructions that affect Flag Settings #1


C OV AC
ADD X X X
ADDC X X X
SUBB X X X
MUL 0 X
DIV 0 X
DA X
RRC X
RLC X
Intel 8051: Instruction Set

Instructions that affect Flag Settings #2


C OV AC
SET C 1
CLR C 0
CPL C X
ANL X
ORL X
MOV C, bit X
CJNE X
Operations on PSW X X X
MOVEMENT INSTRUCTIONS
MOV Instruction
MOVX
MOVX
MOVC
PUSH AND POP
Example 2-8
8051
Show the stack and stack pointer from the following. Assume the
REGISTER default stack area.
BANKS AND MOV R6, #25H
STACK MOV R1, #12H
MOV R4, #0F3H
PUSH 6
Pushing onto PUSH 1
Stack PUSH 4
Solution:
After PUSH 6 After PUSH 1 After PUSH 4
0B 0B 0B 0B
0A 0A 0A 0A F3
09 09 09 12 09 12
08 08 25 08 25 08 25
Start SP = 07 SP = 08 SP = 09 SP = 0A
Example 2-9
8051
Examining the stack, show the contents of the register and SP after
REGISTER execution of the following instructions. All value are in hex.
BANKS AND POP 3 ; POP stack into R3
STACK POP 5 ; POP stack into R5
POP 2 ; POP stack into R2

Popping From Solution:


Stack
After POP 3 After POP 5 After POP 2
0B 54 0B 0B 0B
0A F9 0A F9 0A 0A
09 76 09 76 09 76 09
08 6C 08 6C 08 6C 08 6C
Start SP = 0B SP = 0A SP = 09 SP = 08
Because locations 20-2FH of RAM are reserved
for bit-addressable memory, so we can change the
SP to other RAM location by using the instruction
“MOV SP, #XX”
‰ When 8051 is powered up, register
8051
REGISTER
bank 1 and the stack are using the
BANKS AND same memory space
STACK ¾ We can reallocate another section of RAM
to the stack
Stack and Bank
1 Conflict
Example 2-10
8051 Examining the stack, show the contents of the register and SP after
REGISTER execution of the following instructions. All value are in hex.
BANKS AND MOV SP, #5FH ;make RAM location 60H
;first stack location
STACK MOV R2, #25H
MOV R1, #12H
MOV R4, #0F3H
Stack And Bank PUSH 2
1 Conflict PUSH 1
PUSH 4
(cont’)
Solution:
After PUSH 2 After PUSH 1 After PUSH 4
63 63 63 63
62 62 62 62 F3
61 61 61 12 61 12
60 60 25 60 25 60 25
Start SP = 5F SP = 60 SP = 61 SP = 62
Data Exchange
XCH and XCHD
JUMP, LOOP AND CALL
INSTRUCTIONS
‰ Repeating a sequence of instructions a
LOOP AND certain number of times is called a
JUMP loop
INSTRUCTIONS
¾ Loop action is performed by
DJNZ reg, Label
Looping
ƒ The register is decremented
ƒ If it is not zero, it jumps to the target address
referred to by the label
A loop can be repeated a ƒ Prior to the start of loop the register is loaded
maximum of 255 times, if with the counter for the number of repetitions
R2 is FFH
ƒ Counter can be R0 - R7 or RAM location
;This program adds value 3 to the ACC ten times
MOV A,#0 ;A=0, clear ACC
MOV R2,#10 ;load counter R2=10
AGAIN: ADD A,#03 ;add 03 to ACC
DJNZ R2,AGAIN ;repeat until R2=0,10 times
MOV R5,A ;save A in R5
‰ If we want to repeat an action more
LOOP AND
JUMP
times than 256, we use a loop inside a
INSTRUCTIONS loop, which is called nested loop
¾ We use multiple registers to hold the
Nested Loop count

Write a program to (a) load the accumulator with the value 55H, and
(b) complement the ACC 700 times

MOV A,#55H ;A=55H


MOV R3,#10 ;R3=10, outer loop count
NEXT: MOV R2,#70 ;R2=70, inner loop count
AGAIN: CPL A ;complement A register
DJNZ R2,AGAIN ;repeat it 70 times
DJNZ R3,NEXT
‰ (cont’)
LOOP AND JNC label ;jump if no carry, CY=0
JUMP ¾ If CY = 0, the CPU starts to fetch and execute
INSTRUCTIONS instruction from the address of the label
¾ If CY = 1, it will not jump but will execute the next
Conditional instruction below JNC
Jumps Find the sum of the values 79H, F5H, E2H. Put the sum in registers
(cont’) R0 (low byte) and R5 (high byte).
MOV R5,#0
MOV A,#0 ;A=0
MOV R5,A ;clear R5
ADD A,#79H ;A=0+79H=79H
; JNC N_1 ;if CY=0, add next number
; INC R5 ;if CY=1, increment R5
N_1: ADD A,#0F5H ;A=79+F5=6E and CY=1
JNC N_2 ;jump if CY=0
INC R5 ;if CY=1,increment R5 (R5=1)
N_2: ADD A,#0E2H ;A=6E+E2=50 and CY=1
JNC OVER ;jump if CY=0
INC R5 ;if CY=1, increment 5
OVER: MOV R0,A ;now R0=50H, and R5=02
8051 conditional jump instructions
LOOP AND Instructions Actions
JUMP JZ Jump if A =
0
INSTRUCTIONS JNZ Jump if A ≠ 0
DJNZ Decrement and Jump if A ≠ 0
Conditional CJNE A,byte Jump if A ≠ byte
CJNE reg,#data Jump if byte ≠ #data
Jumps
(cont’)
JC Jump if CY =
JNC 1
Jump if CY =
JB 0
Jump if bit =
JNB 1
Jump if bit =
JBC 0
Jump if bit = 1 and clear
bit
‰ All conditional jumps are short jumps
¾ The address of the target must within -
128 to +127 bytes of the contents of PC
The unconditional jump is a jump in
‰
LOOP AND which control is transferred
JUMP unconditionally to the target location
INSTRUCTIONS
LJMP (long jump)

Unconditional ¾ 3-byte instruction


Jumps ƒ First byte is the opcode
ƒ Second and third bytes represent the 16-bit
target address
- Any memory location from 0000 to FFFFH
SJMP (short jump)
¾ 2-byte instruction
ƒ First byte is the opcode
ƒ Second byte is the relative target address - 00
to FFH (forward +127 and backward -128 bytes
from the current PC)
‰ To calculate the target address of a
LOOP AND
JUMP
short jump (SJMP, JNC, JZ, DJNZ, etc.)
INSTRUCTIONS ¾ The second byte is added to the PC of the
instruction immediately below the jump
Calculating ‰ If the target address is more than -128
Short Jump to +127 bytes from the address below
Address
the short jump instruction
¾ The assembler will generate an error
stating the jump is out of range
Line PC Opcode Mnemonic Operand
LOOP AND 01 0000 ORG 0000
JUMP 02 0000 7800 MOV R0,#0
03 0002 7455 MOV A,#55H
INSTRUCTIONS 04 0004 6003 JZ NEXT
05 0006 08 INC R0
Calculating 06 0007 04
+ AGAIN: INC A
07 0008 04 INC A
Short Jump 08 0009 2477 NEXT: ADD A,#77H
Address 09 000B 5005 JNC OVER
(cont’) 10 000D E4 CLR A
11 000E F8 MOV R0,A
12 000F F9
+ MOV R1,A
13 0010 FA MOV R2,A
14 0011 FB MOV R3,A
15 0012 2B OVER: ADD A,R3
16 0013 50F2 JNC AGAIN
17 0015 80FE + HERE: SJMP HERE
18 0017 END
‰ Call instruction is used to call subroutine
CALL
¾ Subroutines are often used to perform tasks
INSTRUCTIONS
that need to be performed frequently ¾
This makes a program more structured in
addition to saving memory space
LCALL (long call)
¾ 3-byte instruction
ƒ First byte is the opcode
ƒ Second and third bytes are used for address of
target subroutine
- Subroutine is located anywhere within 64K byte
address space
ACALL (absolute call)
¾ 2-byte instruction
ƒ 11 bits are used for address within 2K-byte range
ORG 0
BACK: MOV A,#55H ;load A with 55H
CALL MOV P1,A ;send 55H to port 1
INSTRUCTIONS LCALL DELAY
MOV
;time
A,#0AAH ;load
delay
A with AA (in hex)
MOV P1,A ;send AAH to port 1
LCALL LCALL DELAY
SJMP BACK ;keep doing this indefinitely
(cont’)
Upon executing “LCALL DELAY”,
the address of instruction below it,
The counter R5 is set to “MOV A,#0AAH” is pushed onto
FFH; so loop is repeated stack, and the 8051 starts to execute
255 times.
at 300H.
;---------- this is delay subroutine ------------
ORG 300H ;put DELAY at address 300H
DELAY: MOV R5,#0FFH;R5=255 (FF in hex), counter
AGAIN: DJNZ R5,AGAIN ;stay here until R5 become 0
RET ;return to caller (when R5 =0)
END
When R5 becomes 0, control falls to the
The amount of time delay depends RET which pops the address from the stack
on the frequency of the 8051 into the PC and resumes executing the
instructions after the CALL.
01 0000 ORG 0
02 0000 7455 BACK: MOV A,#55H ;load A with 55H
03 0002 F590 MOV P1,A ;send 55H to p1
CALL 04 0004 7C99 MOV R4,#99H
05 0006 7D67 MOV R5,#67H
INSTRUCTIONS 06 0008 120300 LCALL DELAY ;time delay
07 000B 74AA MOV A,#0AAH ;load A with AA
08 000D F590 MOV P1,A ;send AAH to p1
Use PUSH/POP 09 000F 120300 LCALL DELAY
10 0012 80EC SJMP BACK ;keeping doing
in Subroutine this
11 0014 ;-------this is the delay subroutine------
12 0300 ORG 300H
13 0300 C004 DELAY: PUSH 4 ;push R4
14 0302 C005 PUSH 5 ;push R5
Normally, the 0304 7CFF MOV R4,#0FFH;R4=FFH
number of PUSH 0306 7DFF NEXT: MOV R5,#0FFH;R5=FFH
and POP 0308 DDFE AGAIN: DJNZ R5,AGAIN
030A DCFA DJNZ R4,NEXT
instructions must
030C D005 POP 5 ;POP into R5
always match in any 030E D004 POP 4 ;POP into R4
called subroutine 031 er
22 031 After first LCALL After PUSH 4 After PUSH 5 e
0B 0B 0B 67 R5
0A 0A 99 R4 0A 99 R4
09 00 PCH 09 00 PCH 09 00 PCH
;MAIN program calling subroutines
ORG 0
CALL MAIN: LCALL SUBR_1 It is common to have one
main program and many
INSTRUCTIONS LCALL
LCALL
SUBR_2
SUBR_3 subroutines that are called
from the main program
HERE: SJMP HERE
Calling ;-----------end of MAIN
Subroutines
SUBR_1: ...
This allows you to make
RET each subroutine into a
;-----------end of subroutine1 separate module
- Each module can be
SUBR_2: ...
tested separately and then
RET brought together with
;-----------end of subroutine2 main program
- In a large program, the
SUBR_3: ... module can be assigned to
different programmers
RET
;-----------end of subroutine3
END ;end of the asm file
ORG 0
CALL BACK: MOV A,#55H ;load A with 55H
MOV P1,A ;send 55H to port 1
INSTRUCTIONS LCALL DELAY ;time delay
MOV A,#0AAH ;load A with AA (in hex)
MOV P1,A ;send AAH to port 1
ACALL LCALL DELAY
(cont’) SJMP BACK ;keep doing this indefinitely

END ;end of asm file

A rewritten program which is more efficiently


ORG 0
MOV A,#55H ;load A with 55H
BACK: MOV P1,A ;send 55H to port 1
ACALL DELAY ;time delay
CPL A ;complement reg A
SJMP BACK ;keep doing this indefinitely

END ;end of asm file


‰ CPU executing an instruction takes a
TIME DELAY
FOR VARIOUS
certain number of clock cycles
8051 CHIPS ¾ These are referred as to as machine cycles
‰ The length of machine cycle
depends on the frequency of the
crystal oscillator connected to 8051
‰ In original 8051, one machine
cycle lasts 12 oscillator periods
Find the period of the machine cycle for 11.0592 MHz crystal
frequency

Solution:
11.0592/12 = 921.6 kHz;
machine cycle is 1/921.6 kHz = 1.085μs
For 8051 system of 11.0592 MHz, find how long it takes to execute
TIME DELAY each instruction.
(a) MOV R3,#55 (b) DEC R3 (c) DJNZ R2 target
FOR VARIOUS (d) LJMP (e) SJMP (f) NOP (g) MUL AB
8051 CHIPS
(cont’) Solution:
Machine cycles Time to execute
(a) 1 1x1.085μs = 1.085μs
(b) 1 1x1.085μs = 1.085μs
(c) 2 2x1.085μs = 2.17μs
(d) 2 2x1.085μs = 2.17μs
(e) 2 2x1.085μs = 2.17μs
(f) 1 1x1.085μs = 1.085μs
(g) 4 4x1.085μs = 4.34μs
Find the size of the delay in following program, if the crystal
TIME DELAY frequency is 11.0592MHz.
FOR VARIOUS
8051 CHIPS MOV A,#55H
AGAIN: MOV P1,A
ACALL DELAY
Delay CPL A
Calculation SJMP AGAIN A simple way to short jump
to itself in order to keep the
;---time delay-------
DELAY: MOV R3,#200 microcontroller busy
HERE: DJNZ R3,HERE HERE: SJMP HERE
RET We can use the following:
SJMP $
Solution:
Machine cycle
DELAY: MOV R3,#200 1
HERE: DJNZ R3,HERE 2
RET 2
Therefore, [(200x2)+1+2]x1.085μs = 436.255μs.
Find the size of the delay in following program, if the crystal
TIME DELAY frequency is 11.0592MHz.
FOR VARIOUS
8051 CHIPS Machine Cycle
DELAY: MOV R3,#250 1
HERE: NOP 1
Increasing NOP 1
Delay Using NOP 1
NOP 1
NOP DJNZ R3,HERE 2
RET 2

Solution:
The time delay inside HERE loop is
[250(1+1+1+1+2)]x1.085μs = 1627.5μs.
Adding the two instructions outside loop we
have 1627.5μs + 3 x 1.085μs = 1630.755μs
Find the size of the delay in following program, if the crystal
TIME DELAY frequency is 11.0592MHz.
FOR VARIOUS Machine Cycle
8051 CHIPS DELAY: MOV R2,#200 1
Notice in nested loop,
AGAIN: MOV R3,#250 1
as in all other time
Large Delay HERE: NOP 1
delay loops, the time
NOP 1
Using Nested DJNZ R3,HERE 2
is approximate since
we have ignored the
Loop DJNZ R2,AGAIN 2
first and last
RET 2
instructions in the
subroutine.
Solution:
For HERE loop, we have (4x250)x1.085μs = 1085μs.
For AGAIN loop repeats HERE loop 200 times, so
we have 200x1085μs = 217000μs. But “MOV R3,#250”
and “DJNZ R2,AGAIN” at the start and end of the
AGAIN loop add (3x200x1.805)=651μs. As a result
we have 217000+651=217651μs.
ARITHMETIC & LOGIC
INSTRUCTIONS AND
PROGRAMS
ADD A,source ;A = A + source
ARITHMETIC ‰ The instruction ADD is used to add two
INSTRUCTIONS operands
¾ Destination operand is always in register A
Addition of
¾ Source operand can be a register,
Unsigned immediate data, or in memory
Numbers
¾ Memory-to-memory arithmetic operations
are never allowed in 8051 Assembly
language
Show how the flag register is affected by the following instruction.
MOV A,#0F5H ;A=F5 hex CY =1, since there is a
ADD A,#0BH;A=F5+0B=00 carry out from D7
PF =1, because the number
Solution:
of 1s is zero (an even
F5H 1111 0101 number), PF is set to 1.
+ 0BH + 0000 1011 AC =1, since there is a
100H 0000 0000 carry from D3 to D4

2
ADD A,source ;A = A + source
ARITHMETIC ‰ The instruction ADD is used to add two
INSTRUCTIONS operands
¾ Destination operand is always in register A
Addition of
¾ Source operand can be a register,
Unsigned immediate data, or in memory
Numbers
¾ Memory-to-memory arithmetic operations
are never allowed in 8051 Assembly
language
Show how the flag register is affected by the following instruction.
MOV A,#0F5H ;A=F5 hex CY =1, since there is a
ADD A,#0BH;A=F5+0B=00 carry out from D7
PF =1, because the number
Solution:
of 1s is zero (an even
F5H 1111 0101 number), PF is set to 1.
+ 0BH + 0000 1011 AC =1, since there is a
100H 0000 0000 carry from D3 to D4

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

3
‰ When adding two 16-bit data operands,
ARITHMETIC the propagation of a carry from lower
INSTRUCTIONS byte to higher byte is concerned
1 When the first byte is added
ADDC and 3C E7 (E7+8D=74, CY=1).
Addition of 16- + 3B 8D The carry is propagated to the
78 74 higher byte, which result in 3C
Bit Numbers
+ 3B + 1 =78 (all in hex)

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

4
‰ The binary representation of the digits 0 to 9
ARITHMETIC is called BCD(Binary Coded Decimal )
INSTRUCTIONS Digit BCD

¾ Unpacked BCD 0 0000


1 0001
BCD Number ƒ In unpacked BCD, the lower 4 2 0010
System bits of the number represent the 3 0011
BCD number, and the rest of the 4 0100
bits are 0 5 0101
6 0110
ƒ Ex. 00001001 and 00000101 are
7 0111
unpacked BCD for 9 and 5 8 1000
¾ Packed BCD 9 1001

ƒ In packed BCD, a single byte has two


BCD number in it, one in the lower 4
bits, and one in the upper 4 bits

ƒ Ex. 0101 1001 is packed BCD for 59H

5
ARITHMETIC ‰ Adding two BCD numbers must give a
INSTRUCTIONS BCD result Adding these two
numbers gives
Unpacked and MOV A, #17H 0011 1111B (3FH),
ADD A, #28H Which is not BCD!
Packed BCD
The result above should have been 17 + 28 = 45 (0100 0101). To
correct this problem, the programmer must add 6 (0110) to the
low digit: 3F + 06 = 45H.

6
‰ Summary of DA instruction
ARITHMETIC ¾ After an ADD or ADDC instruction
INSTRUCTIONS
1. If the lower nibble (4 bits) is greater than 9, or
if AC=1, add 0110 to the lower 4 bits
DA Instruction 2. If the upper nibble is greater than 9, or if
(cont’) CY=1, add 0110 to the upper 4 bits

Example:
HEX BCD
29 0010 1001
+ 18 + 0001 1000
41 0100 0001 AC=1
+ 6 + 0110
47 0100 0111

Since AC=1 after the


addition, ”DA A” will add 6 to
the lower nibble.
The final result is in BCD format.

8
Assume that 5 BCD data items are stored in RAM locations starting
at 40H, as shown below. Write a program to find the sum of all the
ARITHMETIC numbers. The result must be in BCD.
INSTRUCTIONS 40=(71)
41=(11)
42=(65)
DA Instruction 43=(59)
(cont’) 44=(37)
Solution:
MOV R0,#40H ;Load pointer
MOV R2,#5 ;Load counter
CLR A ;A=0
MOV R7,A ;Clear R7
AGAIN: ADD A,@R0 ;add the byte pointer
;to by R0
DA A ;adjust for BCD
JNC NEXT ;if CY=0 don’t
;accumulate carry
INC R7 ;keep track of carries
NEXT: INC R0 ;increment pointer
DJNZ R2,AGAIN ;repeat until R2 is 0

9
‰ In many microprocessor there are two
ARITHMETIC different instructions for subtraction:
INSTRUCTIONS SUB and SUBB (subtract with borrow)
¾ In the 8051 we have only SUBB
Subtraction of
¾ The 8051 uses adder circuitry to perform
Unsigned
the subtraction
Numbers

SUBB A,source ;A = A - source - CY


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

10
‰ SUBB when CY = 0
ARITHMETIC 1. Take the 2’s complement of the
INSTRUCTIONS subtrahend (source operand)
2. Add it to the minuend (A)
Subtraction of 3. Invert the carry
Unsigned
CLR C
Numbers MOV A,#4C ;load A with value 4CH
(cont’) SUBB A,#6EH ;subtract 6E from A
JNC NEXT ;if CY=0 jump to NEXT
CPL A ;if CY=1, take 1’s complement
INC A ;and increment to get 2’s comp
NEXT: MOV R1,A ;save A in R1
c 2’s
Solution: complement
4C 0100 1100 0100 1100
CY=0, the result is positive; - 6E 0110 1110 1001 0010 d+
CY=1, the result is negative
-22 01101 1110
and the destination has the CY =1
2’s complement of the result e Invert carry

11
‰ SUBB when CY = 1
ARITHMETIC
¾ This instruction is used for multi-byte
INSTRUCTIONS numbers and will take care of the borrow
of the lower operand
Subtraction of A = 62H - 96H - 0 = CCH
CLR C
Unsigned MOV A,#62H
CY = 1
;A=62H
Numbers SUBB A,#96H ;62H-96H=CCH with CY=1
(cont’) MOV R7,A ;save the result
MOV A,#27H ;A=27H
SUBB A,#12H ;27H-12H-1=14H
MOV R6,A ;save the result
A = 27H - 12H - 1 = 14H
Solution:
CY = 0
We have 2762H - 1296H = 14CCH.

12
‰ The 8051 supports byte by byte
ARITHMETIC multiplication only
INSTRUCTIONS
The byte are assumed to be unsigned data
¾

Unsigned MUL AB ;AxB, 16-bit result in B, A


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

Unsigned Multiplication Summary (MUL AB)


Multiplication Operand1 Operand2 Result
Byte x byte A B B = high byte
A = low byte

13
‰ The 8051 supports byte over byte
ARITHMETIC
INSTRUCTIONS
division only
The byte are assumed to be unsigned data
¾
Unsigned DIV AB ;divide A by B, A/B
Division
MOV A,#95 ;load 95 to reg. A
MOV B,#10 ;load 10 to reg. B
MUL AB ;A = 09(quotient) and
;B = 05(remainder)

Unsigned Division Summary (DIV AB)


Division Numerator Denominator Quotient Remainder
Byte / byte A B A B

CY is always 0
If B ≠ 0, OV = 0
If B = 0, OV = 1 indicates error

14
(a) Write a program to get hex data in the range of 00 - FFH from
port 1 and convert it to decimal. Save it in R7, R6 and R5.
ARITHMETIC (b) Assuming that P1 has a value of FDH for data, analyze program.
INSTRUCTIONS Solution:
(a)
MOV A,#0FFH
Application for MOV P1,A ;make P1 an input port
DIV MOV
MOV
A,P1
B,#10
;read data from P1
;B=0A hex
DIV AB ;divide by 10
MOV R7,B ;save lower digit
MOV B,#10
DIV AB ;divide by 10 once more
MOV R6,B ;save the next digit
MOV R5,A ;save the last digit
(b) To convert a binary (hex) value to decimal, we divide it by 10
repeatedly until the quotient is less than 10. After each division the
remainder is saves.
Q R
FD/0A = 19 3 (low digit)
19/0A = 2 5 (middle digit)
2 (high digit)
Therefore, we have FDH=253.

15
‰ D7 (MSB) is the sign and D0 to D6 are
SIGNED the magnitude of the number
ARITHMETIC
¾ If D7=0, the operand is positive, and if
INSTRUCTIONS D7=1, it is negative
D7 D6 D5 D4 D3 D2 D1 D0
Signed 8-bit
Operands
Sign Magnitude
‰ Positive numbers are 0 to +127 ‰
Negative number representation (2’s
complement)
1. Write the magnitude of the number in 8-
bit binary (no sign)
2. Invert each
bit 3. Add 1 to it

16
Show how the 8051 would represent -34H

SIGNED Solution:
0011 0100 34H given in binary
ARITHMETIC 1.

1100 1011 invert each bit


INSTRUCTIONS
2.

3. 1100 1100 add 1 (which is CC in hex)


Signed number representation of -34 in 2’s complement is CCH
Signed 8-bit
Operands Decimal Binary Hex
(cont’) -128 1000 0000 80
-127 1000 0001 81
-126 1000 0010 82

-2 1111 1110 FE
-1 1111 1111 FF
0 0000 0000 00
+1 0000 0001 01
+2 0000 0010 02

+127 0111 1111 7F

17
‰ If the result of an operation on signed
SIGNED numbers is too large for the register
ARITHMETIC
¾ An overflow has occurred and the
INSTRUCTIONS
programmer must be noticed
Overflow Examine the following code and analyze the result.
Problem MOV A,#+96 ;A=0110 0000 (A=60H)
MOV R1,#+70 ;R1=0100 0110(R1=46H)
ADD A,R1 ;A=1010 0110
;A=A6H=-90,INVALID
Solution:
+96 0110 0000
+ +70 0100 0110
+ 166 1010 0110 and OV =1
According to the CPU, the result is -90, which is wrong. The CPU
sets OV=1 to indicate the overflow

18
‰ In 8-bit signed number operations,
SIGNED
ARITHMETIC
OV is set to 1 if either occurs:
INSTRUCTIONS 1. There is a carry from D6 to D7, but no
carry out of D7 (CY=0)
OV Flag 2. There is a carry from D7 out (CY=1), but
no carry from D6 to D7
MOV A,#-128 ;A=1000 0000(A=80H)
MOV R4,#-2 ;R4=1111 1110(R4=FEH)
ADD A,R4 ;A=0111 1110(A=7EH=+126,INVALID)
-128 1000 0000
+ -2 1111 1110
-130 0111 1110 and OV=1

OV = 1
The result +126 is wrong

19
MOV A,#-2 ;A=1111 1110(A=FEH)
MOV R1,#-5 ;R1=1111 1011(R1=FBH)
SIGNED ADD A,R1 ;A=1111 1001(A=F9H=-7,
ARITHMETIC ;Correct, OV=0)
INSTRUCTIONS -2 1111 1110
+ -5 1111 1011
-7 1111 1001 and OV=0
OV Flag
(cont’)
OV = 0
The result -7 is correct
MOV A,#+7 ;A=0000 0111(A=07H)
MOV R1,#+18 ;R1=0001 0010(R1=12H)
ADD A,R1 ;A=0001 1001(A=19H=+25,
;Correct,OV=0)
7 0000 0111
+ 18 0001 0010
25 0001 1001 and OV=0
OV = 0
The result +25 is correct

20
‰ In unsigned number addition, we must
SIGNED
ARITHMETIC
monitor the status of CY (carry)
INSTRUCTIONS ¾ Use JNC or JC instructions
‰ In signed number addition, the OV
OV Flag (overflow) flag must be monitored by
(cont’)
the programmer
¾ JB PSW.2 or JNB PSW.2

21
‰ To make the 2’s complement of a
SIGNED
number
ARITHMETIC
INSTRUCTIONS
CPL A ;1’s complement (invert)
ADD A,#1 ;add 1 to make 2’s comp.
2's
Complement

22
ANL destination,source
LOGIC AND ;dest = dest AND source
COMPARE ‰ This instruction will perform a logic
INSTRUCTIONS
AND on the two operands and
AND
place the result in the destination
¾ The destination is normally the
accumulator
¾ The source operand can be a register, in
memory, or immediate

X Y XANDY Show the results of the following.


0 0 0 MOV A,#35H ;A = 35H
0 1 0 ANL A,#0FH ;A = A AND 0FH
35H 0 0 1 1 0 1 0 1 ANL is often used to
1 0 0
0FH 0 0 0 0 1 1 1 1 mask (set to 0) certain
1 1 1 bits of an operand
05H 0 0 0 0 0 1 0 1

23
ORL destination,source
LOGIC AND ;dest = dest OR source
COMPARE ‰ The destination and source operands
INSTRUCTIONS are ORed and the result is placed
in the destination
OR
¾ The destination is normally the
accumulator
¾ The source operand can be a register, in
memory, or immediate

X Y XORY Show the results of the following.


0 0 0 MOV A,#04H ;A = 04
0 1 1 ORL A,#68H ;A = 6C
ORL instruction can be
1 0 1 04H 0 0 0 0 0 1 0 0 used to set certain bits
1 1 1
68H 0 1 1 0 1 0 0 0 of an operand to 1
6CH 0 1 1 0 1 1 0 0

24
XRL destination,source
LOGIC AND ;dest = dest XOR source
COMPARE
‰ This instruction will perform XOR
INSTRUCTIONS
operation on the two operands and
XOR place the result in the destination
¾ The destination is normally the
accumulator
¾ The source operand can be a register, in
memory, or immediate
X Y XXORY Show the results of the following.
0 0 0 MOV A,#54H
0 1 1 XRL A,#78H
XRL instruction can be
1 0 1 54H 0 1 0 1 0 1 0 0 used to toggle certain
1 1 0 78H 0 1 1 1 1 0 0 0 bits of an operand
2CH 0 0 1 0 1 1 0 0

25
The XRL instruction can be used to clear the contents of a register by XORing it with itself.
Show how XRL A,A clears A, assuming that LOGIC AND
AH = 45H.
COMPARE
INSTRUCTIONS 45H 0 1 0 0 0 1 0 1
45H 0 1 0 0 0 1 0 1
00H 0 0 0 0 0 0 0 0
XOR
(cont’) Read and test P1 to see whether it has the value 45H. If it does, send
99H to P2; otherwise, it stays cleared.
XRL can be used to
Solution: see if two registers
MOV P2,#00 ;clear P2 have the same value
MOV P1,#0FFH ;make P1 an input port
MOV R3,#45H ;R3=45H
MOV A,P1 ;read P1
XRL A,R3
JNZ EXIT ;jump if A is not 0
MOV P2,#99H
EXIT: ... If both registers have the same
value, 00 is placed in A. JNZ
and JZ test the contents of the
accumulator.
26
CPL A ;complements the register A
LOGIC AND
COMPARE ‰ This is called 1’s complement
INSTRUCTIONS MOV A, #55H
CPL A ;now A=AAH
Complement ;0101 0101(55H)
;becomes 1010 1010(AAH)
Accumulator
‰ To get the 2’s complement, all we
have to do is to to add 1 to the
1’s complement

27
CJNE destination,source,rel. addr.
LOGIC AND
COMPARE ‰ The actions of comparing and jumping
INSTRUCTIONS are combined into a single instruction
called CJNE (compare and jump if not equal )
Compare
Instruction
¾ The CJNE instruction compares two
operands, and jumps if they are not equal ¾
The destination operand can be in the
accumulator or in one of the Rn registers ¾
The source operand can be in a register, in
memory, or immediate
ƒ The operands themselves remain unchanged ¾ It
changes the CY flag to indicate if the
destination operand is larger or smaller

28
CJNE R5,#80,NOT_EQUAL ;check R5 for 80
LOGIC AND ;R5 = 80
COMPARE NOT_EQUAL:
INSTRUCTIONS JNC NEXT ;jump if R5 > 80
;R5 < 80
NEXT:
Compare
Instruction Compare Carry Flag
(cont’) destination ≥ source CY = 0
destination < source CY = 1
CY flag is always
checked for cases ‰ Notice in the CJNE instruction that any
of greater or less Rn register can be compared with an immediate value
than, but only after
it is determined that ¾ There is no need for register A to be involved
they are not equal

29
RR A ;rotate right A
ROTATE
INSTRUCTION ‰ In rotate right
AND DATA ¾ The 8 bits of the accumulator are rotated
SERIALIZATION right one bit, and
¾ Bit D0 exits from the LSB and enters into
Rotating Right MSB, D7
and Left MSB LSB

MOV A,#36H ;A = 0011 0110


RR A ;A = 0001 1011
RR A ;A = 1000 1101
RR A ;A = 1100 0110
RR A ;A = 0110 0011

31
RL A ;rotate left A
ROTATE
INSTRUCTION ‰ In rotate left
AND DATA ¾The 8 bits of the accumulator are rotated
SERIALIZATION left one bit, and
¾ Bit D7 exits from the MSB and enters into LSB D0
Rotating Right
and Left
(cont’)
MSB LSB

MOV A,#72H ;A = 0111 0010


RL A ;A = 1110 0100
RL A ;A = 1100 1001

32
RRC A ;rotate right through carry
ROTATE
INSTRUCTION ‰ In RRC A
AND DATA ¾ Bits are rotated from left to right
SERIALIZATION ¾ They exit the LSB to the carry flag, and
the carry flag enters the MSB
Rotating
through Carry
MSB LSB CY

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

33
RLC A ;rotate left through carry
ROTATE
INSTRUCTION ‰ In RLC A
AND DATA ¾ Bits are shifted from right to left
SERIALIZATION ¾ They exit the MSB and enter the carry flag,
and the carry flag enters the LSB
Rotating
through Carry
(cont’) CY MSB LSB

Write a program that finds the number of 1s in a given byte.


MOV R1,#0
MOV R7,#8 ;count=08
MOV A,#97H
AGAIN: RLC A
JNC NEXT ;check for CY
INC R1 ;if CY=1 add to count
NEXT: DJNZ R7,AGAIN

34
‰ Transfer a byte of data serially by
ROTATE
INSTRUCTION ¾ Moving CY to any pin of ports P0 - P3
AND DATA ¾ Using rotate instruction
SERIALIZATION Write a program to transfer value 41H serially (one bit at a time)
via pin P2.1. Put two highs at the start and end of the data. Send the
byte LSB first.
Serializing Data
Solution:
(cont’) MOV A,#41H
SETB P2.1 ;high
SETB P2.1 ;high
MOV R5,#8
AGAIN: RRC A
MOV P2.1,C ;send CY to P2.1
DJNZ R5,HERE
SETB P2.1 ;high
SETB P2.1 ;high
Pin
Register A CY P2.1
D7 D0

36
Write a program to bring in a byte of data serially one bit at a time
ROTATE via pin P2.7 and save it in register R2. The byte comes in with the
INSTRUCTION LSB first.
AND DATA Solution:
SERIALIZATION MOV R5,#8
AGAIN: MOV C,P2.7 ;bring in bit
RRC A
Serializing Data DJNZ R5,HERE
(cont’) MOV R2,A ;save it
Pin
P2.7 CY Register A
D7 D0

37
‰ There are several instructions by which
ROTATE
INSTRUCTION
the CY flag can be manipulated directly
AND DATA Instruction Function
SERIALIZATION SETB C Make CY = 1
CLR C Clear carry bit (CY = 0)
Single-bit CPL C Complement carry bit
Operations with MOV b,C Copy carry status to bit location (CY = b)
MOV C,b Copy bit location status to carry (b = CY)
CY JNC target Jump to target if CY = 0
JC target Jump to target if CY = 1
ANL C,bit AND CY with bit and save it on CY
ANL C,/bit AND CY with inverted bit and save it on CY
ORL C,bit OR CY with bit and save it on CY
ORL C,/bit OR CY with inverted bit and save it on CY

38
Assume that bit P2.2 is used to control an outdoor light and bit P2.5
ROTATE a light inside a building. Show how to turn on the outside light and
INSTRUCTION turn off the inside one.
AND DATA Solution:
SERIALIZATION SETB C ;CY = 1
ORL C,P2.2 ;CY = P2.2 ORed w/ CY
MOV P2.2,C ;turn it on if not on
Single-bit CLR C ;CY = 0
ANL C,P2.5 ;CY = P2.5 ANDed w/ CY
Operations with MOV P2.5,C ;turn it off if not off
CY
(cont’) Write a program that finds the number of 1s in a given byte.
Solution:
MOV R1,#0 ;R1 keeps number of 1s
MOV R7,#8 ;counter, rotate 8 times
MOV A,#97H ;find number of 1s in 97H
AGAIN: RLC A ;rotate it thru CY
JNC NEXT ;check CY
INC R1 ;if CY=1, inc count
NEXT: DJNZ R7,AGAIN ;go thru 8 times

39
SWAP A
ROTATE
INSTRUCTION
‰ It swaps the lower nibble and the higher nibble
AND DATA
SERIALIZATION ¾ In other words, the lower 4 bits are put
into the higher 4 bits and the higher 4 bits
SWAP are put into the lower 4 bits
‰ lệnh SWAP chỉ sử dụng thanh chứa A

before : D7-D4 D3-D0

after : D3-D0 D7-D4

40
(a) Find the contents of register A in the following code.
ROTATE (b) In the absence of a SWAP instruction, how would you
INSTRUCTION exchange the nibbles? Write a simple program to show the
AND DATA process.
SERIALIZATION Solution:
(a)
SWAP MOV A,#72H ;A = 72H
(cont’) SWAP A ;A = 27H
(b)
MOV A,#72H ;A = 0111 0010
RL A ;A = 0111 0010
RL A ;A = 0111 0010
RL A ;A = 0111 0010
RL A ;A = 0111 0010

41
BCD AND ASCII ASCII code and BCD for digits 0 - 9
APPLICATION Key ASCII (hex) Binary BCD (unpacked)
PROGRAMS 0 30 011 0000 0000 0000
1 31 011 0001 0000 0001
2 32 011 0010 0000 0010
3 33 011 0011 0000 0011
4 34 011 0100 0000 0100
5 35 011 0101 0000 0101
6 36 011 0110 0000 0110
7 37 011 0111 0000 0111
8 38 011 1000 0000 1000
9 39 011 1001 0000 1001

42
‰ The DS5000T microcontrollers have a
BCD AND ASCII real-time clock (RTC)
APPLICATION
¾ The RTC provides the time of day (hour,
PROGRAMS
minute, second) and the date (year,
month, day) continuously, regardless of
Packed BCD to whether the power is on or off
ACSII
Conversion
‰ However this data is provided in
packed BCD
¾ To be displayed on an LCD or printed by
the printer, it must be in ACSII format
Packed BCD Unpacked BCD ASCII

29H 02H & 09H 32H & 39H


0010 1001 0000 0010 & 0011 0010 &
0000 1001 0011 1001

43
‰ To convert ASCII to packed BCD
BCD AND ASCII
APPLICATION ¾ It is first converted to unpacked BCD (to
PROGRAMS get rid of the 3)
¾ Combined to make packed BCD
ASCII to
key ASCII Unpacked BCD Packed BCD
Packed BCD
Conversion 4 34 0000 0100
7 37 0000 0111 0100 0111 or 47H

MOV A, #’4’;A=34H, hex for ‘4’


MOV R1,#’7’;R1=37H,hex for ‘7’
ANL A, #0FH;mask upper nibble (A=04)
ANL R1,#0FH;mask upper nibble (R1=07)
SWAP A ;A=40H
ORL A, R1 ;A=47H, packed BCD

44
Assume that register A has packed BCD, write a program to convert
BCD AND ASCII packed BCD to two ASCII numbers and place them in R2 and R6.
APPLICATION
MOV A,#29H ;A=29H, packed BCD
PROGRAMS MOV R2,A ;keep a copy of BCD data
ANL A,#0FH ;mask the upper nibble (A=09)
ASCII to ORL A,#30H ;make it an ASCII, A=39H(‘9’)
MOV R6,A ;save it
Packed BCD MOV A,R2 ;A=29H, get the original
Conversion data
(cont’) ANL A,#0F0H ;mask the lower nibble
RR A ;rotate right
RR A ;rotate right
RR A ;rotate right SWAP A
RR A ;rotate right
ORL A,#30H ;A=32H, ASCII char. ’2’
MOV R2,A ;save ASCII char in R2

45
Assume that the lower three bits of P1 are connected to three
BCD AND ASCII switches. Write a program to send the following ASCII characters
APPLICATION to P2 based on the status of the switches.
PROGRAMS 000 ‘0’
001 ‘1’
010 ‘2’
Using a Look- 011 ‘3’
100 ‘4’
up Table for 101 ‘5’
ASCII 110 ‘6’
111 ‘7’
Solution:
MOV DPTR,#MYTABLE
MOV A,P1 ;get SW status
ANL A,#07H ;mask all but lower 3
MOVC A,@A+DPTR ;get data from table
MOV P2,A ;display value
SJMP $ ;stay here
;------------------
ORG 400H
MYTABLE DB ‘0’,‘1’,‘2’,‘3’,‘4’,‘5’,‘6’,‘7’
END

46
‰ To ensure the integrity of the ROM
BCD AND ASCII
APPLICATION
contents, every system must perform
PROGRAMS the checksum calculation
¾ The process of checksum will detect any
Checksum Byte corruption of the contents of ROM
in ROM ¾ The checksum process uses what is called
a checksum byte
ƒ The checksum byte is an extra byte that is
tagged to the end of series of bytes of data

47
‰ To calculate the checksum byte of a
BCD AND ASCII
APPLICATION
series of bytes of data
PROGRAMS ¾ Add the bytes together and drop the
carries
Checksum Byte ¾ Take the 2’s complement of the total sum,
in ROM and it becomes the last byte of the series
(cont’)
‰ To perform the checksum
operation, add all the bytes,
including the checksum byte
¾ The result must be zero
¾ If it is not zero, one or more bytes of data
have been changed

48
Assume that we have 4 bytes of hexadecimal data: 25H, 62H, 3FH, and 52H.
(a) Find the checksum byte, (b) perform the checksum operation to ensure
data integrity, and (c) if the second byte 62H has been changed
APPLICATION to 22H, show how checksum detects the error.
Solution:
PROGRAMS (a) Find the checksum byte.
25H The checksum is calculated by first adding the
+ 62H bytes. The sum is 118H, and dropping the carry,
Checksum Byte + 3FH we get 18H. The checksum byte is the 2’s
+ 52H complement of 18H, which is E8H
in ROM 118H
(b) Perform the checksum operation to ensure data integrity.
(cont’) 25H
+ 62H Adding the series of bytes including the checksum
+ 3FH byte must result in zero. This indicates that all the
+ 52H bytes are unchanged and no byte is corrupted.
+ E8H
200H (dropping the carries)
(c) If the second byte 62H has been changed to 22H, show how
checksum detects the error.
25H
+ 22H Adding the series of bytes including the checksum
+ 3FH byte shows that the result is not zero, which indicates
+ 52H that one or more bytes have been corrupted.
+ E8H
1C0H (dropping the carry, we get C0H)

49
‰ Many ADC (analog-to-digital converter)
BCD AND ASCII
APPLICATION
chips provide output data in binary
PROGRAMS (hex)
¾ To display the data on an LCD or PC
Binary (Hex) screen, we need to convert it to ASCII
to ASCII ƒ Convert 8-bit binary (hex) data to decimal
Conversion digits, 000 - 255
ƒ Convert the decimal digits to ASCII digits,
30H - 39H

50
2.5. Cấu trúc Ngắt trong 8051
‰ An interrupt is an external or internal
INTERRUPTS event that interrupts the
microcontroller to inform it that a
Interrupts vs.
device needs its service
Polling
‰ A single microcontroller can serve
several devices by two ways
¾ 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
ƒ The program which is associated with the
interrupt is called the interrupt service routine
(ISR) or interrupt handler
‰ (cont’)
INTERRUPTS
¾ Polling
ƒ The microcontroller continuously monitors the
Interrupts vs. status of a given device
Polling ƒ When the conditions met, it performs the sẻvice
(cont’)
ƒ After that, it moves on to monitor the next
device until every one is serviced

‰ Polling can monitor the status of


several devices and serve each of
them as certain conditions are met
¾ The polling method is not efficient, since it
wastes much of the microcontroller’s time by
polling devices that do not need service
¾ ex. JNB TF,target
‰ The advantage of interrupts is that the
INTERRUPTS
microcontroller can serve many
Interrupts vs. devices (not all at the same time)
Polling ¾ Each devices can get the attention of the
(cont’) 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
‰ The microcontroller can also ignore
(mask) a device request for service
¾ This is not possible for the polling method
‰ For every interrupt, there must be an
INTERRUPTS
interrupt service routine (ISR), or
Interrupt interrupt handler
Service Routine ¾ When an interrupt is invoked, the micro-
controller runs the interrupt service
routine
¾ For every interrupt, there is a fixed
location in memory that holds the address
of its ISR
¾ The group of memory locations set aside
to hold the addresses of ISRs is called
interrupt vector table
INTERRUPTS

Interrupt
Service Routine
‰ Upon activation of an interrupt, the
INTERRUPTS
microcontroller goes through the
Steps in following steps
Executing an 1. It finishes the instruction it is executing
Interrupt and saves the address of the next
instruction (PC) on the stack
2. It also saves the current status of all the
interrupts internally (i.e: not on the stack) 3.
It jumps to a fixed location in memory, called
the interrupt vector table, that holds the
address of the ISR
(cont’)
INTERRUPTS 4. The microcontroller gets the address of
the ISR from the interrupt vector table
Steps in and jumps to it
Executing an ƒ It starts to execute the interrupt service
Interrupt subroutine until it reaches the last instruction
(cont’) of the subroutine which is RETI (return from
interrupt)
5. Upon executing the RETI instruction, the
microcontroller returns to the place
where it was interrupted
ƒ First, it gets the program counter (PC)
address from the stack by popping the top
two bytes of the stack into the PC
ƒ Then it starts to execute from that address
‰ Six interrupts are allocated as follows
INTERRUPTS
¾ Reset - power-up reset
Six Interrupts ¾ Two interrupts are set aside for the timers:
in 8051 one for timer 0 and one for timer 1
¾ Two interrupts are set aside for hardware
external interrupts
ƒ P3.2 and P3.3 are for the external hardware
interrupts INT0 (or EX1), and INT1 (or EX2) ¾
Serial communication has a single interrupt
that belongs to both receive and transfer
Interrupt vector table
INTERRUPTS
Interrupt ROM Location Pin
(hex)
Six Interrupts Reset 0000 9
in 8051 External HW (INT0) 0003 P3.2 (12)
(cont’) Timer 0 (TF0) 000B
External HW (INT1) 0013 P3.3 (13)
Timer 1 (TF1) 001B
Serial COM (RI and TI) 0023

ORG 0 ;wake-up ROM reset location


LJMP MAIN ;by-pass int. vector table
;---- the wake-up program
ORG 30H
MAIN: Only three bytes of ROM space
assigned to the reset pin. We put
the LJMP as the first instruction
END and redirect the processor away
from the interrupt vector table.
‰ Upon reset, all interrupts are disabled
INTERRUPTS
(masked), meaning that none will be
Enabling and responded to by the microcontroller if
Disabling an they are activated
Interrupt ‰ 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
IE (Interrupt Enable) Register
INTERRUPTS
D7 D0
EA -- ET2 ES ET1 EX1 ET0 EX0
Enabling and
Disabling an EA (enable all) must be set to 1 in order
Interrupt for rest of the register to take effect

(cont’) EA IE.7 Disables all interrupts


-- IE.6 Not implemented, reserved for future use
ET2 IE.5 Enables or disables timer 2 overflow or capture
interrupt (8952)
ES IE.4 Enables or disables the serial port interrupt
ET1 IE.3 Enables or disables timer 1 overflow interrupt
EX1 IE.2 Enables or disables external interrupt 1
ET0 IE.1 Enables or disables timer 0 overflow interrupt
EX0 IE.0 Enables or disables external interrupt 0
‰ To enable an interrupt, we take the
INTERRUPTS
following steps:
Enabling and 1. Bit D7 of the IE register (EA) must be set
Disabling an to high to allow the rest of register to
Interrupt take effect
(cont’) 2. The value of EA
¾ If EA = 1, interrupts are enabled and will be
responded to if their corresponding bits in IE
are high
¾ If EA = 0, no interrupt will be responded to,
even if the associated bit in the IE register is
high
Example 11-1
INTERRUPTS Show the instructions to (a) enable the serial interrupt, timer 0
interrupt, and external hardware interrupt 1 (EX1),and (b) disable
Enabling and (mask) the timer 0 interrupt, then (c) show how to disable all the
interrupts with a single instruction.
Disabling an
Solution:
Interrupt
(cont’) (a) MOV IE,#10010110B ;enable serial,
;timer 0, EX1
Another way to perform the same manipulation is
SETB IE.7 ;EA=1, global enable
SETB IE.4 ;enable serial interrupt
SETB IE.1 ;enable Timer 0 interrupt
SETB IE.2 ;enable EX1
(b) CLR IE.1 ;mask (disable) timer 0
;interrupt only
(c) CLR IE.7 ;disable all interrupts
Chương 2
Intel 8051: Interrupt Control
7 6 5 4 3 2 1 0
IE EA - - ES ET! EX1 ET0 EX0

• EA: Enable/Disable all interrupts


• If EA=0 no interrupts will be acknowledged
• If EA=1 each interrupt source is individually
enabled/disbled
• ES: Serial Port interrupt enable bit
• ET: Timer interrupt enabled bit
• EX: External interrupt enable bit
Chương 2
Intel 8051: Interrupt Control
IT 0=0

IN T 0 IE 0
•5interrupt IT 0=1

sources
• 2 external TF0

(INT0, INT1) IT 1=0

• 2 timers IN T 1 IE 1
IN T E R R U P T
SOURCE

(TF0, TF1) IT 1=1

• Serial Port TF1


(RI or TI)
RI
TI
Chương 2
Intel 8051: Interrupt Control
• External interrupts
• Level-activated or transition-activated IT0=0

depending on bits IT0, IT1 in register TCON INT0

IT0=1
IE0

• The flags that generate these interrupts are


IE0, IE1 in TCON
• Cleared by hardware if the interrupt was transition-activated
• if the interrupt was level-activated,
external source controls request bits
• If external interrupt is level-activated,
the external source has to hold request active,
until the requested interrupt is actually generated.
• External source has to deactivate the request
before interrupt service is completed,
or else another interrupt will be generated
Chương 2
Intel 8051: Interrupt Control
• Timer interrupts
• Interrupts are generated by TF0 and TF1 in register TCON
• When a timer interrupt is generated, the flag that generated
it is cleared by hardware when the service routine is
vectored to
• Serial Port interrupt
• generated by the logical OR of bits RI and TI in register SCON

TI
RI
Chương 2

Intel 8051: Interrupt Control


7 6 5 4 3 2 1 0
IP - - - PS PT1 PX1 PT0 PX0

• Priority bit=1: High Priority; Priority bit=0: Low Priority


• PS: Serial Port priority bit
• PT: Timer priority bit
• PX: External priority bit
Chương 2
Intel 8051: Interrupt Control
• A low-priority interrupt can be interrupted by a higher priority
interrupt, but not by another low-priority interrupt
• A high priority interrupt
cannot be interrupted by any other interrupt source
• If two requests are received simultaneously,
the request of higher priority level is serviced
• If requests of the same priority level are received simultaneously, an
internal polling sequence determines which request is serviced
• ``priority within level'' structure is only used
to resolve simultaneous requests of the same priority level.
Chương 2
Intel 8051: Interrupt Control
Interrupt Priority
within Level Polling Sequence
1 (Highest) External Interrupt 0
2 Timer 0
3 External Interrupt 1
4 Timer 1
5 (Lowest) Serial Port

You might also like