Professional Documents
Culture Documents
Charitable Trust
Microcontrollers Laboratory
Manual
BTEC15F4700
IV Semester
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:
CHALLENGING EXPERIMENT
11. Elevator interface to 8051.
12. Simple Calculator using 6 digit seven segment displays and Hex Keyboard
interface to 8051.
Contents
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
Course Objectives:
7. To Serial communication
Course outcomes:
Introduction to Microcontrollers:
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.
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.
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:
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.
INTERUPTS
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.
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.
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.
10) Select File from menu bar and select Save AS.
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).
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.
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.
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.
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.
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.
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.
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
Sample programs
Write result of the following instructions below for each example
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
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
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
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
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
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
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
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.
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
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
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.
RESULT:
Before Execution: 5 location at X:8027h & X:8041h are filled up with data
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.
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.
RESULT:
Before execution: Unsorted array 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
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.
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
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
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
RESULT:
CUBE OF 56H IS 9B498 WHICH IS STORED AS 98,B4,98 (LOWER BYTE FIRST)
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
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
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
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
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 )
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
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)
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.
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.
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.
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
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.
[ TIMER 1 ][ TIMER0 ]
7 6 5 4 3 2 1 0
TF1 TR1 TF0 TR0 IE1 IT1 IE0 IT0
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
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).
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
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
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
HARDWARE INTERFACING
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).
Square waveform
Triangular waveform
Ramp waveform
Sine waveform
Block diagram:
Waveform:
#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
Waveform:
#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
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;
}
}
}
Compute different step values (θ = 0°, 30°, 60°, 90°, 120°, 150°, 180°, 210°, 240°, 270°,
300°, 330°, 360°.) of sine using the equation.
Waveform:
#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];
}
}
}
per step.
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’.
9 1 1 0 0 1 AD-ON; BC-off
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
Port Windings
pins
P0.0- A B C D
P0.3 Step# Remarks Action
02 6 0 0 1 0
03 7 0 0 1 1
01 8 0 0 0 1
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.
Block diagram:
#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:
Block diagram:
#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 */
}
}
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.
Challenge Experiment:
a) Write an assembly language program to exchange n=5 Bytes of data at location 0027h and at
Q.1
location 0041h.
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)
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.
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.
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 &
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.
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) 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 (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).