Top Banner
Users Lab Manual (Experiments) S 2 N Systems, Pune. Cell No. 9011097672 EXPT. NO.: 1 TITLE : Executing simple programs using simulator PROBLEM DEFINITION: A. Write a program to add two 16-bit numbers. B. Write a program to convert temperature in degree Celsius to degree Fahrenheit. C. Write a program to convert temperature in degree Fahrenheit to degree Celsius. D. Write a program to add ‘n’ 8 bit numbers found in internal RAM locations 40H onwards & store the result in R6 (LSB) & R7 (MSB). E. Write a program to add BCD 7795H to 4548H and save the BCD result in RAM memory locations starting at 40H. S/W USED : Keil uVision2 Compiler / Assembler THEORY: A microcontroller has a CPU (a microprocessor) in addition to a fixed amount of ROM, RAM, I/O ports and a timer etc. all on a single chip. The 8-bit microcontrollers were developed by Intel, Motorola, Zilog, Philips, Microchip etc. 8051 Microcontroller: The 8051 is the first microcontroller of the MCS-51 family, introduced by Intel Corporation at the end of the 1980s. The 8051 family with its many enhanced members enjoys the largest market share, estimated to be about 40% among the various microcontroller architectures. The salient features of the 8051 microcontroller are given below. I. 8 bit CPU with resisters A and B. II. On-chip clock oscillator. III. 4Kbytes on-chip Internal ROM (program memory) IV. Internal ROM of 128 bytes – A. 4 register banks each containing 8 resisters B. 16 bytes which may be addressed at the bit level
96
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: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO.: 1

TITLE : Executing simple programs using simulator

PROBLEM DEFINITION:

A. Write a program to add two 16-bit numbers.

B. Write a program to convert temperature in degree Celsius to

degree Fahrenheit.

C. Write a program to convert temperature in degree

Fahrenheit to degree Celsius.

D. Write a program to add ‘n’ 8 bit numbers found in internal

RAM locations 40H onwards & store the result in R6 (LSB) &

R7 (MSB).

E. Write a program to add BCD 7795H to 4548H and save the

BCD result in RAM memory locations starting at 40H.

S/W USED : Keil uVision2 Compiler / Assembler

THEORY:

A microcontroller has a CPU (a microprocessor) in addition to a

fixed amount of ROM, RAM, I/O ports and a timer etc. all on a single chip.

The 8-bit microcontrollers were developed by Intel, Motorola, Zilog,

Philips, Microchip etc.

8051 Microcontroller:

The 8051 is the first microcontroller of the MCS-51 family,

introduced by Intel Corporation at the end of the 1980s. The 8051 family

with its many enhanced members enjoys the largest market share,

estimated to be about 40% among the various microcontroller

architectures. The salient features of the 8051 microcontroller are given

below.

I. 8 bit CPU with resisters A and B.

II. On-chip clock oscillator.

III. 4Kbytes on-chip Internal ROM (program memory)

IV. Internal ROM of 128 bytes –

A. 4 register banks each containing 8 resisters

B. 16 bytes which may be addressed at the bit level

Page 2: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

C. 80 bytes of general purpose data memory

V. 32 Input/output pins arranged as four 8- bit ports: P0 to P3

VI. Two 16 bits timer/counters i.e. T0 & T1

VII. Full duplex serial data receiver/transmitter (SBUF)

VIII. 16 bit PC (program counter) and DPTR (data pointer).

IX. 8 bit PSW (program status word).

X. 8 bit SP (stack pointer).

XI. Control resisters (like TCON, TMOD, SCON, PCON, IP

XII. 64-kbytes of program memory address space

XIII. 64-kbytes of data memory address space

XIV. 16-bit address bus multiplexed with port 0 and port 2; 8-bit data

bus multiplexed with port 0.

XV. Five-vector interrupt structure with two priority levels.

Block Diagram and Pin Diagram

Figure 1.1: Block diagram of 8051 microcontroller

Page 3: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Figure 1.2: Pin diagram of 8051 microcontroller

Internal memory organization:-

Microcontroller 8085 has mainly internal RAM and ROM memory.

Internal Memory organized in 8051 is such that the data memory and the

program code memory are entirely different memory entities. However

additional memory can be added externally.

a. Internal ROM

� 8051 has 4 KB of Internal ROM. Programmer code contained in

internal ROM occupies the address space 0000H to 0FFFH (i.e.

12bits).

� Program Counter (PC) is ordinarily used to address program code

bytes from address 0000H to 0FFFH.

� Program addresses higher than 0FFFH which exceed the internal

ROM capacity will cause 8051 to automatically fetch byte from the

external memory.

Page 4: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

� Code bytes can also be fetched exclusively from the external

memory addresses 0000H to FFFFH, by connecting external access

pin EA on DIP to ground.

b. Internal RAM

� 8051 has 128 bytes internal RAM which is distributed in four

register banks, bit addressable memory, scratch pad memory.

� A total 32 bytes from address locations 00H to 1FH are set aside for

register banks and the stack. These 32 bytes are divided into 4

banks of registers in which each bank has 8 resisters, R0 –R7.

� A bit addressable area of 16 bytes occupies RAM address 20H to

2FH forming 128 addressable bits.

� A total of 80 bytes from locations 30H to 7FH are used for read and

write storage or what is normally called a scratch pad. These 80

locations of RAM are widely used for the purpose of storing data

and parameters by programmers.

Figure 1.3: Internal RAM organization

Page 5: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

ADDRESSING MODES OF 8051:

1. Immediate Addressing Mode:–

o This mode allows using immediate data as a part of instruction.

o The value of a constant (immediate data) follows the opcode.

o When 8051 executes an immediate data mode the PC increments

automatically by 1 to the point to the bytes(s) following the opcode

byte in program memory. Whenever data is found there is copied

into destination addresses.

Mnemonic Operations

MOV A, # n Copy the immediate byte n to A

MOV DPTR, # nn Copy the immediate data nn to DPTR

MOV RO, # 3Oh Copying 3Oh into R0

2. Register addressing mode: –

o Certain registers names may be used as a part of opcode mnemonic

for destination or source. e.g. A, DPTR and R0 to R7

o The registers used in opcode as R0 to R7 are from the current

register bank which is chosen by the bits RS0 and RS1 of PSW.

o Register to register move using the register addressing mode occur

between A and Rn.

Mnemonic Operations

MOV A, Rn Copy the data from register Rr to register A

MOV Rn, A Copy the data from register A to register Rr

MOV R0, R5 Invalid statement

3. Direct Addressing Mode: –

o All 128 bytes of internal RAM and SFR may be directly

addressable using single byte address.

o Internal RAM uses addresses from 00h to 7FH to each address

byte.

o This addressing mode consists of direct address and SFR register

addresses.

Mnemonic Operations

MOV A, 80h Copy the data from P0 to register A

MOV R0, 12h Copy the data from RAM loc to register R0

Page 6: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

MOV 5ch, A Copy the content of A to address 5ch

MOV 0A8h, 77h Copy the data from RAM loc 77h to IE reg.

4. Indirect Addressing Mode:-

o The indirect addressing mode uses register R1, R0 and DPTR to

hold the address that will be finally used in the data move, the

register itself is not the address but rather the number in

register. Indirect addressing cannot be used to refer to SFR

registers. Both R0 and R1 can hold 8-bit address and DPTR can

hold 16-bit address.

Mnemonic Operations

MOV @Rp, #nn Copy immediate data to the address in Rp.

MOV @Rp, add Copy the memory contents to the addr. in Rp.

MOV @Rp, A Copy the content of A to address in Rp.

MOV A, @Rp Copy the contents of address in Rp to A.

MOV add, @Rp Copy the contents of the addr. in Rp to mem loc.

REFERENCES :

1. The 8051 Microcontroller & Embedded systems - M. Mazidi

2. The 8051 Microcontroller Architecture, Programming &

Applications - Kenneth Ayala

Page 7: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

1B) Write a program to convert temperature in degree Celsius to

degree Fahrenheit.

Assumptions: [R0] – holds the data 0C (in Hex format)

[R1] – Holds the result oF (in Hex format)

This program will for only temperature range 00 C to 830 C, since it

will not consider the carry. Also result is 30 F less due to fractions.

ORG 0000H

SJMP MAIN ; Skip the interrupt vector

ORG 0030H

MAIN:MOV A, R0 ; Move data in to accumulator

MOV B, #05

DIV AB ; Divide data with 09.

MOV B, #09

MUL AB ; Multiply 05 with result in last step

MOV R1,#32 ; Add 32 to the result in last step

ADD A, R1

MOV R1, A ; Move result in register R1

HERE:SJMP HERE

END

1C) Write a program to convert temperature in degree Fahrenheit

to degree Celsius.

Assumptions: [R0] – holds the data oF (in Hex format)

[R1] – Holds the result 0C (in Hex format)

This program will for only temperature range 00 F to 830 F,

since it will not consider the carry.

ORG 0000H

SJMP MAIN ; Skip the interrupt vector

ORG 0030H

MAIN: MOV A, R0 ; Move data in to accumulator

MOV R1,#32

SUBB A, R1 ; Subtract 32 from data

MOV B, #05

MUL AB ; Multiply 05 with result in last step

MOV B, #09

DIV AB ; Divide last step result with 09.

MOV R1, A ; Move result in register R1.

HERE: SJMP HERE

END

Page 8: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

1D) Write a program to add ‘n’ 8 bit numbers found in internal RAM

locations 40H onwards & store the result in R6 (LSB) & R7 (MSB).

ORG 0000H

SJMP START

ORG 0030H

START: MOV R1,#40H ; Starting address of memory locations

MOV R2,#0AH ; counter value

MOV A,#00H ; Clear the accumulator to store the result

MOV R4,00H ; clear the R4 to store the carry

MOV R5,00H ; clear the R5 to store the result

NEXT: ADD A,@R1 ; Add the contents of memory loc. To A.

JNC CARRY ; check for carry

INC R4 ; increment for carry

INC R1 ; INCREMENT POINTER

DJNZ R2, NEXT ; decrement the counter and jump if not

zero.

MOV R5, A ; Store the result in register R5

MOV R1, #50H ; Initialize the memory pointer to store

result

MOV @R1, R4 ; store carry to memory locations

INC R1 : Increment memory pointer

MOV @R1, R5 ; Store the result

HERE: SJMP HERE

END

Page 9: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

1E) Write a program to add BCD 7795H to 4548H and save the BCD

result in RAM memory locations starting at 40H.

ORG 0000H

SJMP START ; skip the interrupt vector

ORG 0030H

START: MOV A,#95H ; LSB of first no. in to accumulator

ADD A,#48H ; add LSB of second no. to

accumulator

DA A ; Decimal adjust

MOV 40H,A ; store result at memory location

MOV A,#77H ; MSB of first no. in to accumulator

ADDC A,#45H ; add MSB of second no. to

accumulator

DA A ; Decimal adjust

MOV 41H,A ;store result at memory location

CLR A

RLC A ; Check for carry from MSB.

MOV 42H, A

HERE: SJMP HERE

END

1A) Write a program to add two 16-bit numbers.

ORG 0000H SJMP MAIN ; Skip the interrupt vector table

ORG 0030H ; START AT LOCATION 0030H

MAIN:MOV R0,#99H ;LSB OF NO.1 MOV R1,#99H ;MSB OF NO.1

MOV R2,#99H ;LSB OF NO.2 MOV R3,#0ABH ;MSB OF NO.2

MOV A,R0 ADD A,R2

MOV R4,A ;STORE LSB OF RESULT IN R4 MOV A,R1

ADDC A,R3 ;A=A+R3+CY MOV R5,A ;STORE MSB OF RESULT IN R5

HERE:SJMP HERE END

Page 10: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO.: 2

TITLE : Executing complex programs using simulator

PROBLEM DEFINITION:

A. Write a program that finds the number of zeros in an 8-bit

data item.

B. Write a program to arrange an array in

ascending/descending order.

C. Write a program using lookup table, using the DPTR as the

base that finds the square of the number in A.

D. Write a program to copy a block of 10 bytes of data from

Internal RAM locations 30H to Internal RAM locations 60H.

E. Write a program to copy a block of 10 bytes of data from

External RAM locations 0200H to Internal RAM locations 40H.

S/W USED : Keil uVision2 Compiler / Assembler

THEORY:

INSTRUCTION SET OF 8051:

8051 instructions consist of 1 byte of opcode and 0 to 2 bytes of

operands. The instructions use 8-bit registers (like A, B, R0 – R7) and

also 16-bit registers (Like DPTR, PC). The Instructions of 8051 can be

broadly classified under the following headings:

i. Data transfer instructions

ii. Arithmetic instructions

iii. Logical instructions

iv. Branch instructions

v. Subroutine instructions

vi. Bit manipulation instructions

Page 11: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

1. Data transfer instructions:

Data is stored at a source address and moved to a destination address. The following five types of opcodes are used to move data.

a. MOV dst, src b. MOVX dst, src

c. MOVC d. XCH

e. PUSH and POP

The MOV opcodes involve the data transfers within the 8051 memory. This memory divided into the following four distinct physical

parts. i. Internal RAM

ii. Internal special function registers iii. External RAM

iv. Internal and External ROM

Data transfer operation Instruction

Move the contents of accumulator A to register Rn MOV Rn, A

Move the contents of register Rn to accumulator A. MOV A, Rn

Move an immediate 8-bit data to

i. Accumulator ii. Register Rn

iii. Direct memory location iv. Indirect memory location

v. Data pointer (DPTR) register

MOV A, #data MOV Rn, #data

MOV direct, #data MOV @Rp, #data

MOV DPTR, #16bit data

Move the contents of a memory location to Accumulator A and vice versa using direct

addressing

MOV A, direct MOV direct, A

Move the contents of a memory location to

Accumulator A and vice versa using indirect addressing

MOV A, @Rp

MOV @Rp, A

Move the contents of a memory location to Register

and vice versa using direct addressing

MOV Rn, direct

MOV direct, Rn

Move the contents of a memory location to another

memory locations using direct addressing and indirect addressing

MOV direct1, direct2

MOV direct, @Rp MOV @Rp, direct

Move the contents of an external memory location

pointed by Rp to Accumulator A and vice versa.

MOVX A, @Rp

MOVX @Rp, A

Move the contents of an external memory location

pointed by DPTR to Accumulator A and vice versa.

MOVX A, @dptr

MOVX @dptr, A

Move the contents of program memory to Accumulator A.

MOVC A, @A+DPTR MOVC A, @A+PC

Page 12: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Exchange Accumulator A with byte variable XCH A, Rn

XCH A, @Rp XCH A, Direct

Exchange the digits: exchanges the low order nibble of the accumulator A with that of the internal

memory location pointed by Rp.

XCHD A, @Ri

Push and Pop Instructions PUSH direct POP direct

2. Arithmetic instructions:

8051 has powerful instructions in the arithmetic group compared to

other microcontrollers. It can perform addition, subtraction, multiplication and division operations on 8-bit numbers.

a. Addition:

• All addition is done with A as destination address. • Some instructions may be use carry flag as an additional source

of a single bit that is included in the operation at the LSB position.

• AC flag is set when a carry is generated from lower nibble to higher nibble i.e. from D3 to D4.

• OV flag set if a carry is out of MSB bit i.e. D7. • All four addressing modes can be used for subtraction.

Addition operation Instruction

Add the contents of Accumulator A with immediate

data without / with carry and store the result in A

ADD A, #data

ADDC A, #data

Add the contents of Accumulator A with register Rn

without / with carry and store the result in A

ADD A, Rn

ADDC A, Rn

Add the contents of Accumulator A with contents of memory location without / with carry and store the

result in A using direct addressing.

ADD A, direct ADDC A, direct

Add the contents of Accumulator A with contents of

memory location without / with carry and store the result in A using indirect addressing.

ADD A, @Rp

ADDC A, @Rp

b. Subtraction: • The 8051 has commands to program subtraction of two signed

or unsigned numbers. • Register A is a destination address of all types of subtraction

instruction.

• All four addressing modes can be used for subtraction. • The carry flag is treated as borrow and subtract carry flag from

the resultant.

Page 13: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

• Carry Flag, Auxiliary carry flag, Overflow flags are affected.

Subtraction operation Instruction

Subtract immediate data and contents of carry flag from Accumulator A and store the result in A

SUBB A, #data

Subtract contents of register Rn and contents of

carry flag from Accumulator A and store the result in A.

SUBB A, Rn

Subtract contents of memory location and contents of carry flag from Accumulator A and store the

result in A using direct addressing.

SUBB A, direct

Subtract contents of memory location and contents of carry flag from Accumulator A and store the

result in A using indirect addressing.

SUBB A, @Rp

c. Multiplication:

• Instruction: MUL AB • Only two registers are used A & B.

• Multiplies the unsigned 8-bit integer in the register A and register B.

• After multiplication lower byte is put into A and higher order in B.

• The carry flag is always cleared to 0 after multiplication. • The overflow flag will be set if product is greater than FF. In this

high order byte is stored in register B.

d. Division: • Instruction: DIV AB

• Only registers A & B are used. • Divides the unsigned 8-bit integer in the accumulator A by the

unsigned 8-bit integer in register B.

• The quotient is stored in the Accumulator A and remainder is stored in register B.

• OV flag is set to 0 unless B holds the 00h before division, then OV flag is set to 1 to show division by 0.

d. Increment instructions:

• Instruction: INC <Byte> • Increments the indicated variable by 1.

• Flags are not affected. All addressing modes are supported.

Increment operation Instruction

Increments the contents Accumulator A by 1. INC A

Increments the contents of register Rn by 1 INC Rn

Page 14: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Increments the contents of memory location by 1

using direct addressing.

INC direct

Increments the contents of memory location by 1

using indirect addressing.

INC @Rp

Increments the contents of DPTR by 1 INC DPTR

d. Decrement instructions: • Instruction: DEC <Byte>

• Decrements the indicated variable by 1. • Flags are not affected. All addressing modes are supported.

Decrement operation Instruction

Decrements the contents Accumulator A by 1. DEC A

Decrements the contents of register Rn by 1 DEC Rn

Decrements the contents of memory location by 1 using direct addressing.

DEC direct

Decrements the contents of memory location by 1 using indirect addressing.

DEC @Rp

Decrements the contents of DPTR by 1 DEC DPTR

d. Decimal Adjustment after addition:

• Instruction: DA A

• Adjusts the sum of two packed BCD numbers found in Accumulator A; leave the adjusted number in accumulator A.

3. Logical instructions: Logical instructions are very useful in input / output operations.

They can perform the various operations such as AND, OR, EXOR, Complement, swap and rotate.

a. AND operation (ANL)

• Bitwise logically AND the contents of destination and source. • Flags are not affected.

Logical AND operation Instruction

AND the immediate data with contents of Accumulator A or with contents of memory locations

using direct addressing.

ANL A, #data ANL direct, #data

AND the contents Accumulator A with contents of

register Rn and store the result in A.

ANL A, Rn

AND the contents Accumulator A with the contents of memory location using direct addressing.

ANL A, direct ANL direct, A

AND the contents Accumulator A with the contents ANL A, @Rp

Page 15: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

of memory location using indirect addressing.

b. OR operation (ORL)

• Bitwise logically OR the contents of destination and source. • Flags are not affected.

Logical OR operation Instruction

OR the immediate data with contents of Accumulator A or with contents of memory locations

using direct addressing.

ORL A, #data ORL direct, #data

OR the contents Accumulator A with contents of

register Rn and store the result in A.

ORL A, Rn

OR the contents Accumulator A with the contents of memory location using direct addressing.

ORL A, direct ORL direct, A

OR the contents Accumulator A with the contents of memory location using indirect addressing.

ORL A, @Rp

c. EX-OR operation (XRL) • Bitwise logically OR the contents of destination and source.

• Flags are not affected.

Logical EX-OR operation Instruction

EX-OR the immediate data with contents of Accumulator A or with contents of memory locations

using direct addressing.

XRL A, #data XRL direct, #data

EX-OR the contents Accumulator A with contents of

register Rn and store the result in A.

XRL A, Rn

EX-OR the contents Accumulator A with the contents of memory location using direct

addressing.

XRL A, direct XRL direct, A

EX-OR the contents Accumulator A with the

contents of memory location using indirect

addressing.

XRL A, @Rp

d. Clear, Complement and swap the accumulator • CPL A: This will complement all the bits of accumulator.

• CLR A: This instruction will clear all the accumulator bits

to 0. • SWAP A: This instruction interchanges the low and high

order nibbles of the accumulator A.

e. Rotate Instructions • Rotate the only contents of accumulator A by 1-bit.

• Carry flag is affected by the rotate instructions

Page 16: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Rotate operation Instruction

Rotate the Accumulator A one bit position to the

left.

RL A

Rotate the Accumulator A through carry flag one bit

position to the left.

RLC A

Rotate the Accumulator A one bit position to the right.

RR A

Rotate the Accumulator A through carry flag one bit position to the right.

RRC A

4. Branch (Jump) instructions: When jump instruction is executed by the 8051, a jump occurs,

which can be a forward or a backward jump. The 8051 supports two types of jump instructions.

a) Unconditional jump instructions

b) Conditional jump instructions a. Bit Jumps

b. Byte Jumps

a. Unconditional jump instructions • Unconditional jump do not test any condition to determine the

jump. • The execution of this instruction always results in a branch.

• The destination address is provided as a part of the instruction. • Unconditional jump instructions are used to jump any location in

the memory.

Unconditional Jump operation Instruction

Jump to absolute long range 16-bit address (0000h to FFFFh). No PSW flags are affected.

LJMP LADD

Jump to absolute short range 11-bit address (0000 – 07FFH). No flags are affected.

AJMP SADD

Jump to the relative 8-bit address (00-FFH). No

PSW flags are affected.

SJMP RADD

Jump to the address formed by adding A to the

DPTR.

JMP @A+DPTR

b. Conditional jump instructions • Jumps operate by testing for conditions that are specified in the

jump mnemonic.

Page 17: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

• If the condition is true, then the jump is taken i.e. the PC is altered

to the address that is part of the jump instructions. • If the condition is false, then the instruction immediately following

the jump instruction is executed. • There are two types conditional jump instructions

o Bit jumps: operates according to the status of the Carry flag or the status of any bit addressable location.

o Byte jumps: test the bytes of data in contrast bit test.

Conditional Bit Jump operation Instruction

Jump relative if the carry flag is set to 1. JC RADD

Jump relative if the carry flag is reset to 0. JNC RADD

Jump relative if the addressable bit is set to 1. JB bit, radd

Jump relative if the addressable bit is reset to 0. JNB bit, radd

Jump relative if the addressable bit is set to 1 and

clear the addressable bit to 0 after jump.

JBC bit, radd

Conditional Byte Jump operation Instruction

Jump relative if the accumulator contents are 0. JZ RADD

Jump relative if the accumulator contents are not 0. JNZ RADD

Decrement the register Rn by 1 and jump to the

relative address if the result is not 0.

DJNZ Rn, radd

Decrement the direct address by 1 and jump to the relative address if the result is not 0.

DJNZ direct, radd

Compare the contents of the register A with the contents of the direct address; if they are not equal

then jump to the relative address.

CJNE A, direct, radd

Compare the contents of the register A with the immediate data; if they are not equal then jump to

the relative address.

CJNE A, #data, radd

Compare the contents of the register Rn with the

immediate data; if they are not equal then jump to the relative address.

CJNE Rn, #data, radd

Compare the contents of memory locations pointed

by Rp with the immediate data; if they are not equal then jump to the relative address.

CJNE Rp, #data, radd

Page 18: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Figure 2.1: Jump Instruction Ranges

5. Bit Manipulation instructions:

The 8051 supports a single bit operation. The internal RAM conatins 128 addressable bits (20H to 2FH) 00 to 7FH. SFR supports 128

addressable bits and all the I/O ports are bit addressable. Each I/O line can be treated as a separate single bit port. The 8051 provides bit

manipulation instruction to perform operations such as AND, OR, SET, CLEAR, Complement and also conditional bit manipulation jump

instruction. Conditional bit manipulation jump instructions are discussed under the jump instructions.

The bit manipulation instructions operate on any addressable RAM or SFR bit. The carry flag (CF) in the PSW register is the destination for

most of the op-codes because the flag can be tested and the program flow changed using jump instructions.

Note that in bit manipulation instruction no flags, other than carry flag, are affected, unless the flag is an addressed bit.

Bit level operation Instruction

Page 19: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

AND carry and addressed bit; put the result in CF ANL C, bit

AND carry and the complement of the addressed bit; put the result in CF; the addressed bit is not

altered.

ANL C, /bit

OR carry and addressed bit; put the result in CF ORL C, bit

OR carry and the complement of the addressed bit;

put the result in CF; the addressed bit is not altered.

ORL C, /bit

Complement the carry flag CPL C

Complement the addressed bit CPL bit

Clear the carry flag to 0 CLR C

Clear the addressed bit to 0 CLR bit

Set the carry flag to 1 SETB C

Set the addressed bit to 1 SETB bit

Copy the addressed bit to carry flag MOV C, bit

Copy the carry flag to addressed bit MOV bit, C

REFERENCES :

1. The 8051 Microcontroller & Embedded systems - M. Mazidi

2. The 8051 Microcontroller Architecture, Programming &

Applications - Kenneth Ayala

Page 20: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

2A) Write a program that finds the number of zeros in an 8-bit data

item.

ORG 0000H

SJMP MAIN ; skip the interrupt vector table

ORG 0030H

MAIN: MOV A, 40H ; load regi. A with direct memory address

MOV R5, #08H ; load R5 with count value

MOV R6, #00H ; clear the Regi. R6 to store the result

UP: RRC A ; Rotate the Accumulator thru carry to right

JC SKIP ; branch if bit is not zero

INC R6 ; increment if bit is zero.

SKIP: DJNZ R5, UP ; decrement counter and if not zero

HERE: SJMP HERE

END

2C) Write a program using lookup table, using the DPTR as the base

that finds the square of the number in A.

ORG 0000H

SJMP MAIN

ORG 0030

MAIN: MOV A, 30H ; get the no. from direct memory addr. 30H.

MOV DPTR,#0100H ; initialize DPTE with lookup table address

MOVC A, @A+DPTR ; get the square of no from lookup table

MOV 31H, A ; store the result at direct memory addr.

31H

HERE: SJMP HERE

END

ORG 0100H ; look table consists of square of numbers

SQUARE: DB 0,1,4,9,16,25,36,49,64,81,100

END

Page 21: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

2B) Write a program to arrange an array in ascending/descending

order.

Assumptions:

Memory Location (31H) : No. of bytes to sort

Memory location (32H and onwards) : Bytes to be sorted

ORG 0000H

LJMP START ; Skip the interrupt vector table

ORG 0030H

START: MOV R3, 31H ; initialize the outer counter (no. of passes)

DEC R3

CLR A

BACK0: MOV R1,31H ; initialize the outer counter ( for

comparing)

DEC R1

MOV R0,#32H ; initialize the memory pointer

BACK1: MOV 05H,@R0 ; move data to direct memory address 05h

INC R0 ; increment memory pointer

MOV A,@R0 ; move next to accumulator

CJNE A,05H,NEXT1 ; compare the two bytes

NEXT1: JNC AHEAD1 ; jump if [A] < [05H]; otherwise do

swapping

MOV A,05H ; swapping data between [A], [05]

MOV 05H,@R0

MOV @R0,A

DEC R0

MOV @R0,05H

INC R0 ; increment memory pointer

AHEAD1: DJNZ R1,BACK1 ; decrement inner counter & jump if not zero.

DJNZ R3,BACK0 ; decrement outer counter & jump if not zero.

EXIT: SJMP EXIT

END

NOTE: For descending order use instruction “JC AHEAD1” instead of

“JNC AHEAD1”.

Page 22: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

2D) Write a program to copy a block of 10 bytes of data from

Internal RAM locations 30H to Internal RAM locations 60H.

Assumptions:

Memory Location (30H onwards) : Source data address

Memory location (60H onwards) : Destination data

address ORG 0000H

SJMP START ; Skip the interrupt vector

ORG 0030H

START: MOV R0, #30H ; initialize the memory pointer with source

MOV R1, #60H ;Initialize the memory pointer with destn

MOV B, #0AH ; Counter

BACK: MOV A,@R0 ; Move source contents to accumulator

MOV @R1, A ; Move accumulator contents to destination

INC R0 ; Increment the source memory pointer

INC R1 ; Increment the destination memory pointer

DJNZ B, BACK ; decrement the counter & jump if not zero.

HERE: SJMP HERE

END

2E) Write a program to copy a block of 10 bytes of data from

External RAM locations 0200H to Internal RAM locations 40H.

Assumptions:

Memory Location (40H onwards) : Destination Internal data addr.

Memory location (0200H onwards) : Source external data address

ORG 0000H

SJMP START ; Skip the interrupt vector

ORG 0030H

START: MOV DPTR, #0200H ; initialize DPTR with source address

MOV R1, #40H ;Initialize the memory pointer with destn

MOV B, #0AH ; Counter

BACK: MOVX A,@DPTR ; Move source contents to accumulator

MOV @R1, A ; Move accumulator contents to destination

INC DPTR ; Increment the source memory pointer

INC R1 ; Increment the destination memory pointer

DJNZ B, BACK ; decrement the counter & jump if not zero.

HERE: SJMP HERE

END

Page 23: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO. : 3

TITLE : Executing programs on subroutines using simulator

PROBLEM DEFINITION:

A. Write a counter program to count continuously from 00 to

99h in BCD with a delay of 750ms between each count.

Display the count at any output port (Use looping for delay

and show delay calculation). Use simulator to show the

result.

B. Write a program to generate a square wave of 50 Hz on the

pin P2.4. (Use timer for delay generation). Use simulator to

show the result.

S/W & H/W USED : Keil uVision2 Compiler / Assembler

THEORY:

SUBROUTINES IN 8051:

A subroutine is a program that may be used many times in the

execution of a larger program. This makes a program more structured in

addition to saving memory space. Subroutines are usually handled by

special instructions like CALL, RET. The following sequences of events are

occurred for subroutines.

i. When CALL instruction is executed, the return address of the next

instruction after the call instruction is found in the PC.

ii. Return address bytes are pushed on the stack.

iii. The stack pointer is incremented for each push on the stack.

iv. The subroutine address is placed in the program counter and

subroutine is executed.

v. A RET instruction is encountered at the end of the subroutine.

vi. Two pop operations restore the return address to the PC from the

stack area in internal RAM.

vii. The stack pointer is decremented for each address byte pop.

Page 24: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Subroutine instructions

1. LCALL addr16:

Long call instruction is used to call subroutines located

anywhere within the 64k-byte address space of the 8051.This

is the 3 byte instruction. The instruction saves the next

instruction address on the stack and PC is loaded with the 16-

bit address of subroutine specified in instruction.

2. ACALL addr11:

Absolute call is 2-byte instruction. The target address of the

subroutine must be within 2Kbytes because only 11 bits of

the 2 bytes are used for the address.

3. RET (return from subroutine):

Return instruction is the last instruction of any subroutine to

return to main program. RET instruction pops the stack and

contents of the stack are loaded in PC.

4. RETI (return from interrupt):

RETI instruction is the last instruction of any interrupt service

routine to return to main program. It is similar to RET

instruction, only difference is RETI also clears the TF0, TF1,

IE0, IE1.

TIME DELAY GENRATION:

Most used subroutine is one that generates a programmable time

delay. Time delays may be done by using software loops that essentially do nothing for some period or by using hardware timers that count

internal clock pulses. The key to writing this program is to calculate the exact time each instruction will take at the clock frequency in use.

Following terms are very helpful to write a subroutine which generates desired time delay.

T-state: T-state is defined as one subdivision of the operation performed

in one clock period. The terms T-state and clock period are often used

synonymously.

Machine Cycle: Machine cycle in 8051 is defined as 12 oscillator periods.

The 8051, take one to four machine cycles to execute an instruction. To

calculate the machine cycle for the 8051, we take 1/12 of crystal

frequency, and then take its inverse.

Page 25: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Assume crystal frequency of 11.0592 Mhz

M/C frequency = 11.0592 Mhz/12 = 921.6 KHz

Machine Cycle = 1/921.6 KHz = 1.085 us (microseconds)

Instruction Cycle: Instruction cycle is defined as the time required for

completing the execution of an instruction. One instruction cycle consists

of one to four machine cycles.

e.g. 2 Machine cycles are required for instruction DJNZ R2, target to be

executed. Then instruction cycle is calculated as follows.

Instruction cycle = No. Machine cycles x Machine cycle period

= 2 x 1.085 us

= 2.17 us

Simple (single loop) Delay Subroutine

Label Mnemonics Machine cycles

Delay: MOV R3, #200 1

Here: DJNZ R3, Here 2

RET 2

• DJNZ instruction executed for 200 times.

• Here loop generates time delay = (200x2)x1.085us = 434 us.

• MOV and RET instruction are executed only once and they are called as overhead of the delay subroutine.

• Overhead = (1+2)x1.085us = 3.255 us. • Total Time delay = Loop delay + Overhead

= 434 us + 3.255 us = 437.255 us

Complex (nested loop) Delay Subroutine

• Maximum delay generated is 566.6 us using single loop delay

subroutine.

• To get large delay nested loops (loop inside a loop) are used.

Label Mnemonics Machine cycles

Delay: MOV R3, #200 1

Again: MOV R2, #250 1

Here: NOP 1

NOP 1

DJNZ R2, Here 2

DJNZ R3, Again 2

Page 26: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

RET 2

• The Here loop delay = [(1+1+2) x 250] x 1.085us = 1085 us

• The again loop repeats the here loop for 200 times. • Again loop delay = 200 x 1085 us = 217000

• Overhead = (3 x200) x 1.085 us = 651 us • Total delay = 217000 + 651 us = 217.651 ms.

Calculation for desired Time delay

• Suppose we want to generate the delay of 100us.

• Simple delay subroutine can generate the 100us delay since delay

is less than maximum delay (566 us) generated by subroutine.

Label Mnemonics Machine cycles

Delay: MOV R3, #YY 1

Here: DJNZ R3, Here 2

RET 2

• Find out the value of YY to get desired time delay.

• Time delay (Td) = Loop Delay + Overhead (as per above

discussion)

• Loop delay = YY x 1.085 us, overhead = 3 x 1.085 us = 3.255 us

• Td = YY x 1.085 us + 3.255 us

• Therefore YY = (Td – 3.255us)/1.085us= (100us –

3.255us)/1.085us

• YY = 89.16 = (89)10 = 59H

• In similar manner we can generate the larger delay using nested

loops.

• For larger delay, first calculate the count value for inner loop, then

calculate count value for outer loop considering delay generated by

inner loop.

TIMER/ COUNTER IN 8051:

8051 has 2 timer/ counter. They can be used a timers to generate a time delay or as counter to count events happening outside the

microcontroller. Both Timer 0 and Timer 1 are 16 bits wide. Since the

8051 has an 8-bit architecture, each 16-bit timer register is accessed as two separate registers of low byte and high byte.

• Timer 0 can be accessed as – o TL0 – Timer 0 lower byte

o TH0 – Timer 0 higher byte

Page 27: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

• Timer 1 can be accessed as –

o TL1 - Timer 1 lower byte o TH1 – Timer 1 higher byte

Both timer shares the Timer control (TCON) register, which controls the timer/ counter operation and Timer mode (TMOD) register, which

is used to configure the timer for different operating modes.

TMOD (Timer Mode Register):

• Both the timers used the same 8 bit register to set various

timer operation mode.

• TMOD is 8-bit register where lower 4 byte are set aside for

timer 0 and higher 4 bytes for timer 1. Since, it is not bit addressable; the corresponding bit value is directly loaded

into TMOD. Gate:

• 8051 has both hardware and software controls to start and stop the timers.

• By the means of software controlling instruction timers are used to control to start timer or stop.

C/T:

• This bit in TMOD is used to determine whether timer is to be used as delay generator or event counter.

o If C/T = 0 – used as timer o If C/T = 1 – used as counter

M1 M0:

M1, M0 selects the timer mode.

M1 M0 Mode Operation

0 0 0 13 bit counter, 8 bit C/T with

THX and TLX as 5 bit Prescalar.

0 1 1 16 bit counter, 8 bit C/T with THX and TLX cascaded with no

Prescalar.

1 0 2 8 bit auto reload, THX hold the

value which is to be loaded into TLX after each overflow.

1 1 3 Split timer mode.

Page 28: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

TCON (Timer Control Register):

• Timer run control bits TR0 and TR1 and timer overflow flags

TF0 and TF1 are the part of 8 bit register called TCON. • The upper 4 bits are used to store TR and TF flags of both

timer- 0 and timer 1 while the lower 4 bits are set aside for interrupt.

• Timer run control bit TR0/TR1 is used to start the corresponding timer / counter.

• Timer overflow flag bit TF0/TF1 is set when corresponding timer/ counter is overflowed i.e. count value FFFF h to 0000

h.

Different Modes of timer/ counter – 1. Mode 0 (13 bit timer/counter):

• Mode 0 is exactly like mode 1 except it is 13 bit timer. • Hence it can hold the values from 0000H to 1FFFH in TL and TH.

• When timer rolls over from 1FFFH to 0000H, the overflow flag

i.e. TFX is set.

2. Mode 1 (16 bit Timer / counter): • It is 16 bit timer. Hence allowed values from 0000H to FFFFH to

be loaded in TLX and THX. • After the corresponding 16 bit value is loaded, the timer is

started by setting TRX flags. • After starting, it counts up until it reaches the limit i.e. FFFFH.

When it rolls over from FFFFH to 0000H, it sets timer overflow flag i.e. TFX flag.

• After the rolling over process, the operation in mode 1 can be repeated by loading the initial value in TLX & THX and clearing

TFX bit.

Page 29: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Figure 3.1 : Timer/ Counter in Mode 0 and Mode 1

3. Mode 2 (8 bit auto reload):

• It is 8 bit timer. Hence it allows only values from 00H to FFH to be loaded in THX.

• When THX is loaded into 8 bit value, it sends a copy of it to

corresponding TLX. Then timer must be started which is done by SETB TR1 for T1.

• After rolling over of TLX from FFH to 00H, overflow flag for corresponding timer i.e. TFX is set. TLX auto loaded by value

present in THX.

Figure 3.2: Timer/ Counter in Mode 2

4. Mode 3 (Split timer mode):

• In mode 3, timer0 worked as split timer i.e. two independent timer.

• TL0 uses the TR0 and TF0 bits of timer 0. • TH0 uses the TR1 and TF1 bits of timer 1.

Page 30: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Figure 3.3 : Timer/ Counter in Mode 3

TIME DELAY GENERATION USING TIMER:

Mode 1 and Mode 2 are widely used for most of the applications. Mode 1 is used for time delay generation and mode 2 is used to generate

the baud rate in serial communication. The following steps are taken to generate a time delay using the mode

1 and polling method. i. Load the TMOD value indicating which timer is to be used and

timer mode 1 is selected. ii. Load the registers TL and TH with initial count values. Delay

generated is Depends upon the initial count value. iii. Start the timer. (SETB TR0 or SETB TR1)

iv. Keep the monitoring the timer flag (TF) with the “JNB TF0,

target” or “JNB TF1, target” instruction. v. Get out of the loop when TF becomes high.

vi. Stop the timer. (CLR TR0 or CLR TR1) vii. Clear the TF flag for the next round. (CLR TF0 or CLR TF1)

viii. Go back to the step 2 to load TH and TL values.

The size of the time delay depends on two factors, (a) the crystal frequency and (b) the timer’s 16-bit register in mode 1. The largest delay

is achieved by the making both TH and TL zero. Formula for delay calculations using mode 1 of the timer for crystal

frequency of XTAL = 11.0592 MHz, (TH, TL) = (NNNNN)10 is as follows.

Time Delay (Td) = (65536 - NNNNN) x 1.085 us.

Page 31: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Therefore Maximum delay = (65536 – 0000) x 1.085 us = 71 ms.

Finding the Values to be loaded into timer for desired delay

Assume the 11.0592 MHz as crystal frequency for 8051. • Divide the desired time delay by 1.085us. ( n = Td/1.085us)

• Perform 65536 – n. where n is the decimal value from step 1. • Convert the result of step 2 to hexadecimal, where yyxx is the

initial hex value to be loaded into the timer’s registers. • Set TL = xx and TH = yy.

REFERENCES :

1. The 8051 Microcontroller & Embedded systems - M. Mazidi

2. The 8051 Microcontroller Architecture, Programming &

Applications - Kenneth Ayala

Page 32: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

3A) Write a counter program to count continuously from 00 to 99h

in BCD with a delay of 750ms between each count. Display the

count at any output port (Use looping for delay and show delay

calculation). Use simulator to show the result.

ORG 0000H

SJMP START ; Skip the interrupt vector

ORG 0030H

START: CLR A ; clear the accumulator

BACK: MOV P2, A ; move the value on PORT 2

ADD A, #01 ; Increment counter by adding 1

DA A ; Decimal adjust to make BCD.

ACALL DEL_750ms ; call delay

HERE: SJMP BACK

DEL_750ms: MOV R1, #15 ; generates delay of 750ms

LOOP1: MOV R2, #100 ; generates delay of 50ms

LOOP2: MOV R3, #229 ; generates delay of 500us

LOOP3: DJNZ R3, LOOP3

DJNZ R2, LOOP2

DJNZ R1, LOOP1

RET ; return to main program

END

3B) Write a program to generate a square wave of 50 Hz on the pin

P2.4. (Use timer for delay generation). Use simulator to show the

result.

ORG 0000H

LJMP START ; SKIP THE INTERRUPT VECTOR TABLE

ORG 0030H

START: MOV TMOD, #10H ; SELECT TIMER 1 MODE 1

BACK: MOV TH1, #0DCH ; LOAD COUNT TO GET REQD. FREQ

MOV TL1, #00H

SETB TR1 ; START TIMER

LOOP: JNB TF1, LOOP ; CHECK IF OVERFLOW HAS OCCURED

CPL P2.4 ; COMPLEMENT P2.4

CLR TF1 ; CLEAR TIMER OVERFLOW FLAG

CLR TR1 ; STOP TIMER

SJMP BACK

END

Page 33: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO. : 4

TITLE : Interfacing LED to 8051

PROBLEM DEFINITION:

A. Write a program in which falling edge of pulse is detected by

interrupt port pin P3.3 (INT1). In response to this LED,

which is connected to port P1.3, is turned on it stay on for

50ms and then turned off.

B. Write a program to interface LED to P2.0 and toggle it after

every 20ms. (Use Timer for delay and interrupts)

C. Write a program to interface LEDs to 8051 so that a rolling

display is observed on the LEDs connected to port P1 (Use

Timer for delay).

S/W & H/W USED : 1. Keil uVision2 Compiler / Assembler

2. Flashmagic Software for downloading

3. 8051 Trainer kit with LED array

THEORY:

INTERRUPTS: • Whenever any peripheral device needs the 8051 service, it

notifies the microcontroller by sending interrupt signal. • Upon receiving interrupt signal, microcontroller interrupt

whatever it is doing and gives it service to the device. • Program associated with the interrupt is called ‘Interrupt

Service Routine’ (ISR).

• Advantage of using interrupts is that the microcontroller can serve many devices (not all at the same time)

• Each device can get the attention of the microcontroller based on the priority assigned to the device.

• The polling method cannot assign priority since it checks all devices in a round robin fashion.

• Also by polling method, microcontroller’s time wastage occurs as it also checks devices which don’t need the service.

Interrupt service routine (ISR): when peripheral devices activate an

interrupt signal, the processor branches to a program called interrupt

Page 34: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

service routine (ISR). The program is written by the user for performing

tasks that the interrupting device wants the processor to execute.

Interrupt Vector Table (IVT): The term interrupt vector refers to the starting address of the ISR. The processor needs to determine the

starting address of the ISR before it can provide service. The group of the memory locations set aside to hold the addresses of ISRs is called the

interrupt vector table.

The steps in executing an interrupts: • Microcontroller finishes the instruction that it is executing and saves

the address of the next instruction (PC) on the stack. • It saves the current status of all interrupt internally (i.e. not on

stack). • It jumps to fixed location in memory called interrupt vector table

that holds the address of ISR.

• The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it.

• Microcontroller executes ISR until it executes the last instruction of ISR i.e. RETI.

• Upon executing RETI, microcontroller returns to the address where it was interrupted. It gets the address by popping the 1st two bytes

of the stack into PC and then further starts execution.

8051 interrupt structure: In reality, only five interrupts are available to the user in the 8051,

but many manufacturers’ datasheets state that there are six interrupts since they include reset. The six interrupts in the 8051 are allocated as

follows. 1. Reset: When the reset is activated, the 8051 will reset, terminate the

all activities and set the all SFR with default values; then jumps to

address location 0000h. 2. Two interrupts are set aside for external hardware interrupts (INT0 &

INT1). These external interrupts are also referred to as EX1 and EX2. 3. Two interrupts are set aside for the timers: one for timer 0 (TF0) and

for timer 1 (TF1). 4. Serial communication has a single interrupt that belongs to both

receive and transmit.

No. Interrupts ROM location (IVT) Pin number Flag clearing

1 Reset 0000 9 Auto

2 INT0 0003 P3.2 (12) Auto

3 TF0 000B Auto

4 INT1 0013 P3.3 (13) Auto

5 TF1 001B Auto

Page 35: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

6 RI and TI 0023 Programmer clears it

The above table shows that a limited number of bytes are set aside

for each interrupt. Only 8-bytes are reserved for ISR of the each interrupt. If the service routine for a given interrupt is short enough to fit

in the memory space allocated to it, it is placed in the vector table;

otherwise, an LJMP instruction is placed in the vector table; otherwise an LJMP instruction is placed in the vector table to point to the address of

the ISR.

Enabling and disabling the interrupts: Each of the interrupt sources can be individually enabled or

disabled by setting or clearing a bit in interrupt enable (IE) register. Upon reset, all interrupts are disabled. To enable the interrupt, steps are-

1) Bit D7 of IE i.e. EA must be set high to enable interrupts. 2) If the corresponding bits of IE are high, then the

corresponding interrupts are enabled.

Interrupt Enable (IE) Register

D7 D6 D5 D4 D3 D2 D1 D0

EA - ET2 ES ET1 EX1 ET0 EX0

o D7 - EA:- EA = 0 – no interrupt is acknowledged EA = 1 – all interrupts are enable

o D6 - Not implemented, reserved for further use o D5 – ET2:– Enable or disable timer 2 overflow interrupt.

o D4 – ES: – Serial communication interrupt. o D3 – ET1:– Timer 1 overflow interrupt.

o D2 – EX1:– External interrupt 1. o D1 – ET0:– Timer 0 interrupt.

o D0 – EX0:– External interrupt 0.

Timer Interrupts: The timer flag (TF) is raised when the timer rolls over and it is

monitored with the instruction “JNB TFx, target”. In delay generation using polling method, we have to wait until the TF is raised. The problem

with this method is that the microcontroller is tied down while waiting for

TF to be raised and cannot do any thing else. Using interrupts solves this problem and avoids tying down the

controller. If the timer interrupt in the IE register is enabled, whenever the timer overflows, TF is raised, and the microcontroller is interrupted in

whatever it is doing and jumps to the interrupt vector table to the service the ISR of timer. In the ISR of the timer, notice that there is no need for

Page 36: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

clearing the TF before the RETI instruction. This is because the 8051

clears the TF flag internally upon jumping to the interrupt vector table.

External Hardware Interrupts: There are only two external hardware interrupts in the 8051 : INT0

and INT1. They are enabled and disabled using IE register bit IE.0 and IE.2. There are two types of activation for the external hardware

interrupts 1. Level triggered

2. Edge triggered

Level triggered interrupt: In the level triggered mode, INT0 and INT1 pins are normally high

and if the low level signal is applied to them, it triggers the interrupt. Then the microcontroller stops whatever it is doing and jumps to the IVT

to service the interrupt. This is called a level triggered or level activated

interrupt and is the default mode upon reset of the 8051. The low level signal must be removed before the execution of the last instruction of the

interrupt service routine, RETI; otherwise, another interrupt will be generated. In other words, if the low-level interrupt signal is not removed

before the ISR is finished it is interpreted as another interrupt and the 8051 jumps to the IVT to execute the ISR again.

Pins P3.2 and P3.3 are used for normal I/O unless the INT0 and INT1 bits in the IE register are enabled. After the hardware interrupts in

the IE register enabled, the controller keeps sampling the INT pin for a low-level signal once each machine cycle. To ensure the activation of the

hardware interrupt at the INT pin, make sure that the duration of low level signal is around the 4 machine cycles, but no more. This is due to

that the level triggered interrupt is not latched. Thus the pin must be held in a low state until the start of the ISR execution.

Edge triggered interrupts: When a high to low signal is applied to pin P3.2 or P3.3, the

controller will be interrupted and forced to jump to IVT to service the ISR of the external hardware interrupt. This is called an edge triggered

interrupt. Upon reset, 8051 make INT0 and INT1 as low level triggered interrupt. To make edge triggered, we must program the bits of Timer

control (TCON) register. The TCON register holds, among other bits, the IT0 and IT1 flag bits that determine level or edge triggered mode of the

hardware interrupts. IT0 and IT1 are also referred as TCON.0 and TCON.2 since the TCON is bit addressable. Upon reset, TCON.0 (IT0) and TCON.2

(IT1) are both zeros, meaning that the external hardware interrupts are low level triggered. By making these bits high with instructions such as

Page 37: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

“SETB TCON.0” and “SETB TCON.2”, the external hardware interrupts

become edge triggered.

Timer Control (TCON) Register

D7 D6 D5 D4 D3 D2 D1 D0

TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0

o IE1 and IE0: external interrupt edge flag

� Set by CPU when edge is detected of external interrupt.

� Cleared by CPU when edge is processed. � This flag does not latch low level triggered

interrupts.

o IT1 and IT0: interrupt 1 type control bit � Set to 1 to specify falling edge triggered external

interrupt.

� Clear to 0 to specify low level triggered external interrupt.

In edge triggered interrupts, the external the external source must

be held high for at least one machine cycle and then held low for at least one machine cycle to ensure that the transition is seen by the

microcontroller. The falling edge is latched by the 8051 and is held by the TCON register. The TCON.1 (IE0) and TCON.3 (IE1) bits hold the latched

falling edge of pins INT0 and INT1, respectively. IE0 and IE1 function as interrupt in service flags. When and interrupt in service flag is raised, it

indicates to the external world that the interrupt is being serviced and no new interrupt on this INT pin will be responded to until this service is

finished.

Interrupt priority: When the 8051 is powered up, the priorities are assigned according to table 4.1. In reality the priority scheme is nothing but an internal polling

sequence in which the 8051 polls the interrupts in the sequence listed in table 4.1 and responds accordingly.

Highest to lowest priority External interrupt 0 INT0

Timer interrupt 0 TF0

External interrupt 1 INT1

Timer interrupt 1 TF1

Serial communication RI + TI

Table 4.1: Interrupt priority on reset

Page 38: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

We can alter the sequence of table 4.1 by assigning a higher

priority to any one of the interrupts. This is done by programming a register called IP (Interrupt Priority Register) which is shown below. Upon

the power on reset, the IP register contains all 0s, making the priority based on table 4.1. To give a higher priority to any of the interrupts, we

make the corresponding bit in the IP register high.

Interrupt Priority (IP) Register

D7 D6 D5 D4 D3 D2 D1 D0

-- -- PT2 PS PT1 PX1 PT0 PX0

Priority bit = 1 assigns high priority. Priority bit = 0 assigns low priority.

• PT2 (IP.5) : Timer 2 interrupt Priority bit (8052 only)

• PS (IP.4) : Serial port interrupt Priority bit • PT1 (IP.3) : Timer 1 interrupt Priority bit

• PX1 (IP.2) : External interrupt priority bit

• PT0 (IP.1) : Timer 0 interrupt Priority bit • PX0 (IP.0) : External interrupt Priority bit

Nested Interrupts: What happens if the 8051 is executing an ISR belonging to an interrupt and another interrupt is activated? In such cases, a priority

interrupt can interrupt a low-level interrupt. This is called as nested interrupts or interrupts inside an interrupt. In the 8051 a low priority

interrupt can be interrupted by higher priority interrupt, but not by another low-priority interrupt. Although all the interrupts are latched and

kept internally, no low-priority interrupt can get the immediate attention

of the CPU until the 8051 has finished servicing the high priority interrupts.

Interfacing LED’s to 8051: All the LED’s are connected by common anode method which is

shown in figure 4.1. That means the positive leg of each LED is connected to VCC and negative leg to the port pins of the microcontroller. Logic 0 on

the port pin will make LED ON and Logic 1 will make it OFF. The LED board can be interfaced to all the ports (Port 0, Port 1, Port 2, and Port 3)

on trainer board.

Page 39: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Figure 4.1: LED interfacing board.

REFERENCES :

1. The 8051 Microcontroller & Embedded systems - M. Mazidi

2. The 8051 Microcontroller Architecture, Programming &

Applications - Kenneth Ayala

3. Lab Manual for Universal Microcontroller Development Board,

S2N Systems, Pune.

Page 40: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

4A) Write a program in which falling edge of pulse is detected by

interrupt port pin P3.3 (INT1). In response to this LED, which is

connected to port P1.3, is turned on it stay on for 50ms and then

turned off.

ORG 0000H

SJMP START ; Skip the interrupt vector

ORG 0013H ; ISR address of External Interrupt 1

SETB P1.3 ; Turn on the LED

ACALL DEL_50ms ; keep LED on for 50ms

CLR P1.3 ; Turn off the LED after delay

RETI ; Return from interrupt

ORG 0030H

START: SETB TCON.2 ; make INT1 edge triggered

MOV IE, #10000100B ; Enable external interrupt 1

HERE: SJMP HERE ; loop continuously

DEL_50ms: MOV R1, #100 ; generates delay of 50ms

LOOP1: MOV R2, #231 ; generates delay of 500us

LOOP2: DJNZ R2, LOOP2

DJNZ R1, LOOP1

RET

END

4B) Write a program to interface LED to P2.0 and toggle it after

every 20ms. (Use Timer for delay and interrupts)

ORG 0000H

SJMP MAIN

ORG 001BH ; TIMER 1 ISR ADDRESS

CPL P2.0 ; TOGGLE THE BIT P2.0

MOV TMOD, #10H ; TIMER 1 ISR

MOV TL1,#0FFH ; TO GENERATE 50% DUTY CYCLE

MOV TH1,#0DBH ; TO GENERATE 50% DUTY CYCLE

RETI

MAIN: MOV TMOD,#0001000B; TIMER IN MOD - 1

MOV TL1, #0FFH ; TO GENERATE 50% DUTY CYCLE

MOV TH1, #0DBH ; TO GENERATE 50% DUTY CYCLE

MOV IE, #10001000B ; ENABLE INTERRUPT

SETB TR1 ; START THE TIMER

HERE: SJMP HERE

END

Page 41: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

4C) Write a program to interface LEDs to 8051 so that a rolling

display is observed on the LEDs connected to port P1 (Use Timer for

delay).

ORG 0000H

LJMP START ; SKIP THE INTERRUPT VECTOR

ORG 0030H

START: MOV A, #0FEH ; LOAD WITH 01H

AGAIN: MOV P1, A ; MOVE CONTENTS OF A TO P1

ACALL DELAY ; CALL DELAY SUBROUTINE

ACALL DELAY

ACALL DELAY

RR A ; ROTATE BITS OF A ONE BIT RIGHT

SJMP AGAIN ; REPEAT STEPS

DELAY: MOV TMOD, #10H ; SELECT TIMER 1 MODE 1

MOV TH1, #0H ; LOAD COUNT TO GET REQD. DELAY

MOV TL1, #0H

SETB TR1 ; START TIMER

BACK: JNB TF1, BACK ; CHECK IF OVERFLOW HAS

OCCURED

CLR TR1 ; CLEAR TIMER

CLR TF1 ; CLEAR OVERFLOW FLAG

RET ; RETURN TO MAIN POGRAM

END

Page 42: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO.: 5

TITLE : Communicating serially to PC using 8051

PROBLEM DEFINITION:

A. Write a program for the 8051 to transfer letter ‘A’ serially at

4800-baud rate, 8 bit data, 1 stop bit continuously (Show TH

value calculation for the given baud).

B. Write a program for the 8051 to transfer the message ‘CWIT,

PUNE’ serially at 9600 baud, 8 bit data, 1 stop bit

continuously (Show TH value calculation for the given baud).

S/W & H/W USED : 1. Keil uVision2 Compiler / Assembler

2. Flashmagic Software for downloading

3. 8051 Trainer kit

4. Hyperterminal

THEORY:

Serial Communication: The 8051 microcontroller is parallel device that transfers eight bits

of data simultaneously over eight data lines to parallel I/O devices. However, in many situations, parallel data transfer is impractical. For

example, parallel data transfer over a long is very expensive. Hence, a serial communication is widely used in long distance communication.

In serial data communication, 8-bit data is converted to serial bits using a parallel in serial out shift register and then it is transmitted over a

single data line. The data byte is always transmitted with least significant bit first.

Communication links: Serial communication is classified into three types of

communication. 1. Simplex communication link: In simplex transmission, the line is

dedicated for transmission. The transmitter sends and the receiver receives the data.

Page 43: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

2. Half duplex communication link: In half duplex, the communication link can be used for either transmission or

reception. Data is transmitted in only one direction at a time.

3. Full duplex communication link: If the data is transmitted in both ways at the same time, it is a full duplex i.e. transmission and

reception can proceed simultaneously. This communication link requires two wires for data, one for transmission and one for

reception.

Types of Serial communication: Serial data communication uses two types of communication.

1. Synchronous serial data communication: In this transmitter and receiver are synchronized. It uses a common clack to

synchronize the receiver and the transmitter. First the synch

character is sent and then the data is transmitted. This format is generally used for high speed transmission. In Synchronous serial

data communication a block of data is transmitted at a time. 2. Asynchronous Serial data transmission: In this, different clock

sources are used for transmitter and receiver. In this mode, data is transmitted with start and stop bits. A transmission begins with

start bit, followed by data and then stop bit. For error checking purpose parity bit is included just prior to stop bit. In Asynchronous

serial data communication a single byte is transmitted at a time.

Baud rate: The rate at which the bits are transmitted is called baud or transfer

rate. The baud rate is the reciprocal of the time to send one bit. In asynchronous transmission, baud rate is not equal to number of bits per

second. This is because; each byte is preceded by a start bit and followed

by parity and stop bit. For example, in synchronous transmission, if data is transmitted with 9600 baud, it means that 9600 bits are transmitted in

one second. For bit transmission time = 1 second/ 9600 = 0.104 ms.

RS-232 standards: To allow compatibility among data communication equipment made

by various manufactures, an interfacing standard called Rs232 was set by the Electronics Industries Association (EIA) in 1960. In 1963 it was

modified and called RS232A. RS232B and RS232C were issued in 1965 and 1969, respectively. Today Rs232is the most widely used serial I/O

interfacing standard. This standard is used in PCs and numerous equipments. However, since the standard was set long before the advent

of logic family, its input and output voltage levels are not TTL compatible.

Page 44: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

In RS232, a logic one (1) is represented by -3 to -25V and referred as

MARK while logic zero (0) is represented by +3 to +25V and referred as SPACE. For this reason to connect any RS232 to a microcontroller system

we must use voltage converters such as MAX232 to convert the TTL logic level to RS232 voltage levels and vice-versa. MAX232 IC chips are

commonly referred as line drivers.

Serial Data Format

The serial data format includes one start bit, between five and eight data bits, and one stop bit. A parity bit and an additional stop bit might

be included in the format as well. The figure 4.1 below illustrates the serial data format.

Figure 5.1: Serial data format

The format for serial port data is often expressed using the

following notation: Number of data bits - parity type - number of stop

bits.

For example, 8-N-1 is interpreted as eight data bits, no parity bit,

and one stop bit, while 7-E-2 is interpreted as seven data bits, even

parity, and two stop bits.

The data bits are often referred to as a character because these bits

usually represent an ASCII character. The remaining bits are called

framing bits because they frame the data bits.

Serial Pin outs (D25 and D9 Connectors)

Page 45: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

DB-25 Pin No. DB-9 Pin No. Abbreviation Full Name

Pin 2 Pin 3 TD Transmit Data

Pin 3 Pin 2 RD Receive Data

Pin 4 Pin 7 RTS Request To Send

Pin 5 Pin 8 CTS Clear To Send

Pin 6 Pin 6 DSR Data Set Ready

Pin 7 Pin 5 SG Signal Ground

Pin 8 Pin 1 CD Carrier Detect

Pin 20 Pin 4 DTR Data Terminal

Ready

Pin 22 Pin 9 RI Ring Indicator

Table 4.2: D Type 9 Pin and D Type 25 Pin Connectors

Pin Functions

Abbreviation Full Name Function

TD Transmit Data Serial Data Output (TXD)

RD Receive Data Serial Data Input (RXD)

CTS Clear to Send This line indicates that the Modem

is ready to exchange data.

DCD Data Carrier Detect

When the modem detects a "Carrier" from the modem at the

other end of the phone line, this Line becomes active.

DSR Data Set Ready This tells the UART that the

modem is ready to establish a link.

DTR Data Terminal

Ready

This is the opposite to DSR. This

tells the Modem that the UART is ready to link.

RTS Request To Send This line informs the Modem that the UART is ready to exchange

data.

RI Ring Indicator Goes active when modem detects a ringing signal from the PSTN.

Table 5.3: Serial Port Pin Functions 8051 connection to RS232:

Page 46: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

The 8051 has two pins that are used specifically for transferring and

receiving data serially. These two pins are called TXD, RXD and are part of the port 3 group. Pin 11 of the 8051 (P3.1) assigned to TXD and pin 10

(P3.0) is designated as RXD. These pins TTL compatible; therefore they require line driver to make them RS232 compatible. One example of such

a converter is MAX232 from Maxim Corporation which converts from RS232 voltage levels to TTL voltage levels and vice versa. One advantage

of the MAX232 is that it uses a +5V power source which is the same as the source voltage for the 8051.

1

2

3

4

5

6

7

8

9

J8

D Connector 9

C1+1

VS+2

C1-3

C2+4

C2-5

VS-6

T2OUT7

R2IN8

R2OUT9

T2IN10

T1IN11

R1OUT12

R1IN13

T1OUT14

GND15

VCC

16

U3

MAX232N

1 uFC12

1 uF

C10

1 uF

C11

VCC

1 uFC8

1 uFC9

TXD

RXD

8051 serial communication:

The 8051 supports a full duplex serial port. The 8051 transfers and receives the data serially with different baud rate. Three special function

registers support serial communication, namely, SBUF register, SCON register, PCON register.

1. SBUF Register: serial buffer (SBUF) register is an 8-bit register. It

has separate SBUF registers for data transmission and for data reception. These two registers are accessed by the same name,

SBUF. One of the registers is write-only and used to hold data to

transmit via TXD pin. The other is read only and holds the received data from external source via RXD pin. For a byte of data to be

transferred via the TXD line, it must be placed in SBUF register. Similarly, SBUF holds the 8-bit data received by the RXD pin and

read to accept the received data. 2. SCON register: The contents of the Serial Control (SCON) register

are shown below. This register contains mode selection bits, serial port interrupt bit (TI and RI) and also the ninth data bit for

transmission and reception (TB8 and RB8). 3. PCON register: The SMOD bit (bit 7) of PCON register controls the

baud rate in asynchronous mode transmission.

Page 47: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Serial Port Control (SCON) Register

D7 D6 D5 D4 D3 D2 D1 D0

SM0 SM1 SM2 REN TB8 RB8 TI RI

o SM0 (SCON.7) : Serial communication mode selection bit

o SM1 (SCON.6) : Serial communication mode selection bit

SM0 SM1 Mode Description Baud rate

0 0 Mode 0 8-bit shift register

mode

Fosc / 12

0 1 Mode 1 8-bit UART Variable (set by timer 1)

1 0 Mode 2 9-bit UART Fosc/ 32 or Fosc/64

1 1 Mode 3 9-bit UART Variable (set by timer 1)

o SM2 (SCON.5) : Multiprocessor communication bit. In modes 2 and 3, if set this will enable multiprocessor

communication.

o REN (SCON.4) : Enable serial reception

o TB8 (SCON.3) : This is 9th bit that is transmitted in mode 2 & 3.

o RB8 (SCON.2) : 9th data bit is received in modes 2 & 3.

o TI (SCON.1) : Transmit interrupt flag, set by hardware

must be cleared by software.

o RI (SCON.0) : Receive interrupt flag, set by hardware

must be cleared by software.

Page 48: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Power mode Control (PCON) Register

D7 D6 D5 D4 D3 D2 D1 D0

SMOD -- -- -- GF1 GF0 PD IDL

o SMD (PCON.7) : Serial rate modify bit. Set to 1 by program

to double baud rate using timer 1 for modes 1, 2, and 3. cleared by program to use timer 1 baud rate.

o GF1 (PCON.3) : General Purpose user flag bit.

o GF0 (PCON.2) : General Purpose user flag bit. o PD (PCON.1) : Power down bit. Set to 1 by program to

enter power down configuration for CHMOS processors. o IDL (PCON.0) : Idle mode bit. Set to 1 by program to

enter idle mode configuration for CHMOS processors.

Baud Rate in the 8051:

The 8051 transfers and receives data serially at many different

baud rates. The baud rate in the 8051 is programmable. This is done with the help of timer 1.

The 8051 divides the crystal frequency by 12 to get the machine cycle frequency. In case of XTAL = 11.0592 MHz, the machine cycle

frequency is 921.6 KHz. The 8051’s serial communication UART circuitry divides the machine cycle frequency of 921.6 KHz by 32 once more

before it is used by timer 1 to set the baud rate. Therefore, 921.6 KHZ/32 gives 28,800 Hz. This is the number we will use throughout this section to

find the Timer 1 value to set the baud rate. When Timer 1 is used to set the baud rate it must be programmed timer mode 2 i.e. 8-bit auto-reload

mode.

Making the SMOD = 1, we can double baud rate. When SMOD = 1, machine cycle frequency is divided by 16 instead of 32 (921.6 KHz / 16 =

57,600 Hz), this frequency used by timer 1 to set the baud rate. Therefore, Fbaud = 28.8 KHz if SMOD = 0

Fbaud = 57.6 KHz if SMOD = 1

Baud Rate Calculation Fbaud = 28.8 KHz

TH1 (Decimal) TH1 (Hex)

9600 28.8 KHz / 9600 -3 FD

4800 28.8 KHz / 4800 -6 FA

2400 28.8 KHz / 2400 -12 F4

1200 28.8 KHz / 1200 -24 E8

Table 5.1: Timer 1 – TH1 Register values for various baud rates

Page 49: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Programming the 8051 to transfer data serially

1. The TMOD register is loaded with the value 20H, indicating the use of the Timer 1 in mode 2 (8-bit auto reload) to set the baud rate.

2. The TH1 is loaded with one of the values in table 5.1 to set the baud rate for serial data transfer.

3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-bit data is framed with start and stop bits.

4. TR1 is set to 1 start timer 1. 5. TI is cleared by the “CLR TI” instruction.

6. The character byte to be transferred serially is written into the SBUF register.

7. The TI flag bit is monitored with the use of the instruction JNB TI,

target to see if the character has been transferred completely. 8. To transfer the next character, go to step 5.

REFERENCES :

1. The 8051 Microcontroller & Embedded systems - M. Mazidi

2. The 8051 Microcontroller Architecture, Programming &

Applications - Kenneth Ayala

3. Lab Manual for Universal Microcontroller Development Board,

S2N Systems, Pune.

Page 50: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

5A) Write a program for the 8051 to transfer letter ‘A’ serially at 4800-

baud rate, 8 bit data, 1 stop bit continuously (Show TH value calculation

for the given baud).

ORG 0000H

LJMP START

ORG 0030H

START: MOV TMOD, #20H ; select timer 1 mode 2

MOV TH1, #0FAH ; load count to get baud rate of 4800

MOV SCON, #50H ; initialize UART in mode 2

; 8 bit data and 1 stop bit

SETB TR1 ; start timer

AGAIN: MOV SBUF, #'A' ; load char ‘A’ in SBUF

BACK: JNB TI, BACK ; Check for transmit interrupt flag

CLR TI ; Clear transmit interrupt flag

SJMP AGAIN

END

5B) Write a program for the 8051 to transfer the message ‘CWIT’

serially at 9600 baud, 8 bit data, 1 stop bit continuously (Show TH value

calculation for the given baud).

ORG 0000H

LJMP START

ORG 0030H

START: MOV TMOD, #20H ; select timer 1 mode 2

MOV TH1, #0FDH ; load count to get reqd. baud rate of 9600

MOV SCON, #50H ; initialise uart in mode 2

; 8 bit data and 1 stop bit

SETB TR1 ; start timer

LOOP: MOV A, #'C' ; load 1st letter ‘C’ in a

ACALL LOAD ; call load subroutine

MOV A, #'W' ; load 2nd letter ‘W’ in a

ACALL LOAD ; call load subroutine

MOV A, #'I' ; load 3rd letter ‘I’ in a

ACALL LOAD ; call load subroutine

MOV A, #'T' ; load 4th letter ‘T’ in a

ACALL LOAD ; call load subroutine

SJMP LOOP ; repeat steps

LOAD: MOV SBUF, A

HERE: JNB TI, HERE ; Check for transmit interrupt flag

CLR TI ; Clear transmit interrupt flag

RET

END

Page 51: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO.: 6

TITLE : Interfacing ADC 0808 to 8051

PROBLEM DEFINITION:

A. Draw the complete interfacing diagram of ADC 808 to 8051

and explain the pin connections in the figure.

B. Write a program to interface ADC 808 to 8051. Apply the

analog input and get the corresponding digital output. Write

the result in a tabular form.

S/W & H/W USED : 1. Keil uVision2 Simulator Software,

2. Flashmagic Software for downloading

3. 8051 Trainer kit

4. ADC 808 interfacing card

THEORY:

ADC Devices: Analog to digital converters are among the most widely used

devices for data acquisitions. Digital computers use binary (discrete) value but in physical world everything is analog (continuous). A physical

quantity is converted to electrical signals using device called transducer or also called as sensors. Sensors and many other natural quantities

produce an output that is voltage (or current). There fore we need an analog - to - digital converter to translate the analog signal to digital

numbers so that the microcontroller can read and process them. An ADC has an n bit resolution where n can be 8, 10, 16, 0r even 24 bits. The

higher resolution ADC provides a smaller step size, where step size is smallest change that can be discerned by an ADC. This is shown in Table

6.1. In addition to resolution, conversion time is another major factor in judging an ADC. Conversion time is defined as the time it takes the ADC

to convert the analog input to digital (binary) number. The ADC chips are

either parallel or serial. In parallel ADC, we have 8 or more pins dedicated to bring out the binary data, but in serial ADC we have only one pin for

data out.

Page 52: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

n - bit Number of steps Step Size (mV)

8 256 5/256 = 19.53

10 1024 5/1024 = 4.88

12 4096 5/4096 = 1.2

16 65536 5/65536 = 0.076

Table 6.1: Resolution verses step size for ADC.

ADC 0808 chip with analog channels ADC0808, from national semiconductors, has 8 analog inputs.

ADC0808 allows us to monitor up to 8 different analog inputs using only a single chip. ADC0808 has an 8-bit data output. The 8 analog inputs

channels are multiplexed and selected according to table given below using three address pins, A, B, and C.

In ADC0808 Vref (+) and Vref (-) set the reference voltage. If Vref (-) = Gnd and Vref (+) = 5V, the step size is 5V/ 256 = 19.53 mV. Therefore,

to get a 10 mV step size we need to set Vref (+) = 2.56V and Vref(-) =

Gnd. From figure natice ALE pin. We use A, B, and C addresses to select IN0 – IN7, and activate ALE to latch in the address. SC for start

conversion. EOC is for end-of-conversion, and OE is for output enable (READ). Table shows the step size relation to the Vref Voltage.

Select Analog Channel C B A

IN0 0 0 0

IN1 0 0 1

IN2 0 1 0

IN3 0 1 1

IN4 1 0 0

IN5 1 0 1

IN6 1 1 0

IN7 1 1 1

Table 6.2: ADC0808 analog channel selection.

Vref (v) Vin (V) Step Size (mV)

Not connected 0 to 5 5/256 = 19.53

4.0 0 to 4 4/256 = 15.32

3.0 0 to 3 3/256 = 11.71

2.56 0 to 2.56 2.56/256 = 10

2.0 0 to 2 2/256 = 7.81

1 0 to 1 1/ 256 = 3.90

Table 6.3: Vref relation to Vin range for ADC 0808

Timing Diagram

Page 53: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Figure 6.1: Timing Diagram for ADC0808

Figure 6.2: ADC0808 interfaced to 8051

Steps to program the ADC0808

The following are steps to get data from an ADC0808.

Page 54: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

1. Select an analog channel by providing bits to A, B, and C addresses

according to table. 2. Activate the ALE (address latch enable) pin. It needs an L-to-H

pulse to latch in the address. 3. Activate SC (start conversion) by an L-to-H pulse to initiate

conversion. 4. Monitor EOC (end of conversion) to see whether conversion is

finished. H-to-l output indicates that data is converted and ready to be picked up.

5. Activate OE (output enable) to read data out of ADC chip. An L-to-H pulse to the OE pin will bring digital data out of the chip. Also notice

that the OE is the same as the RD pin in other ADC chip. Notice that in ADC0808 there is no self-clocking and the clock must be

provided from an external source to the CLK pin. Although the speed of conversion depends on the frequency of the clock connected to the

CLK pin, it cannot be faster than 100 microseconds.

REFERENCES :

1. The 8051 Microcontroller & Embedded systems - M. Mazidi

2. The 8051 Microcontroller Architecture, Programming &

Applications - Kenneth Ayala

3. Lab Manual for Universal Microcontroller Development Board,

S2N Systems, Pune.

Page 55: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

6A) Write a program to interface ADC 808 to 8051. Apply the

analog input and get the corresponding digital output. Write the

result in a tabular form.

; System description

CHA EQU P2.0 CHB EQU P2.1

CHC EQU P2.2 ALE EQU P0.2

START EQU P0.1 OE EQU P0.0

EOC EQU P0.4

ADCOP EQU P3

ORG 0000H SJMP MAIN ; skip the interrupt vector table

ORG 0030H

MAIN: MOV P3,#0FFH ; Port 3 as input port MOV P0,#0F0H ; Higher nibble of Port 0 as input port

BACK: SETB CHA ; Select IN1 as input source CLR CHB

CLR CHC CLR ALE ; Generate the pulse on ALE

NOP SETB ALE ; to latch address

NOP

CLR ALE CLR START ; Generate the Start pulse

NOP SETB START

NOP CLR START

CHECK: JNB EOC,CHECK ; Check for end of conversion SETB OE ; Set the output enable

MOV A, ADCOP : Get digital data output in Accumulator MOV P1,A ; Show the result on LED’s

CLR OE SJMP BACK : take another reading.

END

Page 56: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO. : 7

TITLE : Interfacing DAC 808 to 8051

PROBLEM DEFINITION:

A. Draw the interfacing diagram of DAC 808 and explain all the

pin connections in the figure.

B. Write a program to interface DAC 808 to 8051. Apply the

digital input and get the corresponding square wave output.

C. Write a program to interface DAC 808 to 8051. Apply the

digital input and get the corresponding triangular wave

output.

S/W & H/W USED : 1. Keil uVision2 Simulator Software,

2. Flashmagic Software for downloading

3. 8051 Trainer kit

4. DAC 808 interfacing card

THEORY: Digital-to-analog (DAC) converter:

The digital to analog converter (DAC) is a widely used to convert

digital pulses to analog signals. There two methods of creating DAC: 1. binary weighted, 2. R/2R ladder. The vast majority of integrated circuit

DACs use the R/2R method since it can achieve a much higher degree of precision. The first criterion judging a DAC is its resolution, which is a

nfunction of the number of binary inputs. The common ones are 8, 10 and 12 bits. The number of data bit inputs decides the resolution of the

DAC since the number of analog output levels is equal to 2n, where n is the number of data bit inputs. Therefore, an 8-bit input DAC such as the

DAC0808 provides 256 discrete voltage (or current) levels of output. Similarly, the 12-bit DAC provides 4096 discrete voltage levels.

DAC 0808

Page 57: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

In the DAC 0808, the digital inputs are converted to current (I out),

and by connecting a register to the I out pin, we convert the result to voltage. The total current provided by the I out pin is a function of the

binary numbers at then D0 – D7 inputs of the DAC0808 and the reference current (I out), and is as fallows:

+++++++=256

0

128

1

64

2

32

3

16

4

8

5

4

6

2

7 DDDDDDDDII refout

Where D0 is the LSB, D7 is the MSB for the inputs, and I ref is the input

current that must be applied to pin 14. The Iref current is generally set to 2.0 mA. Figure shows the generation of current reference (setting Iref =

2mA) by using the standard 5-V power supply and 1K and 1.5K- ohm standard resistors. Now assuming that Iref = 2mA, if all the inputs to the

DACare high, the maximum output current is 1.99mA.

Converting I out to voltage in DAC0808

Ideally we connect the output pin Iout to a resistor, convert this current to voltage, and monitor the output on scope. In real life, however

this can cause inaccuracy since the input resistance of the load where it is connected will also affect the output voltage. For this reason, the Iref

current output is isolated by connecting it to an op-amp such as 741 with Rf = 5K ohms for the feedback resistor. Assuming that R= 5K ohms, by

changing the binary input, the output voltage changes as shown in below program

CLR A AGAIN: MOV P1, A ; send data to DAC

INC A ; count from 0 to ffh ACALL DELAY ; let DAC recover

SJMP AGAIN

Page 58: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Figure 7.1: 8051 connections to DAC0808.

REFERENCES :

1. The 8051 Microcontroller & Embedded systems - M. Mazidi

2. The 8051 Microcontroller Architecture, Programming &

Applications - Kenneth Ayala

3. Lab Manual for Universal Microcontroller Development Board,

S2N Systems, Pune.

Page 59: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

7A) Write a program to interface DAC 808 to 8051. Apply the digital

input and get the corresponding square wave output.

ORG 0000H

SJMP START

ORG 0030H START: MOV A, #0

BACK: MOV P2, A

ACALL DELAY CPL A

SJMP BACK

DELAY: MOV R2, #0FFH HERE: DJNZ R2, HERE

RET

END

7B) Write a program to interface DAC 808 to 8051. Apply the digital

input and get the corresponding triangular wave output.

ORG 0000H

SJMP START

ORG 0030H START: MOV A, #0FFH

BACK1: INC A

MOV P2, A CJNE A, #0FFH, BACK1

BACK2: DEC A

MOV P2, A CJNE A, #00H, BACK2

SJMP BACK1

END

Page 60: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO. : 8

TITLE : Interfacing Stepper Motor to 8051

PROBLEM DEFINITION:

A. Draw the complete interfacing diagram of stepper motor and

explain all the pin connections in the figure.

B. Write a program to interface stepper motor to 8051 and

rotate it through clock-wise / anti clockwise direction

continuously.

C. Write a program to interface stepper motor to 8051 and

rotate it through clock-wise / anti clockwise direction through

1800.

S/W & H/W USED : 1. Keil uVision2 Simulator Software,

2. Flashmagic Software for downloading

3. 8051 Trainer kit

4. Stepper motor interfacing card

THEORY:

A stepper motor is a widely used device that translates electrical

pulses into mechanical movement. In applications such as disk drives, dot matrix printers, and robotics, the stepper motor is used for position

control. Stepper motors commonly have a permanent magnet rotor (also called the shaft) surrounded by a stator (see Figure 8.1). There are also

steppers called variable reluctance stepper motors that do not have a PM rotor. The most common stepper motors have four stator windings that

are paired with a center-tapped common as shown in Figure 8.2. This type of stepper motor is commonly referred to as a four-phase or uni-

polar stepper motor. The center tap allows a change of current direction in each of two coils when a winding is grounded, thereby resulting in a

polarity change of the stator.

Page 61: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Figure 8.1: Rotor Alignment

Figure 8.2: Stator windings configuration

Notice that while a conventional motor shaft runs freely, the stepper motor shaft moves in a fixed repeatable increment, which allows

one to move it to a precise position. This repeatable fixed movement is possible as a result of basic magnetic theory where poles of the same

polarity repel and opposite poles attract. The direction of the rotation is dictated by the stator poles. The stator poles are determined by the

current sent through the wire coils. As the direction of the current is changed, the polarity is also changed causing the reverse motion of the

rotor. The stepper motor discussed here has a total of 6 leads: 4 leads representing the four stator windings and 2 commons for the center-

tapped leads. As the sequence of power is applied to each stator winding, the rotor will rotate. There are several widely used sequences where each

has a different degree of precision. Table 8.1 shows a 2-phase, 4-step

stepping sequence.

Page 62: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

clockwise Step

#

Winding

A

Winding

B

Winding

C

Winding

D

Counter

clockwise

1 1 0 0 1

2 1 1 0 0

3 0 1 1 0

4 0 0 1 1

Table 8.1: Normal 4-step Sequence

It must be noted that although we can start with any of the

sequences in Table 8.1, once we start we must continue in the proper order. For example, if we start with step 3 (0110), we must continue in

the sequence of steps 4, 1, 2, etc.

STEP ANGLE: How much movement is associated with a single step? This

depends on the internal construction of the motor, in particular the

number of teeth on the stator and the rotor. The step angle is the minimum degree of rotation associated with a single step. Various motors

have different step angles. Table 8.2 shows some step angles for various motors. In table 8.4, notice the term steps per revolution. This is the total

number of steps needed to rotate one complete rotation or 360 degrees (e. g., 180 steps * 2 degrees =360).

It must be noted that perhaps contrary to one’s initial impression, a stepper motor does not need more terminal leads for the

stator to achieve smaller steps. All the stepper motors discussed in this section have 4 leads for the stator winding and 2 COM wires for the

center tap. Although some manufacturers set aside only one lead for the common signal instead of two, they always have 4 leads for the stators.

Next we discuss some associated terminology in order to understand the stepper motor further.

Step angle Steps per revolution

0.72 500

1.8 200

2.0 180

2.5 144

5.0 72

7.5 48

15 24

Table 8.2: Stepper motor step angles

Page 63: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

STEPS PER SECOND AND RPM RELATION

The relation between rpm (revolutions per minute), steps per revolution, and steps per second is as follows.

60

__sec__

revolutionperstepsrpmondpersteps

×=

The four-step sequence and number of teeth on rotor

The switching sequence shown earlier in Table 8.1 is called the 4-step switching sequence since after four steps the same two winding will

be “ON”. How much movement is associated with these four steps? After completing every four steps, the rotor moves only one tooth pitch.

Therefore, in a stepper motor with 200 steps per revolution, the rotor has 50 teeth since 4x 50 =200 steps are needed to complete one revolution.

This leads to the conclusion that the minimum step angle is always a

function of the number of teeth on the rotor. In other words, the smaller the step angle, the more teeth the rotor passes. One might wonder what

happens if we want to move 45 degrees, since the steps are 2 degrees each. To allow for finer resolution, all stepper motor allows what is called

an 8- step sequence. The 8-step sequence is also called half-stepping, since in the 8-step sequence each step is half of the normal step angle.

For example, a motor with a 2-degree step angle can be used as a 1-degree step angle if the sequence of Table 8.3 is applied.

clockwise Step

#

Winding

A

Winding

B

Winding

C

Winding

D

Counter

clockwise

1 1 0 0 1

2 1 0 0 0

3 1 1 0 0

4 0 1 0 0

5 0 1 1 0

6 0 0 1 0

7 0 0 1 1

8 0 0 0 1

Table 8.3: Half-step 8-step Sequence

Motor speed The motor speed, measured in steps per second (steps/s), is a

function of the switching rate. By changing the length of the time delay loop in the program, we can achieve various rotation speeds.

Holding torque The fallowing is a definition of holding torque: “with the motor

shaft at standstill or zero rpm condition, the amount of torque, from an external source, required to break away the shaft from its holding

Page 64: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

position. This is measured with rated voltage and current applied to the

motor.” The unit of torque is ounce-inch (or kg-cm).

Wave drive 4-step sequence In addition to the 8-step and 4-step sequences discussed

earlier, there is another sequence called the wave drive 4-step sequence. It is shown in table 8.3 is simply the combination of the wave drive 4-

step and normal 4-step sequences shown in Table 8.4 and 8.1, respectively. Experimenting with the wave drive 4-step is left to the

reader.

clockwise Step #

Winding A

Winding B

Winding C

Winding D

Counter clockwise

1 1 0 0 0

2 0 1 0 0

3 0 0 1 0 4 0 0 0 1

Table 8.4: Wave Drive 4-Step Sequence

Unipolar versus bipolar stepper motor interface There are three common types of stepper motor interfacing:

universal, unipolar, and bipolar. They can be identified by the number of connections to the motor. A universal stepper motor has eight, while the

unipolar has six and the bipolar has four. The universal stepper motor can be configured for all three modes, while the unipolar can be either

unipolar or bipolar. Obviously the bipolar cannot be configured for

universal nor unipolar mode. Figure 8.3 shows the basic internal connections of all three types of configurations.

a) Universal b) Unipolar c) Bipolar

Figure 8.3: Common stepper motor types

Page 65: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Unipolar stepper motor can be controlled using the basic interfacing

shown in Figure 8.4, whereas the bipolar stepper requires H-Bridge circuitry. Bipolar stepper motor require a higher operational current than

the unipolar, the advantage of this is a higher holding torque.

Using transistors as drivers:

Figure 8.4 shows an interface to a unipolar stepper motor using transistors. Diodes are used to reduce the back EMF spike created when

the coils are energized and de-energized, similar to the electromechanical relays discussed earlier.

8051

uc

P0.0

P0.1

P0.2

P0.3

VCC

VCC

VCC

VCC

COM

COM

W_A

W_B

W_C W_D

Stepper

Motor

Figure 8.4 : Stepper motor interfacing to 8051

REFERENCES :

1. The 8051 Microcontroller & Embedded systems - M. Mazidi

2. The 8051 Microcontroller Architecture, Programming &

Applications - Kenneth Ayala

3. Lab Manual for Universal Microcontroller Development Board,

S2N Systems, Pune.

Page 66: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

8A) Write a program to interface stepper motor to 8051 and rotate

it through clock-wise / anti clockwise direction continuously

ORG 0000H

LJMP START ; Skip the interrupt vector table

ORG 0030H

START: MOV P0, #0AH ; Load the excitation for wdg. A and D

ACALL DELAY

MOV P0, #06H ; Load the excitation for wdg. A and B

ACALL DELAY

MOV P0, #05H ; Load the excitation for wdg. B and C

ACALL DELAY

MOV P0, #09H ; Load the excitation for wdg. C and D

ACALL DELAY

SJMP START

DELAY: MOV TMOD,#10H

MOV TH1,#00H

MOV TL1,#00H

SETB TR1

BACK1: JNB TF1,BACK1

CLR TF1

CLR TR1

RET

END

Note: Anti clock wise direction change the sequence form 0A, 06, 05, 09

to 09, 05, 06, 0A.

Page 67: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

8B) Write a program to interface stepper motor to 8051 and rotate

it through clock-wise / anti clockwise direction through 1800.

ORG 0000H

LJMP START ; Skip the interrupt vector table

ORG 0030H

START: MOV R2, #25 ; Load the count for 180 degree roatation

BACK: MOV P0, #0AH ; Load the excitation for wdg. A and D

ACALL DELAY

MOV P0, #06H ; Load the excitation for wdg. A and B

ACALL DELAY

MOV P0, #05H ; Load the excitation for wdg. B and C

ACALL DELAY

MOV P0, #09H ; Load the excitation for wdg. C and D

ACALL DELAY

DJNZ R2, BACK

HERE: SJMP HERE

DELAY: MOV TMOD,#10H

MOV TH1,#00H

MOV TL1,#00H

SETB TR1

BACK1: JNB TF1,BACK1

CLR TF1

CLR TR1

RET

END

Note: Anti clock wise direction change the sequence form 0A, 06, 05, 09

to 09, 05, 06, 0A.

Page 68: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO. : 9

TITLE : Interfacing 16x2 LCD to 8051

PROBLEM DEFINITION:

A. Draw the interfacing diagram of 16x2 LCD to 8051 and

explain all the necessary pin connections in the figure.

B. Write a program to interface a 16x2 LCD to 8051 and display

‘S-Square-N Sys.’ on first line and ‘PUNE’ on second line of

the LCD.

S/W & H/W USED : 1. Keil uVision2 Simulator Software,

2. Flashmagic Software for downloading

3. 8051 Trainer kit

4. LCD interfacing card

THEORY:

LCD Interfacing In recent years the LCD is finding widespread use replacing LED’s.

This is due to the following reason:

1. The declining prices of LCD.

2. The ability to display numbers, characters, and graphics. This is in contrast to LEDs, which are limited to numbers and few characters.

3. In corporation of a refreshing controller into the LCD, thereby reliving the CPU of the task of refreshing the LCD. In contrast, the

LED must be refreshed by the CPU to keep displaying the data. 4. Ease of programming for characters and graphics.

Most of LCD’s available in the market are based on controller HD44780.

The LCD display can be interfaced either in 4-bit interface or 8-bit interface mode.

Page 69: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

LCD pin descriptions: Vcc, Vss and Vee:

While Vcc and Vss provide +5V and ground, repectively, Vee is used for controlling LCD contrast.

Register Select (RS):

There are two very important registers inside the LCD. The RS pin is used for their selection as follows.

a. RS = 0: the instruction command code register is selected, allowing the user to send a command such as clear display, cursor at home.

b. RS = 1: the data register is selected, allowing the user to send the

data to be displayed on the LCD.

Read/write (R/W): R/W input allows the user to write information to the LCD or read

information from it. R/W = 1 when reading, R/W = 0 when writing.

Enable (EN): The enable pin is used by the LCD to latch information presented to

its data pins. When data is supplied to data pins, a high to low pulse must be applied to the pin in order for the LCD to latch in the data present at

the data pins. This pulse must be a minimum of 450ns wide.

Data bus (D0 – D7): The 8-bit data pins, D0-D7 are used to send the information to the

LCD or read the contents of the LCD’s internal registers. To display the

numbers and letters, we send ASCII codes to these pins while making RS=1.

There are also instruction command codes that can be sent to the LCD to clear the display or blink the cursor.

We also use RS = 0 to check the busy flag bit to see if the LCD is ready to receive information. The busy flag is D& and can be read when

R/W = 1 and RS=0. When D7 =1, the LCD is busy taking care of internal operations and will not accept any new information. When D7 = 0, the

LCD is ready to receive new information.

Page 70: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Pin assignment for <= 80 character displays

Pin number Symbol Level I/O Function

1 Vss - - Power supply (GND)

2 Vcc - - Power supply (+5V)

3 Vee - - Contrast adjust

4 RS 0/1 I 0 = Instruction input

1 = Data input

5 R/W 0/1 I 0 = Write to LCD module

1 = Read from LCD module

6 E 1, 1->0 I Enable signal

7 DB0 0/1 I/O Data bus line 0 (LSB)

8 DB1 0/1 I/O Data bus line 1

9 DB2 0/1 I/O Data bus line 2

10 DB3 0/1 I/O Data bus line 3

11 DB4 0/1 I/O Data bus line 4

12 DB5 0/1 I/O Data bus line 5

13 DB6 0/1 I/O Data bus line 6

14 DB7 0/1 I/O Data bus line 7 (MSB)

15 VB+ 1 -

16 VB- 0 - Backlight Supply

Table 9.1: Pin details of 16x2 LCD module

Page 71: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Instruction set of LCD

Code Instruction

RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Description

Clear display 0 0 0 0 0 0 0 0 0 1 Clears display and returns

cursor to the home position (address 0).

Cursor home 0 0 0 0 0 0 0 0 1 *

Returns cursor to home

position (address 0). Also returns display being shifted to

the original position. DDRAM contents remain unchanged.

Entry mode set 0 0 0 0 0 0 0 1 I/D S

Sets cursor move direction

(I/D), specifies to shift the

display (S). These operations are performed during data

read/write.

Display On/Off control

0 0 0 0 0 0 1 D C B Sets On/Off of all display (D), cursor On/Off (C) and blink of

cursor position character (B).

Cursor/display shift 0 0 0 0 0 1 S/C R/L * *

Sets cursor-move or display-shift (S/C), shift direction (R/L).

DDRAM contents remains

unchanged.

Function set 0 0 0 0 1 DL N F * * Sets interface data length (DL),

number of display line (N) and

character font(F).

Set CGRAM address

0 0 0 1 CGRAM address Sets the CGRAM address. CGRAM data is sent and

received after this setting.

Set DDRAM address

0 0 1 DDRAM address Sets the DDRAM address. DDRAM data is sent and

received after this setting.

Read busy-flag and address counter

0 1 BF CGRAM / DDRAM address

Reads Busy-flag (BF) indicating internal operation is being

performed and reads CGRAM or DDRAM address counter

contents (depending on

previous instruction).

Write to CGRAM or DDRAM

1 0 Write data Writes data to CGRAM or DDRAM.

Read from CGRAM

or DDRAM 1 1 Read data

Reads data from CGRAM or

DDRAM.

Page 72: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Bit names and abbreviations

Bit name Setting / Status

I/D 0 = Decrement cursor position 1 = Increment cursor position

S 0 = No display shift 1 = Display shift

D 0 = Display off 1 = Display on

C 0 = Cursor off 1 = Cursor on

B 0 = Cursor blink off 1 = Cursor blink on

S/C 0 = Move cursor 1 = Shift display

R/L 0 = Shift left 1 = Shift right

DL 0 = 4-bit interface 1 = 8-bit interface

N 0 = 1/8 or 1/11 Duty (1 line) 1 = 1/16 Duty (2 lines)

F 0 = 5x7 dots 1 = 5x10 dots

BF 0 = Can accept instruction 1 = Internal operation in progress

- DDRAM = Display Data RAM.

- CGRAM = Character Generator RAM.

- DDRAM address corresponds to cursor position.

- * = Don't care.

8-bit Interface of LCD

LCD command codes

Page 73: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Sr. No. Command to LCD instruction Code (Hex)

01 Clear display screen 01

02 Return home 02

03 Decrement cursor (shift cursor to left) 04

04 Increment cursor (shift cursor to right) 06

05 Shift display right 05

06 Shift display left 07

07 Display off, cursor off 08

08 Display off, cursor on 0A

09 Display on, cursor off 0C

10 Display on cursor blinking 0E

11 Shift cursor position to left 10

12 Shift cursor position to right 14

13 Shift the entire display to left 18

14 Shift the entire display to right 1C

15 Force cursor to beginning of 1st line. 80

16 Force cursor to beginning of 2nd line. C0

17 2 lines and 5x7 matrixes. 38

Figure: LCD interfacing to 8051.

REFERENCES :

Page 74: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

1. The 8051 Microcontroller & Embedded systems - M. Mazidi

2. The 8051 Microcontroller Architecture, Programming &

Applications - Kenneth Ayala

3. Lab Manual for Universal Microcontroller Development Board,

S2N Systems, Pune.

9A) Write a program to interface a 16x2 LCD to 8051 and display

‘S-Square-N Sys.’ on first line and ‘PUNE’ on second line of the LCD. EN EQU P3.0 RW EQU P3.1

RS EQU P3.2 LCD_DATA EQU P2

ORG 0000H SJMP MAIN

ORG 0030H MAIN: MOV A, #38H ; LCD of 2lines, 5x7 matrix, bus - 8bit

ACALL CAMMAND ACALL DELAY MOV A, #38H ; repeat above three instructions

ACALL CAMMAND ACALL DELAY

MOV A, #0EH ; cursor ON, display ON ACALL CAMMAND ACALL DELAY

MOV A, #06H ; increment curser pointer ACALL CAMMAND

ACALL DELAY MOV A, #01H ; Clear the display ACALL CAMMAND

ACALL DELAY MOV A, #80H ; set address of first line.

ACALL CAMMAND ACALL DELAY MOV DPTR, #MSG1; Initialize the DPTR with message

NEXT: CLR A MOVC A, @A+DPTR

CJNE A, #0FFH, TRANS1 SJMP SKIP1 TRANS1: ACALL DATA_WRITE ; write on LCD

ACALL DELAY INC DPTR ; Next character

SJMP NEXT

SKIP1: MOV A, #0C0H ; set address of second line. ACALL CAMMAND

Page 75: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

ACALL DELAY MOV DPTR, #MSG2 ; Initialize the DPTR with message ‘PUNE’

NEXT2: CLR A MOVC A,@A+DPTR

CJNE A, #0FFH, TRANS2 SJMP SKIP2 TRANS2: ACALL DATA_WRITE

ACALL DELAY INC DPTR

SJMP NEXT2 SKIP2: SJMP SKIP2

CAMMAND: MOV P2, A; PUT DATA IN TO PORT 2.0 CLR RS; R0=0 FOR COMMAND CLR RW; RW=0 WRITE OPERATION

SETB EN; FOT LOW TO HIGH PULSE ACALL DELAY

NOP NOP

CLR EN RET

DATA_WRITE: MOV P2,A SETB RS

CLR RW SETB EN ACALL DELAY

NOP NOP

CLR EN RET

DELAY: MOV R3, #50 HERE1: MOV R4, #255

HERE2 : DJNZ R4, HERE2 DJNZ R3, HERE1 RET

MSG1: DB "S-Square-N Sys.",0FFH

MSG2: DB "PUNE",0FFH END

Page 76: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO. : 10

TITLE : Interfacing 4x4 matrix keypad to 8051

PROBLEM DEFINITION:

A. Draw the interfacing diagram of 4x4 keypad to 8051 and

explain all the necessary pin connections in the figure.

B. Write a program to interface 4x4 keypad to 8051 and display

the key pressed on the LED.

C. Write a program to interface 4x4 keypad to 8051 and display

the key pressed on the 7-segment Display.

S/W & H/W USED : 1. Keil uVision2 Simulator Software,

2. Flashmagic Software for downloading

3. 8051 Trainer kit

4. Keypad interfacing card

5. 7- Segment interfacing card

THEORY :

Interfacing the keyboard to the 8051 At the lowest level, keyboards are organized in a matrix of rows and columns. The CPU accesses both rows and columns through ports;

therefore, with two 8-bit ports, an 8x8 matrix of keys can be connected to a microprocessor. When a key is pressed, a row and a column make a

contact; otherwise, there is no connection between rows and columns. In IBM PC keyboards, a single microcontroller (consisting of a

microprocessor, RAM and EPROM of the several ports all on a single chip) takes care of hardware and software interfacing of the keyboard. In such

systems, it is the function of programs stored in the EPROM of the microcontroller to scan the keys continuously, identify which one has

been activated, and present it to the motherboard. In this section we look at the mechanism by which the 8051 scans and identifies the key.

Scanning and identifying the key

Page 77: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Figure shows a 4 x 4 matrix connected to port 0 of the 8051. The

lower nibble (P0.0 to P0.3) is acting as input port and the higher nibble (P0.4 to P0.7) is acting as output port. The rows (scan lines) are

connected to an output port and the columns (return lines) are connected to an input port. If no key has been pressed, the input port will yield 1’s

for all columns since they are all connected to high (Vcc). If all the rows are grounded and a key is pressed, one of the columns will have 0 since

the key pressed provides the path to ground. It is the function of the microcontroller to scan the keyboard continuously to detect and identify

the key pressed. How it is done is explained next.

Grounding rows and reading the columns To detect a pressed key, the microcontroller grounds all rows by providing 0 to the output latch, and then it reads the columns. If the data

read from the columns is P0.7- P0.4 = 1111, no key has been pressed and the process continues until a key press is detected. However, if one

of the column bits has a zero, this means that a key in the P0.6 column has been pressed. After a key press is detected, the microcontroller will

go through the process of identifying the key. Starting with the top row, the microcontroller grounds it by providing a low to row P0.0 only; then it

reads the columns. If the data read is all 1’s, no key in that row is activated and the process is moved to the next row. It grounds the next

row P0.1, reads the columns, and checks for any zero. This process continues until the row is identified. After identification of the row in

which the key has been pressed, the next task is to find out which column the pressed key belongs to. This should be easy since the microcontroller

knows at any time which row and column are being accessed.

In the program for detection and identification of key activation, it is

assumed that lower nibble of Port 0 and higher nibble of Port 0 are initialized as output and input, respectively. Program goes through the

following four major stages.

1. To make sure that the preceding key has released, 0s are output to all rows at once, and the columns are read and checked repeatedly

until the columns are high. When all columns are found to be high, the program waits for a short amount of time before it goes to the

next stage if waiting for a key to be pressed. 2. To see if any key pressed, the columns are scanned over and over

in an infinite loop until one of them has a 0 on it. Remember that the output latches connected to rows still have their initial zero

(provided in stage 1), making them grounded. After the key press

detection, the microcontroller waits 20 ms for the bounce and then scans the columns again. This serves two functions: (a) it ensures

Page 78: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

that the first key press detection was not an erroneous one due to a

spike noise, and (b) the 20 ms delay prevents the same key press from being interpreted as a multiple key press. If after 20-ms delay

the key is still pressed, it goes tot the next stage to detect which row it belongs to; otherwise, it goes back into the loop to detect a

real key press.

8051

uc

P0.5

P0.0

P0.1

P0.2

P0.3

P0.6

P0.7

P0.4

VCC

Figure 10.1: Matrix Keyboard connection Port 0

3. To detect which row the key press belongs to, the microcontroller grounds one row at a time, reading the columns each time. If it

finds that all columns are high, this means that the key press

cannot belong to that row; therefore, it grounds the next row and continues until it finds the row the key press belongs to. Upon

finding the row that the key press belongs to, it sets up the starting address for the look-up table holding the scan codes (or the ASCII

value) for that row and goes to the next stage to identify the key 4. To identify the key press, the microcontroller rotates the column

bits, one bit at a time, into the carry flag and checks to see if it is low. Upon finding the zero, it pulls out the ASCII code for that key

from the look-up table; otherwise, it increments the pointer to the next element of the look-up table. Figure 12-7 flowcharts this

process. While the key press detection is standard for all keyboards, the

process for determining which key is pressed varies. The look-up table method shown in Program can be modified to work with any matrix up to

8 x 8 matrix.

Page 79: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

.

REFERENCES :

1. The 8051 Microcontroller & Embedded systems - M. Mazidi

2. The 8051 Microcontroller Architecture, Programming &

Applications - Kenneth Ayala

3. Lab Manual for Universal Microcontroller Development Board,

S2N Systems, Pune.

10A) Write a program to interface a 4x4 keypad to 8051 and display

the key pressed on the LED connected to port 1 (P1).

;SCAN LINES P0.0 TO P0.3 ;RETURN LINES P0.4 TO P0.7

KEYPORT EQU P0 LEDPORT EQU P1

ORG 0000H SJMP MAIN ; Skip the interrupt vector table

ORG 0030H

MAIN: MOV KEYPORT, #0F0H ; Make return line as input and scan lines zero MOV A, KEYPORT ; Read the return lines

ANL A, #0F0H ; Mask the unused bits CJNE A, #0F0H, CHECK1 ; key pressed branch to check1 SJMP MAIN ; branch to main till key pressed

CHECK1: ACALL DELAY_20MS ; wait for debounce time MOV A, KEYPORT ; check key closure

ANL A, #0F0H ; mask unused bits CJNE A, #0F0H, NEXT ; key pressed baranch to next to find row SJMP MAIN ; branch to main till key pressed

NEXT: MOV KEYPORT, #0FEH ; Ground scan line 0 MOV A, KEYPORT ; read the retrun lines

ANL A, #0F0H CJNE A, #0F0H, SCAN_R0W0 ; branch if key is in scan line 0 MOV KEYPORT, #0FDH ; Ground scan line 1

MOV A, KEYPORT ; read the retrun lines ANL A, #0F0H

CJNE A, #0F0H, SCAN_R0W1 ; branch if key is in scan line 1 MOV KEYPORT, #0FBH ; Ground scan line 2

Page 80: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

MOV A, KEYPORT ; read the return lines ANL A, #0F0H

CJNE A, #0F0H, SCAN_R0W2 ; branch if key is in scan line 2 MOV KEYPORT, #0F7H ; Ground scan line 3

MOV A, KEYPORT ; read the retrun lines ANL A, #0F0H CJNE A, #0F0H, SCAN_R0W3 ; branch if key is in scan line 3

SJMP MAIN SCAN_R0W0: MOV DPTR, #R0W0; Initialise the DPTR with address of Row 0

SJMP FIND_KEY SCAN_R0W1: MOV DPTR, #R0W1; Initialise the DPTR with address of Row 1 SJMP FIND_KEY

SCAN_R0W2: MOV DPTR, #R0W2; Initialise the DPTR with address of Row 2 SJMP FIND_KEY

SCAN_R0W3: MOV DPTR, #R0W3; Initialise the DPTR with address of Row 3 FIND_KEY: RLC A ; rotate left until the zero JNC FOUND_KEY

INC DPTR ; find column and update DPTR SJMP FIND_KEY

FOUND_KEY: CLR A ; clear the accumulator MOVC A, @A+DPTR ; get the key code

MOV LEDPORT, A ; send the data to P1 to which LED interfaced LJMP MAIN

DELAY_20MS:

MOV R6,#20H ; delay program NEXT6: MOV R7,#0FFH NEXT7: DJNZ R7,NEXT7

DJNZ R6, NEXT6 RET

; Key code to display on LED's R0W0: DB 0FFH, 0FEH, 0FDH, 0FCH ; 0 1 2 3

R0W1: DB 0FBH, 0FAH, 0F9H, 0F8H ; 4 5 6 7 R0W2: DB 0F7H, 0F6H, 0F5H, 0F4H ; 8 9 A B

R0W3: DB 0F3H, 0F2H, 0F1H, 0F0H ; C D E F END

Page 81: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

10B) Write a program to interface a 4x4 keypad to 8051 and display

the key pressed on 7-segment display.

;SCAN LINES P0.0 TO P0.3 ;RETURN LINES P0.4 TO P0.7

KEYPORT EQU P0

LEDPORT EQU P1 ORG 0000H

SJMP MAIN

ORG 0030H MAIN: CLR P3.7 MOV KEYPORT, #0F0H ; Make return line as input and scan lines zero

MOV A, KEYPORT ; Read the return lines ANL A, #0F0H ; Mask the unused bits

CJNE A, #0F0H, CHECK1 ; key pressed branch to check1 SJMP MAIN ; branch to main till key pressed

CHECK1: ACALL DELAY_20MS ; wait for debounce time MOV A, KEYPORT ; check key closure

ANL A, #0F0H ; mask unused bits CJNE A, #0F0H, NEXT ; key pressed baranch to next to find row SJMP MAIN ; branch to main till key pressed

NEXT: MOV KEYPORT, #0FEH ; Ground scan line 0

MOV A, KEYPORT ; read the retrun lines ANL A, #0F0H

CJNE A, #0F0H, SCAN_R0W0 ; branch if key is in scan line 0 MOV KEYPORT, #0FDH ; Ground scan line 1 MOV A, KEYPORT ; read the retrun lines

ANL A, #0F0H CJNE A, #0F0H, SCAN_R0W1 ; branch if key is in scan line 1

MOV KEYPORT, #0FBH ; Ground scan line 2 MOV A, KEYPORT ; read the return lines

ANL A, #0F0H CJNE A, #0F0H, SCAN_R0W2 ; branch if key is in scan line 2

MOV KEYPORT, #0F7H ; Ground scan line 3 MOV A, KEYPORT ; read the retrun lines ANL A, #0F0H

CJNE A, #0F0H, SCAN_R0W3 ; branch if key is in scan line 3 SJMP MAIN

SCAN_R0W0: MOV DPTR, #R0W0 ; Initialise the DPTR with address of Row0

Page 82: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

SJMP FIND_KEY

SCAN_R0W1: MOV DPTR, #R0W1 ; Initialise the DPTR with address of Row1 SJMP FIND_KEY

SCAN_R0W2: MOV DPTR, #R0W2 ; Initialise the DPTR with address of Row2 SJMP FIND_KEY

SCAN_R0W3: MOV DPTR, #R0W3 ; Initialise the DPTR with address of Row3

FIND_KEY: RLC A ; rotate left until the zero JNC FOUND_KEY

INC DPTR ; find column and update DPTR SJMP FIND_KEY

FOUND_KEY: CLR A ; clear the accumulator MOVC A, @A+DPTR ; get the key code

MOV LEDPORT, A ; send the data to P2 to which LED interfaced

LJMP MAIN

DELAY_20MS: MOV R6,#20H ; delay program NEXT6: MOV R7,#0FFH

NEXT7: DJNZ R7,NEXT7 DJNZ R6, NEXT6

RET ; 7 segment code to display key code on 7-segment display

R0W0: DB 88H, 0EBH, 4CH, 49H ; 0 1 2 3 R0W1: DB 2BH, 19H, 18H, 0CBH ; 4 5 6 7

R0W2: DB 08H, 09H, 0AH, 38H ; 8 9 A B R0W3: DB 7CH, 68H, 1CH, 1EH ; C D E F

END

Page 83: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

EXPT. NO. : 11

TITLE : To Study various design and Development Tools

for Microcontroller

PROBLEM DEFINITION:

Explain the following design and development tools for

microcontrollers

1. Assembler

2. Compiler

3. Simulator

4. Emulator

5. Logic analyzer

THEORY:

Assembling and running an 8051 program

The steps to create an executable assembly language program are

outlined as follows:

1. First we use an editor to type in a program. Many excellent editors

or word processors are available that can be used to create and/or

edit the program. A widely used editor is the MS-DOS EDIT

program (or notepad in windows), which comes with all Microsoft

operating systems. Notice that the editor must be able to produce

an ASCII file. For many assemblers, the file names follow the usual

DOS conventions, but the source file has the extension “asm” or

“src”, depending on which assembler you are using. Check your

assembler for your convention. The “asm” extension for the source

file is used by an assembler in the next step.

2. The “asm” source file containing the program code created in step 1

is fed to an 8051 assembler. The assembler converts the

instructions into machine code. The assembler will produce an

Page 84: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

object file and list file. The extension for the object file is “obj” while

the extension for the list file is “lst”.

3. Assemblers require a third step called linking. The link program

takes one or more object files and produces an absolute file with

the extension “abs”. This abs file is used by 8051 trainers that have

monitor program.

4. Next, the “abs” file is fed into a program called “OH” (object to hex

converter), which creates a file with extension “hex” that is ready to

burn into ROM. This program comes with all 8051 assemblers.

Recent Windows-based assemblers combine steps 2 through 4 into

one step.

Figure 1.4: Steps to create program

More about “.asm” and “.obj” files:

The “asm” file is also called the source file and for this reason some

assemblers require that this file have the “src” extension. Check your

Page 85: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

8051 assembler to see which extension it requires. As mentioned

earlier, this file is created with an editor such as DOS EDIT or Windows

Notepad. The 8051 assembler converts the asm files Assembly

language instructions into machine language and provides the obj

(object) file. In addition to creating the object file, the assembler also

produces the lst (list) file.

.LST (list) file:

The lst file, which is optional, is very useful to the programmer

because it lists all the opcodes and addresses as well as errors that the

assembler detected. Many assemblers assume that the list file is not

wanted unless you indicate that you want to produce it. This file can

be accessed by an editor such as DOS EDIT and displayed on monitor

or sent to the printer to produce a hard copy. The programmer uses

the list file to find syntax error. It is only after fixing all the errors

indicated in the list file that the .obj file is ready to be input to the

linker program.

EMULATOR:

Another way to run your program to is with an emulator. An

emulator is a mixture of hardware and software. It is used to test and

debug the hardware and software of an external system, such as the

prototype of a microprocessor based instrument. Part of the hardware

of an emulator is a multi-wire cable which connects the host system to

the system being developed. A plug at the end of the cable is plugged

into the prototype system in place of its microcontroller. Through this

connection the software of the emulator allows us to download object

program code into RAM in the system being tested and run it. An

emulator allows us to load and run programs, examine and change the

contents of registers, memory locations and insert the breakpoints in

the program. The emulator also takes a snapshot of the contents of

registers, activity on the address and data bus and the state of the

flags as each instruction executes. The emulator stores this trace data,

as it is called, in a large RAM.

µvision assembler /C compiler and Simulator

The µvision3 IDE is windows based software development platform

that combines a robust editor and project manager. µvision3 integrates

Page 86: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

all tools including C compiler, macro assembler, linker/locator and HEX

file generator. µvision3 helps the expedite the development process of

embedded applications.

Creating applications for 8051 using Keil µVision compiler

1. Starting the µVision IDE:

Click on START button and select Programs/Keil µVision. The screen should look something like this. There are 3 different windows viz. Editor

window, Workspace window and output window as shown below.

Page 87: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

2. To create a new project, from PROJECT menu, select NEW PROJECT.

The screen should look something like this.

3. The open dialog window will be displayed. Select the desired path where you wish to create this new project. Create new folder for every

new project.

Page 88: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

4. When you create a new project, µVision3 asks you to select a CPU for

the project. The select device dialog box shows the µVision3 device database. Select the microcontroller Philips P89V51RD2.

5. After the Project is created, the screen should look something like this.

Page 89: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

6. To create a new source file either .asm or .c, from FILE menu, select NEW. The screen should look something like this.

7. After editing the program in source file, save the source file with .asm

extension (it is very must to give extension otherwise file is treated as normal text file.) in project folder.

Page 90: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

8. Once the source file is created, add .asm file to your project. You can select the source group in the project workspace and files and click the

right mouse key to open a local menu.

9. The option ‘Add files’ opens the standard files dialog. Select the desired

file which is created.

Page 91: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

10. After adding the file, go to options for the target to select the proper crystal frequency and Hex file creation. You can select the Target 1 in the

project workspace and click the right mouse key to open a local menu.

11. After selecting the options for Target, the screen should look

something like this. Then type the desired clock frequency as shown below.

Page 92: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

12. To check the options for creating the Hex file go to output tab of options for target window. Then specify the name of Hex file (default is

project name) and check the box to create hex file as shown below.

13. To build a project, go to PROJECT – Build target, translate all

source files and link the application with a click on the Build target toolbar icon. When you build an application with syntax errors, compiler will

display errors and warning messages in the output window. A double click on a message line opens the source file on the correct location in editor

window.

Page 93: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Page 94: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

14. After successful creation .obj file and .hex file go to DEBUG –

Start/stop debug session to debug / single step the program.

15. After clicking the start debug session, the screen should look

something like this. To view the parallel ports, time/counter, interrupt go to Peripherals Menu. To view the memory window, serial window go to

View Menu. To single step press F10.

Page 95: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

Downloading and running user programs

Microcontroller P89V51RD2 includes on-chip flash, which is in-system programmable (ISP) for storing user program and non-volatile

data. Therefore it is possible to download user program into on-chip flash, through serial port connected to PC. For this purpose software FLASH

MAGIC is used. To down load the program using FLASH MAGIC follow the steps as below.

1. Connect the Power supply and keep the board in switched off

mode. 2. Connect the RS232 port of trainer kit to COM1 of a PC using serial

communication cable. 3. Start the flash magic by START – PROGRAMS – FLASH MAGIC –

Flash magic.exe. You will get the screen as below.

4. Do proper settings in flash magic (Device: P89V51RD2, COM port:

COM1, Baud rate: 9600, Interface: None (ISP), enable erase block used by the HEX file.

Page 96: User Manual Experiments)

Users Lab Manual (Experiments)

S2N Systems, Pune. Cell No. 9011097672

5. Click on Verify after programming to verify the program.

6. Very Important: Do not select set security bit, Fill unused Flash, Gen block checksums, Prog Clocks bit.

7. Once the all settings are completed, select the Hex file which is to be downloaded.

8. Use the browse option to go to the required directory. Click on the hex file you want to download to the target hardware.

9. After selection of the file. Click on the START button. Following

message will be displayed. 10. At this point you should power ON the board. If the board is

already powered ON, then you should press the reset switch on the

board. 11. After the above, the above message will disappear and the

programming will start. 12. Finally you will get the message on the bottom of the flash

magic screen is finished. 13. To run the program, RESET the board or POWER OFF and

POWER ON the board again.

REFERENCES:

1. Microprocessors and Interfacing - Douglas Hall

2. www.flashmagic.com

3. www.keil.com