You are on page 1of 72

Rukmini Educational

Charitable Trust

Microcontrollers Laboratory
Manual
BTEC15F4700
IV Semester

School of Electronics and


Communication Engineering
www.reva.edu.in

Campus Address: Rukmini Knowledge Park, Kattigenahalli, Yelahanka, Bengaluru - 560 064
REVA University School of ECE

MICROCONTROLLERS LAB

SYLLABUS
Sub Code : BTEC15F4700L IA Marks : 20
Hrs/ Week: 03 Exam Hours : 03
Total Hrs. : 42 Exam Marks : 30

I. PROGRAMMING

1. Data Transfer - Block move, Exchange, Sorting, Finding largest element in an array.
2. Arithmetic Instructions - Addition/subtraction, multiplication and division,
Square, Cube – (16 bits Arithmetic operations – bit addressable).
3. Counters.
4. Boolean & Logical Instructions (Bit manipulations).
5. Conditional CALL & RETURN.
6. Code conversion: BCD – ASCII; ASCII – Decimal; Decimal - ASCII;
HEX to Decimal and Decimal to HEX.
7. Programs to generate delay, Programs using serial port and on-Chip timer /
Counter.

I. INTERFACING:

Write C programs to interface 8051 chip to Interfacing modules to develop


single chip solutions.

8. Alphanumeric LCD panel and Hex keypad input interface to 8051.


9. Generate different waveforms Sine, Square, Triangular, Ramp etc. using
DAC interface to 8051; change the frequency and amplitude.
10. Stepper and DC motor control interface to 8051.

CHALLENGING EXPERIMENT
11. Elevator interface to 8051.
12. Simple Calculator using 6 digit seven segment displays and Hex Keyboard
interface to 8051.

Microcontrollers Lab BTEC15F4700 Page |1


REVA University School of ECE

Contents

Sl. No TITLE PAGE No.

Introduction To Microcontroller-8051 4
1 Introduction to Keil tool 9
 Sample Programs
2 Data Transfer:- 28
 Block move
 Exchange
 Sorting
 Finding largest element in an array.
3 Arithmetic Instructions -:- 35
 Addition/subtraction
 multiplication and division
 Square, Cube – (16 bits Arithmetic operations – bit
addressable)
4 Boolean & Logical Instructions (Bit manipulations). Using 40
Conditional CALL & RETURN.
5 Counters. 43
6 Programs to generate delay, Programs using serial port and 45
on-Chip timer /Counter.
7 Code conversion:- 48
 BCD – ASCII
 ASCII – Decimal
 Decimal – ASCII
 HEX to Decimal
 Decimal to HEX.
8 Programs to generate delay, Programs using serial port and 31
on-Chip timer /Counter.
8051 interfacing with the different Modules

9 Interfacing DAC to 8051 and generating the following wave 52


forms:
 Sine wave
 Triangle wave
 Ramp wave
 Square wave with varying amplitude and frequency
10 Stepper and DC motor control interface to 8051. 59
11 Interfacing Alphanumeric LCD panel and Hex keypad input 62
to 8051.
Challenge Experiment 68
Practical exam Question bank 69

Microcontrollers Lab BTEC15F4700 Page |2


REVA University School of ECE

Course Objectives:

1. To Know the différent register set in 8051.

2. To Know the different memory in 8051.

3. To Asses the diffrent memory.

4. To transfer data between register and register.


And register and memory, memory and memory.

5. To know the effect of arithmetic instruction on program status word

6. To program the timer, counter.

7. To Serial communication

8. To interface extranal devices, DAC, DC MOTER, STEPPER MOTER and KEY


BOARD.

Course outcomes:

On successful completion of the course the students shall be able to :

1. Debug and Optimize the Given Code.

2. Interpret the results of microcontroller programs.

3. Predict and solve real time programs using microcontroller programming.

Microcontrollers Lab BTEC15F4700 Page |3


REVA University School of ECE

Introduction to Microcontrollers:

A microcontroller can be compared to a small stand alone computer; it is a very powerful


device, which is capable of executing a series of preprogrammed tasks and interacting with
other hardware devices. Being packed in a tiny integrated circuit (IC) whose size and weight
is usually negligible, it is becoming the perfect controller for robots or any machines
requiring some kind of intelligent automation. A single microcontroller can be sufficient to
control a small mobile robot, an automatic washer machine or a security system. Any
microcontroller contains a memory to store the program to be executed, and a number of
input/output lines that can be used to interact with other devices, like reading the state of a
sensor or controlling a motor.

Nowadays, microcontrollers are so cheap and easily available that it is common to use them
instead of simple logic circuits like counters for the sole purpose of gaining some design
flexibility and saving some space. Some machines and robots will even rely on a multitude of
microcontrollers, each one dedicated to a certain task. Most recent microcontrollers are 'In
System Programmable', meaning that you can modify the program being executed, without
removing the microcontroller from its place.

Today, microcontrollers are an indispensable tool for the robotics hobbyist as well as for the
engineer. Starting in this field can be a little difficult, because you usually can't understand
how everything works inside that integrated circuit, so you have to study the system
gradually, a small part at a time, until you can figure out the whole image and understand
how the system works.

Comparison Of Microprocessor And Microcontroller

Microprocessor and Microcontroller differ in their functionalities. Microprocessor has more


generalized functions, where as Microcontroller is more specific to its task.

A Microprocessor may not be programmed to handle real-time tasks but Microcontroller in


devices that need to control temperature of water or perhaps measure the temperature of a
room require real time monitoring and therefore with its inbuilt set of instructions the
microcontroller works on its own.

Microprocessor requires constant input by a human such as in a personal computer so that


instructions can be booted. Microprocessor is the memory of the computing machine
whereas the microcontroller integrates the entire computer in a single chip. Not only does it
have the memory embedded in it but also has input and output ports plus peripherals such
as timers and converters. All this can be handled with a single touch.

Microcontrollers Lab BTEC15F4700 Page |4


REVA University School of ECE

The 8051 microcontroller architecture

The 8051 is the name of a big family of microcontrollers. The device which we are going to
use along this tutorial is the 'AT89S52' which is a typical 8051 microcontroller
manufactured by Atmel™. Note that this part doesn't aim to explain the functioning of the
different components of a 89S52 microcontroller, but rather to give you a general idea of the
organization of the chip and the available features, which shall be explained in detail along
this tutorial.

The block diagram provided by Atmel™ in their datasheet showing the architecture the
89S52 device can seem very complicated, and since we are going to use the C high level
language to program it, a simpler architecture can be represented as the figure

This figures shows the main features and components that the designer can interact with.
You can notice that the 89S52 has 4 different ports, each one having 8 Input/output lines
providing a total of 32 I/O lines. Those ports can be used to output DATA and orders do
other devices, or to read the state of a sensor, or a switch. Most of the ports of the 89S52
have 'dual function' meaning that they can be used for two different functions: the first one
is to perform input/output operations and the second one is used to implement special
features of the microcontroller like counting external pulses, interrupting the execution of
the program according to external events, performing serial data transfer or connecting the
chip to a computer to update the software.
Each port has 8 pins, and will be treated from the software point of view as an 8-bit variable
called 'register', each bit being connected to a different Input/Output pin.You can also notice
two different memory types: RAM and EEPROM. Shortly, RAM is used to store variable
during program execution, while the EEPROM memory is used to store the program itself,
that's why it is often referred to as the 'program memory'. The memory organization will be
discussed in detail later.
The special features of the 89S52 microcontroller are grouped in the blue box at the bottom
of figure At this stage of the tutorial, it is just important to note that the 89S52 incorporates
hardware circuits that can be used to prevent the processor from executing various
repetitive tasks and save processing power for more complex calculations. Those simple
tasks can be counting the number of external pulses on a pin, or generating precise timing
sequences.

Microcontrollers Lab BTEC15F4700 Page |5


REVA University School of ECE

It is clear that the CPU (Central Processing Unit) is the heart of the microcontrollers; it is
the CPU that will Read the program from the FLASH memory and execute it by interacting
with the different peripherals discussed above.

Features of 8051:

The main features of 8051 microcontroller are:

1) RAM – 128 Bytes (Data memory)


2) ROM – 4Kbytes (ROM signify the on – chip program space)
3) Serial Port – Using UART makes it simpler to interface for serial communication.
4) Two 16 bit Timer/ Counter
5) Input/output Pins – 4 Ports of 8 bits each on a single chip.
6) Five Interrupt Sources
7) 8 – bit ALU (Arithmetic Logic Unit)

Microcontrollers Lab BTEC15F4700 Page |6


REVA University School of ECE

8) Harvard Memory Architecture – It has 16 bit Address bus (each of RAM and ROM)
and 8 bit Data Bus.
9) 8051 can execute 1 million one cycle instructions per second with a clock frequency of
12MHz.
This microcontroller is also called as “System on a chip” because it has all the features on a
single chip

AT89C51ED2 Microcontroller

Description

AT89C51RD2/ED2 is high performance CMOS Flash version of the 80C51 CMOS single
chip 8- bit microcontroller. It contains a 64-Kbyte Flash memory block for code and for data.
The 64-Kbytes Flash memory can be programmed either in parallel mode or in serial mode
with the ISP capability or with software. The programming voltage is internally generated
from the standard VCC pin.
The AT89C51RD2/ED2 retains all of the features of the Atmel 80C51 with 256 bytes of
internal RAM, a 5 source 4-level interrupt controller and three timer/counters. The
AT89C51ED2 provides 2048 bytes of EEPROM for nonvolatile data storage.
In addition, the AT89C51RD2/ED2 has a Programmable Counter Array, an XRAM of 1792
bytes, a Hardware Watchdog Timer, SPI interface, Keyboard, a more versatile serial
channel that facilitates multiprocessor communication (EUART) and a speed improvement
mechanism (X2 Mode).
The fully static design of the AT89C51RD2/ED2 allows reducing system power consumption
by bringing the clock frequency down to any value, including DC, without loss of data.
The AT89C51RD2/ED2 has 2 software-selectable modes of reduced activity and an 8-bit
clock prescaler for further reduction in power consumption. In the Idle mode the CPU is
frozen while the peripherals and the interrupt system are still operating. In the Power-down
mode the RAM is saved and all other functions are inoperative.

The added features of the AT89C51RD2/ED2 make it more powerful for applications that
need pulse width modulation, high speed I/O and counting capabilities such as alarms,
motor control, corded phones, and smart card readers.

Microcontrollers Lab BTEC15F4700 Page |7


REVA University School of ECE

INTERUPTS

Five sources of interrupt (both external and internal).


Two External interrupts INTO and INTI are provided with push button switches: these can
also be used as general-purpose switches.
I/O (Port) Lines Four 10-pin connectors for all the 32 I/O lines.
P0,P1 and P2 Port lines are available on a 26-pin connector,
16X2 LCD & SERIAL I/O are also available.

Microcontrollers Lab BTEC15F4700 Page |8


REVA University School of ECE

Creating and compiling a µ vision 3 project


1) Double Click on the µ vision 3 icon on the desktop
2) If there is any project opened, close it by selecting close project option from project
menu of the Keil µ vision IDE menu bar.

3) Click on project menu and select new µ vision project.

Microcontrollers Lab BTEC15F4700 Page |9


REVA University School of ECE

4) Create new project window will open. Select the location new volume (D) drive.
Create one new folder & open that folder.

5) Write file name. There is no need give any extension along with the project name, as
keil will automatically assign. Click on save.

Microcontrollers Lab BTEC15F4700 P a g e | 10


REVA University School of ECE

6) Select the device for the application through the provided Device Database in Select
device for target ‘target1’ window. (Device database – Atmel – AT89C51ED2) and
click OK.

Microcontrollers Lab BTEC15F4700 P a g e | 11


REVA University School of ECE

7) Keil µ vision IDE will ask for Copy standard 8051 startup code to project folder and
add file to project? Click on NO.

8) Observe the project workspace window, which is on the left side of the Keil IDE, It
will contain Target1 and Source group1.

Microcontrollers Lab BTEC15F4700 P a g e | 12


REVA University School of ECE

9) Select File from the menu bar and choose New.

10) Select File from menu bar and select Save AS.

Microcontrollers Lab BTEC15F4700 P a g e | 13


REVA University School of ECE

11) A window called Save As will open and prompt for the location where to store the
file. For convenience sake, save this file in the same folder where the project has
created.
12) While naming the file, if program is written in ‘C’ language save file with .C
extension (Ex---test.C), or if the program is written in Assembly language save ASM
file with .ASM extension Ex---test.ASM).

13) Write complete program. Select File click Save.

Microcontrollers Lab BTEC15F4700 P a g e | 14


REVA University School of ECE

14) Right click on Source Group 1 in project Workspace window and click on Add files to
group ‘Source Group 1’ or double click on Source Group 1 to add the required files to
the project.

15) Select the required .C or .ASM (.A51) files and click on Add & click on close button.

Microcontrollers Lab BTEC15F4700 P a g e | 15


REVA University School of ECE

16) From Project menu select Build target option. This will generate the output file in
OMF51 format. If there are any errors or warnings rectify them and rebuild the
target.

17) If it shows 0 errors on output window, then the program is ready to execute.

Microcontrollers Lab BTEC15F4700 P a g e | 16


REVA University School of ECE

18) From Project menu select Options for Target ‘Target 1’ option.

19) Select Target in the Options for Target ‘Target 1’ window. Change crystal frequency
Xtal (MHz) = 11.0592 & select at same window click Debug.

Microcontrollers Lab BTEC15F4700 P a g e | 17


REVA University School of ECE

20) To work in simulator mode (i.e. without hardware select Use Simulator radio button
or to downloaded to hardware, select keil monitor radio button and from drop down
menu Keil Monitor 51 Driver & click OK.

To download the program to hardware kit follows steps from step 21 to 25.
21) Check Load Application at Startup option and if it is a C program then check Run to
main () option.

Microcontrollers Lab BTEC15F4700 P a g e | 18


REVA University School of ECE

22) If mode of communication is in USB cable then Right click on My Computer icon on
desktop and select Manage option.

23) In the Computer Management window select Device manager, expand the Ports
(COM & LPT) option observe the port number assigned to ESA MCB 51.

Close the Computer Management window.

Microcontrollers Lab BTEC15F4700 P a g e | 19


REVA University School of ECE

24) Open the Keil window, from Project menu and select Option for Target ‘Target 1”
option. Click Debug & select Settings.
25) Select the COM port & click OK.

26) Select Debug menu. Click Start/Stop Debug Session & click run.

Microcontrollers Lab BTEC15F4700 P a g e | 20


REVA University School of ECE

27) Once program is loaded in the hardware kit, observe the output. Before stopping the
debug session (i.e., by selecting stop debug on µ vision window) press RESET button
in ESA MCB 51kit compulsorily.

RESET

Note: To access data RAM area type address as D: 0020h.


Similarly to access the DPTR region (XRAM-present on chip in AT89C51 ED2) say 9000h
location type in X: 09000H.

Microcontrollers Lab BTEC15F4700 P a g e | 21


REVA University School of ECE

Sample programs
Write result of the following instructions below for each example

Data Movement operation


Example: 01
org 0000h
sjmp 30h
org 30h
mov r0,#34h
mov a,#24h
mov a,r0 ;Check the change in the content of A and R0 if any
here:sjmp here
end

Example: 02

org 0000h
sjmp 30h
org 30h
mov a,00h ; (A)= and (R0) =
mov r0,#24h
mov 24h,#20h ; contents of RAM location 24h=
mov a,@r0 ; Check the change in the content of A and R0 if any
here: sjmp here
end

Example: 03

org 0000h
sjmp 30h
org 30h
mov a,#40h ; (A) =
mov dptr,#34h ; (DPTR)=
movx @dptr,a ;comments on this instruction
mov a,#00h
movx a,@dptr
here: sjmp here
end

Microcontrollers Lab BTEC15F4700 P a g e | 22


REVA University School of ECE

Example: 04

org 0000h
mov DPTR,#1234h ; (DPTR) =
mov a,#00h ; (a)=
movc a,@a+DPTR ; comment on this instruction and check out the respective
end register and memory location content

Addition operation
Example: 05
org 0000h
sjmp 30h
org 30h
mov r1,#27h ; (r1) =
mov a,#45h ; (a) =
add a,#34h ; (a) =
add a,r1 ; (a) = (r1)=
add a,01h ; (a) = (01)=
add a,@r1 ; comment on this instruction
addc a,#34h ; (PSW) = (a)= (r1)=
addc a,r1 ; (PSW) = (a)= (r1)=
addc a,01h ; (PSW)= (a)= (r1)=
addc a,@r1 ; comment on this instruction
here: sjmp here
end

Example: 06
org 0000h
sjmp 30h
org 30h
mov r1,#27h ; (r1)=
mov a,#45h ; (a) =
subb a,#34h ; (a) = (PSW)=
subb a,r1 ; (a)= (r1)=
subb a,01h ; (a) (PSW)=
subb a,@r1 ; comment on this instruction & check the content of the required
register
here: sjmp here
end

Microcontrollers Lab BTEC15F4700 P a g e | 23


REVA University School of ECE

Multiplication and Division operation


Example: 07
org 0000h
sjmp 30h
org 30h
mov b,#27h ; (b)=
mov a,#45h ; (a)=
mul ab ; (a)= (b)=
here: sjmp here
end

Example: 08

org 0000h
sjmp 30h
org 30h
mov b,#27h ; (b)=
mov a,#45h ; (a)=
div ab ; (a)= (b) =
here: sjmp here
end

Rotate Operation
Example: 09

org 0000h
mov a,#66h ; (a)=
clr c
rl a ; (a)= flag C =
rlc a ; (a)= flag C =
rr a ; (a)= flag C =
rrc a ; (a)= flag C =
here: sjmp here
end

Microcontrollers Lab BTEC15F4700 P a g e | 24


REVA University School of ECE

Boolean operation
Example: 10

AND Operation

org 0000h
mov a,#23h ; (a)=
mov r1,#45h ; (r1)=
anl a,r1 ; (a)= (r1) =
anl a,01h ; Comment on this instruction and check out of the respective
registers
here: sjmp here
end

Example: 11
OR Operation

org 0000h
mov a,#23h ; (a)=
mov r1,#41h ; (r1)=
orl a,#56h ; (a)=
orl a,r1 ; (a)= (r1)=
orl a,@r1 ; Comment on this instruction
anl a,01h ; (a)= (r1)=
here: sjmp here
end

Example: 12
EX-OR Operation

org 0000h
mov a,#23h ; (a)=
mov r1,#45h ; (r1)=
xrl a,#56h ; (a)=
orl a,r1 ; (a)= (r1)=
orl a,@r1 ; Comment on this instruction
anl a,01h ; (a)= (r1)=
here: sjmp here
end

Microcontrollers Lab BTEC15F4700 P a g e | 25


REVA University School of ECE

Example: 13
COMPLIMENT instruction

org 0000h
mov a,#23h ; (a) =
cpl a ; (a) =
here: sjmp here
end

Example: 14
Clear Instruction

org 0000h
mov a,#34h ; (a) =
clr a ;(a) =
here: sjmp here
end

Example: 15
Exchange Operation
org 0000h
mov a,#23h ; (a) =
mov r1,#45h ; (r1)
xch a,@r1 ; (a) =
xch a,01h
xch a,@r1
here: sjmp here
end

Example: 16
Increment & Decrement Operations

org 0000h
sjmp 30h
mov a,#45h ; (a)=
mov r1,#27h ; (r1)=
dec r1 ;(r1)=
dec a
dec @r1
inc r1 ; (r1)=
inc a ; (a)=
inc @r1
inc dptr ; (dptr)=
end

Microcontrollers Lab BTEC15F4700 P a g e | 26


REVA University School of ECE

Example: 17
Decimal Adjustment operations
org 0000h
mov b,#27h ; (b) =
mov a,#45h ; (a) =
add ab ; (a) =
da a ; (a) =
here: sjmp here
end

Example:18
Jump Operations

org 0000h
sjmp 30h
org 30h
mov a,#55h ; (a)=
mov r1,#34h ; (r1)=
add a,r1 ; (a)=
jc loop
jnc loop1
jb c,loop
jnb c,loop1
jbc 08h,loop

loop: clr c ; c flag =


loop1: setb c ; c flag =
mov a,#45h ; (a)=
mov r1,#45h ; (r1)=
mov 45h,#45h ; (45h)=
cjne a,01h,loop
cjne r1,#45h,loop
cjne @r1,#45h,loop
djnz 45h,loop1
dec a ; (a)=
jz loop ; (pc)=
jnz loop1 ; (pc)=
end

Microcontrollers Lab BTEC15F4700 P a g e | 27


REVA University School of ECE

1.DATA TRANSFER INSTRUCTIONS

Write an assembly language program to transfer n=10 bytes of data from location 8035h to
location 8050h (without overlap).

ORG 0000H
SJMP 30H
ORG 30H
MOV DPH, #80H //Initialize DPH with higher byte of source and destination address
MOV R0, #35H // Initialize R0 with lower byte of source starting address
MOV R1,#50H // Initialize R1 with lower byte of destination starting address
MOV R3,#0AH // R3 is used as a counter
BACK: MOV DPL, R0 // Load DPL with lower byte of source address
MOVX A,@dptr //Transfer the contents of source to accumulator
MOV DPL,R1 // Load DPL with lower byte of destination address

MOVX @dptr,A // Data of accumulator stored in destination


INC R0 // Increment source pointer
INC R1 // Increment destination pointer
DJNZ R3, BACK //Decrement the counter and repeat the loop until the counter is
zero
HERE: SJMP HERE
END

RESULT:
Before Execution: 10 locations X:8035h are filled up with data.

After Execution: 10 location X:8050h are filled up with data from 8035h.

Microcontrollers Lab BTEC15F4700 P a g e | 28


REVA University School of ECE

Write an assembly language program to transfer n=10 bytes of data from location 8035h to
location 8038h (with overlap).

ORG 0000H
SJMP 30H
ORG 30H
MOV DPH, #80H //Initialize DPH with higher byte of source and destination address
MOV R0, #3EH // Initialize R0 with lower byte of source ending address
MOV R1,#41H // Initialize R1 with lower byte of destination ending address
MOV R3,#0AH // R3 is used as a counter
BACK: MOV DPL, R0 // Load DPL with lower byte of source address
MOVX A,@dptr //Transfer the contents of source to accumulator
MOV DPL,R1 // Load DPL with lower byte of destination address
MOVX @dptr,A // Data of accumulator stored in destination
DEC R0 // decrement source pointer
DEC R1 // decrement destination pointer
DJNZ R3, BACK //Decrement the counter and repeat the loop until the
counter is zero

HERE: SJMP HERE


END

RESULT:
Before Execution: 10 locations X:8035h are filled up with data.

After Execution: 10 location X:8041h are filled up with data from 803Eh.

Algorithm
1. Initialize registers to hold count data & also the source & destination addresses.
2. Get data from source location into accumulator and transfer to the destination location.
3. Decrement the count register and repeat step 2 till count is zero
Note: For data transfer with overlap start transferring data from the last location of source
array to the last location of the destination array

Microcontrollers Lab BTEC15F4700 P a g e | 29


REVA University School of ECE

ASSEMBLAY LANGUAGE PROGRAM TO EXCHANGE A BLOCK OF DATA.


2.Write an assembly language program to exchange n=5 bytes of data at location 0027 and
at location 0041h.

ORG 00H
SJMP 30H
ORG 30H
MOV R0,#27H // Initialize R0 with starting address of first memory block.
MOV R1,#41H // Initialize R1 with starting address of second memory block.
MOV R3,#05H // R3 is used as counter
BACK: MOVX A,@R0 // Load accumulator with contents of first memory block.
MOV R2,A //R2 is used to store Intermediately the content of first memory block.

MOVX A,@R1 //Load accumulator with the contents of second memory block.

MOVX @r0,a //Load accumulator contents to first memory block.


MOV a,r2 //Load accumulator with contents of first memory block.
movx @r1,a //Load accumulator contents to second memory block.

INC R0 // Increment first memory block pointer


INC R1 // Increment second memory block pointer
DJNZ R3, BACK // Decrement the counter till it is zero.
HERE: SJMP HERE
END

Alter using XCH command.


ORG 0000H
SJMP 30H
ORG 30H
MOV R0,#27H //source address
MOV R1,#41H //destination address
MOV R3, #05H // count
BACK: MOVX A,@r0
MOV r2,a
MOVX a,@r1
MOVX @r0,a
XCH a,r2
MOVX @r1,a
INC R0
INC R1
DJNZ R3, BACK
HERE: SJMP HERE
END
Note: XCH instruction directly exchanges source and destination contents. No intermediate
register is required.

Microcontrollers Lab BTEC15F4700 P a g e | 30


REVA University School of ECE

RESULT:
Before Execution: 5 location at X:8027h & X:8041h are filled up with data

After Execution: The data at X:8027h & 8041h are exchanged.

Algorithm
Initialize registers to hold count data (array size) & also the source & destination
addresses.
Get data from source location in to accumulator and save in a register.
Get data from the destination location in to accumulator.
Exchange the data at the two memory locations.
Decrement the count register and repeat from step 2 to 4 till count is zero.

Microcontrollers Lab BTEC15F4700 P a g e | 31


REVA University School of ECE

3) ASSEMBLY LANGUAGE PROGRAM TO SORT NUMBERS.


// BUBBLE SORT PROGRAM
Write an assembly language program to an to sort an array of n=6 bytes of data in
descending order stored from location 9000h. (use bubble sort algorithm)

Org 0000h
Sjmp 30h
Org 30h
Mov r0,#05h
L1:mov dptr,#9000h
Mov a,r0
Mov r1,a
L2:movx a,@dptr
Mov b,a
Inc dptr
Movx a,@dptr
Clr c
Mov r2,a
Subb a,b
Jc noexchg
Mov a,b
Movx @dptr,a
Dec dpl
Mov a,r2
Movx @dptr,a
Inc dptr
Noexchg:djnz r1,l2
Djnz r0,l1
Here:sjmp here
End

Algorithm
Store the elements of the array from the address 9000h
Initialize a pass counter with array size-1 count (for number of passes).
Load compare counter with pass counter contents & initialize DPTR to point to the
start address of the array (here 9000h).
Store the current and the next array elements pointed by DPTR in registers B
and r2 respectively.
subtract the next element from the current element.
If the carry flag is set (for ascending order) then exchange the 2 numbers in the array.
Decrement the compare counter and repeat through step 4 until the counter becomes 0.
Decrement the pass counter and repeat through step 3 until the counter becomes 0.

Microcontrollers Lab BTEC15F4700 P a g e | 32


REVA University School of ECE

RESULT:
Before execution: Unsorted array at 9000h

After Execution: Sorted Array (Descending order ) at 9000h

4). Write an assembly language program to find the largest element in a given string of n=6
bytes at location 4000h. Store the element at location 4062h.

ORG 0000H
SJMP 30H
ORG 30H
MOV R3,#05H //length of the array
MOV DPTR,#4000H //starting address of the array
MOVX A,@ DPTR
MOV r1,a
NEXTBYTE: INC DPTR
MOVX A, @DPTR
CLR C // RESET BORROW FLAG
MOV R2,A // next number in the array
SUBB A, R1 // OTHER Num – PREVIOUS LARGEST NO.
JC SKIP // JNC for smallest element
MOV A,r2 // UPDATE larger number in r1
MOV R1,A
Skip: DJNZ R3, NEXTBYTE
MOV DPL, #62H // LOCATION OF THE RESULT- 4062H
MOV A,R1 //LARGEST NUMBER
MOVX @DPTR,A //STORE AT#4062H
OVER: SJMP OVER
END

Microcontrollers Lab BTEC15F4700 P a g e | 33


REVA University School of ECE

Algorithm
Store the elements of the array the address 4000h
Store the length of the array in r3 and set it as counter
DPTR is loaded with starting address of the array
Store the first number of the array in r1 (r1 is assigned to hold the largest number)
Increment DPTR
Subtract the number pointed by DPTR from the contents of r1 (to compare whether the next
array element is larger than the one in r1)
If the element pointed by DPTR is larger then load the larger number in to r1
Decrement the counter and repeat through 5 until the counter becomes 0
Store the largest number in r1 in address 4062h

RESULT:
Before execution: After Execution: Location 4062 has the largest element.

Microcontrollers Lab BTEC15F4700 P a g e | 34


REVA University School of ECE

II) ARITHMETIC INSTRUCTIONS


ASSEMBLY LANGUAGE PROGRAM ILLUSTRATING ADDITION, SUBTRACTION,
MULTICATION AND DIVISION.

5) Write an ALP to perform the following:


If x=0 perform w + v; else if x=1 – perform w- v; else if x=2-perform w*v; else if x=3 –
perform w/v, where w & V are eight bit numbers.

ORG 0000H
SJMP 30H
ORG 30H
MOV R0, #40H
MOVX A,@R0
MOV R1,A //R1 HAS CONDITION
INC R0
MOVX A,@R0
MOV B, A //B HAS 1ST NUMBER -V
INC R0
MOVX A,@R0 // A HAS 2ND NUMBER-W
CJNE R1,#00,CKSUB
ADD A,B // PERFORM ADDITION
MOV B,#00 //BHAS CARRY
JNC SKIP
MOV B,#01H
SKIP:SJMP LAST
CKSUB: CJNE R1,#01,CKMUL
CLR C
SUBB A,B
MOV B,#00 //B INDICATES BORROW
JNC SKIP1
MOV B,#0FFH //FF INDICATES NEGA NUMBER
SKIP1:SJMP LAST
CKMUL: CJNE R1,#02,CKDIV
MUL AB //16 bit product in AB with A having lower byte
SJMP LAST
CKDIV: CJNE R1,#03,OTHER
DIV AB
SJMP LAST
OTHER:MOV A,#00
MOV B,#00
LAST: INC R0
MOVX @R0,A
INC R0
MOV A,B
MOVX @R0,A
HERE:SJMP HERE
END

Microcontrollers Lab BTEC15F4700 P a g e | 35


REVA University School of ECE

Algorithm
Store the condition x in r1
Load the first and second numbers to A and B registers respectively
Compare the contents of r1 perform the operations add, sub etc accordingly.
Store the result present in A and B registers to the appropriate memory locations

RESULT: Before execution: ADD After Execution: ADD

After Execution: SUB After Execution:sub

Before Execution: MUL After Execution: MUL

Before Execution: Divi After Execution: Divi

Microcontrollers Lab BTEC15F4700 P a g e | 36


REVA University School of ECE

ASSEMBLY PROGAM ILUSTRATING SQURE AND CUBE OPERATIONS.


//cube is an example of 16 –bit arithmetic operation.
// depending on flag condition, square or cube is performed
//flag is a bit in the bit addressable RAM, say 1, bit location 20h is used, then bit address is
00

6)An eight bit number X is stored in external memory location 9000h.write an ALP to
compute (i) the square of the number X if LSB of data RAM 20h (bit address
00H) is set (ii) the cube of the number X if LSB of data RAM 20h (bit address 00) is reset.
Store your result at locations 9001,9002,9003h.

ORG 0000H
SJMP 30H
ORG 30H
MOV DPTR,#9000H
MOVX A,@DPTR //GET NUMBER-X
MOV R0,A //STORE IN R0
MOV B,A
MUL AB //SQUARE IT - X^2
CLR C //FOR STORING RESULT
JB 00,LAST //IF BIT 01 IS SET THEN END,ELSE DO CUBE
PUSH B //STORE UPPER PART OF SQUARE
MOV B,A //B-L UPPER PART OF X^2
MOV A,R0 //A-X
MUL AB //X*lower X^2
INC DPTR //X*LOWER X^2
MOVX @DPTR,A //STORE PARTIAL RESULT
MOV A,B
MOV R2,A //UPPER PART OF X*LOWER X^2IN R2
POP B //GET BACK UPPER PART OF SQUARE
MOV A,R0 //A-X
MUL AB //X*UPPER X^2
ADD A,R2 //ADD TO PARTIAL RESULT
LAST:INC DPTR
MOVX @DPTR,A
MOV A,B
ADDC A,#00 //ADD CARRY TO B(FOR SQUQRE RESULT,C=0)
INC DPTR
MOVX @DPTR,A
HERE:SJMP HERE
END

Microcontrollers Lab BTEC15F4700 P a g e | 37


REVA University School of ECE

RESULT:
CUBE OF 56H IS 9B498 WHICH IS STORED AS 98,B4,98 (LOWER BYTE FIRST)

Before: Execution After:Execution

Before Execution: Squar After Execution: Squar

To get square make the D0 bit of memory 20h high, say FF,01,03, etc. the bit address is
01.similary bit address 78h correspond to D0 bit of data ram location 2fh.
Algorithm:
Store the eight bit number x in A, r0 & B registers.
Multiply A and B registers to obtain the square (say SQH:SQL) of the number X.
Check if bit 01 is set. if set go to end (storing the result),else do the cube operations.
The high part of the square result (SQH) is stored on the stack.
Multiply the low part of the square result (SQL) with X (partial cube result).
Store the low part of the above result at 900h & the part in R2.
Retrieve the high part of the square result (SQH) stored on the stack & multiply with x.
Add the low part of the above result (SQH*X) with R2 and store in 9002h.
Add the high part (SQH*X) with the resulting carry and store in 9003.
Microcontrollers Lab BTEC15F4700 P a g e | 38
REVA University School of ECE

III) PROGRAM ILSTRATING BIT MANIPULATIONS


7) Two eight bit NUM1 & NUM2are stored in external memory locations 8000h & 8001h
respectively. Write an ALP to compare the 2 nos.
Reflect your result as: if NUM1 > NUM2, SET LSB of data RAM 2F (bit address 78H) If
NUM1< NUM2,SET MSB OF 2F (7FH).if NUM1=NUM2-clear both LSB &MSB of bit
addressable memory location 2Fh

ORG 0000H
SJMP 30H
ORG 30H
MOV DPTR,#8000H
MOVX A,@DPTR
MOV R0,A
INC DPTR
MOVX A,@DPTR
CLR C
SUBB A,R0
JZ EQUAL
JNC N2GREATER
CLR 7FH
SETB 78H
SJMP END1
N2GREATER:CLR 78H
SETB 7FH
SJMP END1
EQUAL:CLR 78H
CLR 7FH
END1:SJMP END1
END

Algorithm:
Store the elements of the array from the address 4000h
Move the fist number in r0 and the second number in register A respectively
Clear carry flag and subtract the two numbers, if the carry flag is 0 (if the nos are equal ),
clear both LSB & MSB of bit addressable memory location 2Fh
If the carry bit is set then set MSB of 2F (7FH), else LSB of data RAM 2F (bit address 78H).

Result :
1 ) Before execution: X:08000h = 45 & X:8001 = 35 after Execution: D:02FH = 01
2) Before execution: X;08000h = 25 & X:8001 = 35 After execution: D:02FH = 80
3) Before execution: X:08000h = 45 & X:80001 = 45 After execution: D:02FH = 00

Microcontrollers Lab BTEC15F4700 P a g e | 39


REVA University School of ECE

IV) LOGICAL INSTRUCTIONS


8) ASSEMBLY PROGRAM ILLUSTRATING LOGICAL INSTIONS (BYTE LEVEL)
3eight bit numbers X, NUM1 & NUM2 are stored in internal data RAM location 20h. 21h &
22H respectively .write an ALP to compute the following.
IF X=0 THENNUM1 (AND) NUM2, IF X=1; THEN NUM1(OR) NUM2,
IF X=2; THEN NUM1 (XOR) NUM2, ELSE RES = 00 RES IS 23H LOCATION

ORG 0000H
SJMP 30H
ORG 30H
MOV A, 20h // do not use #, as data ram 20h is to be accessed
MOV R1,A //X IN R1
MOV A,21H //A-NUM1
CJNE R1,#0,CKOR
ANL A, 22H
SJMP END1
CKOR:CJNE R1,#01, CKXOR
ORL A, 22H
SJMP END1
CKXOR:CJNE R1,#02,OTHER
XRL A, 22H
SJMP END1
OTHER: CLR A
END1: MOV 23H,A //STORE RESULT
HERE:SJMP HERE
END

Algorithm:
Point to the data RAM register 20h and store the condition x.
Point to 21h and 22h and mov the first number to A register.
Compare the contents of r1 and perform the operations accordingly
The result will be stored in 23H register.
RESULT: 1) Before Execution: D:020H = 00, 21 = 0F, 22 = 12 after execution D:023H = 02
2) Before execution D: 020H = 01, 21 = 0F, 22 = 12 After execution D: 023H = IF
3) Before execution D: 020H = 02, 21=0F, 22=12 After execution D: 023H =ID
4) Before execution D: 020H = 34, 21 = 0F, 22=12 After execution D: 023H = 00

Microcontrollers Lab BTEC15F4700 P a g e | 40


REVA University School of ECE

The above program can also written as shown below (using indirect addressing)

ORG 0000H
SJMP 30H
ORG 30H
Mov r0,#20h
MOV A,@R0 //ON CHIP DATA RAM-DONOT MOVX
MOV R1,A //X IN R1
INC R0
MOV A,@R0 //A-NUM1
INC R0 // R0 POINTS TO NUM2
CJNE R1,#0,CKOR
ANL A,@R0
SJMP END1
CKOR:CJNE R1,#01, CKXOR
ORL A, @R0
SJMP END1
CKXOR:CJNE R1,#02,OTHER
XRL A, @R0
SJMP END1
OTHER: CLR A
END1:INC R0
MOV @R0,A //STORE RESULT
HERE:SJMP HERE
END

Microcontrollers Lab BTEC15F4700 P a g e | 41


REVA University School of ECE

Boolean variable instructions are also called bit level logical instructions
9) 3 eight bit numbers X, NUM1 & NUM2 are stored in internal data RAM locations 20h,
21h & 22H respectively. Write an ALP to compute the following.
IF X=0; THEN LSB OF NUM1 (AND) LSB OF NUM2,
IF X=1; THEN MSB OF NUM1 (OR) MSB OF NUM2,
IF X=2; THEN COMPLEMENT MSB OF NUM1
STORE THE BIT RESULT IN RES, WHERW RES IS MSB OF 23H LOCSTION

ORG 00H
SJMP 30h
ORG 30h
MOV R0,20H //R0-X
CJNE R0,#0,CK1
MOV C, 08H //LSB OF NUM1 (21H)-BIT ADDRESS-08
ANL C,10H
SJMP LAST //LSB OF NUM2(22H)-BIT ADDRESS-10
CK1:CJNE R0,#1,CK2
MOV C,0FH //MSB OF NUM1(21H) – BIT ADDRESS-OF
ORL C,17H //MSB OF NUM2(22H) – BIT ADDRESS -17
SJMP LAST
CK2:CJNE R0,#2,CK3
MOV C,0FH //MSB OF NUM1(21H) – BIT ADDRESS –OF
CPL C
SJMP LAST
CK3:CLR C
LAST:MOV 1FH,C //RES IS OF 23H LOCATION -1FH
HERE:SJMP HERE
END

RESULT: 20H= 00 => AND OF LSBs=1 (hence 80 in 23h location) 20h = 01 = > OR of MSBs
= 0 (hence 00 in 23h location )

Microcontrollers Lab BTEC15F4700 P a g e | 42


REVA University School of ECE

Algorithm:
Move the condition X (from 20h location) into R0 register
If X=0: then move LSB bit of 21h to carry flag and ‘AND’ carry flag with LSB bit of 22h. Go
to step5
IF X=1: then complement MSB bit 21h to carry and ‘OR’ carry flag with MSB bit of 22h. GO
to step5
If X=0: then complement MSB bit of 21h and move it to carry flag. Goto step5
Store carry flag at MSB bit of 23h location.

V) COUNTERS
ASSEMBLY PROGRAM ILLUSTRATING HEX UP/DOWN COUNTERS.
counter program-hex/binary counters

10) Write an ALP to implement (display) an eight bit up/down binary (hex) counters on
watch window.
Note: to run this program, after selecting DEBUG session in the main menu use
View-> watch& call stack window, in the watches select watch 1(or 2) and
Press F2and enter a (for accumulator A)

ORG 00H
SJMP 30H
ORG 30H
MOV a,#00
BACK: ACALL DELAY
INC a //DEC A BINARY DOW COUNTER
JNZ BACK
HERE:SJMP HERE
DELAY: MOV r1,#0FFH
DECR1:MOV r2,#0FFH
DECR: MOV r3,#0FFH
DJNZ r3,$
DJNZ r2,DECR
DJNZ r1,DECR1
RET
END
RESULT: Accumulator A is incremented in binary from 00, 01,
02,……09,0A,0B,….OF,10,11,……FF

Microcontrollers Lab BTEC15F4700 P a g e | 43


REVA University School of ECE

Algorithm:
Move 00 to A register
Call the delay subroutine for 1 second, in delay program move FFH to registers r1, r2 and
r3, loop and decrement until 0.
Increment A register (decrement for down counter)

ASSEMBLY PROGRAM ILLUSTRATING BCD UP/DOWN COUNTERS.


// counter program – BCD up/down counters
11) Write an ALP to implement (display) an eight bit up/down BCD counters on watch
window.
ORG 00H
SJMP 30H
ORG 30H
MOV a,#00
BACK:ACALL DELAY
ADD A,#99H //ADD01 for BCD upcounter
DA A //for bcd counter
JNZ BACK
HERE:SJMP HERE
DELAY:MOV r1,#0FFH
DECR1:MOV r2,#0FFH
DECR:MOV r3,#0FFH
DJNZ r3,$
DJNZ r2, DECR
DJNZ r1, DECR1
RET
END

Algorithm:
Move 00 to A register
Call the delay subroutine for 1 second (in delay program move FFH to registers r1,r2 and r3,
loop and decrement 0).
Increment A register(add 99h for the down counter)
Decimal adjust accumulator for the BCD up/down counter.

RESULT: Accumulator A is incremented in BCD from 00, 01, 02…..09, 10, 11,..99.

Microcontrollers Lab BTEC15F4700 P a g e | 44


REVA University School of ECE

VI) SERAL DATA TRANSMISSION


Program illustrating serial data transmission (data-Y E)
Note to use result of this program, after selecting DEBUG session in the main menu use
View-> serial window #1. On running & halting the program, the data is seen in the serial
window.
12) Conduct an experiment to configure 8051 microcontroller to transmit characters (yE) to
a pc using the serial port and display on the serial window.

ORG 00H
SJMP 30H
ORG 30H
MOV TMOD,#20H //timer 1:mode 2
MOV TH1,#-3 //-3=FD loaded in to THI for 9600 baud,11.0592MHZ.
MOV SCON,#50H //8-bit,1 stop bit REN enabled
SETB TR1 //start timer 1
AGAIN:MOV A,#’Y’ //transfer ”Y”
ACALL TRANS
MOV a,#’E’ //transfer “E”
A CALL TRANS
AGAIN1:SJMP AGAIN1
TRANS:MOV SBUF,a //load SBUF
HERE:JNB TI,HERE //wait for last bit to transfer
CLR TI //get ready for next byte
RET
END

RESULT: YE is printed on the serial window each time the program is executed.
Theory: In serial transmission as opposed to parallel transmission, one bit at a time is
transmitted. In serial asynchronous transmission, the data consists of a stat bit
(high),followed by 8 bites of data to be transmitted and finally the stop bit. The byte
character to be transmitted is written in to the SUBF register. It transmits the start bit.
The 8-bit character is transferred one bit at a time. The stop bit transferred. After the
transmission, the TI flag = 1 indicating the completion of transmission. Hence in the
subroutine wait until TI is set. Later clear the TI flag and continue with transmission of the
next byte by writing in to the SBUF register. (the program can also be written in interrupt
mode). The speed of the serial transmission is set by the baud rate which is done with the
help of timer speed of the serial transmission is set by the baud rate which is done with the
help of timer 1. (Refer Ayala).Timer 1 must be programmed in mode 2(that is,8-bit, auto
reload).
Baud rate calculation: crystal freq/(12*32) = (11.059MHz)/(12*32) = 28800.
Serial communication circuit divides the cycle frequency (11.0592MHz)/(12) by 32 before it
is being used by loading timer 1 with -3 (i.e., FF – 3 =FD) for further clock division. For 2400
baud rate, 28800/12 =>-12 = F4 in TH1.

Microcontrollers Lab BTEC15F4700 P a g e | 45


REVA University School of ECE

Algorithm:
Initialize timer 1 to operate in mode 2 by loading TMOD register.
Load TH1 with with-3 to obtain 9600 baud.
Initialize the asynchronous serial communication transmission (SCON) register.
Start timer 1 to generate the baud rate clock.
Transmit the characters “Y” & “E” by writing the SBUF register and waiting for the TI flag.

VII) TIMER DELAY PROGRAM


Program illustrating timer delay
13) Generate a 1 second delay continuously using the on chip timer in interrupt mode

ORG 00H //Reset vector


SJMP 30H

ORG 0BH //TFO vector


SJMP ISR

ORG 30H
MOV a,#00
MOV R0,#0
MOV R1,#0
MOV TMOD,#02H //00000010=run timer 0 in mode 2
MOV TH0,#118 //set up timer 0 to overflow in 0.05msec
MOV IE,#82H //%10000010-enable timer 0 interrupt
SETB TCON.4 //start the timer 0
HERE:SJMP HERE

ISR: CLR TCON.4 //disable timer 0


INC r1 //r1*r2 = 100*200 = 20000 * 0.05msec = 1sec
CJNE r1,#100,SKIP
MOV r1,#00
INC r0
CJNE r0,#200,SKIP
MOV r0,#00H
INC a
SKIP: SETB TCON.4 //enable timer
RETI //Return from interrupt subroutine
END

RESULT: Accumulator A is incremented in binary from


00,01,02…09,0A,0B,….0F,10,11,…FF every 1 second (for 33MHz clock setting and every 3
seconds for 11.0598 MHz)

Microcontrollers Lab BTEC15F4700 P a g e | 46


REVA University School of ECE

Algorithm:
Set up timer 0 in mode 2 operation
Load TH1 with 118 to generate an interrupt every 0.05 msec.
Reset registers a, r1 and r0.
Repeat step 4 continuously.
On interrupt; ISR at 000B location goes to step 6.
Disable timer0.
Update r1 and r0
Check if 20000 interrupts (= 1 sec) over. Yes – increment accumulator a.
Enable timer and return from ISR.

T MOD FUNCTION REGISTER


7 6 5 4 3 2 1 0
Gate C / M1 M0 Gate C / T M1 M0
T

[ TIMER 1 ][ TIMER0 ]

Bit symbol Function M1 M0 Mode


OR gate enable bit 0 0 0-13 bit timer
TC ON
which
Gate FUNCTION
7/3 Controls Runs/stop of 0 1 1-16 bit timer
REGISTER
timer 1/0
Set to 1-by program to 1 0 2-8 bit
make reloadable
timer 1/0 act as a timer
counter by 1 1 3-timer0-2-8
6/2 C/T bit
counting pulses from
external Timers
inputs pins 3.5 (T1) or Timer1 stop
3.4(TO)
Timer/counter
5/1 M1 operating mode
select bit 1
Timer/counter
4/0 M0 operating mode
select bit 0

Microcontrollers Lab BTEC15F4700 P a g e | 47


REVA University School of ECE

7 6 5 4 3 2 1 0
TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0

Bit Symbol Function


7 TF1 Timer 1 overflow flag INTER ADDRESS(HEX)
6 TR1 Timer 1 run control bit ROPT
5 TF0 Timer 0 overflow flag Ti IE0 0003
4 TR0 Timer 0 run control me TFO 000B
r
3 IE1 External interrupt 1edge flag TE1 0013
del
2 IT1 External interrupt 1 signal type TF1 001B
ay
control bit SERIAL 0023
=
1 IE0 External interrupt 0 edge flag 12*(157)/ frequency
0 IT0 External interrupt 0 signal type Timer delay =0.05 msec
control bit Delay =256-((timer delay *
frequency)/12) = 256-(0.05* 10-3*33*10 6)/12
=256-137.5 =118.5 //loaded in THO
To get 1 sec delay
1/0.05mesc = 200*100 in the ISR
(Assuming 33 MHZ crystal frequency. For 11 MHz, the calculations change).

VIII) CONVERSION PROGRAMS

14) Write an ALP to implement decimal to hex conversion

ORG 0000H
SJMP 30h
ORG 30h
MOV DPTR,#40H //2-digit decimal number to be converted is given in data Memory 40h
MOVX A, @DPTR
ANL A, #0F0H //obtain upper decimal digt
SWAP A //bring to the unites place
MOV B,#0AH //MULTIPLY tens digit with #0A-toget tens in hex
MUL AB
MOV r1,a //temporarily store the converted tens value
MOVX A,@DPTR //get the decimal number again
ANL A,#0FH //obtain the unites digit
ADD A,R1 //add to converted tens value
INC DPTR //increment data address
MOVX @DPTR,A //converted hexadecimal number in next location
HERE:SJMP HERE
END

RESULT: before execution- X: 0040H = 45 (DECIMAL/BCD)


After execution: X: 0041h= 2D(hex value)
Microcontrollers Lab BTEC15F4700 P a g e | 48
REVA University School of ECE

Algorithm:
Move the decimal data to be converted from external memory 40h to accumulator.
AND A reg with 0f0h and obtain in upper MSB of the decimal digit and swap the LSB and
MSB of accumulator to bring same to unites place.
Move 0ah to B register and multiply with A reg to convert to hex value, store the converted
tens value in r1.
Get the LSB of the decimal number and add to converted tens value.
Point to next memory location and stores the result (hexadecimal).

15) Write an ALP to implement hex to decimal conversion

ORG 0000H
SJMP 30h
ORG 30h
MOV DPTR,#9000H
MOVX A,@DPTR //Get hex number
MOV B,#10
DIV AB //dine by 10 (0AH)
INC DPTR
XCH A,B
MOVX @DPTR,A //store the remainder (in B ) in units place
XCH A,B
MOV B,#10 // divide the quotient in A by 10
DIV AB
INC DPTR
XCH A,B
MOVX @DPTR,A //Store the remainder (in B) in tens place
XCH A,B
INC DPTR
MOVX @DPTR,A //Store the quotient (in A) hundreds place
HERE:SJMP HERE
END

RESULT: 9000H-FF (HEX NUMBER)


9001 to 9003 – unpacked BCD number (decimal)-5,5,2 (i.e.,255 stored lower digit first)

Algorithm
Move the hex data to be converted to accumulator
Move 10 to B register and divide with A reg to convert to ascii value
Store the converted LSB value in r7
Repeat the step 2 to obtain the converted MSB value
Microcontrollers Lab BTEC15F4700 P a g e | 49
REVA University School of ECE

Store the same in r6


16) Write an ALP to implement BCD to ASCII conversion

ORG 0000H
SJMP 30h
ORG 30h
MOV R1 ,#50H
MOV A,@R1 //get BCD data byte from RAM location 50h
MOV R2,A //store in R2
ANL A,#0FH //get the lower nibble
ORL A,#30H //ADD/or with 30hi..e., 0-9 converted to 30-39h
INC R1
MOV @R1,A // store the lower digit’s
MOV A,R2 //get back the number
SWAP A //swap nibbles in A
ANL A,#0FH //get the upper BCD digit
ORL A,#30H // convert to ASCII
INC R1
MOV @R1,A //store the upper digit’s ASCIL codes-38h 32h
here: sjmp here
END

RESULT: The BCD code 28 at D:0050h is converted to ASCII code-38h 32h

Microcontrollers Lab BTEC15F4700 P a g e | 50


REVA University School of ECE

HARDWARE INTERFACING

1.Waveform generation using dual DAC.


2.Stepper motor interface.
3.3X8 hexadecimal keyboard interface.
4.DC motor interface

Features of embedded C
C is a simple programming language and so very easy to code.
Embedded C has most features of C-language with more stress on certain bit manipulative
instructions.
This feature make it easy to write program for µC and µP.
Keil is a versatile software with a cross compiler that will convert the C program to
assembly language and the program can be executed in the desired target (say 8051).

Some of the bit manipulative instructions used are


Symbol operation
& Bitwise AND
| Bitwise OR
~ Bitwise NOT
>> shift right
<< shift left
^ P0.0

Microcontrollers Lab BTEC15F4700 P a g e | 51


REVA University School of ECE

Microcontrollers Lab BTEC15F4700 P a g e | 52


REVA University School of ECE

Dual DAC interface to generate

Square waveform
Triangular waveform
Ramp waveform
Sine waveform

Block diagram:

Microcontrollers Lab BTEC15F4700 P a g e | 53


REVA University School of ECE

1. a) Algorithm for square wave generation


Let initial amplitude of the square wave be 2.5 v(7F) and frequency count 100.
Output the values 00h(OFF) and 7fh (on) values through P0.
If amplitude key is pressed them increase the voltage in steps of 0.15v(8).
If the frequency key is pressed increment the count in steps of 50.if the count exceeds
1000 reset it back to 100.
Every time amplitude and frequency change output the value thro P0 and note the
waveform on CRO.

Waveform:

Program for square wave

#include <REG51xD2.H>
sbit Amp =P3^3; /* port line to change amplitude */
sbit Fre =P3^2; /*port line to change frequency */
void delay(unsigned int X) /* delay routine */
{
for(;X>0;X--);
}
main()
{
unsigned char on = 0x7f,off=0x00;
unsigned int count = 100;
while(1)
{
if (!Amp) /* if user choice to change amplitude */
{
while(!Amp); /*wait for key relese */
on+=0x08; /*increase the amplitude */
}
if(!Fre) /*if user choice is to change frequency */
{
if(count > 1000) /*if frequency exceeds 1000 reset */
count = 100;
Microcontrollers Lab BTEC15F4700 P a g e | 54
REVA University School of ECE

while(!Fre); /*wait for key release */


count+=50;} /* increase the frequency */
P0=on; /*write amplitude to port */
P1=on;
delay(count);
P0=off; /*clear port */
P1=off;
delay(count);
}}

b) Algorithm for triangular wave generation

Output the initial value 00 through P0.


Increment it in steps of 1 until a count value of FFh (5v) is reached. every time repeat step
1.
Decrement it in steps of 1 until a zero value is reached and repeat step 1.

Waveform:

Program for triangular wave

#include <REG51xD2.H>
main()
{
unsigned char i=0;
P0=0x00; /* P0 as output port */
while(1)
{
Microcontrollers Lab BTEC15F4700 P a g e | 55
REVA University School of ECE

for(i=0;i<0xff;i++) /*generate ON pulse */


{
P1=i;
P0=i;
}
for(i=0xfe;i>0x00;i--) /*generate OFF pulse */
{
P0=i;
P1=i;
}
}
}

c). Algorithm for Ramp wave generation

Output the initial value 00 through P0.


Increment it in steps of 1 until a count value of FFh (5V) is reached every time repeat step
1.
Repeat step 1 & 2.

Waveform:

Program for ramp waveform

#include <REG51xD2.H>
main ()
{ unsigned char i=0;
P0=0x00; /* P0 as output port */
while (1)
{
for (i=0;i<0xff;i++) /*generate ON pulse */
Microcontrollers Lab BTEC15F4700 P a g e | 56
REVA University School of ECE

{
P1=i;
P0=i;
}
}
}

d). Algorithm for for sine wave

Compute different step values (θ = 0°, 30°, 60°, 90°, 120°, 150°, 180°, 210°, 240°, 270°,
300°, 330°, 360°.) of sine using the equation.

Output the values thro P0.


More the steps smoother will be sine wave.

The value sent to DAC is = 128d.

Waveform:

Microcontrollers Lab BTEC15F4700 P a g e | 57


REVA University School of ECE

Program for sine wave

#include <REG51xD2.H>
main()
{
static int a[13]={128,192,238,255,238,192,128,64,17,0,17,64,128};
unsigned char i=0;
P0 = 0x00; /*P0 output port */
while(1)
{
for(i=0;i<13;i++) /*output different values
{ P0=a[i];
P1=a[i];
}
}
}

Microcontrollers Lab BTEC15F4700 P a g e | 58


REVA University School of ECE

2). STEPER MOTOR


Stepper motor interfacing to 8051
A stepper motor translates electrical pulses into mechanical movement. A conventional
motor (AC/DC motor) shaft run freely, whereas the stepper motor shaft moves in a fixed
increment & hence the shaft position can be controlled precisely, say move by 4° & stop.
Stepper motors are used for position control applications such as dot matrix printers, disk
drivers, robotics, etc.
There are two types of stepper motors (SM) --- permanent magnet SM & variable
reluctance SM, depending on the rotor type (whether permanent magnet is used or not). The
permanent magnet SM consists of a permanent magnet rotor) also called the shaft)
surrounded by a stator as shown in fig a. Generally the stator has 4 windings that are
paired with a center-tapped common as shown in fig b. The centre tap allows a change of
current direction in each of the two coils, hence changing the direction of polarity in the
stator poles which return leads to a change in the direction of rotor rotation.
The rotation of the rotor in a SM along the winding energization sequence is shown in
table.
Depending on the number of teeth on the stator & rotor, the stepper motor rotates fixed
steps per revolution. The commonly available number of steps for one revolution is 500, 200,
180, 144, 72, 48, and 24. The steps angle, i.e., the movement of a single step of a stepper
motor is calculated as . Say for 200 steps per revolution. The step angle is

per step.

Similarly step angle for 72 steps per revolution is .


For the 4-step switching sequence shown above, after four steps the same two windings
will be ‘ON’, i.e., the sequence repeats after every 4 steps. After completing 4 steps, the rotor
moves only one tooth pitch. Hence if the rotor has 50 teeth (each teeth is one pole), the no of
steps for one complete revolution is 4 steps x 50 rotor teeth = 200 steps / revolution. Hence
for smaller step angle (i.e., more steps / revolution), the rotor must have more teeth.

To double the number of steps/revolution, say 400 instead of 200, we follow the 8-step
sequence shown in the table. Here, with this method, step size is half the original size &
hence the 8-step sequence is called ‘half stepping’.

Normal 4-step sequence.


Windings
P0.0- Step
P0.3 # A B C D Remarks

9 1 1 0 0 1 AD-ON; BC-off

Microcontrollers Lab BTEC15F4700 P a g e | 59


REVA University School of ECE

C 2 1 1 0 0 AB-ON; CD-off

6 3 0 1 1 0 AD-OFF; BC-on

3 4 0 0 1 1 AB-OFF; CD-on

Half step sequence.

Port Windings
pins

P0.0- A B C D
P0.3 Step# Remarks Action

09 1 1 0 0 1 AD = 11; BC = 00 Rotor aligned with AD mid

08 2 1 0 0 0 A = 1; BCD = 000 Rotor aligned with A

0C 3 1 1 0 0 AB = 11; CD = 00 Rotor aligned with AB mid

04 4 0 1 0 0 B = 1; A is off Rotor aligned with B

06 5 0 1 1 0 AD = 00; BC = 11 Rotor aligned with BC mid

02 6 0 0 1 0

03 7 0 0 1 1

01 8 0 0 0 1

9 Sequence repeats after 9th step

Microcontrollers Lab BTEC15F4700 P a g e | 60


REVA University School of ECE

Interfacing
Now for interfacing the stepper motor to 8051, we need to connect the 4 winding leads
to 4 port pins say P0.0 to P0.3. Since the port pins donot have the sufficient current, to drive
the stepper motor winding (needs > 10mA) a driver such as ULN 2003 consists of 4 sets of
power transistors (to supply more current) and associated diodes (to provide the
freewheeling path to each winding when it is made up off). Here separate power supplies
are used. One for 8051 and another for ULN 2003 & stepper motor. Figure c shows the
interfacing of 8051 to a stepper motor.

Stepper motor unlike DC motor rotates in steps.


Stepper motor has 4 coils which from the stator the stator and a central rotor.
Rotation depends on excitation of stator coils.
Step coil A coil B coil C coil D
1 0 0 0 1
2 1 0 0 0
3 0 1 0 0
4 0 0 1 0
Anyone these value forms the initial value. To get 360 ° revolution 200 steps are required.

Step angle = 360° /200 = 1.8°. (difference between 2 teeth).

Block diagram:

Microcontrollers Lab BTEC15F4700 P a g e | 61


REVA University School of ECE

Algorithm for stepper motor


Configure P0 as output
Apply the initial excitation of 11 to motor coils through P0.
For clockwise motion –rotate right once the excitation and repeat step 2.
For anticlockwise motion –rotate left once the excitation and repeat step 2.

Program for stepper motor interface

#include <REG51xD2.H>
void delay (unsigned int x) /*Delay routine*/
{
for(;x>0;x--);
return;
}
main ()
{
unsigned char Val,i;
P0=0x00;
Val = 0x11;
for(i=0;i<4;i++)
{
P0 = Val;
Val = Val>>1; /*Val= Val>>1; for clockwise direction */
delay (500);
}
}
Microcontrollers Lab BTEC15F4700 P a g e | 62
REVA University School of ECE

DC Motor

Block diagram:

Microcontrollers Lab BTEC15F4700 P a g e | 63


REVA University School of ECE

Algorithm for DC motor interface


Configure P0,P1 as output port and P3 as input port.
Let initially the motor rotate with half speed count 7fh.
If “INR” button IS pressed reduce the count because the speed is inversely proportional to
count.
If “DEC” button is pressed increase the count.

Program for DC motor


#include <REG51xD2.H.>
sbit inr=P3^2; //speed increment switch
sbit dcr= P3^3; // speed decrement switch
main()
{
unsigned char i=0x80;
P0 =0x7f; /*run the motor at half speed.*/
while (1)
{ if (!inr)
{ while (!inr);
if(i>10)
i=i-10; //increase the DC motor speed
}
if(!dcr)
{
while (!dcr);
if(i<0xf0)
i=i+10; //decrease the DC motor speed
}
P0=i;
} }

Microcontrollers Lab BTEC15F4700 P a g e | 64


REVA University School of ECE

3). 3X8 HEX KEYBOARD

Block diagram:

Microcontrollers Lab BTEC15F4700 P a g e | 65


REVA University School of ECE

Algorithm for keyboard interface


Configure P1 as output port to scan the rows and P0 as input port to read the column
values.
First select the last row by grounding that row. Scan the columns of entire row if a key is
pressed in that row then one of the column reds ‘0’.
If now key is pressed in the selected row all 1’s is returned. So scan next row.
repeat the action until all rows are scanned.

Program for 3X8 hex keypad.

#include <REG51xD2.H>
#include "lcd.h"
unsigned char getkey();
void delay(unsigned int);
main()
{
unsigned char key;
InitLcd(); /* Initialise LCD */
WriteString("Key Pressed="); /* Display msg on LCD */
while(1)
{
GotoXY(12,0); /* Set Cursor Position */
key = getkey(); /* Call Getkey method */
}
}
unsigned char getkey()
{
unsigned char i,j,k,indx,t;
P0=0x0ff;
P1=0x0ff;
P2 = 0x00; /* P2 as Output port */
indx = 0x00; /* Index for storing the first value of scanline */
for(i=0x00E;i>=0x00B;i<<=1) /* for 4 scanlines */
{
P2 = i; /* write data to scanline */
t = P0; /* Read readlines connected to P0*/
t = ~t;
if(t>0) /* If key press is true */
{
delay(6000); /* Delay for bouncing */
for(j=0;j<=7;j++) /* Check for 8 lines */
{
t >>=1;
if(t==0) /* if get pressed key*/
{
k = indx+j; /* Display that by converting to Ascii */
Microcontrollers Lab BTEC15F4700 P a g e | 66
REVA University School of ECE

t = k>>4;
t +=0x30;
WriteChar(t); /* Write upper nibble */
t = k & 0x0f;
if(t > 9)
t+=0x37;
else
t+=0x30;
WriteChar(t); /* write lower nibble */
return(indx+j); /* Return index of the key pressed */
}
}
}
indx += 8; /* If no key pressed increment index */
}
}

void delay(unsigned int x) /* Delay routine */


{
for(;x>0;x--);
}

Note: Add hexkeypad header file & library file (lcd.h & lcd-lib- it’s available in desktop) into
the Source Group 1, before executing the program.

Microcontrollers Lab BTEC15F4700 P a g e | 67


REVA University School of ECE

Challenge Experiment:

1. Interface 8051 to control an elevator .

2. Interface 8051 to calculator.

Microcontrollers Lab BTEC15F4700 P a g e | 68


REVA University School of ECE

Practical Exam Question Bank

a) Write an assembly language program to exchange n=5 Bytes of data at location 0027h and at
Q.1
location 0041h.

b) Write a program to generate the sine wave using dual DAC.

a) Write an assembly language program to sort an array of n=6 Bytes of data in descending order
stored from
Q.2
location9000h.(use bubble sort algorithm)

b) Write a program to rotate the stepper motor in anti clockwise direction

a) Write an assembly language program to find the largest element in a given string of n=6 Bytes
at location 4000h. Store the largest element at location 4062h.
Q.3
b) Write a program to control the speed of DC motor using the pin P3.2 for increasing the speed &
P3.3 for decreasing the speed.

a) Write an ALP to perform the following: if x=0 perform W+V; else if X=1 perform W-V; else if
X=2 perform W*V; else if X=3 perform W/V, where W & V are eight bit numbers.
Q.4
b) Write a program using dual DAC to generate a triangular wave on CRO.

a) An eight bit number X is stored in external memory location 9000h. Write an ALP to compute
(i) the square of the number X if LSB of data RAM 20h (bit address 00h) is set. (ii) The cube of
the number X if LSB of data RAM 20h (bit address 00h) is reset. Store your result at locations
Q.5
9001, 9002, 9003h.

b) Write a program to generate the ramp wave using dual DAC.

a) Two eight bit numbers Num1 & Num2 are stored in external memory locations 8000h & 8001h
respectively. Write an ALP to compare the 2 numbers. Reflect your result as: Num1>Num2, SET
LSB of data RAM 2F (bit address 78h) If Num<Num2, SET MSB of 2F (7Fh). If Num1=num2 -
Q.6
clear both LSB & MSB of bit address able memory location 2Fh.

b) Write a program to rotate the stepper motor in clockwise direction.

a) 3 eight bit numbers X, NUM1 & NUM2 are stored in internal data RAM locations 20h, 21h
&22h respectively. Write an ALP to compute the following: if X=0; then NUM1 (AND) NUM2,
Q.7 If X=1; then NUM1 (OR) NUM2, If X=2; then NUM1 (XOR) NUM2, else RES=00, RES is 23h
location where RES is the result of operation.

b) Write a program to control the speed of DC motor using the pin P3.2 for increasing the speed &

Microcontrollers Lab BTEC15F4700 P a g e | 69


REVA University School of ECE

P3.3 for decreasing the speed.

a) 3 eight bit numbers X, NUM1 & NUM2 are stored in internal data RAM locations 20h, 21h
&22h respectively. Write an ALP to compute the following : if X=0; then LSB of NUM1 (AND)
LSB of NUM2 , If X=1; then MSB of NUM1 (OR) MSB of NUM2, If X=2; then complement
Q.8
MSB of NUM1 store the bit result in RES, where RES is MSB of 23h location.

b) Write a program using dual DAC to generate a triangular wave on CRO.

a) Write an ALP to transfer n=10 Bytes from location 8035h to location 8038h (with overlap).
Q.9
b) Write a program to generate the ramp wave using dual DAC.

a) Write an ALP to implement (display) an eight bit up / down BCD counters on watch window.
Q.10
b) Write a program to generate the sine wave using dual DAC.

a) Conduct an experiment to configure 8051 microcontroller to transmit characters (REVA) to a


PC using the serial port and display on the serial window.
Q.11
b) Write a program to control the speed of DC motor using the pin P3.2 for increasing the speed &
P3.3 for decreasing the speed.

a) Generate a 1 second delay continuously using the on chip timer in interrupt mode.
Q.12
b) Write a program to rotate the stepper motor in anticlockwise direction.

a) Write an ALP to implement decimal to hex conversion.


Q.13
b) Write a program to generate a square wave using dual DAC.

a) Write an ALP to implement hex to decimal conversion.


Q.14
b) Write a program to display the value of key pressed in the on board LCD display.

a) Write an ALP to implement BCD to ASCII conversion.


Q.15
b) Write a program to display the value of key pressed in the on board LCD display.

a) Write an ALP to implement (display) an eight bit up / down binary (hex) counters on watch
window.
Q.16
b) Write a program to rotate the stepper motor in anti clockwise direction.

Q.17 a) Write an ALP to transfer n=10 Bytes from location 8035h to location 8041h (without overlap).

Microcontrollers Lab BTEC15F4700 P a g e | 70


REVA University School of ECE

b) Write a program to rotate the stepper motor in clockwise direction.

a) Write an ALP to implement BCD to ASCII conversion.


Q.18
b) Write a program to generate a square wave using dual DAC.

Microcontrollers Lab BTEC15F4700 P a g e | 71

You might also like