Top Banner
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
86
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 8051

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.

Page 2: 8051

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

Page 3: 8051

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.

Page 4: 8051
Page 5: 8051

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.

Page 6: 8051

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.

Page 7: 8051

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

Page 8: 8051

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.

RST

Page 9: 8051

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

- External Access (of Memory)

- Program Store Enable

ALE - Address Latch Enable.

Page 10: 8051

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 *B *PSW SP DPTR DPH DPL *P0 *P1 *P2

*P3*IP

*IE

TMOD*TCON*+T2CON TH0 TL0 TH1 TL1+TH2+TL2+RCAP2H

0000 00000000 00000000 00000000 0111

0000 00000000 00001111 11111111 11111111 11111111 11118051 XXX000008052 XX0000008051 0XX000008052 0X0000000000 0000 0000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 0000

Page 11: 8051

+RCAP2L*SCON SBUF PCON

0000 00000000 0000IndeterminateHMOS 0XXXXXXXCHMOS 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.

Page 12: 8051

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

Page 13: 8051

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 *B *PSW SP DPTR DPH DPL *P0 *P1 *P2

*P3*IP*IE TMOD*TCON*+T2CON TH0 TL0 TH1 TL1+TH2+TL2+RCAP2H

AccumulatorB register

Program Status WordStack Pointer

Data Pointer 2 BytesLow Byte High Byte

Port 0Port 1Port 2Port 3

Interrupt Priority ControlInterrupt Enable Control

Timer/Counter Mode ControlTimer/Counter Control

Timer/Counter 2 ControlTimer/Counter 0 High ByteTimer/Counter 0 Low ByteTimer/Counter 1 High ByteTimer/Counter 1 Low ByteTimer/Counter 2 High ByteTimer/Counter 2 Low Byte

T/C 2 Capture Reg. High Byte

0E0H0F0H0D0H81H

82H83H80H90H

0A0H0B0H0B8H0A8H89H88H

0C8H8CH8AH8DH8BH

0CDH0CCH0CBH

Page 14: 8051

+RCAP2L*SCON SBUF PCON

T/C 2 Capture Reg. Low ByteSerial Control

Serial Data BufferPower Control

0CAH98H90H87H

* = Bit Addressable+ = 8052 only

Page 15: 8051

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 .

Page 16: 8051

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

Page 17: 8051

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) PCPC+1

(ii) A[(A)+(PC)]

Page 18: 8051

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.

Page 19: 8051

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.

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

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

Page 20: 8051

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;

Page 21: 8051

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 R07F H

INC @R0 [R0] [R0]+1 7E will be modified with 00H.

DPTR: 12FE H

Page 22: 8051

INC DPTR: 12FF H

INC DPTR: 1300 H

DEC< byte>

Decrements the specified byte by 1.

No flag is affected.

DEC A AA-1

DEC Rn

DEC direct

DEC @Ri

MULTIPLICATION:

MUL AB ABA*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.

Page 23: 8051

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)

Page 24: 8051

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 ; AA (+)Rn

XRL A, direct; AA(+) (direct)

XRL A, @Ri; AA(+) [(Ri)]

XRL A, #data; AA(+) 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 C0

CLR bit bit0

CLR A A0

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>sd<s

C=1 C=0

d > s d < s

Page 25: 8051

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

PCPC + 3

If A< > (direct)

Then PCPC+ rel

If A<(direct)

Then C1

Else C0

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

Page 26: 8051

ROTATE INSTRUCTIONS

RLA (Rotate Accumulator Left)

No flag is effected

RLC A (Rotate Accumulator Left through Carry)

RRA (Rotate Accumulator Right)

D7 D6 D1 D0

CF

D7 D6 D1 D0

Page 27: 8051

No flag is effected

RRC A (Rotate Accumulator Right through Carry)

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.

D7 D6 D1 D0

CF

D7 D6 D1 D0

Page 28: 8051

PROGRAM CONTROL GROUP changes the sequence of the program.

a) Loop b) Jump c) Call

A) LOOP

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

In 8051, loop action is performed by the instruction

DJNZ reg, label

sr

RetContinue

Page 29: 8051

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

PCPC+2

(Rn)(Rn)-1

if (Rn)>0 or (Rn)<0

then

PCPC + rel

DJNZ direct, rel

B) JUMP GROUP

JMP

LJMP addr

It causes an unconditional branch to the indicated addr.

PCADDR

The destination may be anywhere in 64KB program memory address space.

No flag is effected.

AJMP ADDR

UNCONDITIONAL CONDIOTIONAL

LJMP AJMP SJMPJZ JNZ JCJNC JB JNBJBC

Page 30: 8051

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

instruction

AJMP

PCPC+2

PC10 – 0 page address

SJMP rel

Program control branches unconditionally to the address indicated,

SJMP rel

PCPC+2

PCPC + rel

The range of the destination allowed is from 128 bytes preceding this instruction and

to 127 bytes following it.

CONDITIONAL JUMP INSTRUCTIONS:

ALL CONDITIONAL JUMP INSTRUCTIONS ARE SHORTJUMPS.

1) JB bit, rel jump if bit set

PCPC+3

If (bit) =1

Then

PCPC+REL

JB P1.2, label

JB ACC.2, label_1

The bit tested is not modified. No flag is effected.

2) JBC bit, rel jump if bit set and clear bit

PCPC+3

If (bit) = 1,

Then bit0

PCPC + rel

Page 31: 8051

JBC ACC.2, label_2 will cause program execution to continue by lable_2 with ACC is

modified to 52H (0101 0010) from 56H(0101 0110)

JC rel jump If carry is set

PC PC + 2

IF (C) = 1,THEN

PC PC + rel

JNB bit, rel jump if bit not set

PCPC + rel

The bit tested is not modified.

JNC rel jump if carry not set

PCPC+2

IF (C) =0, THEN PCPC + rel

JNZ rel jump if accumulator not zero

PCPC+2

IF(ACC 0),THEN PCPC + rel.

JZ rel jump if accumulator zero.

PCPC+2

IF(ACC=0),then PCPC + rel

STACK OPERATIONS

The stack is a section of RAM, used by CPU to store information temporarily.

SP holds the address of ‘Top Of Stack (TOS)’. PUSH and POP operations are performed

on stack.

The SP can take values from 00 H to FF H.

PUSHING ONTO THE STACK

MOV R6, #25H

MOV R1, #12H

Page 32: 8051

MOV R4, #0F3H

PUSH 6

PUSH 1

PUSH 4

Initially after push 6 after push 1 after push 4

POP OPERATION:

POP3

POP5

POP2

After the above code is executed, the registers R3, R5 & R2 will be R3=54, R5=F9,

R2=76.

LCALL addr16

The sequence of micro instructions as follows.

25

12

25

F3

12

25

0C

0B

0A

09

2

3

7

DCE

Modem

DTE

ModemParallel to serial converter

Microcontroller1070hzspace1270hzmark

MicrocontrollerSerial to parallel converter

Modemstar

tspacedata

markstop

stop

FraFramiming ng =st=start art bit bit +d+data ata + +

parparity ity bit bit +1 +1 or or 2 2

stostop p

bitbits. s.

NorNormamally lly (w(whehen n

thethere re is is no no datdata), a), highigh h

(lo(logic gic 1)i1)is s

tratransfnsferrerred ed frofrom m

sousource rce to to

desdestintinatiation.on.ASYNCHRONOUS DATA TRANSFER:Receiver

Transmitter

BYSYNC, HDLC, SDLC protocols will come under this

class.ddSyncSyncReceiver

Transmitterreceiverreceiver

transmitter

transmitter

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

C) FULL DUPLEXTransmitter

ReceiverReceiverTransmitterReceiver09

08

54

F9

76

6C

0C

0B

0A

09

08

F9

76

6C

76

6C 6C

Page 33: 8051

PCPC+3

SPSP+1

[SP]PC7: 0

SP SP+1

[SP]PC15: 8

PC ADDR16

CALL instructions implicitly perform two push operations to save return address. The

subroutine can be within “64KB” of program memory.

ORG 0H

HERE: MOV A, #55H

MOV P1, A

LCALL DEALY

MOV A, #0AAH

MOV P1, A

LCALL DELAY

SJMP HERE

ORG 300H

DELAY: MOV R5, #0FFH

AGAIN: DJNZ R5, AGAIN

RET

END

*CHANGE THE DELAY PROGRAM AS FOLOWS & ANALYSE STACK

CONTENTS IN EACH STEP

DELAY: PUSH 4

PUSH5

MOV R4,#0FFH

NEXT_1: MOV R5,#OFFH

NXT: DJNZ R5,NXT

DJNZ R4,NXT_1

POP 5

POP4

Page 34: 8051

RET

ACALL (Absolute Call)

The sequence of micro-operations is as follows

PC<--PC+2

SP<--SP+1

[SP]<--PC7 : 0

DP<--DP+1

[SP]<--PC15:8

PC10:0<--PAGE ADDR

The subroutine must be called with in the same 2K block of the program memory.

DELAY PROGRAM AND ITS CALCULATIONS

NO OF CYCLES

DEALY: MOV R2, #200 1

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.085s for a clock of 11.0592 MHz,

11.0592/12=921.6 KHz

Machine cycle is 1/921.6 KHz = 1.085s

For ‘here loop’, (4250) 1.085 =1085s

For ‘again loop’, 2001085=21700s, excluding over-head.

Page 35: 8051

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.

Page 36: 8051

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=60A

IIL=50A

IIH=650A

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:

Page 37: 8051

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

Page 38: 8051

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

Page 39: 8051

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

Page 40: 8051

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.

Page 41: 8051

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:

Page 42: 8051

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

Page 43: 8051

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.

Page 44: 8051

The 16 bit register of T0 / T1 is accessed as low byte and high byte (TH0 / TH1)

 

 TMOD REGISTER: 

Both timers t0 and t1 use the same register called TMOD to set the various timer operating

modes.

 

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.

THO TLO

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

Page 45: 8051

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

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 =1s.

2) 1/12 X 16 MHZ=1.33MHZ and T=1/1.33MHZ=0.75s

3) 1/12 X 11.0592 MHZ=921.6KHZ and T=1/921.6kHz=1.085s

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

Oscillator12

Page 46: 8051

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.

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

CrystalOscillator

12

TRC/T’

TH TL TF

Page 47: 8051

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.

 

D

E

L

A

Y

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.085s=58.59s  

FFF2 FFF3 FFF4

FFFF 0000

TF=0 TF=0 TF=0 TF=0TF=1

Page 48: 8051

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.0875s=38.274ms

 

Page 49: 8051

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.085s.

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.

 

Page 50: 8051

 

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)

Crystal oscillator 12

TRC/T’

TF goes high whenFFFF

TL TF

Over flow flag

TH

Page 51: 8051

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:

Page 52: 8051

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.

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

TF0 goes high whenTh fromFFFF to 0000

TH0 TL0 TF0T0

P3.4

Page 53: 8051

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

TCON : Timer/Counter Control Register

 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.

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

A) SIMPLEX

Crystal Oscillator % 12

O

O

O

C/ T=0

C/ T =1T0 PinPin 3.4

TR 0

Gate

INT0 PinPin3.2

Page 54: 8051

data transmission is only in one direction

B) HALF DUPLEX

*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.

Transmitter

Receiver

Receiver

Transmitter

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

C) FULL DUPLEX

transmitter

transmitterreceiver

receiver

Transmitter Receiver

Page 55: 8051

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

Sync

Sync

d d

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

Transmitter Receiver

ASYNCHRONOUS DATA TRANSFER:

Page 56: 8051

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:

Framing =start bit +data + parity bit +1 or 2 stop bits. Normally 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 (when there is no data), high (logic 1)is transferred from source to

destination.destination.

stop stop

mark

data

space

start

ModemSerial to parallel converter

Microcontroller

Page 57: 8051

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.

1270hzmark

1070hzspace

MicrocontrollerParallel to serial converter

Modem

DTE

DCE

Modem

2

3

7

1488

1489

RS232C CABLE

1488

1489

Page 58: 8051

VCC

C31 2

6 C1 3 C4

4C2 GND

5 11 T1 in T1 out 14

12 R1 out R1 in 13

10 T2 in T2 out 7

9 R2 out R2 in 8

gndTTL side 15 RS232 side

VCC

C31 2

6 C1 3 C4

4C2 GND

5 11 T1 in T1 out 14

12 R1 out R1 in 13

10 T2 in T2 out 7

9 R2 out R2 in 8

gndTTL side 15 RS232 side

Page 59: 8051

VCC

1 3 11

14 15 12 16

1017

2 T1 in T1 out 5

3 R1 out R1 in 4

1 T2 in T2 out 18

20 R2 out R2 in 19

gndTTL side RS233 side

SERIAL COMMUNICATIONNAME EXAMPLE 17With XTAL = 11.5092MHz, find the TH1 value needed to have the following baud rates. (a) 9600 (b) 2400 (c)1200Solution: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.

Page 60: 8051

XTAL OSC DIVIDE BY 12

DIVIDE BY 32

BY UART

11.0592MHZ MACHINE CYCLE FREQ

921.6KHZ

28800HZ

E8-241200

F4-122400

FA-64800

FD-39600

TH1(HEX)TH1 (DECIMAL)

BUAD RATE

TIMER 1 TH1 VALUES FOR VARIOUS BAUD RATES

SBUF REGISTERIt 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 16ORG OHMOV TMOD,#20H; Timer 1, mode 2(auto reload)MOV TH1,# -6 H; 4800 baud rateMOV SCON,#50H; 8 BIT ,1 Stop, REN enabledSETB TR1; Start timer 1AGAIN: MOV SBUF, #”A”; letter A to be transferredHERE: JNB TI,HERE ; Wait for the last bitCLR TI; clear TI for next char

Page 61: 8051

SJMP AGAIN ; keep sending AEND 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 SERIALLYTo 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.

Page 62: 8051

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 INTERRUPTUpon 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:

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.

1

1

000BH

001BH

TF0

TF1 JUMPS TO

Page 63: 8051

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.

Page 64: 8051

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.