Vous êtes sur la page 1sur 67

A Brief Introduction of Microcontrollers

Microcontrollers, as the name suggests, are small controllers. They are like single chip
computers that are often embedded into other systems to function as
processing/controlling unit. For example, the remote control you are using probably has
microcontrollers inside that do decoding and other controlling functions. They are also
used in automobiles, washing machines, microwave ovens, toys ... etc, where automation
is needed.

The key features of microcontrollers include:

• High Integration of Functionality

Microcontrollers sometimes are called single-chip computers because they have


on-chip memory and I/O circuitry and other circuitries that enable them to
function as small standalone computers without other supporting circuitry.

• Field Programmability, Flexibility

Microcontrollers often use EEPROM or EPROM as their storage device to allow


field programmability so they are flexible to use. Once the program is tested to be
correct then large quantities of microcontrollers can be programed to be used in
embedded systems.

• Easy to Use

Assembly language is often used in microcontrollers and since they usually


follow a RISC architecture, the instruction set is small. The development package
of microcontrollers often includes an assembler, a simulator, a programmer to
"burn" the chip and a demonstration board. Some packages include a high level
language compiler such as a C compiler and more sophisicated libraries.

8051 Microcontroller:

Despite it’s relatively old age, the 8051 is one of the most popular microcontrollers in use
today. Many derivative microcontrollers have since been developed that are based on--
and compatible with--the 8051. Thus, the ability to program an 8051 is an important skill
for anyone who plans to develop products that will take advantage of microcontrollers.
INTERNAL ARCHITECTURE OF 8051
 It consists of
• 8 bit ALU, with two registers A & B
• 11 bit Program Counter & Data Pointer
• 8 bit Program Status Word
• 8bit Stack Pointer
• 128 bytes Internal RAM
 4 register banks, each containing 8 registers.
 16 bytes, which may be addressed at bit level.
 80 bytes of general purpose data memory.
• Internal ROM / EPROM / Flash memory of 4KB
• Can be extended separate 64KB address space for data &
code memory.
• 32 discrete I/O pins, grouped as four 8 bit ports.
• Full Duplex UART.
• Two l6 bit timer / counter - T0 & T1
• Two external & three internal interrupt sources
• Control registers –TCON, TMOD, SCON, PCON, and
IP & IE
• Oscillator & clock circuits

INTRODUCTION
The 8051 is the original member of the MCS-51family, and is the core for all MCS-
51 devices. The features of the 8051 core are:
• 8-bit CPU optimized for control applications
• Extensive Boolean processing (single-bit logic) capabilities
• 64K program memory address space
• 64K data memory address space
• 4K bytes of on-chip program memory
• 128 bytes of on-chip data RAM
• 32bidirectional and individually addressable I/O lines
• Two 16- bit timer/counter Full duplex UART

• 6- source / 5 vector interrupt structure with two priority levels


• On-chip clock oscillator
The basic architectural structure of this 8051 core is shown below.
The programming model of 8051 is a collection of 8 bit and 16 bit registers and 8 bit
memory locations.
• REGISTERS:
 8051 has 34 general purpose or working registers. Two of them A & B, hold
results of many instructions, particularly Mathematical and logical operations, of
8051 CPU.
 The other 32 Reg. arranged as a part of internal RAM in four banks RBO-RB3.
 A (Accumulator) register is used for many operations - Addition,
Subtraction, integer- multiplication & division and Boolean bit manipulations.

 Reg. B is used with Reg.A for multiplication & division operations and also for data
transfer.

CY AC FO RSI RSO OV - P
Carry out Auxiliary General Register Banks Over flow Parity of
From carry for purpose RB0-RB3 flag Accumulator
MSB of BCD set by
ALU operations hardware to 1
Operand if it contains
odd number
of ones

Note: The contents of (RS1-RS0) enable the working register banks as follows
(0, 0) - Bank 0 (00H-07H)
(0, 1) - Bank 1 (08H-0FH)
(1, 0) - Bank 2 (10H-17H)
(1, 1) - Bank 3 (18H-1FH)
• Carry flag is set whenever there is carry out from MSB. This flag is after 8 bit
ADD/ SUB operation.
• It can also be set to 1 or 0 directly using SETB C or CLR C.
• Auxiliary carry: If there is a carry from D3 to D4 position during Add/sub
operation, this bit will set. Otherwise, it is cleared. This flag is used for BCD
operations.
• Parity Flag reflects the number of 1’s in ‘A’. If ‘A’ contains an odd number of
1’s, then P=1. Therefore P=0, if A has an even number of 1’s.
• Over Flow Flag: This flag is set whenever the result of a signed number operation
is too large to be accommodated in 7bits, causing the Higher order bit to over
flow into the Sign Bit.
8051 PORT LATCHES AND I/O BUFFERS

INTERFACE
8051 OSCILLATOR & CLOCK
• 8051 has on Chip Oscillator but needs an external clock to run it. A Quartz crystal
oscillator is connected to XTAL2 & XTAL1.C1 &C2 are also connected as shown above.
C1= C2= 30pf (typical)
Crystal oscillator=1to 16
MHz.
• Each Machine Cycle is made up of 6 states. A state is basic time interval for
discrete operations of µcontroller such as Opcode fetch, decode an opcode,
Execute an opcode.Two oscillator pulses define a state.
• Program Instructions may require 1/2/3/4 machine cycles, depending on its type.
C ×12
Tinst =
Crystalfre quency

RST
It is an input and is active High (Normally Low) by applying a High pulse to this pin, µc
will be reset and terminate all activities.

On reset PC - 0000
ACC - 0000
B - 0000
PSW - 0000
SR - 0007
DPTR-0000

EA - External Access (of Memory)


PSEN - Program Store Enable
ALE - Address Latch Enable.
• WHAT DO THE SFRs CONTAIN JUST AFTER POWER-ON OR A RESET
The following table lists the contents of each SFR after power-on or a hardware reset

Register Value in Binary


*ACC 0000 0000
*B 0000 0000
*PSW 0000 0000
SP 0000 0111
DPTR
DPH 0000 0000
DPL 0000 0000
*P0 1111 1111
*P1 1111 1111
*P2 1111 1111
*P3 1111 1111
*IP 8051 XXX00000
8052 XX000000
*IE 8051 0XX00000
8052 0X000000
TMOD 0000 0000
*TCON 0000 0000
*+T2CON 0000 0000
TH0 0000 0000
TL0 0000 0000
TH1 0000 0000
TL1 0000 0000
+TH2 0000 0000
+TL2 0000 0000
+RCAP2H 0000 0000
+RCAP2L 0000 0000
*SCON 0000 0000
SBUF Indeterminate
PCON HMOS 0XXXXXXX
CHMOS 0XXX0000

x = Undefined, * = Bit Addressable, + = 8052 only


Memory organization

• 8051 has separate address spaces for program memory


and data memory.
• Program memory can be up to 64KB, lower 4KB may
reside ON-CHIP.
• 8051 can address up to 64KB of data memory.
• It has 128bytes of ON-CHIP RAM and SFR (128B).
• The lower 128bytes can be accessed either by direct
addressing or indirect addressing.
SFR MEMORY MAP
F8 FF
F0 B F7
E8 EF
E0 ACC E7
D8 DF
D0 PSW D7
C8 T2CON RCAP2L RCAP2H TL2 TH2 CF
C0 C7
B8 IP BF
B0 P3 B7
A8 IE AF
A0 P2 A7
98 SCON SBUF 9F
90 P1 97
88 TCON TMOD TL0 TL1 TH0 TH1 8F
80 P0 SP DPL DPH PCON 87

SPECIAL FUNCTION REGISTERS


Symbol Name Address
*ACC Accumulator 0E0H
*B B register 0F0H
*PSW Program Status Word 0D0H
SP Stack Pointer 81H
DPTR Data Pointer 2 Bytes
DPH Low Byte 82H
DPL 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
TMOD Timer/Counter Mode Control 89H
*TCON Timer/Counter Control 88H
*+T2CON Timer/Counter 2 Control 0C8H
TH0 Timer/Counter 0 High Byte 8CH
TL0 Timer/Counter 0 Low Byte 8AH
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 Reg. High Byte 0CBH
+RCAP2L T/C 2 Capture Reg. Low Byte 0CAH
*SCON Serial Control 98H
SBUF Serial Data Buffer 90H
PCON Power Control 87H

* = Bit Addressable
+ = 8052 only
RBO-RB3: 32Bytes kept are aside for register Banks, of four. In each Bank, R0-R7 (8)
registers are present

• Though 4banks of register are kept aside, micro controller at a time can access only one
register bank, where as other register banks will be used as simple RAM locations.
• By default RB0 is selected, on power ON.
• We can switch to other banks, by using D4 & D3 bits of PSW.

• State the contents of RAM locations after the following program.

SetB PSW4 select bank 2


Mov R0, #99h
Mov R1, #85h
Mov R2, #3Fh.

• PC can access the memory from 0000H –FFFFH. Program address higher
than 0FFFH, which exceed the internal ROM capacity will cause 8051 automatically
fetch, External Memory.
• Code bytes can be fetched exclusively from External memory also using EA .
ADDRESSING MODES:
IMMEDIATE ADDRESSING MODE
• The value of a constant can follow the opcode in program memory.
MOV A, #n
MOV Rr, #n
MOV A, #0F1H
MOV dptr, #2045H
MOV R3, #1CH
• It is impossible to have immediate data as destination.

REGISTER ADDRESSING MODE


MOV Rd, Rs
• Rd, Rs can be any general purpose registers A, R0-R7
MOV A, R7
MOV R0, A

DIRECT ADDRESSING MODE:


• In direct addressing mode the operand is specified by an 8-bit address field in
the instruction. Only SFR, internal data RAM can be directly accessed
MOV A, 80H
MOV 32H, R0
• NOTE
 Note that there are gaps in SFR
 Addresses refer above 7FH, will result errors.
 Moving data from a direct address to itself is not predictable.
INDIRECT ADDRESSING MODE:
In this mode a specific register R0, R1 or DPTR, SP holds the address of operand.
MOV A, @R0
MOV @R1, R2

INSTRUCTION SET
DATA TRANSFER GROUP
MOV A, Rn A  Rn
MOV A, direct
MOV A, @Ri A  [Ri]
MOV A, #data A  data
MOV Rn, A
MOV Rn, direct
MOV Rn, #data
MOV direct, A
MOV direct, Rn
MOV direct, direct
MOV direct, @Ri
MOV direct, #data
MOV @Ri, A
MOV @Ri, direct
MOV @Ri, #data
MOV dptr, #data dptr 16-bit data

MOVC A, @A+dptr
It loads accumulator with a code byte or a constant, from
program memory.
A  [(A) + (dptr)]
• The first byte is fetched at address, which is sum of the original
unsigned 8-bit accumulator contents and the contents of 16-bit register PC or dptr.
• 16-bit addition is performed, so a carry out from lower 8-bits
may propagate through higher order bytes.
No flags are affected.

MOVC A,@A+PC
(i) PCPC+1
(ii) A[(A)+(PC)]

Ex: Rel_PC: INC A


MOVC A, @A+PC
RET
DB 66H
DB 77H
DB 88H

If this subroutine is called with accumulator equal to 01H, it will return 77 in


accumulator.
MOVX <dst>, <src>
MOVX A, @dptr

MOVX instruction transfers data between accumulator and a byte of external data
memory
a) In one type R0/R1 provides 8-bit address
b) In second type data pointer provides 16-bit address.

Ex: Assume external 256 byte RAM is interfaced to micro controller [8155].
Location 34H of RAM holds the value of 56H. Now R0 holds 12H, R1 holds 34H
MOVX A,@R1
MOVX @R0,A
This sequence copies 56H into both accumulator and external RAM 12H.
MOVX A, @Ri
MOVX A, @dptr
MOVX @Ri, A
MOVX @dptr, A

EXCHANGE INSTRUCTION:
XCH A, <byte>
Exchanges the contents of accumulator with the contents of the indicated variable.
XCH A, Rn
XCH A, direct
XCH A, @Ri
XCHD A, @Ri Exchange digit (of bit 3-0) of accumulator with
that of internal RAM location, addressed at Ri. Higher order bits(bits 7-4) and flags
are not affected.
( A3−0 ) ↔( Ri 3−0 )

B. ARITHMETIC GROUP:
ADD A, <src byte>
Adds ‘Acc’ with src byte & leaves the result into ‘Acc’.
The carry & AC flags are set, if there is a carry out from Bit 7 or Bit 3
respectively, otherwise cleared.
Overflow flag is set if there is a Carry out of bit 6 but not out of bit 7 or a
carry out of bit 7 but not bit 6. Otherwise OV flag is cleared.

Ex: Assume ‘A’ holds 0C3H & R0 holds 0AAH. Thus ADD A, R0 will leave 6DH in

1100 0011 = A
1010 1010 = R0

1 0110 1101

Accumulator AC=0, C=1, OF=1, P=1


ADD A, Rn ; A  A+ (Rn)
ADD A, direct ; A A+ (direct)
ADD A, @ RI ; A A+ [Ri]
ADD A, #data; A A+ data
ADD WITH CARRY:
ADDC A, Rn ; A A+ Rn+ CY

ADDC A, direct; A A+ (direct) + CY


ADDC A, @Ri; A A + [Ri] + CY
ADDC A, #data; A A + data + CY

BCD ADDITION:
Unpacked BCD & packed BCD are 45 & 04 or 05 respectively.
DAA: Decimal Adjust Accumulator
Instruction provides a correction after binary addition
MOV A, #47H
MOV B, #25H 0100 0111
ADD A, B + 0010 0101
DA A 0110 1100
0110
Valid BCD 0111 0010

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

SUBTRACTION:
SUBB A, <src byte>
SUBB A, Rn ; A A--(c) –Rn
SUBB A, direct;
SUBB A, @Ri;
SUBB A, #data;
EXAMPLE
A= 0C9H R2= 54H CY=1
SUBB A, R2 leaves value 74H in accumulator
1100 1001 =0C9H 0101 0100
1010 1100 =(-54H) 1’s 1010 1011
1 0111 0101 + 1
2’s 1010 1100
Complement the carry
C=0, AC=0, OF=1
For subtraction, STEP 1: Get 1’s complement & then 2’s complement of
src byte to obtain -ve source byte.

STEP 2: Add A with (--src byte)

STEP 3: Complement the carry flag & AC flag

NOTE: If the state of carry is not known before subtraction it should be


cleared using CLR C instruction.

INC <byte>
Increments the specified byte by ‘1’. No flag is affected.
INC A
INC Ri
INC @Ri
INC direct
INC dptr
EXAMPLE
R0 holds 7EH & internal RAM 7EH holds FF H.
INC R0 R0 R0+1 R07F H
INC @R0 [R0] [R0]+1 7E will be modified with 00H.
DPTR: 12FE H
INC DPTR: 12FF H
INC DPTR: 1300 H
DEC< byte>
Decrements the specified byte by 1.
No flag is affected.
DEC A AA-1
DEC Rn
DEC direct
DEC @Ri
MULTIPLICATION:
MUL AB ABA*B
Multiplies A (unsigned integer) with B(unsigned integer).

The low order byte of 16 bit product is left in accumulator and higher order byte of 16
bit product in B register.
If the product is greater than FF H, OF flag is set, otherwise cleared CF is always cleared.
DIVISION: DIV AB
Quotient A(15--8) (A)/(B)
Reminder B(7—0)
Divides an unsigned eight bit integer in accumulator by unsigned eight
bit integer in register B. Accumulator receives the Quotient portion & register B
receives reminder. CY& OF are cleared.

LOGIC INSTRUCTIONS
ANL <dst>, <src>
Performs bit wise logical - AND operation between dst & src, stores the
result in dst. No flags are affected.
ANL A, R0 A A ^ R0
ANL P1, #41H; clears bits 7, 5, 4, 3, 2&1 of port 1.
• When this instruction is used to modify an output port, the value used as
the original port data will be read from the output data latch, not the input
pins. This feature is called “Read – Modify – Write”.
ANL A, Rn
ANL A, direct
ANL A, @Ri
ANL A, #data
ANL direct, A
ANL direct, #data (direct)(direct) ^ (data)

ANL C, <src data>


It clears carry flag, if src bit is 0. Otherwise leaves the CF in its current data.
ANL C, bit C(C) ^ (bit)
ANL C,/bit C(C ) ^(complement of bit)
ANL C,/OV ; And with inverse of overflow flag.

ORL <dest>, <src>


It performs bit wise logical OR between source & destination, result is
kept at destination. No flag is affected.
ORL A, Rn A A v Rn
ORL A, direct A A v (direct)
ORL A, @Ri A A v [(Ri)]
ORL A, #data A A v (#data)
ORL direct, A (direct)(direct) v A
ORL direct, #data (direct)(direct) v data.
ORL C, <src byte>
Set the ‘CF’, if src bit is 1, leave the carry bit in current state, if src bit is
zero.
ORL C, bit; (C)(C ) v (bit)
ORL C, /bit; (C)(C) v (complement of bit)

XRL <dest>, <src>


It performs bit wise logical X-OR operation between src & dest , leaves the
result in dest. No flag is affected.
XRL A, Rn ; AA (+)Rn
XRL A, direct; AA(+) (direct)
XRL A, @Ri; AA(+) [(Ri)]
XRL A, #data; AA(+) data
XRL direct, A; (direct)(direct)(+) A
XRL direct, #data; (direct)(direct)(+)data

CLR bit

The indicated bit is reset to ‘zero’. It can operate on any directly addressable bit.
CLR C C0
CLR bit bit0
CLR A A0
CPL A A(complement of A)
Each bit of accumulator is logically complemented (1’s complement).

CPL bit

The specified bit is complemented.

CPL P1.1 P1.1 (P1.1)’


CPL C C (C)’
COMPARE INSTRUCTION
CJNE dest, src, rel-addr.
d<s
d>s
d>s d<s

C=1 C=0

It compares the
magnitudes of src &
dest and branches, if
they are not equal. The
branch address is
computed by adding the signed relative displacement to ‘PC’.
CJNE A, direct, rel
PCPC + 3
If A< > (direct)
Then PCPC+ rel
If A<(direct)
Then C1
Else C0
CJNE A, #data, rel
CJNE Rn, #data, rel
CJNE @Ri, #data, rel
EXERCISE:
Assume internal RAM memory locations 40H to 44H
Contain the daily temperature for five days as shown below. Search if any of the values
equals 65. If value 65 exists in the table, give its location to R4, otherwise make R4=0.
[40H]: 76
[41H]: 79
[42H]: 69
[43H]: 65
[44H]: 62

ROTATE INSTRUCTIONS
RLA (Rotate Accumulator Left)

D7 D6 D1 D0

No flag is effected
RLC A (Rotate Accumulator Left
through Carry)

CF

D7 D6 D1 D0

RRA (Rotate Accumulator Right)

D7 D6 D1 D0

No flag is effected

RRC A (Rotate Accumulator Right


through Carry)
CF

D7 D6 D1 D0

SWAP A:
Interchanges low and high order nibbles of A
SWAP A (A3: 0  A7: 4 )
• In the absence of SWAP A, How would you interchange the nibbles of ‘A’?
• Write a program that finds the number of ‘1’s in a given byte.
PROGRAM CONTROL GROUP changes the sequence of the program.
a) Loop b) Jump c) Call

sr
A) LOOP

Continue Ret

Repeating a sequence of instructions certain number of times is called “LOOP”


In 8051, loop action is performed by the instruction
DJNZ reg, label
• Decrements the ‘register’ and braches to the address label if the resulting
value is not zero.
• No flag is affected
• The branch destination would be computed by adding signed relative
displacement value to ‘
DJNZ Rn, rel
PCPC+2
(Rn)(Rn)-1
if (Rn)>0 or (Rn)<0
then
PCPC + rel
DJNZ direct, rel

B) JUMP GROUP
JMP

UNCONDITIONAL CONDIOTIONAL
JZ
LJMP AJMP SJMP JNZ
JC
JNC
JB
JNB
JBC
LJMP addr
It causes an unconditional branch to the indicated addr.
PCADDR
• The destination may be anywhere in 64KB program memory address space.
• No flag is effected.

AJMP ADDR
09
2 Transfers program execution to the indicated address, which is formed at runtime by
concatenating the high order five bytes of PC with 12 bits address, specified in the
3
instruction
7 AJMP
PCPC+2
PC10 – 0  page address
SJMP rel
D
CE Program control branches unconditionally to the address indicated,
SJMP rel
PCPC+2
M PCPC + rel
od
The range of the destination allowed is from 128 bytes preceding this instruction and
e
m to 127 bytes following it.

D
T
Mo
de
m
Par
allel CONDITIONAL JUMP INSTRUCTIONS:
to
seri ALL CONDITIONAL JUMP INSTRUCTIONS ARE SHORTJUMPS.
al 1) JB bit, rel jump if bit set
con
vert PCPC+3
er If (bit) =1
Mic Then
roc PCPC+REL
ontr
olle JB P1.2, label
r
JB ACC.2, label_1
10
70 The bit tested is not modified. No flag is effected.
hz
2) JBC bit, rel jump if bit set and clear bit
spa
ce PCPC+3
12 If (bit) = 1,
70
hz Then bit0
m PCPC + rel
ar JBC ACC.2, label_2 will cause program execution to continue by lable_2 with ACC is
k
modified to 52H (0101 0010) from 56H(0101 0110)

Mic JC rel jump If carry is set


roc PC PC + 2
ontr
olle IF (C) = 1,THEN
r PC PC + rel
Se
rial JNB bit, rel jump if bit not set
to PCPC + rel
par The bit tested is not modified.
all
el JNC rel jump if carry not set
co PCPC+2
nv IF (C) =0, THEN PCPC + rel
ert
er JNZ rel jump if accumulator not zero
PCPC+2
Mo
de IF(ACC ≠ 0),THEN PCPC + rel.
m
star
t
spa
ce
dat
ma
rk
sto
p
sto
p
Fra JZ rel jump if accumulator zero.
mi
PCPC+2
ng
=st IF(ACC=0),then PCPC + rel
art
bit
+d
ata
+
par
ity
bit STACK OPERATIONS
+1 The stack is a section of RAM, used by CPU to store information temporarily.
or
2 SP holds the address of ‘Top Of Stack (TOS)’. PUSH and POP operations are performed
sto on stack.
p
bit The SP can take values from 00 H to FF H.
s.
Nor
ma PUSHING ONTO THE STACK
lly MOV R6, #25H
(w
he MOV R1, #12H
n MOV R4, #0F3H
the
re PUSH 6
is PUSH 1
no
dat PUSH 4
a),
hig
h Initially after push 6 after push 1 after push 4
(lo
gic
1)i
0C
s
tra
0B
nsf
err
0A
ed
F3
fro
08
m 12 12
sou
rce 25 25 25
to
des
tin
ati
on.
As
ch
ro
no
us
dat
a POP OPERATION:
tra POP3
nsf POP5
er:
POP2
Re
cei 0C
ve 0B 54
r
0A F9 F9
Tr
an 09 76 76 76
sm 08 6C 6C 6C 6C
itt
er
After the above code is executed, the registers R3, R5 & R2 will be R3=54, R5=F9,
BY
SY R2=76.
NC,
HD
LC,
SD
LCALL addr16
LC
pro The sequence of micro instructions as follows.
toc
ols PCPC+3
will
SPSP+1
co
me [SP]PC7: 0
un
der SP SP+1
thi [SP]PC15: 8
s
cla PC  ADDR16
ss.
CALL instructions implicitly perform two push operations to save return address. The
d
d subroutine can be within “64KB” of program memory.
Sy ORG 0H
nc
Sy HERE: MOV A, #55H
nc MOV P1, A
Re LCALL DEALY
cei
ve MOV A, #0AAH
r MOV P1, A
Tr
an
sm
itt
er
cei
ve
r
re
cei LCALL DELAY
ve
SJMP HERE
r
tra ORG 300H
ns DELAY: MOV R5, #0FFH
mi AGAIN: DJNZ R5, AGAIN
tte
r RET
END
tra *CHANGE THE DELAY PROGRAM AS FOLOWS & ANALYSE STACK
ns
CONTENTS IN EACH STEP
mi
tte DELAY: PUSH 4
r PUSH5
Dat
a MOV R4,#0FFH
tran NEXT_1: MOV R5,#OFFH
smi
ssio NXT: DJNZ R5,NXT
n is DJNZ R4,NXT_1
in
both POP 5
dire POP4
ctio
ns, RET
not ACALL (Absolute Call)
at
sing The sequence of micro-operations is as follows
le PC<--PC+2
time
. SP<--SP+1
[SP]<--PC7 : 0
DP<--DP+1
c) [SP]<--PC15:8
full
PC10:0<--PAGE ADDR
du
ple
x The subroutine must be called with in the same 2K block of the program memory.
Tra
ns
mit DELAY PROGRAM AND ITS CALCULATIONS
ter
NO OF CYCLES
Re
cei
ver
Re
cei
Tra
ns
mit
ter
Re
cei
ver DEALY: MOV R2, #200 1
09 AGAIN: MOV R3, #250 1
HERE: NOP 1
NOP 1
DJNZ R3, HERE 2
DJNZ R2, AGAIN 2
RET 1

Assume machine cycle is of 1.085µ s for a clock of 11.0592 MHz,


11.0592/12=921.6 KHz
Machine cycle is 1/921.6 KHz = 1.085µ s
For ‘here loop’, (4× 250) 1.085 =1085µ s
For ‘again loop’, 200× 1085=21700µ s, excluding over-head.
I/O PORTS
The main feature of a microcomputer is the versatility, built in the I/O ports.8051 has 4
I/O ports, namely P0, P1, P2, & P3. Each port has a D type output latch for each pin . By
default, all port latches have ‘1’. The SFR for each port is made up of these 8 latches,
which can be addressed at SFR.
P1, P2 and P3 have internal pull-ups.P0 has open drain outputs. Each I/O line can be used
as input or output independently.
All the port latches in the 8051 have’1’ by default. If a ‘0’ is subsequently written to a
port latch, it can be reconfigured as an input port by writing a ‘1’ into it.
All four ports are bi-directional. Each consists of a latch, an output buffer and an input
buffer.
The output drivers of P0 & P2 and input drivers of P0 are used to access external
memory.
For example eight latches of PO are addressed at 80h.
the fan out of P1, P2, P3 are :
IOL=1.6mA
IOH=60µ A
IIL=50µ A
IIH=650µ A
for P0:
3.2 mA for VOL=0.45V
The output buffers of P1,P2,P3 can each drive 4 LS TTL inputs.
in external bus mode, P0 output buffers can each drive 8 LS TTL inputs. As port pins,
they require external pull ups to drive any inputs.
PORT0:

P0 can be used as I/O port or bidirectional AD0-AD7 for external memory. To configure
P0 as input port, a ‘1’ must be written to the corresponding port’0’ later, thus by turning
off both the transistors, which in turn cause to float in a high impedance state and the pin
essentially connected to the input buffer.
To use it as an output port, the pin latches are programmed to ‘0’ will turn on the lower
FET, grounding pin. All latches that are programmed to ‘1’, still float. Thus, external
pull up resistors are needed to supply a logic high, when it is used as output port.
The typical D F/F will clock in a value from the internal bus in response to a ‘write to
latch’ signal from CPU.
The Q output of flip-flop is placed on the internal bus in response to a ‘read latch’ signal
from CPU.
The level of the port pin itself is placed on the internal bus, in response to a ‘read pin’
signal.
The output drivers of P0 and P2 are switchable to an internal Address and Data bus by an
internal control signal for external memory access.
The data on the latches do not have to be the same as that on pins. There are two separate
data paths, one to read latch another one to read pin data using separate buffers.
The upper buffer is enabled when latch data is read. The lower buffer is enabled when the
pin state is read.
P0 outputs the Low order byte of external memory location time multiplexed with the
byte being written or read.
Output drivers of P0 & P2 are switchable to an internal address and A/D bus by control
signal.
To be used as an input port, the port bit must contain a ‘1’ which turns off the driver FET.
Then for P1, P2, P3, the pin is pulled high by internal pull-up.
‘P0’ differs in not having internal pull-ups. The pull-up Transistor is used only when port
is emitting ‘1’ during external access. Otherwise ‘PU’ is off. Consequently ‘P0’ lines
behave like ‘open drain’ configuration writing a ‘1’ into it, leaves both transistors off,
hence pin is in floating condition.
To use it as an output port, the pin latches are programmed to ‘o’ will turn ON lower
FET, grounding pin.
The D flip-flop will in a value from the internal bus in response to a ‘write to latch’ signal
from CPU.
When P0 is used as an address bus to external memory internal control signals switches
the address lines to the gate of FET’s. A logic ,on an address bit will turn on upper FET
& lower FET provides a logic high at the pin when the address bit is 0 , the lower FET is
on & the upper FET off to provide a logic low at the pin.
After the address has been formed and latched on to external circuits by ALE pulse, the
bus turns to become a data bus.
P0 now reads data from external memory and must be configured as an input, so a logic 1
is automatically written by internal control logic to all P0 latches.

P1-P3 STRUCTURE

TB2

TB1

The structure of P1 is as follows.


The other ports P2 & P3 are basically same except with extra circuitry to allow the dual
function.
To read a port bit, two possibilities are there
I) Reading input pin.
ii) Reading port latch.
READING INPUT PIN
First we shall write ‘1’ into that bit. Then
1. By writing ‘1’ to the port bit, D latch has High on Q and hence Q’ = 0.
2. Since Q’ is low, M1 is off.
3. When M1 is off, it blocks any path to the ground for any signal connected to the input
pin and input is directed to tri-state TB1.
4. When reading the input port using MOV A,P1, we are reading the data from pin, by
enabling TB1.
WRITING ‘0’ TO PORT
To configure as input port, the port must be loaded with ‘0’, resulting Q=0 & Q’ = 1 and
hence M1 is on.
When M1 is on, it provides a path to ground for both Load and input pin, which may lead
to damage the port.
To avoid this damage,
1. Connect a 10 K ohm resistor parallel to Load to limit the current flow through M1.
2. Use a switch with ground only.
3. Connect any input switch through a buffer.
READING THE LATCH
1. The read latch activates TB2 and brings data from the Q latch into CPU.
2. The data is modified, according to instruction (like And or OR), with the contents of
register A.
3. The result is rewritten to the latch.
P1 pins have no dual functions. The output latches is connected directly to the gate of the
lower FET, which has an FET circuit labeled internal FET pull up as an active pull up
load.
Used as an input, a 1 is written to the latch, turning lower FET off, the pin and input to
pin buffer pulled high. An external circuit can overcome the high impedance pull up and
drive the pin low to input a ‘0’ or leave the input high for a ‘1’.
If used as output, the latches containing a ‘1’ can drive the input of an external circuit
high through the pull up. If ‘0’ is written to the latch, the lower FET is ON the pull up is
off and the pin can drive input of the external circuit low.
To aid in speeding up switching times when the pin is used as an output, the internal FET
pull up has another FET in parallel with it. The second FET is turned on for two
oscillator time periods during a low to high transition on the pin. This arrangement
provides a low impedance path to the positive voltage supply to help to reduce rise time
in charging an parasitic capacitance in the external circuitry.
P2:

P2 may be as an input /output port similar to p1. The alternate use of p2 is to supply
high order address byte in conjunction with P0.
P2 outputs the high order byte of external memory address. Otherwise it continues to
emit P2 SFR contents.
P3:
P3 is an I/O port similar to P1. The P3 alternate uses are shown below.
If P3 bit latch contains 1,the output level is controlled by “Alternate output function”
The P3X pin level is also available to the pin’s “Alternate input function”
All P3 pins are multifunctional. They are not only output pins, but also serve the
functions of various special features as listed below. p1 is simple I/0 port

P3.0 RXD (serial input port)


P3.1 TXD (serial output port)
P3.2 INTO (external interrupt)
P3.3 INT1 (External interrupt)
P3.4 T0 (timer/counter ‘0’ external input)
P3.5 T1 (timer/ counter ‘1’ external input)
P3.6 WR
P3.7 RD

READ-MODIFY-WRITE FEATURE:
The instructions that read the latch rather than pins are that read a value, possibly change
it and then rewrite it to the latch. They are called “Read – Modify – Write” instructions.
When destination operand is a port or a port bit, these instructions read the latch rather
than the pins.
ANL
ORL
XRL
JBC
CPL
INC
DEC
DJNZ
MOV PX.Y,C
CLR PX.Y
SETB PX.Y
The reason that read modify write instructions are directed to the latch rather than the pin
is to avoid a possible misinterpretation of the voltage level at pin.
For example. A port bit might be used to drive base of a transistor. When a 1 is written to
the bit, the transistor is turned on. If the CPU then reads the same port bit at the pin rather
than the latch, it will lead the base voltage of the transistor and interpret it as a ‘0’.
Reading the latch rather than the pin will return the correct value of ‘1’.
We shall see one example to understand the concept of read modify write feature.
BACK: MOV A, #55H
MOV P1,A
ACALL DEALY
MOV P1,A
ACALL DELAY
SJMP BACK
The above code toggles every bit of P1 continuously. We change it as follows
MOV P1, #55H
BACK: ACALL DEALY
MOV P1, #0AAH
ACALL DELAY
SJMP BACK
the ports of 8051 can be accessed using R-M-W technique. This feature saves many lines
of code by combining in a single a instruction all three action.
1. Reading the latch.
2. Modifying it
3. Writing to the latch.
AGAIN: MOV P1, #55H
XLR P1, #0FFH
ACALL DELAY
SJMP AGAIN

TIMER / COUNTER PROGRAMMING IN THE 8051:


The 8051 has two timers\counters. They can be used either as timers to generate time delay
or as counters to count events happening outside the micro computer. Now we shall see
how they are programmed.
PROGRAMMING 8051 TIMERS:
8051 has two timers, timer 0 & timer 1. this module has two 16bit registers. T0 and T1
registers. These registers can be configured to operate either as timers or event counters.
In the ‘timer’ function. The register is incremented every machine cycle. Thus, one can
think it as counting machine cycles. Since a machine cycle consists of 12 oscillator
periods, the count rate is 1/12 of the oscillator frequency.
The 16 bit register of T0 / T1 is accessed as low byte and high byte (TH0 / TH1)
THO TLO
TMOD REGISTER:
Both timers t0 and t1 use the same register called TMOD to set the various timer operating
modes.

DB15 DB0
GATE C/T’ M1 M0 GATE C/T’ M1 M0

GATE: Gating control when set timer/counter is enabled only while the INTx pin is high
and TRx pin is set. When cleared, the timer is enabled whenever the TRx control bit is set.
C / T: Timer / Counter selected cleared for timer application(c input from interval system
clock). Set for counter operation (input from Tx input pin).

M1, M0ℵ MODE BITS


M1 M0 MODE OPERATING MODE

0 0 0 13 bit timer mode


0 1 1 16 bit timer mode
1 0 2 8 bit timer mode
1 1 3 split timer mode

SOURCE OF THE CLOCK:


if C/T =0 the crystal frequency attached to the 8051 is the source of the clock for the timer.
Find the timer’s clock frequency and its period for various 8051 based systems with the
following crystal frequency.
1) 12 MHZ
2) 16 MHZ
11.0592 MHZ

Oscillator ÷ 12
The frequency for the timer is always 1/12th of the frequency of crystal attached to the
8051
1) 1/12 X 12 MHZ =1MHZ and T=1/1MHZ =1µ s.
2) 1/12 X 16 MHZ=1.33MHZ and T=1/1.33MHZ=0.75µ s
3) 1/12 X 11.0592 MHZ=921.6KHZ and T=1/921.6kHz=1.085µ s
INFLUENCE OF GATE:
It is to start or stop the timer, using hardware or software control.
SETB TR1, CLR TR1 for timer 1 and
SETB TR0,CLR TR0 for timer 0 instruction start or stop timers as long as gate =0in
TMOD register.
The use of external hardware to stop or start the timer is discussed later.

MODE 0:
This mode is compatible for MCS 48 family. The 13 bit counter can hold values between
0000 to 1FFF in TH and TL registers. Therefore, when the timer reaches its maximum of
1FFF it rolls over to 0000 and TF is raised.
MODE 1:
The characteristics of this mode are as follows:
1) it is a 16 bit timer. It allows values of 0000 to FFFFH into timer register TH and TL.
2) After TH and TL are loaded with 16 bit initial value. The timer must be started. This
is done by SETB TR0 for SETB TR1 for T1.
3) After timer is started, it starts to count up. It counts up to FFFFH . when it rolls over
from FFFFH to 0000, it sets a flag bit timer flag(TF). This flag can be monitored. When it
is raised, one option is to stop the timer with the instruction CLR TR0 or CLR TR1.
4)After the timer reaches its limit and rolls over, in order to repeat the process the register
TH and TL must be reloaded with the original value and TF must be reset to 0.

Crystal TH TL TF
÷ 12
Oscillator

TR
C/T’
MODE 1 PROGRAMMING:
To generate a time delay, using time mode, the following steps are taken:
• load the TMOD value register indicating which timer (T0 0r T1) is to be used and which
timer mode is selected.
• Load register TL and TH with initial count values.
• Start the timer.
• Keep monitoring the status of timer flag (TF). Come out of the loop, when TF becomes
HIGH.
• Stop the timer.
• Clear the TF flag for the next count.
• Go back to step 2.
NAME EXAMPLE 11
ORG 0H
MOV TMOD, #01H
HERE: MOV TL0, #0F2 H 2
MOV TH0, #OFFH 2
CPL P1.5 1
ACALL DELAY 2
SJMP HERE 2
DELAY: SETB TR0 1
AGAIN: SJNB TF0, AGAIN 14
CLR TR0 1
CLR TF0 1
RET 1
27

. In the above program, observe the following:


• TMOD is loaded.
• FFF2H is loaded into TH0-TL0.
• P1.5 is toggled for the high and low portions of the pulse.
• The DELAY subroutine, timer0 is started by SETB TR0 instruction.
• Timer0 counts up with the passing of each clock. As timer counts up, it goes through
FFF3, ….., FFFF, 0000 states. Now TF0 becomes HIGH.
•T0 is stopped by the instruction CLR TR0.And the process is repeated.
FFF2 FFF3 FFF4 FFFF 0000

TF=0 TF=0 TF=1


TF=0 TF=0

DELAY CALCULATION:
[(FFFF – YYXX) +1] * 1.085 µ s
The delay calculations for the above example are as follows.
For the entire period,
T=2*27*1.085µ s=58.59µ s
Problem: Find the delay generated by T0 in the following code.
CLR P2.3
MOV TMOD,#01H
HERE: MOV TL0,#3EH
MOV TH0,#0B8H
SETB P 2.3
SETB TR0
AGAIN: JNB TF0, AGAIN
CLR TR0
CLR TF0
CLR P2.3
NAME EXAMPLE 12
ORG 0H
MOV TMOD,#10H ; timer 1, mode 1(16 bit)
AGAIN: MOV TL1,#34H ; TL1=34h,low byte of timer
MOV TH1,#76H ; TH1=76H ,Hi byte
; (7634H=Timer value0
SETB TR1 ; start the timer 1
BACK: JNB TF1,BACK ; stay till the timer rolls over
CLR TR1 ; stop the timer 1
CPL P1.5 ; comp. P1.5 to get hi, lo
CLR TF1 ; clear timer flag1
SJMP AGAIN ; reload timer since mode1is not auto reload.
END
EXPLANATION:
The above program generates a square wave on pin P1.5 continuously using timer 1 for a
time delay. find the frequency of the square wave if XTAL=11.0592MHZ . in your
calculation, do not include the OVERHEAD due to instructions in the loop. Since FFFFh-
7634h=89CBh+1=89CCh and 89CCH=35276 clock count and
35276X1.0875µ s=38.274ms

Problem:
To find values of TH and TL registers, once the amount of time delay is known.
Assuming that XTAL = 11.0592 MHz write a program to generate a square wave of 2Khz
frequency on pin P1.5.
Assuming XTAL= 11.0592 MHZ, the following steps are to be followed.
1) Divide the desired time delay by 1.085µ s.
2) Perform 65536-n where n is the decimal value we got in step1.
3) Convert the result of step to hex.
4) Set TL and TH registers accordingly.
Assume that XTAL =11.0592 MHZ, what value do we need to load into the timer’s
register, to have a delay of 5ms; show the program for timer 0 to create a pulse width of 5
ms on P2.3.
Step 1: 5 ms / 1.085 µ s= 4608 clocks.
2. 65536 – 4608 = 60228.
3. EE00H
4. TH : EE & TL :00H.
PROGRAM:
NAME EXAMPLE-13
ORG 0H
CLR P2.3
MOV TMOD,#01H
HERE:MOV TL0,#00H
MOV TH0,#0EEH
SETB P2.3
SETB TR0
AGAIN:JNB TF0,AGAIN
CLR TR0
CLR TF0.
SJMP HERE.

Crystal
oscillator ÷ 12 TL TF

TR Over flow flag


C/T’
TH
TF goes high
when
FFFF

THE CHARACTERISTICS OF MOD 2 ARE AS FOLLOWS:


1) It is an 8-bit timer and it allows values of 00h to FFH.
2) After TH is loaded with the 8 bit value,8051 gives a copy of it to TL. Then the timer
must be started. This is done by the instruction ‘SETB TR0’ for T0 and ‘SETB TR1’ for
T1.
3) After the timer is started; it starts to count up by incrementing the TL register. It
counts up until it reaches its limit of FFH. When it rolls over from FFH to 00 H; it sets high
the TF (timer flag). If we are using timer 0, TF0 goes high. If we are using T/C TF1 is
raised.
4) When the TL register roll from FFH to 0 and TF is set to 1. TL is reloaded
automatically with the original value kept at TH register. To repeat the process, we must
simply clear TF and automatically reloads the originally values.
In auto reload, TH is loaded with the initial count and a copy of it is given to TL.
This reloading leaves TH unchanged still holding a copy of original value.
MODE 2 PROGRAMMING:
NAME EXAMPLE14
ORG 0000H
MOV TMOD, #2H; Timer 0, mode 2 (8 bit auto reload)
MOV TH0, #0
AGAIN: MOV R5, #250
ACALL Delay
CPL P1.0
SJMP AGAIN
Delay: SETB TR0
Back: JNB TF0, Back
CLR TR0
CLR TF0
DJNZ R5, Delay
RET
END
In the above program, time period is, T= 2(250*256*1.085µS)
= 138.8mS
COUNTER PROGRAMMING:
In the counter function, the register T0 and T1 are incremented in response to a 1 to 0
transition at its external inputs T0, T1.In this function, the external input is sampled during
S5P2 of every machine cycle.
When the samples show a high in one cycle and a low in the next cycle, the count is
incremented.
The new count value appears in the register during S3P1 of the cycle following the one in
which the transition was detected.
Since it takes two machine cycles (24 oscillator periods) to recognize a 1 to 0 transition.
The maximum count rate is 1/24 of the oscillator frequency. It is to ensure that given level
is sampled at least once before it changes, it should be held for at least one machine cycle.
P3.4 is used as T0, timer/counter 0 external input.
P3.5 is used as T1, timer/counter 0 external input.
Example –15:
Q. Assuming that clock pulses are fed in to pin T1, write a program for counter 1
in mode 2 to count the pulses and display the state of TL1 count on P2.
Solution:
MOV TMOD,#01100000B ;counter 1, mode 2, C/T=1
;external pulses
MOV TH1, #0 ;clear TH1
SETB P3.5 ; make T1 input
AGAIN: SETB TR 1 ; start the counter
BACK: MOV A, TL1 ; get copy of count TL1
MOV P2, A ; display it on port 2
JNB TF1, BACK ; keep doing it if TF=0
CLR TR 1 ;stop the counter 1
CLR TF 1 ;make TF=0
SJMP AGAIN ; keep doing it
Notice in the above program the role of the instruction “SETB P3.5”. Since ports
are set up for output when 8051 is powered up, we make P3.5 an input port by
making it high. In other words, we must configure (set high) the T1 pin (Pin3.5) to
allow pulses to be fed into it.

T0 TF0
TH0 TL0

P3.4 TF0 goes high when


Th fromFFFF to 0000
Equivalent instructions for the timer control registers
FOR TIMER 0
SETB TR0 = SETB TCON.4
CLR TR0 = CLR TCON.4
SETB TF0 = SETB TCON.5
CLR TF0 = CLR TCON.5
FOR TIMER 1
SETB TR1 = SETB TCON.6
CLR TR1 = CLR TCON.6
SETB TF1 = SETB TCON.7
CLR TF1 = CLR TCON.7
TCON : Timer/Counter Control Register

TF 1 TR1 TF 0 TR 0 IE 1 IT 1 IE 0 IT 1

THE CASE OF GATE = 1 IN TMOD:


So far, the task of timer is started through software using SETB TR0 and TR1 instruction.
If gate bit in TMOD is set to 1, the start and stop of a timer are done externally through
pins P3.2 and P3.3 of T0 & T1.
This way of operation has several applications.
For example, assume that on 8051 system is used to sound an alarm every second using T0,
in addition to many things. A switch can be connected to pin 3.2 , which can be used to
turn on and off the timer, there by shutting down the alarm.
Crystal
Oscillator % 12

C/ T=0
O O

C/ T =1
T0 Pin
Pin 3.4

TR 0

O
Gate
INT0 Pin
Pin3.2

SERIAL

COMMUNICATION
Fundamentals of serial communication
Serial communication means data transfer is bit by bit.
It has 3 modes of operation

A) SIMPLEX

Transmitter Receiver
data transmission is only in one direction

B) HALF DUPLEX

Transmitter Receiver

Receiver Transmitter

Data transmission is in both directions, not at single time.

c) full duplex

transmitter receiver

receiver transmitter

*data transmission is in both ways. i.e. Simultaneously

Serial communication to work the byte of data must be converted to serial bits
using a parallel –in –serial out shift register, and then it can be transmitted over a single
data line. Similarly at receiving end, there must be a serial- in-parellel_out register, to
receive serial data and pack them into a byte.
If the data has to be transferred on the telephone line, a MODEM must be
connected to convert 0&1’s to audio tones.

* When the distance is short, the digital signal can be transferred as it is on a


simple wire and requires no modulation. This is how a IBM pc key board transfer the
data to the mother board.

Serial data uses two methods.


1. Asynchronous data transfer – transmits byte by byte
2. Synchronous data transfer --transfers a block of data at a time.
It is possible to write software to use either of these methods but they are
complicated.
A special IC is commonly used for this purpose.
UART (universal asynchronous receiver transmitter)
USART (universal synchronous and receiver transmitter)
8051 has a built it in UART

SYNCHRONOUS DATA TRANSFER


In synchronous format; a receiver and a transmitter are synchronized.
A block of characters are transmitted along with synchronization information.
The transmission rate is greater than 20k bits per second.

Transmitter Receiver

Syn Syn
d d
c c

BYSYNC, HDLC, SDLC protocols will come under this class.

Asynchronous data transfer:

Transmitter Receiver
start stop stop
data

mark
space

Framing =start bit +data + parity bit +1 or 2 stop bits. Normally


(when there is no data), high (logic 1)is transferred from source to
destination.

RATE OF TRANSMISSION
The rate at which the bits are transmitted in bps.
Baud: The number of signal changes per one second.
As far as conductor wire is concerned, the band rate and bps are same and hence they are
interchangeable

ERROR CHECKS IN DATA COMMUNICATION:


Parity check can only one bit of error can be detected. Check sum is another variety to
check error. Check sum is a sum of all data byte string (without strings).
Error checks in data communication.
Parity check can only one bit of error can be detected. Check sum is another variety to
check error. Check sum is a sum of all data byte string (without strings).

DATA COMMUNICATION OVER TELEPHONE:

Serial to
parallel Modem
Microcontroller
converter
Parallel to serial
Microcontroller converter Modem

1270hz 1070hz
space
mark

RS232C cable

1488

1489
2
DCE
1489 3

DTE 7 1488
Modem

DATA TERMINAL EQUIPMENT: Generally computer or microprocessor that are


sending and receiving data. Data communication equipment modems and other
equipment that are used to send data for long distance. Digital data communication uses
modem and & standard phone lines.
Max 232: It is a single chip, which converts TTL levels to Rs232c to voltage levels and
vice versa.
VCC

C3
1 2
6
C1 3 C4
4
C2 GND
5
11 T1in T1out 14

12 R1out R1in 13

10T2in T2out 7

9 R2out R2in8

gnd
TTLside 15 RS232side

8051
MAX232

P3.1 11 11
TxD 5
14 2 gnd

13 3
P3.0 10 12
RxD
DB--9
VCC

13 11

14 15
12 16
10
17

2 T1 in T1 out 5

3 R1 out R1 in 4

1 T2 in T2 out 18

20 R2 out R2 in 19

gnd
TTL side RS233 side

SERIAL COMMUNICATION
NAME EXAMPLE 17
With XTAL = 11.5092MHz, find the TH1 value needed to have the following baud rates.
(a) 9600 (b) 2400 (c)1200
Solution:
With XTAL=11.0592MHz, we have :
The machine cycle frequency of the 8051=11.0592/12=921.6KHz, and
921.6KHz/32=28,800Hz is the frequency provided by UART to timer 1 to set baud rate.

(a) 28,800/3 =9600 Where –3=FD(hex) is loaded into TH1


(b) 28,800/12=2400 Where-12=F4(hex) is loaded into TH1
(c) 28,800/24=1200 Where-24=E8(hex) is loaded into TH1

Notice that dividing 1/12th of the crystal frequency by 32 is the default value upon
activation of the 8051 RESET pin. We can change this default setting. This is explained
at the end of this chapter.
11.0592MHZ MACHINE
CYCLE 28800HZ
FREQ

XTAL OSC DIVIDE BY DIVIDE BY


12 32
BY UART
921.6
KHZ

TIMER 1 TH1 VALUES FOR VARIOUS BAUD RATES

BUAD RATE TH1 TH1(HEX)


(DECIMAL)
9600 -3 FD

4800 -6 FA

2400 -12 F4

1200 -24 E8

SBUF REGISTER
It is an eight bit register used for serial communication in 8051.
For a byte to be transformed via TXD line, it must be placed in SBUF. Similarly, SBUF
holds the byte of data when it is received by 8051’s RXD line.
The following is a program to transfer letter ‘A’ serially at 4800 baud , continuously.
Observe the status of serial window, serial port and timer port for results.

NAME EXAMPLE 16
ORG OH
MOV TMOD,#20H; Timer 1, mode 2(auto reload)
MOV TH1,# -6 H; 4800 baud rate
MOV SCON,#50H; 8 BIT ,1 Stop, REN enabled
SETB TR1; Start timer 1
AGAIN: MOV SBUF, #”A”; letter A to be transferred
HERE: JNB TI,HERE ; Wait for the last bit
CLR TI; clear TI for next char
SJMP AGAIN ; keep sending A
END
THE SIGNIFICANCE OF TI FLAG: once the timer is on TI is reset (=0). When the stop bit
is transferred, 8051 rises the TI flag is set, indicating that the last character was
transmitted and ready to transfer next character. By monitoring TI flag we make sure that
we are not overloading the SBUF register. When 8051 finishes transferring a byte, it
raises the TI flag to indicate it is ready for the next character. After SBUF is loaded with
a new byte , TI flag is forced to zero to transmit the new byte.

PROGRAMMING THE 8051 TO RECEIVE DATA SERIALLY


To transfer character bytes serially, the following steps must be followed:
the TMOD register loaded with the value 20h, indicating the timer 1 in mode 2 to the
baud rate.
The TH1 is loaded to set the baud rate for serial data transfer.
The SCON register is loaded with the value 50h, indicating the mode 1 , where an 8-bit
data is started with start and stop bits.
TR1 is set to start timer1.
RI is cleared by software.
The RI bit is monitored to whether entered character is received or not.
When RI is raised, SBUF has the byte, move its contents to a safe place.
To transfer next character, go to step 5.
The importance of RI flag : when the stop bit is received during receiving, 8051 makes
RI=1, indicating that an entire byte is received.

By checking RI flag, when it is raised we know that the byte is received and is residing in
SBUF register.
After content of SBUF is placed in a safe place, RI must be forced to reset to allow the
next received character to place in SBUF register.

Assume that the 8051 serial port is connected to the COM port of IBM pc and PC is to
send and receive data serially, P1 and P2 are connected to LED’S and switches
respectively

Write an 8051 program to a Send to PC the message “WE ARE READY” b)


Receive any data sent by PC and put it on LED’S connected port 1.c) Get data
on switches connected to P2 and send it to PC serially The program should
perform part-a once, but parts b and c continuously. Use the 4800 baud rate.
Observe the results on serial window, timer port, and P1 and P2.

INTERRUPTS
Micro controller can extend its services to any peripheral devices in two
ways. In POLLING method microcontroller checks all the devices in round robin fashion.
In INTERRUPT method, the peripheral device notifies the micro controller by sending it
an interrupt signal. Up on receiving an interrupt signal, micro controller interrupts the
current task and calls ISR.
For every interrupt, there must be an ISR. When an interrupt is invoked, the
micro controller executes the ISR. For every interrupt, there is a fixed memory location
that holds the address of the ISR.

STEPS IN EXECUTING AN INTERRUPT


Upon activation of an interrupt, the micro controller goes through the following steps.
1.It finishes the execution of the current instructions and saves the address of next
instruction on TOS.
2.It also saves the current status of Interrupts.
3.It jumps to a fixed location from IVT.
4.It executes FSR, until RETI instruction.
5.Upon executing RETI, micro controller return to the main program where it was
interrupted, by retrieving the return address from IOS.

SIX INTERRUPTS IN 8051:


RESET: when reset pin is activated, 8051 jumps to address 0000h.
Two interrupts for timers.
Two interrupts for external hardware. INT0 & INT1.
Serial communication has a single interrupt.

EA IE.7 Disables all interrupts. If EA=0 interrupt is acknowledged. If EA=1, each


interrupt source is individually enabled or disabled by setting or clearing it’s
enable bit .
--- IE.6 Not implemented, reserved for future use*
ET2 IE.5 Enables or disables timer2 overflow or capture Interrupt (8952).
ES IE.4 Enables or disables the serial port interrupts.
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.

PROGRAMMING TIMER INTERRUPTS:


TF0

1 000BH

TF1 JUMPS TO

1 001BH

It is understood from timer application of 8051 that the timer flag is raised when the timer
rolls over. In polling TF, we have to wait till TF is raised. In Interrupt mode, the utility of
Micro controller is optimized.
It will be made clear this point from the following example.
1. We must avoid the memory space allocated to the interrupt vector table. Therefore, we
place all the initialization codes in memory starting at 30h. the LJMP instruction is the first
instruction that the 8051 executes when it is powered up. LJMP redirects the controller
away from the interrupt vector table.
2. The ISR for timer 0 is located starting at memory location 000Bh since it is small
enough to fit the address space allocated to this interrupt.
3. We enabled the timer 0 interrupt with “MOV IE,#10000010B” in MAIN.
4.While the P0 data is brought in and issued to P1 continuously, whenever timer 0 is rolled
over, the TF0 flag is raised, and the microcontroller gets out of “BACK” loop and goes to
000Bh to execute the ISR associated with timer0.

In the ISR for timer 0, notice that there is no need for a “CLR TF0” instruction before the
RETI instruction. The reason for this is that the 8051 clears the TF flag internally upon
jumping to the interrupt vector table.
Example 1: Write a program that continuously gets 8-bit data from P0 and sends it to P1
while simultaneously creating a square wave of 200μs period on pin P2.1. use timer 0 to
create the square wave. Assume that XTAL = 11.0592MHz.
MORE ABOUT TCON REGISTER:
Next we look at the TCON register more closely to understand its role in handling
interrupts. Figure 11.6 shows the bits of the TCON register

TF1 TCON.7 Timer 1 overflow flag. Set by hardware when timer/counter1


overflows. Cleared by hardware as the processor vectors
to the interrupt service routine.

TR1 TCON.6 Timer 1 run control bit. Set/cleared by software to turn


timer or counter1 on/off.

TF0 TCON.5 Timer 0 overflow flag. Set by hardware when timer/counter 0


overflows. Cleared by hardware as the processor vectors to
the service routine.
TR0 TCON.4 Timer 0 run control bit. Set/cleared by software to turn
Timer/counter 0 on/off.
IE1 TCON.3 External interrupt 1 edge flag. Set by CPU when the External interrupt
edge (H-to-L transition) detected Cleared by CPU when the interrupt is processed.
Note: This flag does not latch low level triggered
Interrupts.
ITI TCON.2 Interrupt 1 type control bit. Set/cleared by software to
Specify falling edge/low level triggered external interrupt.
IE0 TCON.1 External interrupt 0 edge flag . Set by CPU when external
Interrupt(H-to-L transition) edge detected. Cleared by CPU
When interrupt is processed.
Note: This flag does not latch low level triggered interrupts.

IT0 AND IT1:


TCON.0 and TCON.2 are referred to as IT0 and IT1, respectively. These two bits set
the low level or edge triggered modes of the external hardware interrupts of the INT0 and
INT1 pins. They are both 0 upon reset, which makes them low level triggered. The
programmer can make any one of them high to make the external hardware interrupt edge
triggered. In a given system based on the 8051, once they are set to 0 or 1 they will not be
altered again since the designer has fixed the interrupt either as edge or level triggered.

IE0 AND IE1:


TCON.1 and TCON.3 are referred to as IE0 and IE1, respectively. These bits are used
by the 8051 to keep track of the edge triggered interrupt only. In other words if the IT0 and
IT1 are 0, meaning that the hardware interrupts are low level triggered, IE0 and IE1 are not
used at all. The IE0 and IE1 bits are used by the 8051 only to latch the high to low edge
transition on the INT0 and INT1 pins. Upon the edge transition pulse on the INT0 (or
INT1) pin, the 8051 marks ( sets high) the IE x bit in the TCON register, jumps to the
vector in the interrupt vector table, and starts to execute the ISR. While it is executing the
ISR, no H to L pulse transition on the INT0 (or INT1) is recognized, thereby preventing
any interrupt inside the interrupt. Only the execution of the RETI instruction at the end of
the ISR will clear the IEx, bit indicating that a new H to L pulse will activate the interrupt
again.
From this discussion we can see that the IE0 and IE1 bits are used internally by the 8051 t
indicate whether or not an interrupt is in use. In other words, the programmer is not
concerned with these bits since it is solely for internal use.

TR0 AND TR1:


These are the D4(TCON.4) and D6(TCON.7) bits of the TCON register. We were
introduced to these bits earlier. They are used to start or stop timers 0 and 1, respectively.
Although we have used syntax such as “SETB TCON.4”and “CLR TCON.4” since TCON
is a bit addressable register.

TF0 AND TF1:


These are the D5(TCON.5) and D7(TCON.7) bits of the TCON register. We were
introduced to these bits in earlier chapters . They are used by timers 0 and 1, respectively,
to indicate if the timer has rolled over.

Although we have used the syntax “JNB TFx, TARGET” and “CLR TRx”, we could have
used instructions such as “JNB TCON.5,TARGET” and “CLR TCON.5” since TCON is bit
addressable.

Vous aimerez peut-être aussi