Anda di halaman 1dari 178

The 8051 Microcontroller

Architecture & Interfacing

Facilitated By:
Siva Prasad.
UTS
Your Expectations…
Topics that will be covered in this Module
 Embedded Systems Overview

 Processor Architecture
 Internal Architecture of 8051 Microcontroller
 Cross Platform Development Model
 ALP & Addressing Modes
 Instruction Set Architecture
 Study of various on chip peripherals
 External interfacing Techniques
 Timers & Counters

 Serial Communication
 Interrupt Handling
 Embedded Communication Protocols
Objectives of the Module
Goals:-
 Deep Level Of Understanding Of 8051
Architecture & Internal Mechanisms.
 Understanding Of External Interfacing
Techniques.
 Basic Understanding Of Embedded
Systems Development Environment.
Embedded System Definition
• An Embedded system
 Employs a combination of hardware & software ( a
“computational engine”) to perform a specific function.
 Is a part of larger system that may not be a computer.
 Works in a reactive & time constrained environment.
 Software is used for providing features & flexibility.
 Hardware (processor, ASICs, memory,…) is used for
performance (& sometimes security)
• There are wide range of applications for embedded
systems. Following are few Domains.
– Consumer Products
– Automobile
– Aerospace/Avionics & defense applications
– Process Control & Industrial Automation
Embedded ? System ?
Embedded can mean: System can mean:
– Instructions (code or logic) are – A set of one or more
permanently loaded into the
processor.
microelectronic devices
with some, or all, of the
– Dedicated purpose (not
general purpose).Not capacities of a computer.
designed to be programmed – A processor (such as a
by the end user always runs mainframe computer,
on a fixed application. minicomputer or PC) is
– The components of the usually a general purpose,
system are internal to the
which provides facilities
device that contains them,
and not necessarily visible, for incorporating other
even to experts. features & development
– The design depends on the environments.
environment in which the
system will be mounted.
CPUs
• CPUs can be
– Microprocessors or Micro controllers

• Any CPU can be studied by knowing following


features of CPU
– Clock speed, Address bus size, Data bus size, Register size
– Register set, Instruction set, Address spaces
– Interrupt support
– Instruction and Data cache
– Memory management
– Protection features (user/supervisor modes)
Memory
• The semiconductor memory can be classified
into two types
– Volatile Memory
– Non-volatile memory
• Volatile memory
– Static RAM
– Dynamic RAM
• Non-volatile memory
– ROM
– EPROM
– EEPROM
– FLASH
– Battery backup RAM
I/O Interfaces
• In an embedded system I/O interfaces are responsible
for controlling or monitoring the functionality. Following
are the typical interfaces found in an embedded system
• Digital Interface
– Digital input and output lines
• Analog interface
– Analog input and output channels
• Serial interface
– RS-232, RS-485, I2C,CAN,SPI
• LAN Interface
• Display Interface
– LCD,LED
Basic Concepts
• Microprocessor Vs Microcontroller
• Microcontroller Classification
• Architecture Types
• CISC & RISC
• Memory Mapped IO & IO Mapped IO
• Embedded Development Environment
Micro Processors

• Micro Processor is the Integration of a


number of useful function in a single IC
Package .These functions are
1)Execute the stored set of instructions to
carry out user defined task.
2)Ability to access external memory chips
for both read and write data from and to
the memory
Microprocessor Vs Microcontroller
• Contains ALU,GP • In addition in built ROM,
Registers,SP,PC,Clock RAM, IO devices,Timers
timing circuit and interrupts ideal for applications in
• Provides the advantage of which cost & space are
versatility to designer to critical.
decide upon the additional
features required. • Many bit handling
• one or two bit handling instructions are present &
instructions & here the here the pins are
instruction set is aimed at programmable
expediting external memory • Requires less H/W, reduces
access process PCB size & increases
• Requires more H/W, reliabilit
increase in PCB size
Classification of Microcontrollers
• μc are classified into :
– 8 bit μc e.g.: Intel 8051, Motorola HC05
– 16 bit μc e.g.: Siemens 80167, Intel 80C196
– 32 bit μc e.g.: ARM, Power PC 8xxx
– 64 bit μc e.g.: Texas 64xxx series
– 128 bit μc e.g.:
• The number of bits indicate the internal data bus of a μc.
It shows how many bits of data the μc can process
simultaneously.
Princeton(Vonneumann) Vs Harvard
• Single Main Memory holding • Contains 2 separate
both program and Data memory spaces- code
• Data/Instruction size remains & data
same
• Simple memory structure • Different code/data path
Since single fetch operation at sizes possible
a time • Complex memory
• Comparatively slower in Structure
execution
• Faster in execution
• eg: 8085,68K series
(parallelism)
• eg: 8051,PIC,DSP
processors
Architectures

CODE CPU DATA

CPU CODE & DATA


RISC Vs CISC
Fixed width instructions Variable length
instruction
Few formats of Several formats of
instructions instructions
Load/Store Architecture Memory values can be
used as operands in
instructions
Large Register bank Small Register Bank
Instructions are Cannot pipeline
pipelinable instructions
RISC CISC
Hardwired instruction Microcode ROMS
decode instruction decoder
Single cycle Multi cycle execution
execution of on instruction
instruction
Memory Mapped IO IO Mapped
IO
• IO devices are treated as • IO devices are
like memory separately interfaced
• Memory related • Separate instruction set
instructions should be available
used to access IO

memory memory
Input
Input CPU
CPU memory
output output
Embedded Development
Environment
 Host – Target Development Environment
 Cross Compilers
 Typical Microcontroller Firmware
development
cycle

 Downloading
 Debugging Features
Host - Target Development
Environment
• The distinguishing feature of embedded software development is
host-target development environment
• All the development tools like Editors, compilers and linkers are
available on the host machine
• Typical host machines are Windows 95/98, NT and Unix
workstations where the above development tools are available
• Application programs will be written on the host, get compiled,
linked and get the executable file
• Target systems are the ones where compiled and linked code is
executed
• Target systems being a microprocessor based boards does not offer
any development environment themselves, so an host machine is
required.
Cross Compiler
• Another distinguishing feature of embedded
software development is cross compiler
• Runs on a machine based on one type of CPU and
produces a machine instructions for a different
kind of CPU
• Allows execution at development time
• Possible to target multiple instruction sets
Microcontroller’s Firmware Development Cycle
Downloading
• Downloading is the process of loading the
executable image prepared on the host
system on to a target board
• There are various methods to download
the code to a target machine. They are:
– Serial ports
– EPROM/FLASH
– Floppy disks
– Ethernet
– Across a common Bus
Debug monitor commands
• Following are the typical commands of
debug monitor
– Display memory, Modify memory, Disassemble memory, Fill
memory, Search Memory, Move memory
– Display registers, Modify registers
– Display I/O locations, Modify I/O locations
– Download application program, Pass control to the application
program, Single stepping the assembly instructions
– Set break points, Display break points, Clear break point
Microcontroller
• Microcontroller is a device which integrates number of
components of a microprocessor system onto a single chip. It
typically includes:-
 CPU (Central Processing unit)
 RAM & ROM
 I/O inputs & outputs – Serial & Parallel
 Timers
 Interrupt Controller
By including the features that are specific to the task
(Control) , Cost is relatively low.Microcontroller are a “one chip
solutions” which drastically reduces parts count and design
costs.
Microcontroller
Microcontroller
General features of a
Microcontroller
• Microprocessor:
> Heart of the Microcontroller
> Can understand a fixed set of commands
> Can generate signals to control external
devices
> Contains limited set of on chip memory
called Registers
On Chip Memory

• Used to store information


Memory

RAM (Volatile)
ROM(Non Volatile)
1.SRAM
1.PROM
2.DRAM
2.UV-EPROM
3.NV-RAM
3.EEPROM
4.FLASH
I/O Ports
• Used to interface with the peripheral devices and
the controller.
Additional on chip peripherals
on an advanced 8051 controller
• Watchdog Timer & Power Monitoring
• ADC & DAC
• SPI,I2C,CAN
• Built in Temp. Sensor
• Flash Memory & External On Chip RAM
• JTAG Support
• Internal Programmable Oscillator
A/D converter
• Converts Analog to Digital

Transducer A/D CPU


Session-2
• Design requirements
• Choosing a 8 bit controller
• Companies producing 8051
• Block diagram of 8051
• Architectural concepts
• 8051 flavors
Design Requirements & Selection of Microcontrollers

Cost

Avail Speed

Dev MICRO
Tools CONTROLLER Package

No of Power
Pins Consp
Memory
Major 8 bit Controller Family
• Motorola 6811
• Intel 8051
• Microchip 16Fxx
• Zilog Z80
Companies Producing 8051
• Intel
• Atmel
• Philips
• Seimens
• Dallas
• Maxim
• Sharp and many more…
Block Diagram
External interrupts

4K ROM
Interrupt program 128 bytes Timer0 Counter
Control code
RAM Timer1 Inputs

CPU

Bus Serial
4 I/O Ports Port
OSC Control

TXD RXD
P0 P2 P1 P3
Address/Data
Pin Description of 8051

P1.0 1 40 Vcc
P1.1 2 39 P0.0(AD0)
P1.2 3 8 38 P0.1(AD1)
P1.3 4 37 P0.2(AD2)
P1.4 5 36 P0.3(AD3)
P1.5 6 35 P0.4(AD4)
P1.6
P1.7
7
8
0 34
33
P0.5(AD5)
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 5 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
(RD)P3.7
16
17
1 25
24
P2.4(A12)
P2.3(A11)
XTAL2 18 23 P2.2(A10)
XTAL1 19 22 P2.1(A9)
GND 20 21 P2.0(A8)
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.
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 for 2 machine cycles.
– It is a power-on reset.
• High logical state on this input halts the MCU and
clears all the registers.
• Bringing this pin back to logical state zero starts the
program a new as if the power had just been turned on.
In another words, positive voltage impulse on this pin
resets the MCU.

– Way 1 : Power-on reset circuit

– Way 2 : Power-on reset with debounce


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
XTAL Connection to
External Clock Source

NC XTAL2

Using a TTL oscillator


EXTERNAL
XTAL2 is unconnected. OSCILLATOR
SIGNAL XTAL1

GND
Architectural concepts of 8051
Microcontroller
• Operates with single Power Supply +5V
• 8-bit CPU optimized for control applications
• 16-bit Program Counter (PC) and 16-bit
Data Pointer (DPTR)
• 8-bit Program Status Word (PSW)
• 8-bit Stack Pointer (SP)
• 4K Bytes of On-Chip Program Memory
(Internal ROM or EPROM or Flash)
• 128 bytes of On-Chip Data Memory (Internal RAM):
Four Register Banks, each containing 8 registers
(R0 to R7)
(Total 32 registers)
16 bytes of bit addressable memory i.e.., 128 bits
80 bytes of general-purpose data memory
(Scratch Pad Area)
• Special Function Registers (SFR’s) to configure/operate
microcontroller
• 32 bit bi-directional I/O Lines (4 ports - P0 to P3)
• Two 16-bit timers/counters (T0 and T1)
•Full duplex UART (Universal Asynchronous
Receiver/Transmitter)
•6-source/5-vector interrupts (2 external and 3
internal) with two priority levels
•On-Chip oscillator and clock circuitry
(Address - 0E0h)

• 8 - Bit Register
• Used for operations such as
• Addition
• Subtraction
• Multiplication
• Division &
• Bit Manipulations
• Used for Data Transfer Between 8051 & External
memory
• Used to store Results obtained from Arithmetic as
well as logical Operations
• Bit Addressable Register
(Address - 0F0h)

• Used for direct Multiplication & Division


operations with Accumulator.
• Can be used as general purpose storage location
with its direct address 0F0h.
• Bit Addressable Register.
(Address - 0D0h)
• 8 - Bit Register
• Consists of 5 FLAGS
• 4 MATH FLAGS
• Carry
•Auxiliary Carry
• Parity
• Overflow
• 1 USER DEFINED FLAG
Bit Flag Description

7 CY Carry flag; used in arithmetic, jump,


rotate and Boolean instructions.
6 AC Auxiliary carry; used for BCD
arithmetic
5 F0 User defined flag 0
4 RS1 Register bank select bit-1
3 RS0 Register bank select bit-0
RS1 RS0 Bank Select
0 0 Bank - 0
0 1 Bank - 1
1 0 Bank - 2
1 1 Bank - 3

Bit Flag Description

2 OV Overflow flag; used in arithmetic


instructions
1 - Reserved for future use

0 P Parity flag; shows parity of register A;


‘1’ => Odd parity; ‘0’ => Even Parity
(Address - 81h)

• 8 - Bit Register.
• Stack Pointer is Initialized to 07h at RESET
condition.
• Instructions such as PUSH and POP modify SP.
• UP - GROWING stack.
• Can be reinitialized to any desired location by the
user.
(Direct Address - NIL)

• 16 - Bit Register
• Used to hold the Address of external Data
Memory.
• Can be used as two individual 8 - bit registers
such as
• Data Pointer High (DPL) - Address 82h
• Data Pointer Low (DPH) - Address 83h
DPH 83h DPL 82h

DPTR

• No direct address is assigned for DPTR but can be


individually addressed
(Direct Address - NIL)

• 16 - Bit Register
• Used to hold the Address of the next instruction
to be executed
• Not directly accessible to the programmer.
• No internal address.
• Group of registers used for specific purposes
in 8051 microcontroller mainly to
• Configure
• Control, &
• operate.
• Uses address locations from 80h to 0ffh.
• Accumulator - A*
• Register B - B*
• Program Counter - PC
• Data Pointer - DPTR
• Stack Pointer - SP
• Program Status Word - PSW
• Ports - P0* , P1* , P2* , P3* .
• Timer Load Registers - TL0/1 & TH0/1
• Timer Config. & Ctrl Reg. - TCON*, TMOD
• Serial Comm. Control Register - SCON*
• Serial Comm. Buffer Register - SBUF
• Program Control Register - PCON
• Interrupt Enable Register - IE*
• Interrupt Priority Register - IP*

NOTE:
Registers marked with * are both Bit as well as Byte Addressable
• External bus of 8051 is grouped
into 4 ports namely:
• Port - 0
• Port - 1
• Port - 2
• Port - 3
• These ports supports all the three types of
buses namely:

• Address Bus,
• Data Bus, &
• Control Bus.
• All the ports are Bi - directional.
• All the ports are Bit as well as Byte addressable.
• The addresses of the ports are as shown below:

PORTS ADDRESS
PORT 0 080h
PORT 1 090h
PORT 2 0A0h
PORT 3 0B0h
8051 BLOCK DIAGRAM
I/O

Port 0
A0-A7
ALU PSW SFR
D0-D7

Port 1
I/O

A B

Port 2
I/O
A8-A15

DPTR
PC DPH ROM
I/O

Port 3
DPL INT
CNTR
SERIAL
RD/WR
Friday, October 22, 2010
~EA
BYTE / BIT SFR
ALE System Timing
ADDRESSIBLE
PSEN IE
System Interrupt
XTAL1 RB3 IP
Timers
XTAL2 PCON
RB2
RESET Data Buffers SBUF
VCC Memory Controls RB1
SCON
GND
RB0 TCON
TMOD
TL0
TH0
TL1
TH1

INTERNAL RAM STRUCTURE


Friday, October 22, 2010
A* B* IP* IE* TMOD TCON*
E0 F0 B8 A8 89 88

MATH REGISTERS INTERRUPT REGISTERS TIMER CONTROL REG

THO TLO TH1 TL1


8C 8A 8D 8B

TIMER / COUNTER REGISTERS

SCON* SBUF PCON PSW*


98 99 87 D0

SERIAL DATA REGISTERS FLAGS

SP
81

Friday, October 22, 2010


DPTR
DPH DPL PC
83 82

PORT 0* PORT 1* PORT 2* PORT 3*


LATCH LATCH LATCH LATCH
80 90 A0 B0

Friday, October 22, 2010


TIMERS & COUNTERS
THE TIMER CONTROL (TCON)
7 6 5 4 3 2 1 0
TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0

7 TF1 Timer 1 Overflow flag. Set when timer rolls from all 1s to 0. Cleared when processor
vectors to execute interrupt service routine located at program address 001Bh.
6 TR1 Timer 1 run control bit. Set to 1 by program to enable timer to count; cleared to 0 by program to
halt timer. Does not reset timer.
5 TF0 Timer 0 Over flow flag. Set when timer rolls from all 1s to 0. Cleared when processor
vectors to execute interrupt service routine located at program address 000Bh.
4 TR0 Timer 0 run control bit. Set to 1 by program to enable timer to count; cleared to 0 by program to
halt timer. Does not reset timer.
3 IE1 External interrupt 1 Edge flag. Set to 1 when a high-to-low edge signal is received on port 3 pin
3.3 (INT 1). Cleared when processor vectors to interrupt service routine located at program
address 0013h. Not related to timer operations.
2 IT1 External interrupt 1 signal type control bit. Set to 1 by program to enable external interrupt 1 to
be triggered by a falling edge signal. Set to 0 by program to enable a low-level signal or external
interrupt 1 to generate an interrupt.
1 IE0 External interrupt 0 Edge flag. Set to 1 when a high-to-low edge signal is received on port 3 pin
3.2 (INT 0). Cleared when processor vectors to interrupt service routine located at program
address 0003h. Not related to timer operations.
0 IT0 External interrupt 0 signal type control bit. Set to 1 by program to enable external interrupt 0 to
be triggered by a falling edge signal. Set to 0 by program to enable a low-level signal or external
interrupt 0 to generate an interrupt. Friday, October 22, 2010
THE TIMER MODE CONTROL (TMOD)
7 6 5 4 3 2 1 0
Gate C/T M1 M0 Gate C/T M1 M0

Timer 1 Timer 0

7/3 Gate OR gate enable bit which controls Run/ Stop of timer
6/2 C/T Set to 1 by program to make timer act as counter
5/1 M1 Mode select bit 1
4/0 M0 Mode select bit 0
M1 M0 Mode
0 0 0
0 1 1
1 0 2
1 1 3

Friday, October 22, 2010


• 8051 supports two types of memories.
They are:
• Internal Memory
• External Memory
PROGRAM MEMORY ORGANIZATION

• 8051 Microcontroller supports


• 64 Kbytes of External Program Memory
• 4Kbytes of Internal Program Memory plus
60K bytes of External Program Memory.
INTERNAL MEMORY ORGANIZATION
• On - Chip memory in built to the
Microcontroller.
• It has separate
• on - chip DATA Memory - 128 bytes RAM
• on - chip PROGRAM Memory - 4Kbytes of
ROM
INTERNAL RANDOM ACCESS MEMORY (RAM)

• 128 bytes of internal memory is grouped as:


• Register Bank
• Bit Addressable Area
• Scratch Pad Area
Internal Data Memory

Accessible by Accessible by direct


indirect addressing Addressing(SFR Area)
(80-FF)=128 bytes (80-FF)=128 bytes

Accessible by direct
& indirect addressing
(00-7F)=128 bytes
Lower 128 bytes of internal RAM

Scratch Pad Area


(30-7F)
SP=07
Bit & Byte Addressable RS1=0
Area (20-2F) RS0=0
Bank3(18-1F)
Bank2 (10-17)
Bank1(08-0F)
Bank0 (00-07)
REGISTER BANK

REGISTER BANK 0 REGISTER BANK 1 REGISTER BANK 2 REGISTER BANK 3


RB0 07h RB0 0Fh RB0 17h RB0 1Fh

RB0 00h RB0 08h RB0 10h RB0 18h


• Toselect the register banks, there are 2 bits
present in PSW:
• RS0
• RS1
BIT ADDRESSABLE AREA

• 16 eight bit locations, ranging from 20h to 2Fh


are bit addressable.
16 locations * 8 bits = 128 bits

i.e.., 128 bits can be individually addressed.


• These bits can be addressed as
20.0h to 2F.7h
or
00h to 7Fh.
SCRATCH PAD AREA

• Locations from 30h to 7Fh are available as


Scratch Pad area.

• Can store data such as partial results and such


variables.
i.e., as general purpose locations
Thus,
4 - register banks => 32 bytes
1 bit addressable area => 16 bytes
1 scratch pad area => 80 bytes
128 bytes of
INTERNAL RAM
INTERNAL READ ONLY MEMORY (ROM)

0FFFh

4 Kbytes of
Internal
ROM

0000h
EXTERNAL MEMORY ORGANIZATION

• 8051 Microcontroller supports up-to


• 64 Kbytes of Data Memory
• 64 Kbytes of Program Memory
• 8051 Microcontroller is interfaced and accessed
to external memory using 16 address lines
available on PORT0 and PORT 2.
• Address and Data lines are multiplexed using
PORT0.
• De - multiplexing of the address and data lines
are done by ALE signal
DATA MEMORY ORGANIZATION

• 8051 Microcontroller supports


• 64 Kbytes of External Data Memory
• 128bytes of Internal Data Memory
External Memory Interface
ADD-H

8051 Memory
Latch ADD-L
• External Data Memory is accessed using
16 - bit address lines.
RD bar and WR bar are used as strobe signals
• Address range : 0000h to 0FFFFh
- External Memory
00h to 7Fh
- Internal Memory
FFFFh
FFh
SFR’s
Direct
Addressing
64 Kbytes
only
80h of
External
7Fh Direct Memory
& In Direct
Addressing
only
00h
0000h
Program Memory
64K FFFFH

4K External
0FFFH ROM

EA=0
Internal
ROM

EA=1

0000H 0000H

PSEN
Data Memory
64K FFFFH

128 bytes
External
7FH RAM

Internal
RAM

00H 0000H

WR RD
Internal RAM allocation
7FH

General RS1 RS0 Register Bank Address


purpose RAM 0 0 0 00H-07H

0 1 1 08H-0FH

30H 2FH 1 0 2 10H-17H

Mixed Bit/Byte 1 1 3 18H-1FH


Addressable

1FH 20H

Register Bank3
18H 17H
Register Bank2

0FH 10H

Register Bank1
08H 07H Stack
Pointer
Register Bank0
00H
Internal RAM and SFR
region
FFH FFH

Upper Accessible
Accessible SFR
128 by Indirect by Direct
addressing addressing
only Ports,
only
Timers,
Control
Registers,
80H 80H
Accumulator
7FH
,Stack
Pointer,
Accessible
Etc,.
by Direct &
Lower Indirect
128 addressing

00H
SFR Memory map
FF
F8
B F7
F0
EF
E8
ACC E7
E0
DF
D8
PSW D7
D0
CF
C8
C7
C0
IP BF
B8
P3 B7
B0
IE AF
A8
P2 A7
A0
SCON SBUF 9F
98
P1 97
90
TCON TMOD TL0 TL1 TH0 TH1 8F
88
P0 SP DPL DPH PCON 87
80
Program status Word

CY AC F0 RS1 RS0 OV -- P

CY PSW.7 Carry Flag


AC PSW.6 Auxiliary Carry flag
F0 PSW.5 Available to user for general purpose
RS1 PSW.4 Register bank selector bit 1
RS0 PSW.3 Register bank selector bit 0
OV PSW.2 Overflow flag
-- PSW.1 Not defined
P PSW.0 Parity flag. Set/cleared by hardware to
indicate an odd/even number of ‘1’ in the
accumulator.
• External Program Memory is accessed using
16 - bit address lines.
 PSEN is used as read strobe for external
program memory
• Address range : 0000h to 0FFFFh
FFFFh
FFFFh
60Kbytes
of External
ROM
1000h

+ 64 Kbytes
OR of
External
0FFFh ROM

4Kbytes of
Internal 0000h
ROM
0000h
8051 Memory Structure

External
External
(64Kb)
indirect direct
(128) (128)

EA bar=0 EA bar=1 direct


External Internal & indirect
(128)
The 8051 Assembly Language
Overview
• Data transfer instructions
• Addressing modes
• Data processing (arithmetic and logic)
• Program flow instructions
Data Transfer Instructions
MOV dest, source dest  source
6 basic types:
MOV a, byte ;move byte to accumulator
MOV byte, a ;move accumulator to byte
MOV Rn, byte ;move byte to register of
;current bank
MOV direct, byte ;move byte to internal RAM
MOV @Rn, byte ;move byte to internal RAM
;with address contained in Rn
MOV DPTR, data16 ;move 16-bit data into data
;pointer
Other Data Transfer Instructions
• Stack instructions
PUSH byte ;increment stack pointer,
;move byte on stack
POP byte ;move from stack to byte,
;decrement stack pointer
• Exchange instructions
XCH a, byte ;exchange accumulator and
;byte
XCHD a, byte ;exchange low nibbles of
;accumulator and byte
Addressing Modes
Immediate Mode – specify data by its value

mov a, #0 ;put 0 in the accumulator


a = 00000000
mov a, #0x11 ; put 11hex in the accumulator
a = 00010001
mov a, #11 ; put 11 decimal in accumulator
a = 00001011
mov a, #77h ; put 77 hex in accumulator
a = 01110111
Addressing Modes
Direct Mode – specify data by its 8-bit address
mov a, 0x70 ; copy contents of RAM at 70h to a

mov 0xD0, a ; put contents of a into PSW


Addressing Modes
Register Addressing – either source or
destination is one of R0-R7

mov R0, a

mov a, R0
Play with the Register Banks
Addressing Modes
Register Indirect – the address of the source or
destination is specified in registers
Uses registers R0 or R1 for 8-bit address:
mov psw, #0 ; use register bank 0
mov r0, #0x3C
mov @r0, #3 ; memory at 3C gets #3
; M[3C]  3
Uses DPTR register for 16-bit addresses:
mov dptr, #0x9000 ; dptr  9000h
mov a, @dptr ; a  M[9000]

Note that 9000 is an address in external memory


Exercise: Use Register
Indirect to access upper RAM
block
Learn about Include Files
Addressing Modes
• Register Indexed Mode – source or
destination address is the sum of the base
address and the accumulator.
• Base address can be DPTR or PC
mov dptr, #4000h
mov a, #5
movc a, @a + dptr ;a  M[4005]
Addressing Modes
• Register Indexed Mode
• Base address can be DPTR or PC
Addr cseg at 0x1000h
1000 mov a, #5
1002 movc a, @a + PC ;a  M[1008]
PC 1003 nop
Table Lookup
Address Modes
Stack-oriented data transfer – another form of
register indirect addressing, but using SP

mov sp, #0x40 ; Initialize SP


push 0x55 ; SP  SP+1, M[SP]  M[55]
; M[41]  M[55]
pop b ; b  M[55]

Note: can only specify RAM or SFRs (direct mode) to push or pop.
Therefore, to push/pop the accumulator, must use acc, not a:

push acc
push a
Stacks
pop
push

stack pointer

stack
Address Modes
Exchange Instructions – two way data
transfer
XCH a, 0x30 ; a  M[30]
XCH a, R0 ; a  R0
XCH a, @R0 ; a  M[R0]
XCHD a, R0 ; exchange
a[7..4] a[3..0] R0[7..4] R0[3..0]
“digit”
Address Modes
• Bit-Oriented Data Transfer – transfers between individual bits.
• SFRs with addresses divisible by 0 or 8 are bit-addressable. (80, 88, 90, 98, etc)
• Carry flag (C) (bit 7 in the PSW) is used as a single-bit accumulator

Examples:
mov C, P0.0 ; C  bit 0 of P0
Bit Addressable Memory
2F 7F 78
20h – 2Fh (16 locations X
2E 8-bits = 128 bits)
2D
2C
Bit addressing:
2B
mov C, 1Ah
2A
29
or
28 mov C, 23h.2
27
26
25
24
23 1A

22 10
21 0F 08
20 07 06 05 04 03 02 01 00
SPRs that are Bit Addressable
Address Register

SPRs with addresses 0xF8 SPI0CN


0xF0 B
of multiples of 0 and 0xE8 ADC0CN
8 are bit 0xE0 ACC

addressable. 0xD8
0xD0
PCA0CN
PSW
SFRs 0xC8 T2CON
0xC0 SMB0CN
Notice that all 4 0xB8 IP
Pink are
parallel I/O ports are implemented in
0xB0 P3
0xA8 IE
bit addressable. enhanced
C8051F020 0xA0 P2
0x98 SCON
0x90 P1
0x88 TCON
0x80 P0
Go Access the Port Bits….
Part II

The 8051 Assembly Language


Program Template

Use this template as a starting


point for future programs.
Data Processing Instructions

Arithmetic Instructions
Logic Instructions
Arithmetic Instructions
• Add
• Subtract
• Increment
• Decrement
• Multiply
• Divide
• Decimal adjust
Arithmetic Instructions
Mnemonic Description
ADD A, byte add A to byte, put result in A
ADDC A, byte add with carry
SUBB A, byte subtract with borrow
INC A increment A
INC byte increment byte in memory
INC DPTR increment data pointer
DEC A decrement accumulator
DEC byte decrement byte
MUL AB multiply accumulator by b register
DIV AB divide accumulator by b register
DA A decimal adjust the accumulator
ADD Instructions
add a, byte ; a  a + byte
addc a, byte ; a  a + byte + C
These instructions affect 3 bits in PSW:
C = 1 if result of add is greater than FF
AC = 1 if there is a carry out of bit 3
OV = 1 if there is a carry out of bit 7, but not from bit 6,
or visa versa.
Instructions that Affect PSW bits
ADD Examples
mov a, #0x3F • What is the value of
add a, #0xD3 the C, AC, OV flags
after the second
0011 1111 instruction is
1101 0011 executed?
0001 0010
C = 1
AC = 1
OV = 0
Signed Addition and Overflow
0111 1111 (positive 127)
2’s complement: 0111 0011 (positive 115)
0000 0000 00 0 1111 0010 (overflow
cannot represent 242 in 8
… bits 2’s complement)
0111 1111 7F 127
1000 1111 (negative 113)
1000 0000 80 -128
1101 0011 (negative 45)
… 0110 0010 (overflow)
1111 1111 FF -1
0011 1111 (positive)
1101 0011 (negative)
0001 0010 (never overflows)
The ADD example…..
Subtract
SUBB A, byte subtract with borrow

Example:

SUBB A, #0x4F ; A  A – 4F – C

Notice that there is no subtraction WITHOUT borrow. Therefore, if


a subtraction without borrow is desired, it is necessary to clear the C
flag.
Increment and Decrement
INC A increment A
INC byte increment byte in memory
INC DPTR increment data pointer
DEC A decrement accumulator
DEC byte decrement byte

• The increment and decrement instructions do NOT


affect the C flag.

• Notice we can only INCREMENT the data pointer,


not decrement.
Example: Increment 16-bit Word
• Assume 16-bit word in R3:R2

mov a, r2
add a, #1 ; use add rather than increment to affect C
mov r2, a
mov a, r3
addc a, #0 ; add C to most significant byte
mov r3, a
Multiply
When multiplying two 8-bit numbers, the
size of the maximum product is 16-bits
FF x FF = FE01
(255 x 255 = 65025)

MUL AB ; BA  A * B

Note: B gets the HIGH byte, A gets the LOW byte


Go forth and multiply…
Division
Integer Division
DIV AB ; divide A by B

A  Quotient(A/B), B  Remainder(A/B)

OV - used to indicate a divide by zero condition.


C – set to zero
Decimal Adjust
DA a ; decimal adjust a

Used to facilitate BCD addition. Adds “6” to either high or


low nibble after an addition to create a valid BCD
number.

Example:
mov a, #0x23
mov b, #0x29
add a, b ; a  23 + 29 = 4C (wanted 52)
DA a ; a  a + 6 = 52
Logic Instructions

Bitwise logic operations (AND, OR, XOR, NOT)


Clear
Rotate
Swap

Logic instructions do NOT affect the flags in PSW


Bitwise Logic
Examples:
ANL – AND 00001111
ANL 10101100
ORL – OR 00001100
XRL – eXclusive OR
00001111
CPL – Complement ORL 10101100
10101111

00001111
XRL 10101100
10100011

CPL 10101100
01010011
Address Modes with Logic
ANL – AND a, byte
ORL – OR direct, reg. indirect, reg, immediate
XRL – eXclusive oR
byte, a
direct

byte, #constant

CPL – Complement a ex: cpl a


Uses of Logic Instructions
• Force individual bits low, without affecting other
bits.
anl PSW, #0xE7 ;PSW AND 11100111

• Force individual bits high.


orl PSW, #0x18 ;PSW OR 00011000

• Complement individual bits


xrl P1, #0x40 ;P1 XRL 01000000
Other Logic Instructions
• CLR - clear
• RL – rotate left
• RLC – rotate left through Carry
• RR – rotate right
• RRC – rotate right through Carry
• SWAP – swap accumulator nibbles
CLR – Set all bits to 0
CLR A
CLR byte (direct mode)
CLR Ri (register mode)
CLR @Ri (register indirect mode)
Rotate
• Rotate instructions operate only on a

rl a

mov a, #0xF0 ; a 11110000


rl a ; a 11100001
Rotate through Carry

C
rrc a

mov a, #0A9h ; a  A9
add a, #14h ; a  BD (10111101), C0
rrc a ; a  01011110, C1
Swap
swap a

mov a, #72h
swap a ; a  27h
Bit Logic Operations
Some logic operations can be used with single bit
operands
ANL C, bit ANL C, /bit
ORL C, bit ORL C, /bit
CLR C
CLR bit
CPL C “bit” can be any of the bit-addressable RAM
locations or SFRs.
CPL bit
SETB C
SETB bit
Rotate and Multiplication/Division
• Note that a shift left is the same as
multiplying by 2, shift right is divide by 2

mov a, #3 ; A 00000011 (3)


clr C ; C 0
rlc a ; A 00000110 (6)
rlc a ; A 00001100 (12)
rrc a ; A 00000110 (6)
Be Logical…..

Logical Operations Exercise


Program Flow Control
• Unconditional jumps (“go to”)
• Conditional jumps
• Call and return
Unconditional Jumps
• SJMP <rel addr> ; Short jump, relative
address is 8-bit 2’s complement number, so jump can be
up to 127 locations forward, or 128 locations back.
• LJMP <address 16> ; Long jump
• AJMP <address 11> ; Absolute jump to
anywhere within 2K block of program memory
• JMP @A + DPTR ; Long indexed jump
Infinite Loops

Start: mov C, p3.7


mov p1.6, C
sjmp Start

Microcontroller application programs are almost always infinite loops!


Re-locatable Code
Memory specific (NOT Re-locatable)
cseg at 8000h
mov C, p1.6
mov p3.7, C
ljmp 8000h
end
Re-locatable
cseg at 8000h
Start: mov C, p1.6
mov p3.7, C
sjmp Start
end
Conditional Jumps
These instructions cause a jump to occur only if a
condition is true. Otherwise, program execution
continues with the next instruction.

loop: mov a, P1
jz loop ; if a=0, goto loop,
;else goto next
;instruction
mov b, a
Conditional jumps
Mnemonic Description
JZ <rel addr> Jump if a = 0
JNZ <rel addr> Jump if a != 0
JC <rel addr> Jump if C = 1
JNC <rel addr> Jump if C != 1
JB <bit>, <rel addr> Jump if bit = 1
JNB <bit>,<rel addr> Jump if bit != 1
JBC <bir>, <rel addr> Jump if bit =1, clear bit
CJNE A, direct, <rel Compare A and
addr> memory, jump if not
equal
Conditional Jumps for
Branching
if condition is true condition
goto label false
else true
goto next instruction label

jz led_off
setb C
if a = 0 is true mov P1.6, C
send a 0 to LED sjmp skipover
else led_off: clr C
mov P1.6, C
send a 1 to LED skipover: mov A, P0
More Conditional Jumps
Mnemonic Description
CJNE A, #data <rel addr> Compare A and data, jump if
not equal
CJNE Rn, #data <rel addr> Compare Rn and data, jump
if not equal
CJNE @Rn, #data <rel addr> Compare Rn and memory,
jump if not equal
DJNZ Rn, <rel addr> Decrement Rn and then
jump if not zero
DJNZ direct, <rel addr> Decrement memory and then
jump if not zero
Iterative Loops
For A = 0 to 4 do For A = 4 to 0 do
{…} {…}

clr a mov R0, #4


loop: ... loop: ...
inc a ...
cjne a, #4, loop djnz R0, loop
Branch and Jump

Fun with the LED


Call and Return
• Call is similar to a jump, but
– Call instruction pushes PC on stack before
branching

acall <address ll> ; stack  PC


; PC  address 11

lcall <address 16> ; stack  PC


; PC  address 16
Return
• Return is also similar to a jump, but
– Return instruction pops PC from stack to get
address to jump to

ret ; PC  stack
Subroutines
call to the subroutine

Main: ...
acall sublabel
...
...
sublabel:...
... the subroutine
ret
Initializing Stack Pointer
• The Stack Pointer (SP) is initialized to 0x07. (Same
address as R7)
• When using subroutines, the stack will be used to store
the PC, so it is very important to initialize the stack
pointer. Location 2F is often used.

mov SP, #0x2F


Subroutine - Example
$include (c8051f020.inc)
GREEN_LED equ P1.6
cseg at 0
ljmp Main reset vector
cseg at 0x100
Main: mov WDTCN, #0DEh

mov WDTCN, #0ADh


orl P1MDOUT,#40h
mov XBR2, #40h
main program
clr GREEN_LED
Again: acall Delay
cpl GREEN_LED
sjmp Again
Delay: mov R7, #02
Loop1: mov R6, #00h
Loop0: mov R5, #00h
subroutine
djnz R5, $
djnz R6, Loop0
djnz R7, Loop1

ret
END
Subroutine – another example
; Program to compute square root of value on Port 3 (bits 3-0) and
; output on Port 1.
$INCLUDE (C8051F020.inc)
cseg at 0
ljmp Main
reset vector
Main: mov P3MDOUT, #0 ; Set open-drain mode
mov P3, #0xFF ; Port 3 is an input
mov P1MDOUT, #0xFF ; Port 1 is an output
mov XBR2, #40h ; Enable crossbar
loop: mov a, P3 main program
anl a, #0x0F ; Clear bits 7..4 of A
lcall sqrt
mov P1, a
sjmp loop
sqrt: inc a
movc a, @a + PC
subroutine
ret
squares: db 0,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3 data
end
Why Subroutines?
• Subroutines allow us to have "structured"
assembly language programs.
• This is useful for breaking a large design
into manageable parts.
• It saves code space when subroutines can
be called many times in the same
program.
Timeout for Subroutines....

Interrupts
mov a, #2
mov b, #16
mul ab
mov R0, a
Program Execution

mov R1, b interrupt


mov a, #12 ISR: orl P1MDIN, #40h
mov b, #20
mul ab orl P1MDOUT,#40h
add a, R0 setb P1.6
mov R0, a here: sjmp here
mov a, R1 cpl P1.6
addc a, b reti
mov R1, a return
end
Interrupt Sources
• Original 8051 has 5 sources of interrupts
– Timer 1 overflow
– Timer 2 overflow
– External Interrupt 0
– External Interrupt 1
– Serial Port events (buffer full, buffer empty, etc)
• Enhanced version has 22 sources
– More timers, programmable counter array, ADC,
more external interrupts, another serial port (UART)
Interrupt Process
If interrupt event occurs AND interrupt flag for that
event is enabled, AND interrupts are enabled,
then:
1. Current PC is pushed on stack.
2. Program execution continues at the interrupt
vector address for that interrupt.
3. When a RETI instruction is encountered, the
PC is popped from the stack and program
execution resumes where it left off.
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 default priority order.
(see page 117 of datasheet)
• Priority can also be set to “high” or “low”.
Interrupt SFRs

Interrupt enables for the 5 original 8051 interrupts:


Timer 2
Serial (UART0)
Timer 1
Global Interrupt Enable – External 1
must be set to 1 for any Timer 0
interrupt to be enabled 1 = Enable
External 0
0 = Disable
Another Interrupt SFR

Comparator 1 rising edge Program Counter Array

Comparator 1 falling edge ADC0 Window Comparison

Comparator 0 rising edge System Management Bus

Comparator 0 falling edge SPI Interface


Another Interrupt SFR

External ADC 1
Clock
source Serial Timer 4
Valid (UART) 1 ADC 0
External
7 External 6 Timer 3
External Interrupts
• /INT0 (Interrupt 0) and /INT1 (Interrupt 1) are
external input pins.
• Interrupt 6 and Interrupt 7 use Port 3 pins 6 and
7:
INT 6 = P3.6
INT 7 = P3.7
These interrupts can be configured to be
– rising edge-triggered
– falling edge-triggered
External Interrupts

Interrupt flags: Interrupt Edge Configuration:

0 = no falling edges 0 = interrupt on falling edge


detected since bit cleared
1 = interrupt on rising edge
1 = falling edge detected
Example Configuration
Configure Port 3, bit 7 (the pushbutton
switch) to interrupt when it goes low.

anl P3MDOUT, #0x7F ; Set P3.7 to be an input


setb P3.7
mov XBR2, #40h ; Enable crossbar switch
mov P3IF, #0 ; Interrupt on falling edge
mov EIE2, #020h ; Enable EX7 interrupt
mov IE #80h ; Enable global interrupts
Interrupt Vectors
Each interrupt has a specific place in code memory
(a vector) where program execution (interrupt
service routine) begins (p17).
Examples:
External Interrupt 0: 0x0003
Timer 0 overflow: 0x000B
External Interrupt 6: 0x0093 Note that there are
only 8 memory
External Interrupt 7: 0x009B locations between
vectors.
Interrupt Vectors
To avoid overlapping Interrupt Service routines, it is
common to put JUMP instructions at the vector
address. This is similar to the reset vector.
cseg at 009B ; at EX7 vector
ljmp EX7ISR
cseg at 0x100 ; at Main program
Main: ... ; Main program
...
EX7ISR:... ; Interrupt service routine
... ; Can go after main program
reti ; and subroutines.
Example Interrupt Service
Routine
; EX7 ISR to blink the LED 5 times.
; Modifies R0, R5-R7, bank 3.
;----------------------------------------------------
ISRBLK: push PSW ; save state of status word
mov PSW, #18h ; select register bank 3
mov R0, #10 ; initialize counter
Loop2: mov R7, #02h ; delay a while
Loop1: mov R6, #00h
Loop0: mov R5, #00h
djnz R5, $
djnz R6, Loop0
djnz R7, Loop1
cpl P1.6 ; complement LED value
djnz R0, Loop2 ; go on then off 10 times
pop PSW
mov P3IF, #0 ; clear interrupt flag
reti

Anda mungkin juga menyukai