Computer Architecture & Microcontrollers_ MODULE 3,
Module 3: Part 1
Programming with 8051: Simple programming examples in assembly language.
Programming with 8051
1. Simple programming examples in assembly language.
jon of 8-bit data
Write an assembly language program for 8051 microcontroller to add two 8-bit data 30H and SOH and
store the result in RG.
Solution:
MOV A, #30H ;A€30H
ADD A, #50H jA€@A+50H
; Now after addition, A contains the result
MOV R6, A RGA
Note: Additional information
WOD| MOV A, #3@H |* Opcode for “MOV A"is stored in 0000H
Dinacolaessean |" (0000H = default starting address of ROM present in
Program Counter(PC))
@@G4| MOV R6, A ‘© Innext location, data 30H is stored.
‘© Innext location (i.e, 02H), Opcode for “ADD A” is
stored.
_—_________|«._Innext location, data 50H is stored.
Code Memory '* In next location (i.e, 0004H), Opcode for “MOV R6, A”
T is stored.
oji[2|3|4]%
00 74 30 24 50 Op
10 00 00 00 00,00.
Data Memory Since default register bank is register bank 0.
© 1 2 J 4 She a | R6ofregister bank 0's at location O6H inthe internal
7 RAM.
G0 00 00 00/00 00/00 80 00
0) i ji i
416.00 00 00 60 00 00 00 0 | Resultstored in R6 means you can find the resultin
location 06H in the internal RAM.
1.2 Addition of 16-bit data
Write a program to add two 16-bit numbers. The numbers are 3CE7H and 3B8DH. Place the sum in R7 and
R6; R6 should have the lower byte.
Solutic
CRC jmake CY=0
MOV A, #OE7H load the low byte now
ADD A, #8DH jadd the low byte now
Mov R6, A j save the low byte of the sum in RS
MOV A, #3CH load the high byte
‘ADDC A, #3BH add with the carry => 3B + 3C +1 = 78 (in Hexadecimal)
MOV R7, A save the high byte of the sum
College of Engineering, Muttathara 100Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
1.3 Subtraction of 8-bit data
CLR C jmake CY=0
MOV A,#3FH ;load 3FH into A (A = 3FH)
MOV R3,#23H ;load 23H into R3 (R3 = 23H)
SUBB A,R3 ;subtract A - R3, place result in A
Note:
Ac oF 0011 1111 0011 1111
R3 = 23 0010 0011 + 1101 1101\(2's complement)
1c 1 0001 1100
0 CF=0 (step 3)
‘* The flags would be set as follows: CY = 0, AC = 0, and the programmer must look at the carry
flag to determine if the result is positive or negative.
‘* Ifthe CY = Oafter the execution of SUBB, the result is positive;
‘+ IF CY = 1, the result is negative and the destination has the 2's complement of the result.
Normally, the result is left in 2’s complement, but the CPL (complement) and INC instructions
can be used to change it. The CPL instruction performs the 1's complement of the operand;
‘then the operand is incremented (INC) to get the 2’s complement.
1.4 Subtraction of 16-bit data
CLR C pCY~= 0
MOV A, #62H jA_= 62H
SUBB A,#96H 762H -96H = CCH with CY = 1
MOV R7,A ysave the result
MOV A, #27H ;A=27H
SUBB A, #12H ;27H°=\12H - 1 = 14H
MOV R6,A 7Save the result
Solution:
After the SUBB, A = 62H - 96H = CCH and the carry flag is set high indicating
there is a borrow. Since CY = 1, when SUBB is executed the second time A = 27H
— 12H - 1 = 14H. Therefore, we have 2762H — 1296H = 14CCH.
1.5. Multiplication of 8-bit data
MOV A, #25H ;load 25H to reg. A
MOV B,#65H pload 65H in reg. B
MUL AB ;25H * 65H = E99 where
7B = OEH and A = 99H
1.6 Division of 8-bit data
MOV A, #95 jload 95 into A
MOV B,#10 jload 10 into B
DIV AB ;now A = 09 (quotient) and
7B = 05 (remainder)
College of Engineering, Muttathara 101Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
1.7 Find the 2’s complement of the given value
‘The 8051 does not have a special instruction to make the 2's complement of a number. To do that, we
can use the CPL instruction and ADD, as shown next
cPLA 3 1s complement (Invert)
ADD A, #1 3 add 1 to make 2’s complement
Find the 2’s complement of the value 85H.
Solution:
MOV A,#85H 85H = 1000 0101
cPL A 71's comp. 1’S = 0111 1010
ADD A,#1 72's comp. +1
0112 1011 = 7BH
1.8 Data transfer/exchange between specified memory locations
'* Eg: Copy a block of 20 bytes of data available from address 60H to 73H to the location starting
from 40H
Data Memory Data Memory Data Memory Data Memory
4 — 4
2 cygtscamns
70] = 50]
oF rietien ar
| Temporary €
Storage ‘
6c] te j c
oa Rag A
6A = 4
@ Pr
6 4
je, a7
86 %
& Pi
oa “a
6 a
8 Ro a |
‘er ‘Source Destination 47
ee! Pointer Pointer
SOURCE pestinarion. |“ oe ce
Schematics of given problem Schematics of solution technique
Algorithm
Step
Initialize RO as source and [Link] destination pointers and load R7 by 20 (decimal) to serve as the
counter.
Step 2: Copy a byte from source to destination,
storage). Update pointers after copying.
Step 3: Decrement counter by one. Continue at Step 2 if the counter is not zero.
Step 4: Terminate the process.
jing RO and R1 through accumulator (as a temporary
Q) Write an assembly language program for 8051 microcontroller to copy 20 bytes starting from 60H to
location 40H onwards
; First three instructions i
e both source and desti ers and the counter.
START: MOV RO, 60H jload starting source address
MOV R1, #40H jload starting destination address
MoV R7, #20 ; load counter to copy 20 bytes
; In third instruction the assembler takes it as a decimal number and converts it correctly
; Iterative procedure to copy data from source to destination starts from here.
COPY: — MOVA, @RO j get 1 byte from source location
MOV @R1, A store it in destination
College of Engineering, Muttathara 102Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
INC RO jmext source address
INC R1 jnext destination address
DINZ R7, COPY keep copying till over
;R7 =0 indicates data copy over. Following instruction terminates the program.
EXIT: = SIMP EXIT j terminate here
‘© Eg: Shift a block of 8 bytes of data, presently located from SOH to 57H, 1 byte up, so that the data
is available from 51H to S8H.
Temporary
eee Data Memory
Reg. A a
Destination 55 }-+ 58 Start
Pointer 57
Source oe
Pointer a 2
54
Count = Count -1 53.
52
51
R7 50 Finish
4F
Initialize RO as source and R1 as destination pointers for the highest addresses and load R7 by 08
to serve as the counter.
Step 2: Copy a byte via accumulator from source to destination, using RO and R1, through accumulator.
Decrement both pointers by one after copying.
Step 3: Decrement counter by one. Continue at Step 2 if the counter is not zero.
Step 4: Terminate the process.
Q) Write an assembly language program for 8051 microcontroller to shift 8 bytes by 1 byte up.
Following three instructions initialize both pointers and the counter
START: — MOV RO, #57H ; point last location of source
MOV Ri, #58H j point last location of destination
MOV R7, #08 initialize counter for eight shift operations
jn third instruction the assembler takes it as a decimal number and converts it correctly
ize counter for eight shift operations.
SHIFT: — MOVA, @RO get a byte from source
MOV @R1, A jstore it in destination
DEC RO ppoint to next source
DECR1 ; point to next destination
DINZ R?, SHIFT ; keep copying till over
; RT indicates that the operation is over.
; Next instruction is used to terminate the program
EXIT: SJMP EXIT j terminate here
Note: Please note that had it been a case of shifting down, pointers would have been loaded for the other
end (50H and 4FH) and would have been incremented after every iteration.
College of Engineering, Muttathara 103Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
1.9. Sum of a series of 8 bit data.
1.9.1 Sum of Natural Numbers
Q) Write a program to generate and store natural numbers starting from 1 to ‘N’ terms and also find the
sum of these numbers. Assume that the value of ‘N’ is stored in location 30H. Store generated natural
numbers from 40H. Leave the sum in the accumulator.
Data Memory
45
44 “3
Psw[__00 43
42
41 a
RO 40 -+—>-40
Storage Pointer
30) N
Reg. A oT
Sum 8
o7 N
Ro[__o1 06[— 01
Natural Number Cogtiainer 05 orl
R7 NF o7
Term Counter 00 40
Fig: Schematic for natural number generation
Solution:
We select bank #0 and use R6 for generating the natural numbers. Th ese generated numbers are stored
at target locations from R6 using RO as the pointer. Bank #0 is selected through PSW as direct addressing
for source to be used for saving the generated number through indirect addressing. R7 counts down from
N, which was loaded from location 30H. It is assumed that N is not zero. Th e accumulator is used to
calculate the sum after each cycle of iteration. Above Fig. explains the scheme of register allotment.
Following are the adopted algorithm and the program listing.
Algorithm:
Step 1: Select bank #0. initialize RO as destination pointer for storage of generated natural numbers and
load R7 from 30H by N to serve as the counter.
Also, clear R6 and the accumulator to generate the numbers and calculate the sum.
Step 2: Increment R6 by one to generate the next natural number. Save it through RO and add it with
accumulator, Then increment RO to point the next storage location.
Decrement counter R7 by one. Continue at Step 2 if the counter isnot zero.
Terminate the process.
Program to generate and add N natural numbers. Value of N
; Assume @ byte location 30H contain OSH
; Following five instructions complete the initialization procedure.
START: MOVPSW, #00H _; select bank #0
MOV A, #00H initialize the sum to zero
MOV R6, #00H j to start generation of natural numbers
MOV RO, #40H s point to start of storage location
MOV R7, 30H ; counter for N terms of the series
College of Engineering, Muttathara 104Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
; Main loop for natural number generation, storing and addition starts from here.
MAIN: — INCR6 j generate next natural number
MOV @RO,06H —_; save generated number in R6 to its space
ADD A, R6 j find the sum and store it in register A
INC RO j point to next storage location
DJNZ R7, MAIN ; continue up to N terms
; R7 indicates that the process is over. Following instruction terminates the program.
EXIT: SIMP EXIT j terminate here
1.9.2 Sum of given series
Q) Write a program to find the sum of the series 1- 2+3~4+... up to N terms. Assume the non-zero
value of N is available in location 30H. Store the sum in the accumulator.
Program:
; Program to calculate the sum of the given series up to N terms. Nis in location 30H.
Following four instructions complete the initialization procedure.
START: MOV PSW, HOOH —_; select bank #0
MOV A, #00H initialize the sum to zero
MOV R6, #OOH ; to generate terms of the series
MOV R7, 30H j number of terms in R7 as counter
SETB OOH Bit address OOH act a flag
; to check whether the number is odd or even
5 If this bit is set, number is odd => ADD must occur.
; Else, number'is even => SUBB must occur
Start generating numbers and keep on adding terms.
MAIN: — INCR6 j generate next number
JNB OOH, EVEN If the flag bit is not set, jump to label “EVEN”.
ODD: —ADDA, R ; odd numbers to be added
CLR OOH ; Clear the bit to make sure SUBB operation occurs next.
SIMP CHECK
EVE! CLR sto clear carry flag $0 as clear borrow flag before SUBB
SUBB A, RE ; even numbers to be subtracted
SETB OOH Set the bit to make sure ADD operation occurs next.
CHECK: —DJNZ R7, MAIN continue up to N terms
; R7 indicates that the process is over. Following instruction terminates the program.
EXIT; SMP EXIT j terminate here
1.10 Largest/smallest from an array (unsigned integer).
1.10.1 Largest from an array
Program to calculate the Largest of the given array of N terms;
Let N = 9 & location of first element of array
; Following three instructions complete the initialization procedure.
START: MOV R7, #09 ; R7 is used to store number of elements present in the array
MOV RO, #12H j point to location of first element of array
MOV A, @RO j assuming first element is largest no. and saving it in ‘A’ register
SIMP CHECK
start finding largest number in the array
MAIN: — INCRO j point to next storage location
MOV B, @RO ave the element of array at location pointed by RO in ‘B’ register
CINE A, B, NEQ ; compare A with B; if they are not equal, jump to label “NEQ”
College of Engineering, Muttathara 105NEQ:
CHECK:
EXIT:
1.10.2 Smallest from an array
Computer Are!
SIMP CHECK
JNC CHECK =
Mova,B
DJNZ R7, MAIN ©
} R7 indicates that the process is aver. Follo
SIMP EXIT
cture & Microcontrollers_ MODULE 3_S4 EC KTU
Also, if B is greater, CY = 1. Else CY=0
; this instruction will work only if A and B are equal.
; checking whether CY is not set. If it was A
All ports are output ports
1. Interfacing with 8051 using Assembly language programming
1,1 Interfacing with LED
College of Engineering, Muttathara atComputer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
In method 1, the LED will glow only if the PIN value of the 8051 microcontroller is HIGH as current
flows towards the ground.
In method 2, the LED will glow only if the PIN value of the 8051 microcontroller is LOW as current
flows towards PIN from the +5V supply due to its lower potential.
Commonly, used LEDs will have voltage drop of 1.7V and current of 10mA to glow at full intensity.
This is applied through the output pin of the micro controller.
The LED is connected to any other port of 8051 through a current limiting resistor, R. (so as to
prevent voltage drop across LED crossing 1.7V).
Win-1.7)_G-17), 33
Re ao A = Fp kd = 0.33K0 = 3300
Configuring the port pins as output, the state of the port pins can be controlled and set to either
igh or low.
When the port is configured as input, reading the pins will read the voltage state of the pins.
We need to configure the port pins as output for the LED blinking process.
1.1.1 Interfacing with single LED to turn it ON and OFF repeatedly with certain delay
(i.e, LED blinks continuously)
ORG 0000H
START:
SETB P1.3 | Note 1: using one DINZ '
ACALL DELAY | instruction, you can |
CLR P1.3 | create maximum loop |
ACALL DELAY _ | or iteration of 256 by |
SUMP. START ‘ | setting count initial |
DELAY: “MOV RO, #00H * ene en
- | value as OOH |
LOOPT?, “MOV RU, #00H «~~
LOOP2: NOP +
END
College of Engineering, Muttathara
Note 2: Writing any |
assembly code inside |
any loop can create |
more delay. \
DINZ R1, LOOP2
DINZ RO, LOOP1 ae
RETComputer Architecture & Microcontrollers_ MODULE 3_84 EC KTU
Q) A switch is connected to pin P2.0 and an LED to pin P1.3. Write an 8051-assembly code program to get
the status of the switch and send it to the LED
ORG 0000H
SETB P2.0 ;make P2.0 an input
AGAIN: MOV C,P2.0 j;read SW status into CF
MOV P1.3,C ;send SW status to LED
SUMP AGAIN ;keep repeating
END
Not
Just for understanding purpose
“sv
1.1.2 Interfacing with 8 LEDs to make a display pattern
Assume our Aim: To display a rotational transition from one LED to another with certain delay
ORG 0000H
MOV P2;"#0FFH .4 make Port 2 as an output
MOV A, 40FEH set LSB as 0 and other bits as 1
AGAIN: MOV_P2, A send content of A to LEDs in port 2
ACALL DELAY
RSA
SJMP AGAIN ikeep repeating
DELAY? MOV RO, #00H
LOOP1?~MOV‘R1, #00H
LOOP2:) NOP
DJNZ R1, LOOP2
DJNZ RO, LOOPL
RET
END
College of Engineering, Muttathara 113Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
Note: Just for understandir se
Let the Circuit diagram remains the same.
Assume our Aim: To display an oscillating transition from one LED to another with certain delay
ORG 0000H
MOV P2, #0FFH ; makePort 2 as an output
MOV A, #0FEH Set“LSB as Ovand other bits as 1
LEFT: MOV P2, A #3end contentsof A to LEDs in port 2
ACALL DELAY
RL A
CONE A, #7FH, LEFT “pkeepeleft until only MSB is 0
RIGHT: MOV P2, A send content of A to LEDs in port 2
ACALL DELAY
RRA
CINE A, #0FEH,\RIGHT
SUMP LEFT
ep right until only LSB is 0
DELAY: MOV RO, #00H
LOOP1: MOV R1y=#00H
LOOP2: NOP
NOP
NOP,
DJNZ R1, LOOP2
DINZ RO, LOOPL
RET
END
‘Anode — Cathode
Anode!
Reathodo
SIDE Anode Cathode
view R|
a
Cathode svwpol—\s symBoly
LED = Anode
College of Engineering, Muttathara 14Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
Note: (just for understanding)
© Acommon mistake of students is to interface a LED between Vcc and port pin, without any current
limiting resistor is series.
* Another common mistake is to use a port pin to directly source the necessary current for a LED.
1.2 Interfacing with 8051 Seven segment LED display
‘Seven segment displays are available in two types
1) Common anode
2) Common cathode
SCHEMATIC
COMMON
ANODE
a a
by oN
c sy c sy
dy dy
e N “en
is tN
an PK
ps os
K x
(b)
©)
COMMON
CATHODE
Fig: Types of seven-segment displays: (a) schematic, (b) common anode and (c) common cathode
‘© Asonly seven of its segments are used to display any numeric value, hence the name seven
segment.
‘© Assinking larger current is easier than sourcing it, therefore, common cathode type display
devices are adopted in a greater number of designs, than common anode type devices.
5 Lookup table for digits @ to 9 for common cathode
Setting Lookup table at a ROM address
order of segments
ORG 1000H
0B
OB
OB
OB
0B
DB
DB
OB
OB
DB
OR
3FH
18H
58H
4FH
66H
‘6DH
70H
o7H
7FH
FH
pefe
0011
0001
e101
e100
e110
e110
e111
2000
e111
e110
deba
4111.
1000
1011
q441.
e110
1101
1101
e111
1441.
ai.
3 Lookup table for digits @ to 9
College of Engineering, Muttathara
pattern
pattern
pattern
pattern
pattern
pattern
pattern
pattern
pattern
pattern
for
for
for
for
for
for
for
for
for
tor
e
warausune
11sComputer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
ORG 10@@H ; Setting Lookup table at a ROM address
5 pgfe deba = order of segments
DB @8111111B, 9000011@B, 010116118, 010011118, 61100110B, 611011018,
@1111101B, 9@090111B, 911111118, @1101111B8
OR
3 Lookup table for digits @ to 9
ORG 10@@H ; Setting Lookup table at a ROM address
5 pgfe deba = order of segments
D8 3H, 18H, SBH, 4FH, 6H, 6DH, 7DH, 07H, 7FH, 6FH
Code Memory ddx) 0x1000| 0x3F\value
ol1/2/3]4[5]6|7|s koje ls Nolele
1000 3F 18 5B 4F 66 6D 7D 07 7F 6F 00 00.00/00 00 00
Note: Just for understanding purpose
‘ORG 0000H ; initial starting address
MOV DPTR, #1000
MOV A, #3H
MOVCA, @A+DPTR } Copy data from external location to accumulator,
MOV P2, A ; Move the pattern of the digit into port P2
SETB P3.0 ; To activate 7 segment
EXIT: SUMP EXIT
j Lookup table for digits 0 to 9
ORG 0400H ; Setting Lookup table at a ROM address. Here, it is 400H
: pgfe deba = order of segments
DB 3FH,O6H, 5BH, 4FH, 66H, 6DH, 7DH, 07H, 7FH, 6FH
END
College of Engineering, Muttathara 116Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
eT
set to the starting address of lookup table (in ROM).
If you need to display number “3” in 7-segment display, code for 3 will be present at address (400 + 3).
To achieve this, first, Ais set to 3.
Using “MOVC A, @A+DPTR", Content at resultant address location (DPTR + A) is saved in A
Now, A contains pattern of the required digit (’)
Using “MOV P2, A”, Move the pattern of the digit present ‘
KSA KAK
into port P2
~ Note: You can give label to the starting address of lookup table. Assembler will replace the label with its
uddress location in ROM wher it is present in uu instruction.
ORG 0000H _; initial starting address
[Link],#LUT 4+=+~-~-~ 22+ -0o sere eavesneern vw
MOV A, #3H
MOVC A, @A+DPTR 3 Copy data from external location to accumulator
SETB P3.0 3 To activate 7 segment
EXIT: SUMP EXIT
; Lookup table for digits 0 to 9
ORG 0400H ; Setting Lookup table at a ROM address. Here, it is 400H
; pefe dcba = order of segments
LUT: DB 3FH,OGH, SBH, 4FH, 65H, 6DH, 7DH, 07H, 7FH, 6FH
END
Q) Write an 8051 Assembly code program to display numbers from 0 to 9 repeatedly in a sequence on
seven-segment modules. Provide the delay between two numbers.
‘ MOV P2, 4 ; Move the pattern of the digit into port P2
‘ORG 0000H ; initial starting address
START: MOV DPTR, #LUT.
Mov R1, #10 5 R7 = number of digits
REPEAT: CLRA
MOVC A, @A+DPTR ; Copy data from external location to accurtulator LL Main
SETB P3.0 To activate 7 segment Progra
MOV P2, A Move the pattern of the digit into port P2
ACALL DELAY ; Call a delay to so that the transition is visiole ~
<-- INCDPTR ; Point to the next pattern ’
DJNZ Ri, REPEAT; Repeat tll all digits are used once i
SJMP START ; Run this forever till externally stopped : J
DELAY: MOV R7,#00H +
: MOV R6, #00H
MOV RS, #02H
NOP
DINZ RS, LOOPS
i DINZ R6, LOOP2
! DINZ R7, LOOP
oS RET
; Lookup table for digits 0 to 9
ORG 0400H
LUT: DB3FH, 6H, SBH, 4FH, 66H, 6DH, 7DH, 07H, 7FH, 6FH
END
College of Engineering, Muttathara 7
| ;Sub-routine or Sub-program for delayComputer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
Note: In the above question, Main Program can be written as follows
‘ORG 0000H
MOV DPTR, #LUT
START: MOV R1, #00H
REPEAT: — MOVA,R1
MOVC A, @A+DPTR
SETB P3.0
Mov P2, A
ACALL DELAY
INC RL
CINE R1, #10, REPEAT
SJMP START
; Run this forever till externally stopped
Q) Write an 8051 Assembly code program to display numbers from 00 to 99 repeatedly in a sequence on
2 seven-segment modules without multiplexing. Provide the delay between two numbers
‘ORG 0000H
MOV DPTR, #LUT
START: MOV R1, #00H
update: MOV R2, #00H
MOVA, R1
MOVC A, @A+DPTR
SETBP1.0
Mov P2, A
REPEAT: MOV A, R2
MOVC A, @A+DPTR
SETBP1.1
Mov P3, A
ACALL DELAY
INC R2
CINE R2, #10, REPEAT
INC R1
CINE R1, #10, update
SJMP START
;Sub-routine or Sub-program for delay
DELAY: MOVRS, HOOH
LOOPI: MOV R6, #00H
LOOP2: MOV R7, #02H
Loops: NOP
DINZ R7. LOOP3
DINZ R6, LOOP2
DINZ RS, LOOP1
RET
College of Engineering, Muttathara
sinitial starting address
jInitial value of 1st number
ial value of 2nd number
\" gets pattern of the 1st digit present in LUT
fo activate 1st 7 segment
love the pattern of the digit into port P2
\" gets pattern of the 2nd digit present in LUT
; To activate 2nd 7 segment
love the pattern of the
it into port P3
; Call a delay to so that the transition is visible
; Repeat till all digits are used once in 2nd digit place (LSB)
; Update 1st digit place (MSB) tll all digits are used once
un this forever tll externally stopped
118Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
; Lookup table for digits 0 to 9
ORG 400H
LUT: DB 3FH, O6H, SBH, 4FH, 66H, 6DH, 7DH, 07H, 7FH, 6FH
END
Note: Just for understandin se
a
Q) Write an 8051 Assembly code program to display numbers from 00 to 99 repeatedly in a sequence on
2 seven-segment modules with multiplexing. Provide the delay between two numbers.
‘ORG 0000H jinitial starting address
MOV DPTR, #LUT
START: MOV R1, #00H jInitial value of Ist number
update: MOV R2, #00H sInitial value of 2nd number
refresh: MOV R3, #10H
agai MOV A, R1
MOVC A, @A+DPTR \" gets pattern of the 1st digit present in LUT
Mov P3, #018 ;To activate 1st 7 segment
MOV P2, A love the pattern of the digit into port P2
‘ACALL DELAY ; Call a delay to so that the transition is visible
Mov A, R2
MOVC A, @A+DPTR i
\" gets pattern of the 2nd digit present in LUT
Mov P3, #108 ; To activate 2nd 7 segment
MOV P2, A j Move the pattern of the digit into port P3
ACALL DELAY Call a delay to so that the transition is visible
DINZ R3, again ; **display same numbers R3 times to create a illusion of not blinking
College of Engineering, Muttathara 119Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
INC R2
CINE R2, #10, refresh ; Repeat till all digits are used once in 2nd digit place (LSB)
INC RL
CINE R1, #10, update ; Update 1st digit place (MSB) til all digits are used once
SMP START tun this forever till externally stopped
sSub-routine or Sub-program for delay
ei MOV RS, #00H
MOV R6, #20H
NoP
DINZ R6, LOOP2
DINZ RS, LOOP
RET
; Lookup table for digits 0 to 9
ORG 400H
LUT: DB 3FH, O6H, SBH, 4FH, 66H, 6DH, 7DH, 07H, 7FH, 6FH
END
Note: Just for understanding purpose
**Note:
+ Incase of multiplexed 7 segment displays, by repeating the above cycle continuously, so fast that
we beat “Persistence of Vision”.
The human eye needs roughly 80-100 milliseconds to register an event.
‘Ife can loop back within that much time, the human eye will get the “illusion” that all 4 digits are
on simultaneously though that’s not the real case.
‘* This is the same principle behind motion picture or movies.
The [tC however is so fast that it can finish the loop in less than one millisecond.
We therefore take the liberty of adding a small delay (5-10 milliseconds) as each digit is displayed,
to allow the LEDs enough time to fire up. It still gives the UC enough time to finish the loop in the
stipulated time window.
College of Engineering, Muttathara 120Computer Architecture & Mic
ontrollers_ MODULE 3_S4 EC KTU
Module 3: Part 3
Programming 8051 in C- Declaring variables, Simple examples - delay generation, port programming, code
conversion.
Programming 8051 in C
‘© Compilers produce hex files that we download into the ROM of the microcontroller.
‘¢ The size of the hex file produced by the compiler is one of the main concerns of microcontroller
programmers, for two reasons:
1) Microcontrollers have limited on-chip ROM.
2) The code space for the 8051 is limited to 64K bytes.
‘* Advantages for writing programs in C instead of Assembly:
1) It is easier and less time consuming to write in C than Assembly.
2) Cis easier to modify and update.
3) You can use code available in function libraries.
4) C programs are portable to other microcontrollers with litte or no modification.
\dvantages for writing programs in C instead of Assembly:
1) Assembly language programs have fixed size for the HEX files produced, whereas for the
same ‘C’ programs, different ‘C’ compiler produces different HEX code sizes.
2) The 8051 general purpose registers, such 2s RO-R7, A &B are under the control of the ‘C’
compiler & are not accessed by ‘C’ statements.
3) Itis difficult to calculate exact delay for ‘C’ programs.
4) Microcontrollers have limited on-chip ROM & the code space (to store program codes) is
also limited.
Eg: A misuse of data types by the programmer in writing ‘C’ programs such as using ‘int’
(16-bit) data type instead of ‘unsigned char’ (8-bit) can lead to a large size HEX files.
The same problem does not arise in assembly language programs.
1. Data types in C for the 8051.
SI | Data Type Size in Bits Data Range
1. | unsigned char abit Oto 255 (00-FFH)
‘Since 8051 is an 8-bit microcontroller, the character data type is also 8-bit.
* So, char data type is most widely used
* Used for setting a counter value, to represent ASCII character etc
Note: C compilers use the signed char as the default if we do not put the keyword unsigned in front of the
char
‘SI | Data Type ‘Size in Bits Data Range
2. | char (signed) 8-bit, -128 to +127
‘© MSB bit represent sign bit:
‘© Remaining 7-bits are used to represent the magnitude of the number.
* This datatype is needed to represent a given quantity such as temperature, the use of the
signed char data type is @ must.
SI | Data Type Size in Bits Data Range
3. | unsigned int 16-bit (to 65535 (0000-FFFF H)
‘* Used to define 16-bit variables such as memory addresses.
* Used to set counter values of more than 256.
‘* Since 8051 is an 8-bit microcontroller & the int data type takes two bytes of RAM.
(So we must not use int data type unless we have to)
The misuse of int variables will result in a larger HEX file
College of Engineering, Muttathara 11Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
Note: The C compiler uses signed int as a default if we do not use the keyword unsigned
Sl | Data Type Size in Bits Data Range
4, | int (signed) 16-bit 32,768 to +32,767
© MSB bit represent sign bit.
+ _ Remaining 15-bits are used to represent the magnitude of the number.
SI | Data Type Size in Bits Usage a
5. | sbit Lit SFR bit-addressable only
+ Used to access bit addressable SFR only
Si | Data Type Size in Bits Usage
6. | bit Lit RAM bit-addressable only
Used to access bit-addressable section of RAM space 20-2FH only
Usage
Sl | Data Type a
RAM addresses 80-FFH only
7. | sfr
‘Used to access byte-addressable SFR registers
2. Simple examples
Q) Write an 8051 C program to send values 00-FF to port P2
include
void main(void)
{unsigned char i;
for (i=0 j i<=255 j i++) /finstead of 255, its Hexadecimal value OxFF can be given
4 P. // P2is the keyword for Port 2 which is declared in reg51.h file
+
Note:
Run the above program on your simulator to see how P1 displays values 00-FFH in binary.
Q) Write aC program to display number from 00 to FFh to port P2 only once using sfr data type.
sfr P2 =OxA0; //?2 is declared using sfr keyword.
void main(void)
{unsigned char i;
for (i=0; i<=255 ; i++) // instead of 255, its Hexadecimal value OxFF can be given
{Op 2=is
t
Note:
© The program doesn’t use the #include, but the port address PO is declared using sfr
keyword.
‘© sfr P2 =0xA0; implies P2 is a variable of Byte size, which has a definite RAM address of AOH in the
RAM area
‘© Ox indicates the data is in Hexadecimal.
College of Engineering, Muttathara 122Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
Q) Write an 8051 C program to send hex values for ASCII characters of 0, 1, 2, 3, 4, 5, A,B, Gand D to
port P1.
// Program to displays given value only once
#include
void main(void)
{
unsigned char x{]="012345A8CD";
unsigned char i;
fr(i=0 ; i<=10 ; ir)
{ Pl=xlil; }
}
Note:
The ASCII characters can be concatenated to form a string & then we can access’all the characters serially
one after the other using an array indexing.
Eg: After defining as
unsigned char x[ ]="012345ABCD'
To access ‘3', we can use x[3],
Similarly to access ‘A’, we can use x{6].
Run the above program on your simulator to see how Pi. displays values 30H, 31H, 32H, 33H, 34H, 35H,
41H, 42H, 43H, and 44H, the hex values for ASCII 0, 1, 2,and so on.
// Program to display given value continuously
#include
void main(void)
{
unsigned char x{]= “012345ABCD";
unsigned char i
while(1) //repeat forever
Q) Write an 8051 C program to send values of -4 to +4 to port P1.
[sign numbers
#include
void main(void)
{
char x{J (+1-1,42,-2,43,-3,44,-4); // use of Signed char
unsigned char i;
for (i: +)
Pi=x{l);
f
College of Engineering, Muttathara 123Computer Architecture & Microcontrollers_ MODULE
S4EC KTU
Note: Run the above program on your simulator to see how P1 displays values of 1, FFH, 2, FEH, 3, FDH, and
4, FCH, the hex values for +1, -1, +2, ~2, and so on.
Q) Write an 8051 C program to toggle all the bits of P1 continuously.
// Toggle P1 forever
include
void main(voi
{
whiile(1) Hrepeut forever
{
P1=0x55; _//Ox indicates the data is in Hexadecimal
7/0101 0101
P1=0xAA; — // 1010 1010
}
+
Note: Run the above program on your simulator to see how PI toggles continuously.
Examine the asm code generated by the Ccompiler.
Q) Write an 8051 C program to toggle bit DO
delay)
LSB) of the port P1 (P1.0) 50,000 times (without any
include
sbit MYBIT = P1*0; /notice that sbit is declared outside of main
// Here P1.0 is defined as MYBIT. i.e, Single bit
void main(void)
{
ed int 2;
for (2=0 ; 2<=50000 ; z++)
{
MyBIT = 0;
MyBiT = 1;
}
t
Note: Run the above program on your simulator to see how P1.0 toggles continuously
InC program, P1.0 bitis represented as P10
‘Summary: Some Widely Used Data Types for 8051 C
Data Type Size in Bits Data Range/Usage
unsigned cha 8-bit 00 255
char (signed) 8-bit =128 to +127
0 to 65535
32,768 to +32,767
sl bit SER bit-addressable only
bit bit RAM bit-addressable only
str 8-bit RAM addresses 80-FFH only
unsigned int
int (signed)
College of Engineering, Muttathara 124Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
Note: There are two ways to create a time delay in 8051 C:
1) Software delay: Using a simple ‘for’ loop
2) Hardware delay: Using the 8051 timers
2.1. Time Delay generation using a simple ‘for’ loop
In creating a time delay using a for loop, three factors that can affect the time delay size.
1) 8051 design: original 8051/52 design used 12 clock periods per machine cycle many of the newer
generations of the 8051 use fewer clocks per machine cycle. For example, the DS5000 uses 4 clock
periods per machine cycle, while the DS89C4x0 uses only 1 clock per machine cycle
2), Crystal frequency connected to the X1- X2 input pins: The duration of the clock period for the
machine cycle is a function of this crystal frequency
3) Compiler used to compile the C program: if we compile a given 8051 C program with different
compilers, each compiler produces different hex code.
For the above reasons, when we write time delays for C, we must use the oscilloscope to measure the
exact duration
Q) Write an 8051 C program to toggle bits of P1 continuously forever with some delay.
Solution:
// Toggle P1 forever with some delay in between “on” and “off”.
Hinclude
void main(void)
{
unsigned int x;
while(1) repeat forever
{ P1=0x55;
for(x=0 ; x<40000 ; x++); «//delay size unknown
P1=0xAA;
for(x=0 j x<40000 j x+4+)5
t
}
Q) Write an 8051 C program to toggle bits of P1 ports continuously with a 250 ms delay.
Solutior
// This program is tested for the DS89C4x0 with XTAL = 11.0592 MHz.
Hinclude
void MSDelay(unsigned int); ‘// function declaration
void main{void)
{ —— while(1) (repeat forever
{ --P1=0x55;
MsDelay(250);
P1=0xAA;
MsDelay(250);
I
t
void MSDelay(unsigned int itime) // function definition
{ ned int i,
forli=0 ; i< itime ; i++)
College of Engineering, Muttathara 125Computer Architecture & Mierocontrollers_ MODULE 3_S4 EC KTU
for(j=0 ; j < 1275 ; j++);
Note: Run the above program on your Trainer and use the oscilloscope to measure the delay:
“for(j=0 ; j < 1275 ; j++);” will generate 1 millisecond delay using DS89C4x0 with XTAL= 11.0592 MHz
Q) Write an 8051 C program to toggle all the bits of PO and P2 continuously with a 250 ms delay.
Solutior
this program is tested for the DS89CAx0 with XTAL = 11.0592 MHz
include
void MSDelay(unsigned int);
void main{void)
{— while(1) repeat forever
{
P2=0x55;
MsDelay(250);
PO=0xAA;
P2=0xAA;
MsDelay(250);
t
}
void MSDelay(unsigned int itime) // function definition
{ —unsigne
fori=0 ; i< itime ; i++)
for(j=0 ; j < 1275; j+4);
}
2.2 Port programming
2.2.1 Byte size I/O programmi
Ports PO-P3 are byte-accessible, We use the PO-P3 labels as defined in the 8051/52 C header
Q) LEDs are connected to bits P1 and P2. Write an 8051 C program that shows the count from 0 to FFH
(0000 0000 to 1111 1111 in binary) on the LEDs.
Solution:
Hinclude ~//P2 & P1 are keywords for Port 2 & Port 1 which are declared in reg51.h file
#define LED P2 Hnotice how we can define P2
void main(void)
{
P1=00; Helear P1
LED=0; Melear P2
for(;:) //repeat forever, equivalent to “while(1)”
{
Patt; /fincrement Pt
LED++; /fincrement P2
}
}
College of Engineering, Muttathara 126Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
Q) Write an 8051 C program to get a byte of data from P1, wait 1/2 second, and then send it to P2.
Solution:
#include
void MSDelay(unsigned int);
void main(void)
{ unsigned char mybyte;
P1=OxFF; //make P1 an input port
while(1)
{
mybyte=P1; Het a byte from P1
MsDelay(500);
P2=mybyte; Hsend it to P2
}
}
void MSDelay(unsigned int itime) // function definition
{ ned inti, j
for(j=0 ; j < 1275 ; j++);
Q) Write an 8051 C program to get a byte of data from PO. Ifit is less than 100, send it to P1; otherwise,
send it to P2.
Solution:
#include
void main(v:
{ unsigned char mybyte;
PO=OxFF; //To make PO an input port, initialize that port value to 1111 1111
while(1)
{
mybyte=P0; //get a byte from PO
iffmybyte<100)
P1=mybyte; send it to P1 if less than 109
else
P2=mybyte; (//send it to P2 if more than 100
}
}
it-addressable 1/0 programming
‘* The |/O ports of PO-P3 are bit-addressable.
* Wecan access a single bit without disturbing the rest of the port.
* | Weuse the sbit data type to access a single bit of PO-P3.
* One way to do that is to use the Px"y format where x is the port 0,1, 2, or 3, and
that port.
*. For example, P147 indicates P1.7.
‘¢ When using this method, you need to include the reg51.h file.
he bit 0-7 of
College of Engineering, Muttathara 127Computer Architecture & Mierocontrollers_ MODULE 3_S4 EC KTU
Q) Write an 8051 C program to toggle only bit P2.4 continuously without disturbing the rest of the bits of
P2.
Solution:
//toggling an individual bit
Hinclude
sbit mybit = P24; Hnotice the way single bit is declared
void main(voi
{
while(1)
{
mybit Hturn on P2.4
mybit=0; /fturn off P2.4
}
}
Q) Write an 8051 C program to monitor the bit P2.4. if it is high, send 55H to P1; otherwise send AAH to
Pl.
Solution:
include
sbit mybit = P2*4;
void main(void)
{ — mybit (770 make P2.4 an input
while(1) repeat forever
{if (mybi
P1=0x55; _//0x indicates the data is in Hexadecimal
else
P1=0xAA;
}
Q)A door sensor is connected to the P1.1 pin, and a buzzer is connected te P1.7. Write an 8051 C program
to monitor the door sensor, and when it opens, sound the buzzer. You can sound the buzzer by sending a
square wave of a few hundred Hz.
Solution:
include
void MSDelay( unsigned int);
sbit Sensor = P141; //notice the way single bit is defined
sbit Buzzer = P1*7;
{ — Sensor=1; //make P1.1 an input
while(Sensor==1)
{~~ buzzer=0;
MsDelay(200);
buzzer=1;
MsDelay(200};
}
College of Engineering, Muttathara 128Computer Architecture & Mi
-ontrollers_ MODULE 3_S4 EC KTU
void MSDelay(unsigned int itime) / function definition
{unsigned int i, j
for(i=0 j i statement. This allows us to access any byte
of the SFR RAM space 80-FFH. This is a method widely used forthe new generation of 8051
microcontrollers.
Table 1:Single-Bit Addresses of Ports
PO Address PI Address = P2 Address P3 Address Port’s Bit
P0.0 80H P10 90H P2.0 _AOH BOH DO
PO.1 81H Pll 91H PAA ALH BIH DI
P0.2 82H P12 92H A2H B2H D2
P03 83H P13 93H A3H B3H D3
P04 84H P14 94H A4H. B4H D4
POS 85H PLS 95H ASH BSH DS
P0.6 86H P16 96H A6H BoH D6
P07 87H P17 = =697H ATH B7H D7
Example 1: Write an 8051 C program to toggle all the bits of PO, P1, and P2 continuously with a 250 ms
delay. Use the sfr keyword to declare the port addresses.
Solution:
// Accessing Ports as SFRs using the sfr data type
sfr PO = 0x80; U/declaring PO using sfr data type
sfr P1 = 0x90;
sfr P2 = OxA0;
void MSDelay( unsigned int);
void main(void)
{ while(1) //do it forever
{
PO=0x55; P1=0x55; P2=0x55;
MsDelay(250); (7/250 ms delay
PO=0xAA; P1=0xAA; P2=0xAA;
MsDelay(250); (1/250 ms delay
College of Engineering, Muttathara 129Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
void MSDelay(unsigned int itime) 1 function definition
{unsigned inti, j
for(i=0 ; i< itime i++)
for(j=0 ; |< 1275; j+4);
}
Example 2: Write an 8051 C program to turn bit P1.5 on and off 50,000 times.
Solution:
sbit MYBIT = 0x95; //another way to declare bit P1*5
void main(voi
{
unsigned int i;
for (i= 0; 1 < 50000 ; i++)
{
yer
MyBIT=0;
}
}
Note: Using bit data type for bit-addressable RAM
The sbit data type is used for bit-addressable SFR registers only.
Sometimes we need to store some data in a bit-addressable section of the data RAM space 20-2FH.
To do that, we use the bit data type, as shown in Example 3.
Example 3: Write an 8051 C program to get the status of bit P1.0, save it, and send it to P2.7 continuously.
Solution:
#tinclude
sbit inbit = P1°0;
247; Usbit is used to declare SFR bits
/{notice we use bit to declare bit-addressable RAM
void main(void)
{ inbit = 1; //make P1.0 an input
while(1)
get a bit from P1.0
Hand send it to P2.7
2.3 Code conversion
‘* "Many newer microcontrollers have a real-time clock (RTC) that keeps track of the
even when the power is off.
‘* Very often the RTC provides the time and date in packed BCD. However, to display them they must
be converted to ASCII.
‘* In this section, we show the application of logic and rotate instructions in the conversion of BCD
and ASCII.
College of Engineering, Muttathara 130Computer Archite
¢ & Microcontrollers_ MODULE 3_S4 EC KTU
Note : ASCII numbers (for better understanding purpose only)
‘© OnASCII keyboards, when the key “0” is activated, “011 0000” (30H) is provided to the computer.
Similarly, 31H (011 0001) is provided for the key “1,” and so on, as shown in Tables
Key ASCII (hex) Binary BCD (unpacked)
0 0 011 0000 0000.0000.
1 31 011 0001 0000,0001
2 32 O11 0010 (0000 0010
3 33, O11 0011 00000011
4 34 O11 0100 (00000100
5 35 O11 0101 (0000 0101
6 36 O11 0110. 0000 110
7 37 OIL ONT 0000 O11
8 38 O11 1000 (0000 1000
9 39 O11 1001 0000-1001
Note : Packed BCD to ASCII conversion (for better understanding purpose only)
The RTC provides the time of day (hour, minute, second) and the date (year, month, day)
continuously, regardless of whether the power is on or off.
‘© However, this data is provided in packed BCD.
‘* To convert packed BCD to ASCII, it must first be converted to unpacked BCD. Then the unpacked
BCD is tagged with 011 0000 (30H). The following demonstrates converting from packed BCD to
ASCII
Packed BCD Unpacked BCD. ASCII
0x29 0x02), 0x09 0x32, 0x39
00101001 00000010,00001001 00110010, 00111001
Note : ASCII to Packed BCD conversion (for better understanding purpose only)
‘© Toconvert ASCII to packed BCD, itis first converted to unpacked BCD (to get rid of the 3), and then
combined to make packed BCD.
‘+ For example, 4 and.7 on the keyboard give 34H and 37H, respectively. The goal is to produce 47H
or “0100 0111", which is packed BCD.
Key ASCII Unpacked BCD Packed BCD
4 34 00000100
7 37 00000111 01000111 or 47H
‘* After this conversion, the packed BCD numbers are processed and the result will be in packed BCD
format.
Note: Bit-wise Logic Operations in 8051 C (for better understanding purpose only)
AND (&), — OR(I), EX-OR (A), Inverter (~), Shift Right(>>), and Shift left (<<).
‘* These bit-wise operators are widely used in software engineering for embedded systems and
control
College of Engineering, Muttathara 131Computer Architecture & Mierocontrollers_ MODULE 3_S4 EC KTU
0x35 & OxOF; //ANDing
0x04 | 0x68; //ORing
0x54 * 0x78; //XORing
~0x55; //inversing
Ox9A >> 3; //shifting right 3 times
0x77 >> 4; //shifting right 4 times
0x6 << 4; //shifting left 4 times
0x35 & OxOF = 0x05 /* ANDing */
0x04 | 0x68 = Ox6C /* ORing: */
0x54 * 0x78 = 0x2C /* XORing */
~0x55 = OxAA /* Inverting 5SH.*/
Ox9A >> 3= 0x13 /* shifting right.3 times */
0x77 >> 4 = 0x07 /* shifting right 4 times */
0x6 << 4 = 0x60 /* shifting left 4 times */
Q) Write an 8051 C program to convert packed BCD 0x29 to ASCII and display the bytes on P1 and P2.
Solution:
include
void main(void)
{
unsigned char x, y, 2;
unsigned char mybyte = 0x29;
x= mybyte & OxOF; //mask lower 4 bits
P1=x | 0x30; //make it ASCH
y = mybyte & OxFO; //mask upper 4 bits
y=y>>4; //shift it to lower 4 bits
P2=y | 0x30; //make it ASCII
t
Q) Write an 8051 C program to convert ASCII digits of ‘4’ and ‘7’ to packed BCD and display them on P1.
Solution:
ude
void main(void)
{
unsigned char bedbyte;
unsigned char w ='4";
unsigned char
w=w & OxOF; H/mask 3
<4; Ushife left to make upper BCD digit
College of Engineering, Muttathara 132
weers_ MODULE 3_S4 EC KTU
2= 2 & OXF; Umask 3
bedbyte = w | z; //combine to make packed BCD
P1=bedbyte;
t
Q) Write an 8051 C program to get the status of bit P1.0, save it, and send it to P2.7 after inverting it.
Solution: (No!
Hinclude
xr Page 130 Exam,
H/sbit is used to declare SFR bits
bit membit; //notice we use bit to declare bit-addressable RAM
void main(void)
{ — inbit =1; //make P1.0 an input
while(1)
{
membit
outbit
//get a bit from P1.0
‘membit; // invert it and send it to P2.7
}
Q) Write an 8051 C program to convert 11111101 (FD hex) to decimal and display the digits on PO, P1,
and P2.
Solution:
#include
void main(void)
{
unsigned char x, binbyte, di, d2, d3;
binbyte = OxFD; J/einary(hex) byte
x= binbyte / 10; /divide by 10
d1 = binbyte % 10; //find remainder (LSD)
d2.=x% 10;
3 =x/ 10; //most significant digit (MSD)
P1=d2;
Hint:
Quotient Remainder
FDA 19 3 (low digit) LSD
19/0A 2 5 (middle digit)
2 (high digit) (MSD)
College of Engineering, Muttathara 133,Computer Architecture & Microcontrollers_ MODULE 3,
Module 3: Part 4
Interfacing of - LCD display, Keyboard, Stepper Motor, DAC and ADC-- with 8051 and its programming.
1. Interfacing of 16x2 LCD display with 8051 and its programming.
8051 se
P1040 Voc
y.
Pit}; 4107
RS RW E YS
P2.0
P2.1
P22
1.1 Pin Description of the LCD unit
Pin | Function
Vss___| Ground
Vcc__| +5V power supply
rightness (Contrast) Adjust
RS__| Register Select | 0: Command |
ata
R/W__| Read or Write Select | 0: Write | 1: Read
E Latch Enable: Falling Edge Latches Command/ Data
D0-D7 | 8-bit Command or Data Value
1.2 Typical LCD Command Codes
Code _ | Function
38H __| Initialise 16 character, 2 rows 5x7 matrix display layout
OFH _| Display ON, Cursor ON, Cursor Blinking
01H | Clear Display (Clears the On-Chip DRAM of the LCD Unit)
06H _| Cursor increment Mode (Moves Cursor from Left to Right)
80H | Force cursor to beginning of 1st line
1.3 Steps to send Command or Data to the LCD Unit
‘Steps for sending Command Steps for sending Data
1) Put out the command onthe port (P1) | 1) Put out the data on the port (P1)
2) Make Register Select = 0 (Command) 2) Make Register Select = 1 (Data)
3) Make R/W=0 (As we are writing) 3) Make R/W =0 (As we are writing)
4) Make Latch Enable = 1 4) Make Latch Enable = 1
5) Calladelay 5) Call adelay
6). Make Latch Enable = 0 (Falling Edge) 6) Make Latch Enable =0 (Falling Edge)
14 Steps to display a message on LCD using 8051 using assembly language.
Step. Create Look up table of ASCII codes of a given string at sume tocation eg: 04004
Step 2: Make DPTR point to the table
Step 3: Initialise LCD unit by sending command codes: 38H, OFH, 01H, O6H, 80H
Step 4: Initialise R7 with no. of character present in the given string including space.
Step 5: Initialise R6 = 0
College of Engineering, Muttathara 134Step 6:
Step 7:
Step 8:
Step 9:
Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
Using R6 as index, obtain ASCII code of every character from look up table into A
Send this code as Data to the LCD unit
Increment Index R6
Decrement Loop count R7 and Loop till all characters are displayed
Q) Interface LCD to 8051 and write assembly language program to display message “Hello World!” on
it,
Solution:
Table:
Display:
Here:
SCommand:
8051
P1O DO |
PLT D7
RSRW E Ys
P2.0
P2.1
P22
‘ORG 0400H
DB 'Hello World!"
‘ORG 0000H
MOV A, #38H
ACALL SCommand all the “SCommand” function when A = 38H
MOV A, HOFH
ACALL SCommand ; Call the “SCommand” function when A = OFH
MoV A, #01H
ACALL SCommand Call the “SCommand” function when A = 01H
MOV A, #O6H
ACALL SCommand Call the “SCommand” function when A = 06H
MOV A, #80H
ACALL SCommand all the “SCommand” function when A= 80H
MOV DPTR, #Table } Initialise DPTR as a pointer to starting of the look up table
MOV R7, #12 ;R7 =no. of character present in the given string including space
MoV 6, #0 e RE =0
MOVA, R6
MOVC.A, @A+DPTR ; ASCII code from Look Up Table
ACALL SData ; Call the “SData” function when A contain ASCII value (data)
INC R6 ; Increment the Index
DINZR7, Display oop till all 12 characters are displayed
SIMP Here ; ind the program
;Sub-routine or Sub-program for sending command
MOV P1,A ; Put Command value in P1 from A Register
CLR P2.0 ; Make Register Select = 0 for Command
CLR P2.1 ; Make Read/Write Select = 0 for Write
SETB P2.2 ; Make Latch Enable = 1
College of Engineering, Muttathara 135Computer Architecture & Microcontrollers_ MODULE
CLR P2.2 ; Make Latch Enable = 0 (This produces a Falling Edge)
ACALL Delay ; Calla delay
RET
;Sub-routine or Sub-program for sending data
SData: MOV P1, A Put Data value (ASCII Code) in P1 from A Register
SETB P2.0 j Make Register Select = 1 for Data
CLR P21 ; Make Read/Write Select = 0 for Write
SETB P22 j Make Latch Enable = 1
CLR P2.2 ; Make Latch Enable = 0 (This produces a Falling Edge)
ACALL Delay ; Calla delay
RET
;Sub-routine or Sub-program for delay
Delay: MOV RS, #00H
Loop: NOP
DINZR5, Loop
RET
END
Q) Interface LCD to 8051 and write 8051 C language program to display tnessage “Hello World!” on it.
Solutio
include
sfr datapin = 0x90; //P1=LCD data
sbit rs = P2*0;
sbit rw = P2%1;
sbit en = P22;
void ledemd(unsigned char );
void Ieddata(unsigned char );
void MSdelay(unsigned int };
(Fig. 1)
void main(void)
{unsigned char af] :
ed char bl] = {0x38, OxOF, 0x01, 0x06, 0x80};
unsigned char |;
for(i=0; iS ; i++) _// Initialise LCD unit by sending command codes: 38H, OFH, 01H, O6H, 80H
{Icdemd(bfil); }
forli=0 ; i< 12; i++)
{Ieddata(ali]); }
while(1); //to wait forever
}
void ledemd(unsigned char value)
{ datapin = value; // put the value on the pins
// strobe the enable pin
College of Engineering, Muttathara 136Computer Architecture & Microcontrollers_ MODULE 3,
Msdelay(2);
}
void Ieddata(unsigned char value)
{ datapin = value; // put the value on the pins
rs=1;
// strobe the enable pin
Msdelay(2);
en=0;
}
void MSdelay(int ms)
{ unsigned int i,j
js i< ms; i+) /1 Outer “for” loop for given milliseconds value
; js 1275; j++); // inter “for” loop for 1ms delay
2. Interfacing of Stepper Motor with 8051 and its programming.
2.1 Introduction to Stepper Motor (just understanding only }
© Stepper motors are used to translate electrical pulses into mechanical movements.
‘* The main advantage of using the stepper motor is the position control.
* Due to their properties, stepper motors are used in many applications where a simple position
control and the ability to hold position are needed, including:
a *
‘© Components of a stepper motor
College of Engineering, Muttathara 137Computer Architecture & Microcontrollers_ MODULE
|_S4 EC KTU
¥ Stator: The stator is made up of four coils, that are energized by the pulses froma
microcontroller or a stepper controller.
¥ Rotor: The number of steps of the rotor and its alignment with the stator determines the
step angle and steps per revolution.
¥ Permanent magnets: The rotor is mounted on a permanent magnet that attracts or repels
the stator coils and hence the propulsion occurs.
‘Stepper motors are broadly divided into two types
1) Unipolar stepper motor
2) Bipolar stepper motor
© Unipolar stepper motor
A
‘Common wire
to suppply
D
‘Stepper
B
Common wire eo
to suppply
Y The unipolar stepper motor has five or six wires out of which four wires are joined to one of
the ends of each of the four stator coils.
Y The connections at the center of the coils are joined together and are connected to the 12V
supply.
¥ They are called unipolar steppers because power always comes in on this one pole.
College of Engineering, Muttathara 138Computer Architecture & Microcontrollers_ MODULE 3
‘* Bipolar stepper motor
Stepper
c
Y The bipolar stepper motor usually has four wires coming out of it:
Unlike unipolar steppers, bipolar steppers have no common center connection.
Y They have two independent sets of coils instead.
2.2. Interfacing Unipolar stepper motor to 8051 Microcontroller.
av
Hv
CURRENT DRIVER IC
‘com
ae ac fh
2B 2c
sa ac HEE
4B 40
& ecftt
ed
ULN2003A UNIPOLAR STEPPER MOTOR
‘+ We are using Port 2 of 8051 microcontroller to generate high and low pulses and using a current
amplifier IC i.e. ULN2003a to amplify the current to drive the stepper motor using the pulse of the
microcontroller.
‘* On the basis of the way the coils are energized, a Unipolar Stepper motor can be classified into
three categories:
1) Wave Drive Mode
2) Full Drive Mode
3) Half Drive Mode
Wave drive mode
Y Inthis mode, one coil is energized at a time. So all four
Y This mode produces less torque than full step drive mode.
aie energized one after another.
Steps |A|B|C|D | HEX
1_| 1/0] 0/0 | oxos
2 [o|1[ 0] 0 | 0x04
3 [o/0|1/ 0 | oxoz
4 [o/o|o/ 14 | oxo1
College of Engineering, Muttathara 139Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
«Full Drive mode
¥ inthis mode, two coils are energized at the same time.
v This mode produces more torque. Here the power consumption is also high
Steps |A|/B/C|D/ HEX
1 [a/a[o|o | oxoc
2 |o/1| 1/0 | 0x06
3 [o/0|1/ 14 | 0x03
4 [1[o[o|1 | 0x09
* Half Drive Mode
Y In this mode, one and two coils are energized alternately.
Y Atfirst, one coil is energized then two coils are energized.
Y This is basically a combination of wave and full drive mode.
¥ Itincreases the angular rotation of the motor
Steps |A|B|C|D| HEX
1 1 | 0/0} 0 | 0x08
2 1|1/0| 0 | Ox0c
3 0 | 1) 0/| 0 | 0x04
4_[o[a[1] 0 ox06
5 o|o 0 | 0x02
6 ojo 1 | 0x03
7 O10 1 | 0x01
8 1 | 0/0} 1 | 0x09
© Why are we using ULN2003A driver?
¥ AStepper motor consumes a current of 0.1—1 A during step rotation with the load.
¥ An AT89c51 produces a maximum current of 0.045A through the ports.
Y Therefore, the pulses sent from Port 2 are not sufficient to run a stepper motor.
Y Hence, we cannot directly interface stepper motors with microcontrollers like AT89C51
microcontroller.
‘There are two solutions to this problem:
1) Touse a motor driver like L239D OR
2) To use a current amplification IC
<
ULN2003A
Q) Interface Stepper Motor to 8051 and write 8051 C language program to operate it in full drive mode
Solutio
sia
cURRENTORVER ef
con
7 sh “Ee 1
fe Eee ce
ee sje he
& &
8051 are
RDG UNIPOLAR STEPPER MOTOR
#includecreg51.h>
void MSdelay(int ms)
{ unsigned int i j
for(i =0; i< ms; i++) // Outer “for” loop for given milliseconds value
forlj = 0; j< 1275; i+); // Inter “for” loop for ims delay
College of Engineering, Muttathara 140Computer Architecture & Microcontrollers_ MODULE
void main()
{ unsigned int rot_angle[] = {0x0C, 0x06, 0x03, 0x09}; // Full drive Mode
unsigned int i;
while(1) // To repeat infinitely
{for(i =0;i<4; i++)
{ P2=rot_anglelil;
MSdelay(100); _//100 times 1 ms delay
}
Note: Change the value to get other modes
Eg: unsigned int rot_angle[] = {0x08, 0x04, 0x02, 0x01}; // Wave drive Mode
Q) Assembly language program to interface stepper motor with 8051
+
sv
cunsenronwerie f
i cone S
=: Se
P23 He 6 Ee ca
8051 a
RDA UNIPOLAR STEPPER MOTOR
// Wave Drive Mode
ORG OOH
MAIN: MOV P2, #08H
CALL DELAY
MOV P2, #04H
ACALL DELAY
MOV P2, #02H
ACALL DELAY
Mov P2, #01H
ACALL DELAY.
‘SUMP MAIN
sSub-routine or Sub-program for delay
DELAY: MOV R7, #00H
LOOP1: MOV R6, #00H
LOOP2: MOV RS, #08H
LooP3: NOP
DINZRS, LOOP
DINZ R6, LOOP2
DJNZR7, LOOP1
RET
College of Engineering, Muttathara 1mComputer Architecture & Microcontrollers_ MODULE
QA switch is connected to pin P2.7. Write a C program to monitor the status of sw
and perform the following:
(a) If sw =0, the stepper motor moves clockwise.
(b) If sw = 1, the stepper motor moves counter-clockwise.
Soluti
aoa wv
sw
CURRENT DRIVER IC f
‘Switch Pio omg S
7 Py 2 HS S
para ps
ono se]
me 8051 1
UNIPOLAR STEPPER MOTOR
Hinclude
sbit SW=P247;
void MSdelay(int ms)
{ unsigned int i, j;
for(i
} I< ms; i+) // Outer “for” loop for given milliseconds value
j< 1275; j++); // \nter “for” loop for Ims delay
void main()
{ unsigned int rot_angle[] = (0x08, 0x04, 0x02, 0x01}; // Wave drive Mode
unsigned int i;
while(1) /Jinfinite loop for rotation
{ SW=1;//to set PORT PIN asINPUT
for(i =0; i<4; i++)
{ if(SW ==0)
P1 = rot_anglelil;
else
P1 = rot_angle(3-
Msdelay(100);
}
College of Engineering, Muttathara 142Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
3. Interfacing of Keyboard with 8051 and its programming.
3.1 4x4 Matrix Keypad Module - 16 Keys
¥ The 4x4 matrix keypad is an input device, it usually used to provide input value in a project.
¥ thas 16 keys in total, which means it can provide 16 input values.
The 4x4 matrix keyboard has a total of 8 pins.
4 of them are pins for rows and 4 for columns.
Each button is essentially a push button that short-circuits both a row and a column when pushed.
Ashort circuit is formed in the intersection of the row and the column to determine and distinguish
which button was pressed.
For example, if you give the first row (Ri) alow mark anda high value for all columns, for example,
when you press 3, the high mark in column C3 changes to low. At the intersection of R1 and C3 is
the 3-button button. In all cases like this, we can register which button was pressed.
KA4A8
<
3.2. How a microcontroller can read these lines for a button-pressed state
‘©The microcontroller sets
Yall the column line to 1 (8051 port pin as input) and
Yall row lines to 0 (8051 port pin as output).
‘* After that, it checks the column lines one at a time.
‘+ Ifall column connection stays HIGH, the button on the row has not been pressed.
‘* IFit one column goes LOW, the button on that column has been pressed.
‘+. Immediately, it checks the row lines one at a time by setting
¥ all the column line to 0 (8051 port pin as output) and
¥ allow lines to 1 (8051 port pin as input).
College of Engineering, Muttathara 143Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
‘+ Now, the microcontroller knows which row was set to LOW, and which column was detected LOW
when checked.
‘+ Finally, it knows which button was pressed that corresponds to the detected row & column.
1
0 7
+ inet EEE i
t ox Ls fs oe
; Gite mee
t oe =p dal ES
2 mare BEE e3. sssossen
rs ase AF EP
Re ov Rue, ®
7 ale SEE
fe Banke
ssa Bao
oof
no
p20
ro
include
sfr Idata = 0x90; //P:
sbit rs 20;
sbit rw = P21;
sbit en = P22;
.CD data pins (Fig. 1)
sbit R1 = P390; // Connecting 4x4 keypad to Port 3
sbit R2 = P31;
sbit R3 = P342;
sbit R4 = P343;
sbit C1 = P3494;
sit C2 = P345;
sit C3 = P36;
sbit C4 = P347;
unsigned char a[4][4] ={ 2','3', Ah,
'S', '6', 'B'},
‘c),
‘#, 'D'} k
void ledemd(unsigned char );
void leddata(unsigned char );
College of Engineering, Muttathara 144Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
void MSdelay(unsigned int );
void row_finder(unsigned char);
void main(void)
{ unsigned char b[] = {0x38, OxOF, 0x01, 0x06, 0x80);
unsigned char i;
forli=0;i<5;i++)
{ Iedcmad (bli);
}
while(1)
{ C1=C2=C3=C4=1;
R1=R2=R3=R4=0; — //Make Columns as Input and Row as Output
MSdelay(30);
else if (C3:
else if (C4==0) row_finder(3);
}
void row_finder(unsigned char c) //Function for finding the row for column 1
{
//Make Columns as Output and Row as Input
}
void Iedemd(unsigned char value)
{ Idata = value; // put the value on the pins
en=1; // strobe the enable pin
MSdelay(2);
en=0;
i
void leddata(unsigned char value)
{ Idata = value; ‘//put the value on the pins
en=1; // strobe the enable pin
Msdelay(2);
en=0;
}
College of Engineering, Muttathara 14sComputer Architecture & Microcontrollers_ MODULE 3,
void MSdelay(unsigned int ms)
{ unsigned inti, j;
for(i i
// Outer “for” loop for given milliseconds value
for(j = 0; j< 1275; j+4); // inter “for” loop for 1ms delay
4. Interfacing of ADC with 8051 and its programming.
INO —e{ GND Clock Vue
ADCO808/0809
=|
In? —}
| Vee) £0C -——>
a Vict OF ++
SC ALEC BA
PFT Tes,
¢ ADC 0809 is an 8 channel, 8 bit ADC. It converts analog voltage input into an 8 bit digital data
output.
‘* The channel voltage is internally sampled and held into a capacitor.
Conversion takes place internally using “Successive Approximations Algorithm”.
‘© Reference voltage for conversion is provided using +Vser and —Vrer.
'* The clock supply needed for conversion is given through CLK (typically ~ 1MH2).
© There is no self-clocking and the clock must be provided from an external source to the CLK pin.
‘+ Although the speed of conversion depends on the frequency of the clock connected to the CLK
‘© pin, it cannot be faster than 100 microseconds.
4.1 Steps to program the ADC0808/0809
Step 1: To select one input out of 8 options, there are three select lines (C, B and A).
Step 2: We puta voltage channel (analog signal) on selected input (0...7)
Step 3: Latch it using ALE (address latch enable) pin. It needs an L-to-H pulse to latch in the
address.
Step 4: Activate SC (start conversion) by an L-to-H pulse to initiate conversion.
Step 5: EOC (end of conversion) to see whether conversion is finished. H-to-L output indicates that
the data is converted and is ready to be picked up.
Step 6: Activate OE (output enable) to read data out of the ADC chi
will bring digital data out of the chip.
by Teh LIL LIL LL LL L$
wo) —p RL
Fy A Se
. An L-to-H pulse to the OE pin
College of Engineering, Muttathara 146Computer Architecture & Microcontrollers_ MODULE
asv
= mak
rs} —>[ noon v,
bag pf wesc) veto} o 2s6v
Tas tale De 10
108 won
He Tam | fs ne |
IS
—
—
IS 4
i
al v7 cLocey ‘External
he INTR(EOC) I ial
anc 6
[——"N
ALE BIT P2.4
OF BIT P2.5
SC BIT P2.6
EOC BIT P2.7,
ADDR_A BIT P2.0
ADDR_8 BIT P2.1
ADDR_C BIT P2.2
IMYDATA EQU P1
‘ORG 0000H
MOV RO, #20H ; RO = 20H (Pointer to Internal RAM location 20H)
MOV MYDATA, #OFFH ;make P21 an input
BACK: SETB EOC jmake EOC an input
CLR ALE clear ALE
CLR SC sclear WR
CLR OE yelear RD,
CLR ADDR_C sC=0
CLR ADDR_B ;B=0
SETB ADDR_A ‘1 (Select Channel 1)
ACALL DELAY smake sure the addr is stable
SETB ALE jlatch address
ACALL DELAY sdelay for fast DS89C4x0 Chip
SETB SC ;start conversion
ACALL DELAY
CLR ALE
cur sc
HERE: JB EOC, HERE jwait until done
HERE1: JNB EOC, HERE ——_ wait until done
SETB OE jenable RD
ACALL DELAY wait
MOVA,MYDATA read data
MOV @RO, A Store converted data into Internal RAM location pointed by RO
INC RO jIncrement location pointer
DINZ R7, Back jRead converted data into A register
Here: SIMP Here jEnd the program
College of Engineering, Muttathara 147Computer Architecture & Microcontrollers_ MODULE 3,
5. Interfacing of DAC with 8051 and its programming.
aa #5V
ssi DACO808.
RD Ve
WR Veet)
Pi0 |} > po
Shri our
[-—>| 2
[lps :
> {ps veers wwe
[+ ps ss
Sloe
vig] ——> 7
To
scope
VEE COMP_GND
“nv
5.1 Program to Generate Staircase Waveform
FFH
2
ot
oar
Start: MOV A, HOOH ; A = 00H
Back: MOV P1, A; P1=A register
‘ACALL Delay ; Call a delay of 100 milliseconds
INC A; Increment A
JNZ Back ; Loop till A rolls back to OOH.
SJMP Start ; End the program
;Sub-routine or Sub-program for delay
DELAY: MOV R7, #OOH
LOOP1: MOV R6, #00H
LOOP2: MOV RS, #02H
Loop3: NOP:
DJNZ R5, LOOPS
DINZR6, LOOP2
DINZ R7, LOOPL
RET
College of Engineering, Muttathara 148Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
5.2 Program to Generate Sine Waveform
Table 7. Angle versus Voltage Magnitude for Sine Wave
Angle 0 Vout (Voltage Magnitude) Values Sent to DAC (Decimal)
(degrees) Sin 5. V+ (5 V x sin 0) (Voltage Mag. x 25.6)
0 0 5 128
30 05 75 192
60 0.866 9.33 238
90 1.0 10 255
120 0.866 9.33 238
150 0.5 75 192
180 0 5 128
210 -0.5 2.5 64
240 0.866 0.669 17
270 =1.0 0 0
300 —0.866 0.669 17
330 =0.5 2.5 64
360 0 5 128
MOV DPTR,#TABLE
MOV R2,#COUNT
BACK: CLRA
MOVC A, @A+DPTR
MOV P1,A
INC DPTR
DINZ R2, BACK
SJMP AGAIN
ORG 300
TABLE: DB 128,192,238,255,238,192 see Table 7
DB 128,64,17,0,17,64,128
To get a better looking sine wave, regenerate for 2-degree angles
vals
eT re
Sap
at
gL
cL
4
at
a
iL
Me
30605 120 150 180210 240 270 300 380 0
Angle versus Voltage Magnitude for Sine Wave
College of Engineering, Muttathara
149Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
Programming DAC in C (to Generate Sine Waveform)
include
sfr DACDATA = P1;
void main()
{ unsigned char WAVEVALUE[12] = {128,192,238,255,238,192,128,64,17,0,17,64};
unsigned char x;
while(1)
{ for(x=O;x<12;x++)
DACDATA = WAVEVALUE[x];
}
}
Q) Write an embedded C program for 8051 microcontroller to repeatedly display the sequence
0,1,2,3,4,5,6,7,8,9 using a 7 segment display with a delay of 1.5 seconds between each number.
Solution:
reer
include
sfr datapin = OxA0; ‘1/P2.=7 - segment display pins
sbit en = P30;
void MSDelay(unsigned int );
void main(void)
{ Hpattern for 0,1,2,3,4,5,6,7,8,9
unsigned char b[] = { 0x3F, 0x06, 0x5B, Ox4F, 0x66, Ox6D, 0x7D, 0x07, Ox7F, Ox6F };
unsigned char i;
en=1; Ufo enable 7-segment display using transistor
forli=0 ; i<10; i++)
{ datapin = bf};
MsDelay(1500); // delay of 1.5 seconds
+
College of Engineering, Muttathara 150Computer Architecture & Microcontrollers_ MODULE 3_S4 EC KTU
void MSDelay(unsigned int itime) // function to create n millisecond delay
{
Q) Write an embedded C program for 8051 microcontroller to repeatedly display the sequence
1,5,8,0,2,6,4,9,3,7 using a 7 segment display with a delay of 1.5 seconds between each number.
Solution:
#include
sfr datapin = OxA0; 1/P2.=7 segment display pins
sbit en = P30;
void MSDelay(unsigned int );
void main(void)
{unsigned char af] = {1,5,8,0,2,6,4,9,3,7};
unsigned char b[] = { Ox3F, 0x06, 0x5B, Ox4F, 0x66, Ox6D, Ox7D, 0x07, Ox7F, OX6F };
unsigned char i;
en=1;
for(i=0 j i