Вы находитесь на странице: 1из 72

8051 Micro Controller

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 code memory. & IE Oscillator & clock circuits 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 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 &

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

8051 Micro Controller 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.

8051 Micro Controller

8051 Micro Controller

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, integermultiplication & division and Boolean bit manipulations.

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

CY AC Carry out Auxiliary From MSB of ALU Operand carry for BCD operations

FO General purpose

RSI RSO Register Banks RB0-RB3

OV Over flow flag

P Parity of Accumulator set by hardware to 1 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.

8051 Micro Controller 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 1s in A. If A contains an odd number of 1s, then P=1. Therefore P=0, if A has an even number of 1s. 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 Micro Controller

8051 PORT LATCHES AND I/O BUFFERS

INTERFACE

8051 Micro Controller

8051 OSCILLATOR & CLOCK


8051 has on Chip Oscillator but needs an external clock to run it. A Quartz crystal C1= C2= 30pf (typical) Crystal oscillator=1to 16 MHz. oscillator is connected to XTAL2 & XTAL1.C1 &C2 are also connected as shown above.

8051 Micro Controller

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. Tinst = C 12 Crystalfrequency

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 B - 0000 - 0000

ACC - 0000 PSW - 0000

8051 Micro Controller SR - 0007

DPTR-0000

EA Memory)

- External Access (of PSEN - Program Store

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

Register
*ACC *B *PSW SP DPTR DPH DPL *P0 *P1 *P2 *P3 *IP *IE TMOD *TCON *+T2CON TH0 TL0 TH1 TL1

Value in Binary
0000 0000 0000 0000 0000 0000 0000 0111 0000 0000 0000 0000 1111 1111 1111 1111 1111 1111 1111 1111 8051 XXX00000 8052 XX000000 8051 0XX00000 8052 0X000000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000

8051 Micro Controller +TH2 +TL2 +RCAP2H +RCAP2L *SCON SBUF PCON 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 Indeterminate HMOS 0XXXXXXX CHMOS 0XXX0000

10

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

Memory organization

data memory. reside ON-CHIP.

8051 has separate address spaces for program memory and Program memory can be up to 64KB, lower 4KB may 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.

8051 Micro Controller

11

SFR MEMORY MAP


F8 F0 E8 E0 D8 D0 C8 C0 B8 B0 A8 A0 98 90 88 80 B ACC PSW T2CON IP P3 IE P2 SCON P1 TCON P0 RCAP2L RCAP2H TL2 TH2 FF F7 EF E7 DF D7 CF C7 BF B7 AF A7 9F 97 8F 87

SBUF TMOD TL0 SP DPL TL1 DPH TH0 TH1 PCON

SPECIAL FUNCTION REGISTERS Symbol Name Address

8051 Micro Controller *ACC *B *PSW SP DPTR DPH DPL *P0 *P1 *P2 *P3 *IP *IE TMOD *TCON *+T2CON TH0 TL0 TH1 TL1 +TH2 +TL2 +RCAP2H +RCAP2L *SCON SBUF PCON Accumulator B register Program Status Word Stack Pointer Data Pointer 2 Bytes Low Byte High Byte Port 0 Port 1 Port 2 Port 3 Interrupt Priority Control Interrupt Enable Control Timer/Counter Mode Control Timer/Counter Control Timer/Counter 2 Control Timer/Counter 0 High Byte Timer/Counter 0 Low Byte Timer/Counter 1 High Byte Timer/Counter 1 Low Byte Timer/Counter 2 High Byte Timer/Counter 2 Low Byte T/C 2 Capture Reg. High Byte T/C 2 Capture Reg. Low Byte Serial Control Serial Data Buffer Power Control 0E0H 0F0H 0D0H 81H 82H 83H 80H 90H 0A0H 0B0H 0B8H 0A8H 89H 88H 0C8H 8CH 8AH 8DH 8BH 0CDH 0CCH 0CBH 0CAH 98H 90H 87H

12

* = Bit Addressable + = 8052 only

8051 Micro Controller

13

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 Mov R0, #99h Mov R1, #85h Mov R2, #3Fh. select bank 2

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:

8051 Micro Controller

14

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 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. instruction. Only SFR, internal data RAM can be directly accessed

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

8051 Micro Controller

15

DATA TRANSFER GROUP


MOV A, Rn MOV A, direct MOV A, @Ri MOV 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 MOVC A, @A+dptr It loads accumulator with a code byte or a constant, from program memory. A [(A) + (dptr)] No flags are affected. MOVC A,@A+PC (i) PCPC+1 (ii) A[(A)+(PC)] The first byte is fetched at address, which is sum of the original 16-bit addition is performed, so a carry out from lower 8-bits may unsigned 8-bit accumulator contents and the contents of 16-bit register PC or dptr. propagate through higher order bytes. dptr 16-bit data A [Ri] A data A Rn

8051 Micro Controller

16

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.

8051 Micro Controller XCH A, Rn XCH A, direct XCH A, @Ri XCHD A, @Ri affected.
( A3 0 ) ( Ri3 0 )

17

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

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 ADD A, Rn ; A A+ (Rn) AC=0, C=1, OF=1, P=1

ADD A, direct ; A A+ (direct) ADD A, @ RI ; A A+ [Ri] ADD A, #data; A A+ data

8051 Micro Controller

18

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 ADD A, B DA A Valid BCD 0100 0111 + 0010 0101 0110 1100 0110 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; (43): 59; (41): 11; (44): 37; (42) : 65;

SUBTRACTION:
SUBB A, <src byte> SUBB A, Rn ; A A--(c) Rn SUBB A, direct; SUBB A, @Ri; SUBB A, #data;

8051 Micro Controller

19

EXAMPLE
A= 0C9H R2= 54H CY=1 SUBB A, R2 leaves value 74H in accumulator 1100 1001 =0C9H 1010 1100 =(-54H) 1 0111 0101 2s Complement the carry C=0, AC=0, OF=1 For subtraction, STEP 1: Get 1s complement & then 2s 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. 1s 0101 0100 1010 1011 + 1 1010 1100

INC <byte>
Increments the specified byte by 1. No flag is affected. INC A INC Ri INC @Ri INC direct INC dptr

EXAMPLE

8051 Micro Controller R0 holds 7EH & internal RAM 7EH holds FF H. INC R0 INC @R0 DPTR: 12FE H INC DPTR: 12FF H INC DPTR: 1300 H R0 R0+1 [R0] [R0]+1 R07F H 7E will be modified with 00H.

20

DEC< byte>
Decrements the specified byte by 1. No flag is affected. DEC A DEC Rn DEC direct DEC @Ri AA-1

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(70) 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>

8051 Micro Controller 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)

21

ANL C, <src data>


It clears carry flag, if src bit is 0. Otherwise leaves the CF in its current data. ANL C, bit ANL C,/bit C(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 ORL A, direct ORL A, @Ri ORL A, #data ORL direct, A A A v Rn A A v (direct) A A v [(Ri)] A A v (#data) (direct)(direct) v A

ORL direct, #data (direct)(direct) v data.

8051 Micro Controller

22

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; ORL C, /bit; (C)(C ) v (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 ; 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 CLR bit CLR A CPL A A0 A(complement of A) C0 bit0

Each bit of accumulator is logically complemented (1s complement).

CPL bit
The specified bit is complemented. CPL P1.1 CPL C P1.1 (P1.1) C (C)

COMPARE INSTRUCTION
CJNE dest, src, rel-addr. d<s d>s

8051 Micro Controller

23

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

ROTATE INSTRUCTIONS

8051 Micro Controller RLA R0otate Accumulator Left. No flag is effected

24

D7

D6

D1

D0

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)

8051 Micro Controller

25

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 1s in a given byte.

PROGRAM CONTROL GROUP changes the sequence of the program. a) Loop b) Jump c) Call

A) LOOP

sr

Continue

Ret

8051 Micro Controller 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 PCPC+2 (Rn)(Rn)-1 if (Rn)>0 or (Rn)<0 then PCPC + rel DJNZ direct, rel

26

B) JUMP GROUP
JMP UNCONDITIONAL LJMP AJMP SJMP CONDIOTIONAL JZ JNZ JC JNC JB JNB JBC

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.

8051 Micro Controller

27

AJMP ADDR 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
09

PCPC+2 PCPC + rel The range of the destination allowed is from 128 bytes preceding this instruction and to 127 bytes following it.

2 3 7

DC E Mo de m

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 JB P1.2, label ACC.2, label_1 jump if bit set and clear bit

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

D TE
Mo de

2) JBC bit, rel

Par allel to seri al con vert er Mic roc ontr olle r 107 0hz spa ce

8051 Micro Controller PCPC+3 If (bit) = 1, Then bit0 PCPC + rel 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

28

12 70 hz ma rk
Mic roc ontr olle r

Se rial to par all el co nv ert er


Mo de m

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.

star t spa ce data mar k stop stop

Fra min g

=st art bit +da ta + pari ty bit +1 or 2 sto p bits . Nor mall y (wh en ther e is no dat a), hig h (log ic 1)is 0C tran 0B sfer 0A red fro m 08 sou rce to des tina tion .

8051 Micro Controller

29

PUSHING ONTO THE STACK


MOV R6, #25H MOV R1, #12H MOV R4, #0F3H PUSH 6 PUSH 1 PUSH 4

Initially

after push 6

after push 1

after push 4

F3 12 25 25 12 25

POP OPERATION:
POP3 POP5 POP2 0C 0B 0A 09 08 54 F9 76 6C F9 76 6C 76 6C 6C

As yn ch ro no us dat a tra nsf er: Re

ver Tra ns mit ter


BYS YN C, HD LC, SDL C prot ocol s will co me und er this clas s. d d Syn c Syn c

8051 Micro Controller

30

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

Re cei ver Tra ns mit ter rec eiv er rec eiv er tra ns mit ter tra ns mit

Dat a tran smis sion is in both dire ctio ns, not at sing le time .

8051 Micro Controller NEXT_1: NXT: MOV R5,#OFFH DJNZ R5,NXT DJNZ R4,NXT_1 POP 5 POP4 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.

31

c) full du ple x
Tra ns mitt er

Rec eive DELAY PROGRAM AND ITS CALCULATIONS r Rec MOV R2, #200 eive DEALY: r AGAIN: MOV R3, #250 Tra HERE: NOP ns mitt NOP er DJNZ R3, HERE Rec DJNZ R2, AGAIN eive r RET 09

NO OF CYCLES 1 1 1 1 2 2 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, (4 250) 1.085 =1085s

8051 Micro Controller For again loop, 200 1085=21700s, excluding over-head.

32

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 have1 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=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:

8051 Micro Controller

33

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

8051 Micro Controller 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 FETs. 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.

34

P1-P3 STRUCTURE

TB2

8051 Micro Controller

35

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

8051 Micro Controller 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:

36

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.

8051 Micro Controller P2 outputs the high order byte of external memory address. Otherwise it continues to emit P2 SFR contents. P3:

37

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 pins 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 P3.1 P3.2 P3.3 P3.4 P3.5 P3.6 P3.7 RXD (serial input port) TXD (serial output port) INTO (external interrupt) INT1 (External interrupt) T0 (timer/counter 0 external input) T1 (timer/ counter 1 external input) WR RD

8051 Micro Controller

38

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

8051 Micro Controller 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

39

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)

8051 Micro Controller

40

THO

TLO

DB15
TMOD REGISTER:

DB0

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

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


0 0 1 1 1

M0
0 1 0

MODE
0 1 2 3

OPERATING MODE
13 bit timer mode 16 bit timer mode 8 bit timer mode 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 timers clock frequency and its period for various 8051 based systems with the following crystal frequency.

8051 Micro Controller 1) 2) 12 MHZ 16 MHZ

41

11.0592 MHZ

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

12

The frequency for the timer is always 1/12th of the frequency of crystal attached to the 8051

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) 2) 3) it is a 16 bit timer. It allows values of 0000 to FFFFH into timer register TH and TL. After TH and TL are loaded with 16 bit initial value. The timer must be started. This is After timer is started, it starts to count up. It counts up to FFFFH . when it rolls over

done by SETB TR0 for SETB TR1 for T1. 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.

8051 Micro Controller 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.

42

Crystal Oscillator

12 TR

TH

TL

TF

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 MOV TH0, #OFFH CPL P1.5 ACALL DELAY SJMP HERE DELAY: SETB TR0 1 14 AGAIN: SJNB TF0, AGAIN 2 2 1 2 2

8051 Micro Controller CLR TR0 CLR TF0 RET 1 1 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.

43

DELAY CALCULATION:
[(FFFF YYXX) +1] * 1.085 s The delay calculations for the above example are as follows. For the entire period, FFF3 FFF2 T=2*27*1.085s=58.59s
TF=0 TF=0 TF=0 Problem: Find the delay generated by T0TF=0 following code. in the FFF4 FFFF 0000 TF=1

CLR P2.3 MOV TMOD,#01H HERE: MOV TL0,#3EH MOV TH0,#0B8H SETB P 2.3 SETB TR0

8051 Micro Controller 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

44

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 FFFFh7634h=89CBh+1=89CCh and 89CCH=35276 clock count and 35276X1.0875s=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 1) 2) 3) 4) Divide the desired time delay by 1.085s. Perform 65536-n where n is the decimal value we got in step1. Convert the result of step to hex. Set TL and TH registers accordingly. to be followed.

8051 Micro Controller Assume that XTAL =11.0592 MHZ, what value do we need to load into the timers 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.

45

Crystal oscillator

12

TL
TR

TF
Over flow flag

C/T

TH
TF goes high when FFFF

8051 Micro Controller

46

THE CHARACTERISTICS OF MOD 2 ARE AS FOLLOWS:


1) 2) 3) It is an 8-bit timer and it allows values of 00h to FFH. After TH is loaded with the 8 bit value,8051 gives a copy of it to TL. Then the timer After the timer is started; it starts to count up by incrementing the TL register. It counts

must be started. This is done by the instruction SETB TR0 for T0 and SETB TR1 for T1. 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.085S)

8051 Micro Controller = 138.8mS

47

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 SETB P3.5 AGAIN: SETB TR 1 BACK: MOV A, TL1 MOV P2, A JNB TF1, BACK CLR TR 1 CLR TF 1 SJMP AGAIN ;clear TH1 ; make T1 input ; start the counter ; get copy of count TL1 ; display it on port 2 ; keep doing it if TF=0 ;stop the counter 1 ;make TF=0 ; 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

8051 Micro Controller high. In other words, we must configure (set high) the T1 pin (Pin3.5) to allow pulses to be fed into it.

48

T0

TH0

TL0

TF0
TF0 goes high when Th fromFFFF to 0000

P3.4
Equivalent instructions for the timer control registers FOR TIMER 0 SETB TR0 = SETB TCON.4 CLR TR0 CLR TF0 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 = CLR TCON.4 = CLR TCON.5 SETB TF0 = SETB TCON.5

TF 1

TR1

TF 0

TR 0

IE 1

IT 1

IE 0

IT 1

Crystal % 12 So far, the task of timer is started through software using SETB TR0 and TR1 instruction. Oscillator
If gate bit in TMOD is set to 1, the start and stop of a timer are done T=0 C/ externally through pins P3.2 and P3.3 of T0 & T1. This way of operation has several applications.

THE CASE OF GATE = 1 IN TMOD:

For example, assume that on T0 Pin 8051 system is used to sound an alarm every second using T0, in

C/ T =1

Pin can addition to many things. A switch3.4 be connected to pin 3.2 , which can be used to turn on
and off the timer, there by shutting down the alarm.

TR 0 Gate INT0 Pin Pin3.2


O

8051 Micro Controller

49

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

8051 Micro Controller

50

Transmitter

Receiver

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

Transmitter

c) full duplex

transmitter

receiver

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

transmitter

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&1s 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

8051 Micro Controller 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.

51

Transmitter

Receiver

Sync

Sync

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

Asynchronous data transfer:

Transmitter

Receiver

start data

stop

stop

space

mark

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.

8051 Micro Controller 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

52

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 converter

Microcontroller

Modem

8051 Micro Controller

53

Microcontroller

Parallel to serial converter

Modem

1270hz mark

1070hz space

RS232C cable

1488 1489
2

1489

3 7

DCE
1488

DTE

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.

8051 Micro Controller


VC C
C 3

54

1 C 1 C 2 1 T in 1 1 1 R ot 2 1 u 1 T in 0 2
9 R ot 2 u

4 5

6 C 4

GD N T ot 1 u R in 1 1 3 T ot 7 2 u
R in 8 2

1 4

T Ls e T id

gd n
1 5 R 2 2 sid S3 e

8051

MAX232
P3.1 TxD 11 11 14 2 12 13 3 DB--9 gnd

P3.0 10 RxD

8051 Micro Controller


VCC

55

13 14 12 17 2 T1 in 3 R1 out

11 15 16 10

T1 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 (b) 28,800/12=2400 (c) 28,800/24=1200 Where 3=FD(hex) is loaded into TH1 Where-12=F4(hex) is loaded into TH1 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.

1. 52 H 10 9 M Z

MC I E A HN C CE YL FE RQ

280 Z 80 H

XA TL

OC S

D ID B IV E Y 1 2
91 2 .6 KZ H

D ID B IV E Y 3 2 B UR Y AT

8051 Micro Controller

56

TIMER 1 TH1 VALUES FOR VARIOUS BAUD RATES BUAD RATE 9600 4800 2400 1200 TH1 (DECIMAL) -3 -6 -12 -24 TH1(HEX) FD FA F4 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 8051s 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. The following is a program to transfer a message YES serially at 9600 baud, 8-bit data, 1stop bit , continuously. Observe the results on serial window, serial port, and timer 1. NAME EXAMPLE 17 ORG 0H

8051 Micro Controller MOV TMOD,#20H; timer 1, mode2 MOV TH1,#-3H; 9600 baud rate MOV SCON,#50H; 8-BIT, 1-stop bit, REN enabled SETB TR1; start timer 1 AGAIN: MOV A, #Y ; Transfer y ACALL TRANS MOV A,#E ACALL TRANS MOV A,#S; TRANSFER S ACALL TRANS SJMP AGAIN ; Keep doing it : serial letter transfer subroutine TRANS: MOV SBUF,A; Load SBUF HERE: JNB TI,HERE ; wait for the last bit to transfer CLR TI ; Get ready for next byte RET END

57

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

8051 Micro Controller NAME EXAMPLE 18 ORG OH MOV P2,#OFFH;make P2 an input port MOV TMOD , #20H; timer 1 mode 2(auto reload) MOV TH1, #OFA; 4800 baud rate MOV SCON, #50H; 8 bit, 1 stop, REN enabled SETB TR1;start timer1 MOV DPTR,#200H; load pointer for message H_1: CLR A MOVC A.,@A+DPTR; get the character JZ B_1; if last character is get out ACALL SEND; other wise call transfer INC DPTR SJMP H_1 ; stay in loop B_1: MOV A,P2 ; read data on P2 ACALL SEND; transfer it serially ACALL RECV ; Get the serial data MOV P1,A; display it on leds SJMP B_1; stay in loop indefinitely ;---------------serial data transfer. ACC has the data SEND: H_2: MOV SBUF , A; load the data JNB TI,H_2; stay until here last bit CLR TI ; get ready for next character RET ;return to caller ;-------------------- receive data serially in simulator RECV: JNB RI, RECV ; wait here for MOV A, SBUF; save it in ACC CLR RI; get ready for next character RET ; return to caller ;-----------the message ORG 200H MYDATA: DB WE ARE READY, END

58

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.

8051 Micro Controller

59

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

8051 Micro Controller

60

TF0 1 TF1 1 JUMPS TO 001BH 000BH

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 200s period on pin P2.1. use timer 0 to create the square wave. Assume that XTAL = 11.0592MHz. Solution: We will use timer 0 in mode 2 (auto reload). THO=100/1.085s=92. --up on wake up go to main, avoid using memory space; allocated to interrupt vector table

8051 Micro Controller

61

ORG 0H LJMP MAIN ; by pass interrupt vector table ;-ISR for timer 0 to generate square wave ORG 000BH ; timer 0 interrupt vector table CPL P2.1; toggle P2.1 pin RETI ; Return from ISR ;--- the main program for initialization ORG 0030H MAIN: MOV TMOD,#02H ; timer 0 mode 2 auto reload MOV P0,#OFFH MOV TH0, #-92H ;TH0=A4 for -92 MOV IE,#82H ;IE=10000010 enable timer0 SETB TR0 BACK: MOV A, P0 ;get data from P0 MOV P1,A ; issue it to P1 SJMP BACK END EXAMPLE 2: rewrite the above example to create a square wave that has a high portion of 1085s and a low portion of 15s. Assume XTAL=11.0592MHz. use timer 1 . Solution: Since 1085s is 1000x1.085 we need to use mode1 of timer 1. Up on wake up go to main, avoid using memory space allocated to interrupt vector table ORG 0000H LJMP MAIN; by pass interrupt vector table ;--ISR for timer 1 to generate square wave ORG 001BH LJMP ISR_T1 ;jump to ISR ;--the main program for initialization ORG 0030H MAIN: MOV TMOD,#10H ; timer 1m, mode 1 MOV P0,#0FFH MOV TL1,#18H; THE LOW BYTE OF -1000 MOV TH1,#0FCH ; High byte of -1000 Mov IE,#88h ; enable timer 1 interrupt SETB TR1 BACK: MOV A, P0 ; get data from p0 MOV P1, A ; issue it to p1 SJMP BACK ;- TIMER 1 ISR must be reloaded since not auto reload ISR_T1: CLR TR1 ;stop timer 1 CLR P2.1 ;start of low portion MOV R2, #4; 2s

8051 Micro Controller HERE: DJNZ R2, HERE ; 4X2 machine cycle (MC) 8 MC MOV TL1,#18H ; Load T1 low byte value MOV TH1,#0FCH ; load T1 high byte value SETB TR1 SETB P2.1 ; P2.1 =1 back to high RETI

62

END

EXAMPLE 3: write a program to generate a square wave of 50Hz frequency on pin P1.2. Assume that XTAL=11.059MHz. Solution: ORG 0H LJMP MAIN ORG 000BH ;ISR for timer 0 CPL P1.2 MOV TL0.#00H MOV TH0,#0DCH RETI ORG 30H ;---------main program for initialization MAIN: MOV TMOD,#00000001B ; Timer 0, mode1 MOV TLO,#00H MOV TH0,#0DCH MOV IE,#82H SETB TR0 HERE: SJMP HERE END

PROGRAMMING

EXTERNAL

HARDWARE

INTERRUPTS

There are two external interrupts INT0 & INT1, P3.2 & P3.3 are designated for them. The activation levels of these interrupts are 1. Level triggered. 2. Edge triggered.

LEVEL

TRIGGERED

INTERRUPT:

Example Assume that the INT1 pin is connected to a switch that is normally high. Whenever it goes low, it should turn on an LED. The LED is connected to P1.3 and is normally off. When it is turned on it should stay on for a fraction of a second. As long as the switch is pressed low, the LED should stay on. Solution: ORG 0H

8051 Micro Controller LJMP MAIN ; by pass interrupt vector table ;------ ISR for hardware interrupt INT1 to turn on the LED ORG 0013H ;INT1 ISR SETB P1.3 ; turn on LED MOV R3, #255 BACK: DJNZ R3, BACK ; keep LED pm For a while CLR P1.3 ; turn off the LED RETI ;----MAIN program for initialization ORG 30H MAIN: MOV IE,#10000100 ;enable external INT 1 HERE: SJMP HERE ;stay here until get interrupted END

63

EDGE

TRIGGERED

INTERRUPT

EXAMPLE : ASSUMING THAT PIN 3.3 (INT1) is connected to a pulse generator, write a program in which the falling edge of the pulse will send a high to P1.3,which is connected to an LED (or buzzer). In other words, the LED is turned on and off at the same rate as the pulses are applied to the INTI pin. This is an edge triggered version of example above. Solution: ORG 0000H LJMP MAIN ;----ISR for hardware interrupt INT1 to turn on the LED ORG 0013H SETB P1.3 ; Turn on the LED MOV R3, #255 BACK: DJNZ R3, HERE ;keep the buzzer on for a while CLR P1.3; turn off the buzzer RETI ;-----MAIN program for initialization ORG 30H MAIN: SETB TCON.2 ;make INT1 EDGE TRIGGER INTERRUPT MOV IE,#10000100B ;enable external INT1 HERE: SJMP HERE END 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

8051 Micro Controller 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.

64

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.4and CLR TCON.4 since TCON is a bit addressable register.

8051 Micro Controller

65

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.

PROGRAMMING SERIAL COMMUNICATION INTERRUPT:


Previously we have seen serial communication problems in polling mode. Now we explore the interrupt based serial communication, which allows the 8051 to do many things in addition to sending and receiving data from serial communication port.

RI AND TI FLAGS AND INTERRUPTS


TI is raised when the last bit of the framed data the stop bit is transferred, indicating that SBUF is ready to transfer the next byte. RI is raised, when the entire data frame is received. In 8051 there is only one interrupt set aside for serial communication. This interrupt is used to both send and receive data. If the interrupt bit (IE.4) is enabled, when RI or TI is raised, 8051 gets interrupted and jumps to 0023h to execute the ISR. In that ISR we must examine, the TI and RI flags to which one caused the interrupt. EXAMPLE 11.8: Write a program in which the 8051 reads data from P1 and writes it to P2 continuously while giving a copy of it to the serial communication port to be transferred serially. Assume that XTAL=11.0592MHz. Set the baud rate at 9600. Solution: ORG 0000H3 LJMP main ORG 0023H LJMP serial ; jump to serial interrupt ISR ORG 0030H Main: MOV P1, #0FFH ; make P1 an input port MOV TMOD,#20H ; timer 1 , mode 2 (auto reload) MOV TH1, #0FDH ; 9600 baud rate MOV SCON, #50H ; 8-bit ,1 stop, REN enabled MOV IE, #1001000B ; enable serial interrupt SETB TR1 ;start timer 1 Back: MOV A,P1 ; read data from port 1 MOV SBUF,A ; give a copy to SBUF

8051 Micro Controller

66

MOV P2, A ; send it to P2 SJMP Back ; stay in loop indefinitely -----------------------------SERIAL PORT ISR ORG 1000H Serial: JB T1, TRANS ;jump if T1 is high MOV A, SBUF ; other wise due to receive CLR RI ; clear RI since CPU does not RET I ; return from ISR TRANS: CLR TI ; clear TI since CPU does not RET I ;return from ISR END In the above problem notice the role of TI and RI. The moment a byte is written into SBUF it is framed and transferred serially. As a result, when the last bit (stop bit) is transferred the TI is raised, and that causes the serial interrupt to be invoked since the corresponding bit in the IE register is high. In the serial ISR, we check for both TI and RI since both could have invoked interrupt. In other words, there is only one interrupt for both transmit and receive . EXAMPLE 11.9 : Write a program in which the 8051 gets data from P1 and sends it to P2 continuously while incoming data from the serial port is sent to P0. Assume that XTAL= 11.0592MHz. Set the baud rate at 9600. Solution : ORG 0000H LJMP MAIN ORG 0023H LJMP SERIAL ; jump to serial ISR ORG 0030H MAIN: MOV P1, #0FFH ; make P1 an input port MOV TMOD , #20H ; timer 1 , mode 2(auto reload) MOV TH1,# 0FDH ;9600 baud rate MOV SCON, #50H ;8-bit, 1 stop, REN enabled MOV IE,#10010000B ;enable serial interrupt SETB TR1 ;start timer 1 BACK: MOV A,P1 ;read data from port 1 MOV P2, A ;send it to P2 SJMP BACK ; stay in loop indefinitely -------------------------SERIAL PORT ISR ORG 0100H SERIAL: JB T1,TRANS ;jump T1 is high MOV SBUF ;other wise due to receive MOV P0, A ;send incoming data to P0 CLR RI ;clear RI since CPU does not RETI ; return from ISR TRANS: CLR TI ;clear TI since CPU does not

8051 Micro Controller RETI END ;return from ISR

67

EXAMPLE 11.10 : Write a program using interrupts to do the following : Receive the data serially and send it to P0 Have P1 port read and transmitted serially, and a copy given to P2. Make timer 0 generate a square wave of 5KHz frequency on P0.1. Assume that XTAL= 11.0592 MHz . Set the baud rate at 4800. Solution: ORG 0000H LJMP MAIN ORG 000BH ; ISR for timer 0 CPL P0.1 ;toggle P0.1 RETI ORG 0023H LJMP SERIAL ;jump to serial INT.ISR ORG 0030H MAIN : MOV P1, #0FFH ; make P1 an input port MOV TMOD, # 22H ;timer 0 &1, mode 2 , auto reload MOV TH1, #0F6H ; 4800 baud rate MOV SCON, 350H ;8-bit, 1 stop, REN enabled MOV TH0,# --92H ;for 5KHz wave MOV IE,#10010010B ;enable serial, timer 0 INT. SETB TR1 ;start timer 1 SETB TR0 ;start timer 0 BACK : MOV A, P1 ;read data from port 1 MOV SBUF, A ; give a copy to SBUF MOV P2, A ;write it to P2 SJMP BACK ; stay in loop indefinitely -------------------------SERIAL PORT ISR SERIAL : JB TI, TRANS ; jump if TI is high MOV A,SBUF ; other wise due to receive MOV P0,A ;send serial data to P0 CLR RI ;clear RI since CPU does not RETI ;return froe ISR TRANS: CLR TI RETI END

8051 Micro Controller

68

CASE STUDY 1 STEPPER MOTOR CONTROLLER USING 8751


FEATURES: 1) IN CLOCK WISE DIRECTION, STEPPER MOTOR HAS TO BE ROTATED AT 1RPM, 2RPM, 3RPM ..20RPM. 2) IN ANTI CLOCK WISE DIRECTION STEPPER MOTOR HAS TO BE ROTATED AT 50 RPM. 3) TWO SEVEN SEGMENT LEDS TO INDICATE THE SPEED OF STEPPER MOTOR. 4) 4KEYS ARE INTERFACED TO SET THE RPM.

8051 Micro Controller

69

VCCl GND

KEYS
P2.0 P2.3

7447 8 7 5 1
P1.7 P1.4 P1.3 P1.0

7447

P0.0 P0.3 74LS373

SM driver

SM

8051 Micro Controller

70

CASE STUDY 2

74LS138 PSEN OE CE

74LS373 8 0 5 1

ROM
D0 D7

74LS373
CE

74LS245
EA
RD WR

RAM
WE OE

8051 Micro Controller OPERATION: The circuit operates in three modes: 1. Program mode 2. Run mode. 3. Test mode.

71

1. PROGRAM MODE: DESCRIPTION OF this mode UNDER PROJECT: of set points where calibration of the In CIRCUIT the required number
sensor is done and entered in to the controllers memory. So that the microcontroller may increase The temperature of the the project is as shown below : wait for the furnace to the block diagram of furnace up to that set point and settle down, as it takes time to reach up to that temperature.

2. RUN MODE:
This mode of operation corresponds to controlling the furnace by giving an 8 AD output from digital to analog converter to the furnace in a controlled manner up from to set points tillAT28C64 (IC2) are over. all the set points 2

3. TEST MODE:

574

T/c

5 This is the mode where we are going to check the sensor (IC5) by taking the sensors electrical equivalent signal and comparing it with that of the standards one. 5

OUTPUT OF THE CIRCUIT:


74LS373
The output of the project is as shown below:

(IC3)

74LS245

DAC
(IC3)

8 2 5

811
(IC6) Key

To burner

Temperature (c)

5 5 6 that After increasing the temperature up to certain time interval and after boarda soak is (IC4) maintained to allow the furnace to settle down at that temperature so that there will be no fluctuations. At soak interval readings are taken. Set points are shown in figure. 3 74LS138 4 LAMPEX

8051 (IC1)

LCD

Time(hrs)

8051 Micro Controller

72

Вам также может понравиться