Assemblers and Development Tools For 8086 and 8051 Microprocessors
Assemblers and Development Tools For 8086 and 8051 Microprocessors
Assemblers and Development Tools For 8086 and 8051 Microprocessors
ASSEMBLERS
AND
DEVELOPMENT TOOLS
FOR
8086 AND 8051
MICROPROCESSORS
CMPE323 MICROPROCESSORS LAB MANUAL
Dr. Mehmet Bodur
ii
iii
Foreword
Foreword
The objective of this book is to supply sufficient guidance to exploit the tools for
developing microprocessor based design and application projects up to physical level of
the implementation. The contents of is book is a collection of the hands-on experiments to
practice several hardware/interfacing/software issues for an introductory level
microprocessor course in a Computer Engineering program.
You may find considerable amount of practical information to guide a student in using the
modern microprocessor development tools along with the classical assembly programming
environments. The material is displayed in ten experimental chapters, where the first five
experiments are mainly on the development and demonstration of software in 8086
assembly language, next three are on the 8051 hardware for microprocessor interface units
including ports, memory, analog to digital converters and serial communication ports.
Furthermore it contains two 8051 system examples with development details in higher
level languages Keil-C51 C compiler. These two design examples are expected to serve for
term assignments to an introductory level microprocessor course such as CMPE 323 in
Computer Engineering Program of the Computer Engineering Department at Eastern
Mediterranean University, where the experiments are currently carried as lab activities of
CMPE 323 course.
The author of this book is aware of lots of books concentrating on both application design
and practical issues on using microprocessors. In the perspective of the author, the shift of
the microprocessor based applications from the assembly to the higher level languages is
inevitable while the interfacing units, memory size, and processing power of the processors
are developed in Moores law, almost doubling at every two or three years.
Finally it is the authors pleasure to acknowledge his colleagues Dr. Mohammed Salamah
and Prof. Dr. Hasan Komurcugil who contributed to the previously given microprocessor
courses, CMPE222, CMPE 326 and CMPE328. The finalized experiments are a product of
an evolution starting from the mentioned courses.
This kind of books to guide the practical applications on diverged microprocessor
development tools are not expected to be error-free, although the author spent considerable
effort for the correction of the errors during the practical laboratory exercise of the students
who followed the included experimental procedures. The author welcomes your comments,
suggestions, and corrections for the corrected editions of these laboratory notes.
Welcome to work with the microprocessors, their languages, and their development tools.
Dr. Mehmet Bodur
iv
Contents
FOREWORD ...................................................................................................................................................... III
CONTENTS .......................................................................................................................................................... V
1. TASM, EDIT, DEBUG AND EMU8086 ASSEMBLER TOOLS................................................................. 1
1.1
OBJECTIVE ...................................................................................................................................... 1
1.2
INTRODUCTION ............................................................................................................................... 1
1.2.1. Editing the source file................................................................................................................ 1
1.2.2. Assembling to an object file...................................................................................................... 1
1.2.3. Linking to an Executable or Command File.............................................................................. 2
1.2.4. Tracing and Debugging of an EXE file ..................................................................................... 3
1.2.5. Emu86 IDE ................................................................................................................................ 4
1.2.6. EMU8086 Source Editor ........................................................................................................... 4
1.2.7. EMU8086 / MASM / TASM compatibility ................................................................................. 5
1.3
EXPERIMENTAL PART...................................................................................................................... 7
1.3.1. Writing a Source File ................................................................................................................ 7
1.3.2. Assembling with TASM .............................................................................................................. 8
1.3.3. Assembling with Emu8086......................................................................................................... 9
2. DATA TYPES, AND EFFECT OF ALU INSTRUCTIONS ON FLAGS ................................................ 11
2.1
OBJECTIVE .................................................................................................................................... 11
2.2
PRELIMINARY STUDY .................................................................................................................... 11
2.3
EXPERIMENTAL PART.................................................................................................................... 11
2.3.1. Data types and Data directives................................................................................................ 11
2.3.2. ALU Operations and Flags...................................................................................................... 13
3. SIMPLE VIRTUAL 8086 DEVELOPMENT BOARD ............................................................................... 15
3.1
OBJECTIVE .................................................................................................................................... 15
3.2
INTRODUCTION ............................................................................................................................. 15
3.2.1. 8086 and main memory ........................................................................................................... 15
3.2.2. 8086 Processor Bus ................................................................................................................. 15
3.2.3. Address Latching ..................................................................................................................... 16
3.2.4. System Configuration .............................................................................................................. 16
3.2.5. IO Address decoding ............................................................................................................... 16
3.2.6. Simple Output Port UL ............................................................................................................ 18
3.2.7. Simple Input Ports UA and UB................................................................................................ 18
3.2.8. Serial Communication Device ................................................................................................. 19
3.3
EXPERIMENTAL PART.................................................................................................................... 21
3.3.1. Execution of a code on a virtual 8086 system.......................................................................... 21
3.3.2. Adding Port UA and Port UB.................................................................................................. 22
3.3.3. USART and Capitalization ...................................................................................................... 23
4. BIOS AND DOS SERVICES.......................................................................................................................... 29
4.1
OBJECTIVE .................................................................................................................................... 29
4.2
PRELIMINARY STUDY .................................................................................................................... 29
4.3
EXPERIMENTAL PART.................................................................................................................... 29
4.3.1. DOS services for String Display and Input.............................................................................. 29
4.3.2. Subroutines and Include files................................................................................................... 31
vi
vii
10.2.6.
Switches and Operation of the System ................................................................................ 79
10.3
ABOUT KEIL C51 COMPILER ......................................................................................................... 79
10.4
DESIGN REQUIREMENTS ................................................................................................................ 80
10.5
REPORTING ................................................................................................................................... 81
11. APPENDIX .................................................................................................................................................... 83
COMPLETE 8086 INSTRUCTION SET.............................................................................................................. 83
Mnemonics ............................................................................................................................................. 83
Operand types:....................................................................................................................................... 83
Notes: ..................................................................................................................................................... 83
Instructions in alphabetical order: ........................................................................................................ 84
SUMMARY SHEET FOR ASSEMBLY PROGRAMMING ..................................................................................... 96
viii
1.
TASM, EDIT, DEBUG
and Emu8086
Emu8086 Assembler Tools
1.1
Objective
TASM is one of the well known 8086 Assembler programs. This experiment will
introduce you TASM, its input, and output file types.
Our objective covers hands-in experience to use
Notepad to create an assembler source file,
TASM to assemble the a source file into an object code
TLink to link an object code into an executable file.
TD and Emu8086 debuggers to trace an executable file.
1.2
Introduction
Assembly language is the lowest level of symbolic programming for a computer system. It
has several advantages and disadvantages over the higher level programming languages.
Assembly language requires an understanding of the machine architecture, and provides
huge flexibility in developing hardware/software interface programs such as interrupt
service routines, and device drivers. 8086 Turbo Assembler is one of the well known
assembler programs used for PC-XT and AT family computers.
1.2.1.
The source for an assembly program is written into a text file with the extension -.ASM, in
ASCII coding. Any ASCII text editor program can be used to write an assembly source
file. We recommend to use NOTEPAD as a general purpose text editor, or the source
editor of the Emu86, which is especially tailored to write 8086 Flat ASM sources for your
experiments.
1.2.2.
The Turbo Assembler program (TASM.EXE) can be started in the command window by
writing TASM <source-file-name> , and transmitting it to DOS using theENTER key.
The full syntax of TASM command is:
>TASM
>TASM [options] source [,object] [,listing] [,xref]
In DOS and Assembly programming, the names are not case-dependent, which means
writing TASM FIRST, Tasm first, tasm FIRST or tasm firST does not make any
difference.
Assume that you have written the following simple assembly program into a text file with
the name first.asm. To assemble it into first.obj file, you shall simply write the command
>tasm first
1.2.3.
The object files contains the program code but some of the labels are still in symbolic
form. A linker converts them into the executable file replacing all symbols with their
corresponding values. The use of library procedures, and splitting the large programs into
modules are possible since a linker can calculate a label referred from a different object
file. The file first.obj is converted to an executable by the DOS command
>tlink first
Figure 2 shows typical command window message after tasm and tlink is executed.
1.2.4.
Turbo Debugger, td.exe, is an 8086 debugging tool which gives a convenient view of the
CPU status, and the memory segments. The command line syntax of TD has options,
program-file-name, and arguments
>TD [options] [program [arguments]]
-x-
into the command window will start the debugger to load the executable first.exe to its
memory space. The screenshot of TD is shown in Figure 3. In Turbo debugger, you can
execute the instructions step by step and trace the execution of the code. Any message
written to the screen will invoke the screen display mode to let you observe the message.
1.2.5.
Emu86 IDE
1.2.6.
The source editor of EMU86 is a special purpose editor which identifies the 8086
mnemonics, hexadecimal numbers and labels by different colors as seen in Figure 4.
a)
b)
Figure 4. a) EMU8086 Source Editor, and b) assembler status report windows.
5
The compile button on the taskbar starts assembling and linking of the source file. A report
window is opened after the assembling process is completed. Figure 5 shows the emulator
of 8086 which gets opened by clicking on emulate button.
Assemblers And Development Tools For 8086 And 8051 Microprocessors
1.2.7.
Syntax of emu8086 is fully compatible with all major assemblers including MASM and
TASM; though some directives are unique to this assembler.
1) If required to compile using any other assembler you may need to comment out these
directives, and any other directives that start with a '#' sign:
#make_bin#
#make_bin#
#make_boot#
#cs=...#
etc...
2) Emu8086 ignores the ASSUME directive. manual attachment of CS:, DS:, ES: or SS:
segment prefixes is preferred, and required by emu8086 when data is in segment other
then DS. for example:
mov ah, [bx]
mov ah, es:[bx]
3) emu8086 does not require to define segment when you compile segmentless COM file,
however MASM and TASM may require this, for example:
name test
SEGMENT
CSEG
ORG 100h
start: MOV AL,
MOV BL,
XOR AL,
XOR BL,
XOR AL,
CSEG
END
RET
ENDS
start
4) entry point for COM file should always be at 0100h, however in MASM and TASM you
may need to manually set an entry point using END directive even if there is no way to
set it to some other location. emu8086 works just fine, with or without it; however error
message is generated if entry point is set but it is not 100h (the starting offset for com
executable). the entry point of com files is always the first byte.
5) if you compile this code with Microsoft Assembler or with Borland Turbo Assembler,
you should get test.com file (11 bytes). Right click it and select send to and emu8086.
You can see that the disassembled code doesn't contain any directives and it is identical
to code that emu8086 produces even without all those tricky directives.
6) emu8086 has almost 100% compatibility with other similar 16 bit assemblers. the code
that is assembled by emu8086 can easily be assembled with other assemblers such as
TASM or MASM, however not every code that assembles by TASM or MASM can be
assembled by emu8086.
7) a template used by emu8086 to create EXE files is fully compatible with MASM and
TASM.
8) The majority of EXE files produced by MASM are identical to those produced by
emu8086. However, it may not be exactly the same as TASM's executables because
TASM does not calculate the checksum, and has slightly different EXE file structure, but
in general it produces quite the same machine code. There are several ways to encode
the same machine instructions for the 8086 CPU, so generated machine code may vary
when compiled on different compilers.
9) Emu8086 integrated assembler supports shorter versions of byte ptr and word ptr,
these are: b. and w. For MASM and TASM you have to replace w. and w. with byte ptr
and word ptr accordingly.
for example:
lea bx, var1
mov word ptr [bx], 1234h ; works everywhere.
mov w.[bx], 1234h
; same instruction / shorter emu8086
syntax.
hlt
var1
var2
db
db
0
0
10) LABEL directive may not be supported by all assemblers, for example:
TEST1 LABEL BYTE
; ...
LEA DX,TEST1
DX,TEST1
the offset of TEST1 is loaded into DX register. this solutions works for the majority of
leading assemblers.
1.3
Experimental Part
In this experiment you will use TASM, TLINK, and EMU8086 to generate an executable
from an assembly source, and to trace the step-by-step execution of the executable in TD
debugger and in EMU8086 emulator
1.3.1.
Objective: to practice writing and editing an ASCII assembly source file using notepad.
Procedure: Generate a folder asm. Copy the files tasm.exe, tlink.exe, td.exe into asm
folder. Generate a working folder with name exp1, and start a text file in your working
folder In the explorer while folder is open
- click on right button of mouse, and
- select new, select text document. New Text Document.txt will be generated.
- Rename it exp1.asm
Now, you have an empty text file, with the name exp1.asm. Use windows-start > allprograms > accessories > notepad to open the Notepad text editor. Drag the file
exp1.asm to the title-bar of the Notepad. The title will change to exp1.asm Notepad. It
means that you successfully opened the file exp1.asm for editing in notepad. Write the
following source program into the edit window.
------file: exp1.asm----; STUDENT NAME and SURNAME:
; STUDENT NUMBER:
TITLE PROG2
PROG2-2 (EXE) PURPOSE :ADD 4 WORDS OF DATA
PAGE 60,132
.MODEL SMALL
.STACK 64
;----------------------------------------------------------------------------------------------------------------.DATA
DATA_IN
DW 234DH,1DE6H,3BC7H,566AH
ORG 10H
SUM
DW ?
;--------------------------------------------------------.CODE
MAIN PROC FAR
;THIS IS THE PROGRAM ENTRY POINT
MOV
AX,@DATA
;load the data segment adress
MOV
DS,AX
;assign value to DS
MOV
CX,04
;set up loop counter CX=4
MOV
DI,OFFSET DATA_IN ;set up data pointer DI
MOV
SI,OFFSET SUM
MOV
BX,00
;initialize BX
ADD_LP:
ADD
BX,[DI]
;add contents pointed at by [DI] to BX
INC
DI
;increment DI twice
INC
DI
;to point to next word
DEC
CX
;decrement loop counter
JNZ
ADD_LP
;jump if loop counter not zero
MOV
SI,OFFSET SUM
; SI points SUM
MOV
[SI],BX
;store BX to SUM in data segment
MOV
AH,4CH
;set up return
INT
21H
;return to DOS
MAIN ENDP
END MAIN
;this is the program exit point
------end of file -----Use tabs to start the mnemonics at the same column.
Reporting:
Start a text file (you may use notepad ) with name exp1.txt. Fill in the following
title to your text file.
CMPE 323 Experiment
Experimentent-1 Report. <your name surname, student number>
PART1 Assembly source file
Keep your report file in a safe place until you complete the experiment and e-mail it to the
specified address.
1.3.2.
Objective: Assembling the source file with TASM, and tracing it in TD.
Procedure: You have already written the source file exp1.exe .
- Organize a folder structure such as
ASM folder contains
files TASM.EXE, TLINK.EXE, and TD.EXE.
folder exp1, which contains exp1.asm and exp1.bat.
-Edit exp1.asm to contain the complete source text by copy and paste.
Fill your student name and number to the first two lines.
-Edit exp1.bat to have the following text lines in it.
..\
..\tasm -l exp1
pause
..\
..\tlink exp1
pause
..\
..\td exp1
pause
-Click on exp1.bat to execute assembler. You will observe a DOS window opened, and
tasm executed on exp1.asm, with the list option active. DOS window will pause and
will allow you to read the messages generated by TASM. You will observe
exp1.obj, exp1.lst, and exp1.map files generated in folder exp1.
-If you press on space-bar, bat file will continue to execution, and it will execute the
linker tlink on exp1.obj. Tlink will generate exp1.exe file into the exp1 folder. Batch
file will pause until you press the space-bar.
-Press the space-bar again to execute turbo debugger on exp1.exe file. In the debugger,
you can trace the execution by executing each line of the assembly program stepwise.
Reporting:
In td read the hexadecimal contents of the program code exp1.exe (28 bytes), and the
contents of the memory location cs:0009. Start PART2 in your report file, and fill in (as text,
i.e., A3 02 etc)
PART2
B8 68 5B 8E D8 ...
cs:0009 contains ....
Then open exp1.lst, which is generated by turbo assembler in a text editor (notepad).
Copy-and-paste the first page of the listing into your report file
exp1.lst contains -----------------------01/13/11 11:32:32
Turbo Assembler Version 1.0
EXP1.ASM
1
2
3
4 0000
Page 1
0000
0000
0000 234D 1DE6 3BC7 566A
0010 ????
0012
0000
0000 B8 0000s
.STACK 64
;--------------------------------------------------------;--------------------------------------------------------.DATA
DATA_IN DW 234DH,1DE6H,3BC7H,566AH
ORG 10H
SUM
DW ?
;------------------------------;----------------------------------------------------------------------------------------------------------------.CODE
MAIN
PROC FAR
;THIS IS THE PROGRAM ENTRY POINT
MOV
AX,@DATA
;load the
the data segment address
Save your report file in a safe place until you complete the experiment and e-mail it to the
specified address.
1.3.3.
10
11
2.
Data Types,
Types,
and Effect of ALU instructions
on Flags
2.1
Objective
2.2
Preliminary Study
2.3
Experimental Part
2.3.1.
------end of file---------In this program, data8 is a DOS screen message, and all DOS screen messages
shall terminate with a $ character. data8 contains the ASCII message string
to be printed on the screen. mov dx,offset data8 loads the offset of data8 in
12
- Execute the batch file, and press space bar to proceed with tlink and exp2p1.
You will observe the message Hello world written on the dos command
window before pressing the space bar for the third pause.
- Open the exp2p1.lst file in notepad to observe how the data directives place the
data items into the reserved memory locations in the data segment (First start
notepad, then open the file from browser, or drag the file into notepad
window). You will observe the followings in the list file.
Observations-1:
1- The quoted strings are converted to ASCII coding. Check the coded
characters against the following printable ASCII character table.
-0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -A -B -C -D -E -F
! " # $ % & ' ( ) * + , - . /
23- 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
4- @ A B C D E F G H I J K L M N O
5- P Q R S T U V W X Y Z [ \ ] ^ 6- ` a b c d e f g h i j k l m n o
7- p q r s t u v w x y z { | }
2- db directive codes the numbers in single bytes, in the listed order.
3- dw directive codes the numbers in two-byte groups, in little endian
convention.
4- dd codes the numbers in four-byte groups, in little endian convention.
5- dup() codes repeated number of data into data area. In the list file data is
shown by dup() function. However, sufficient number of bytes are
allocated for the duplicate data.
Reporting:
1- Start a text file with the name exp2.txt.
2- Write the Report Title in the following format
CMPE328 Experiment 2,
Part 1
2- Copy the data definition lines (data1 ... data8) from lst file to exp2.txt.
3- Save the text file to report the coming report item.
Procedure-2:
1- Open exp2p1.exe in td (i.e., first start td.exe, then open the file exp2p1.exe in
td).
2- Right click on ds, and change its contents to the immediate value of the first
instruction in the code segment (i.e, for mov ax,5B68 make ds=5B68h.)
3- Click on view > dump to open the data segment window.
4- Right click on command window title-bar. From the pop-up menu click editmark.
13
5- Drag the mouse while left-clicked on data-segment dump window, to mark the
ds- dump from your name to hello world message (including both lines as well).
6- While the marked area stays on the dump window, right-click on command
window title-bar, and click edit-copy in the pop-up window. Then open exp2.txt
in notepad, and use paste to transfer the copied text into exp2.txt. Your text will
be similar to the following, however it will be different in some fields and
addresses.
Assemblers and Development Tools for 8086 and 8051 Microprocessors
Experiment 2,
0000
000C
0012
0014
0018
004A
4E
6E
65
03
05
00
00
00
00
00
77
61
61
72
00
00
00
00
00
00
00
6F
4E 61 6D 65 2D
72 6E 61 6D 65
4E 75 6D 62 65
2D 4C
007B 0123
00000003 02*
(00000005)
48 65 6C 6C 6F
6F 72 6C 64 21
53 75 + data1 db
'Name-Surname'
72
'Number'
45, 4Ch
0123, 0123h
3, 2 dup(5)
6D
6D
2D
00
00
00
00
00
00
48
72
72
62
01
00
00
00
00
00
00
20
24
65
65
4C
00
00
00
00
00
00
65
6C
2D
4E
7B
05
03
14
00
00
00
6C
64
53
75
00
00
00
31
00
00
00
6C
21
75
6D
23
00
00
82
21
00
00
6F
20
data2
data3
data4
+ data5
db
db
dw
dd
20 77 + data8 db
20 24
Name-Sur
nameNumb
er-L{ #?
?
?
?
?
1
!
Hello
world! $
Save exp2.txt, and observe the following items on the edit window.
Observations-2:
1- data3 db 45, 4Ch is expressed in lst file memory listing by 2D 4C (45=2Dh).
2- data4 dw 0123, 0123h is converted to 007B 0123 in the lst file, but it is written
in little endian convention into the memory area as 7B 00 23 01 (shown in
circles).
3- data5 dd 3, 2 dup(5) is expressed in lst file by 00000003 02*(00000005), but
it is filled into memory as 03 00 00 00 05 00 00 00 05 00 00 00 (in littleendian double-words, and 5 repeated twice.)
2.3.2.
Objective is to observe the changes of flags with the add, sub, cmp, inc, dec, and, or,
neg, mov instructions.
Procedure:
- In this experiment you will use Emu8086 emulator.
- Take your list of instructions from your assistant. The list will contain add, sub,
cmp, inc, dec, and, or, neg, and mov instructions with immediate and register
addressing modes.
- Start Emu8086 emulator. Close the welcome window. Open the file
exp2p1.asm. Use Save-as to save it with the name exp2p2.asm.
- Emu8086 does not allow some data directives. Place a semicolon before data6
and data7 to get rid of dq and dt directives.
- Insert the code youve taken from your assistant after the mov ds,ax line.
- Emulate the assembler code by clicking on Emulate toolbar-button.
- In the emulator window, click on flags-button to open the flags-window.
14
Assemblers and Development Tools for 8086 and 8051 Microprocessors
Reporting: Use single-step button to execute each instruction. For each executed
instruction in your list, fill in the flag status into the report file exp2.txt, i.e.,
Part 2
mov
add
sub
or
and
mov
inc
dec
add
sub
sub
cmp
cmp
...
ax,08803h
ax,07654h
ax,0F803h
ax,0F000h
ax,0000Fh
ax,0FFFFh
ax
ax
ax,1
ax,1
ax,08000h
ax,07000h
ax,09000h
AX
8803
FE57
0654
F654
0004
FFFF
0000
FFFF
0000
FFFF
7FFF
7FFF
7FFF
...
CZSOPA
000000
001000
000000
001000
000000
000000
010011
001011
110011
101011
000010
000010
101110
Late and early deliveries will have 20% discount in grading. No excuse acceptable.
15
3.
Simple Virtual 8086
Development Board
3.1
Objective
3.2
Introduction
3.2.1.
Virtual Simulation Model (VSM) samples in ISIS provide 8086 simulation that loads exe
files to its internal memory. The executable files may be produced using any 8086
compiler including C or 8086 Assembler tools.
3.2.2.
ISIS provides a virtual simulation model (VSM) of 8086 including the 8086 processor bus.
The simulation model provided by ISIS contains configurable internal memory which
simplifies simulation of 8086 systems.
Figure 1. 8086 processor of Prosis 7.7. It contains internal memory which is configured by
properties.
Bus is suitable for memory and IO interfacing. In this experiment, we plan to use it for IO
interfacing.
16
3.2.3.
Address Latching
8086 has AD0-AD15 multiplexed address lines which transfers both data and address
signals. Address is valid while ALE is high, and data is valid while ALE is low and either
~RD or ~WR line is low. 74237 octal latches are suitable for address latching purpose.
3.2.4.
System Configuration
SED system has internal 64 k byte memory integrated into the 8086 device, starting from
address 0x00800. The executable file shall be compiled in small model, and include its
stack, data and code within the 64k memory range. The data, control and buffered address
bus of 8086 is utilized to access to an 8-bit output port, two 8-bit input ports, and a
universal serial asynchronous receiver transmitter (USART) unit.
3.2.5.
IO Address decoding
A 74HC138 provides address decoding for the chip select signals of these IO devices.
17
1
1
1
1
0
0
0
0
0
0
0
0
1
1
1
1
0
0
0
1
0
1
1
0
1
0
1
0
X
X
X
X
X
X
X
X
hex
port
324h 327h
328h 32Bh
32Ch 32Fh
330h 333h
UL
UA
UB
USART
For each IO device the first address of the address ranges are used to address the device
conveniently. Simply, 324h is the address of UL, 328h and 32C are the addresses for UA
18
Assemblers and Development Tools for 8086 and 8051 Microprocessors
and UB. We will consider the USART address later since it has two internal registers
namely control and data.
3.2.6.
The output port UL is constructed using 74273 octal D-flip-flops with common clear
(~MR) and common clock (CLK) inputs. ~MR is permanently disabled by connecting it to
high. The active low enable output ~Y1 of the address decoder and the active low write
output of 8086 are connected to the CLK input of the port through a NOR gate to enable
the clock (with a high) when both ~WR and ~Y1 are low.
In the program we use the instructions
mov DX,324h
out DX,AL
to output the contents of AL to output port UL.
~Y1 of
decoder
Figure 4. Simple isolated output port at address 24h installed with LED displays.
The outputs of the 74273 D-flip-flops are connected to digital LED array to display the
output status in a convenient form. Note that the LED indicators glow while the latch
outputs are high. For example, with the instructions
mov DX,324h
mov AL, 03h
out DX, AL
After the execution of the code LEDs of Q0 and Q1 shall remain dark, and Q3, Q4, Q5,
Q6, and Q7 shall start to glow.
3.2.7.
Input Ports UA and UB are designed to read the 8-bit dip-switch status into register AL.
The instructions
mov DX,328h
in AL,DX
and
mov DX,32Ch
in AL,DX
read the status of the switches SW1 and SW2 into AL.
19
from decoder:
~Y2 for UA,
~Y3 for UB
Figure 5. Simple isolated input port at address 328h and 32Ch installed with switch array.
For example, if the switch positions of SW1 were set to On, On, On, Off, On, On, Off, On
(in the order from 1 to 8) and the instruction in AL,28h was executed the corresponding
bit of AL for On position contains 0, and for Off position it will be 1, resulting in AL=12h.
3.2.8.
The USART 8251A is enabled by ~Y4 of the address decoder, and additionally it has a
Control/~Data select line which is connected to A1. Moreover, the ~RD and ~WR lines
provide reading and writing to control and data registers
from decoder:
~Y4
A8
A7
A6
A5
A4
A3
A2
A1
A0
In/Out
hex address
addressed port
1
1
1
1
1
1
1
1
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
1
1
X
X
X
X
Out
In
Out
In
330h 331h
330h 331h
332h 333h
332h 333h
USART has configuration registers which needs initialization. The Reset sequence of the
USART provides safe reset of the device under the control of program.
xor AL, AL
20
After this initialization code, USART is ready to transmit characters by putting them into
data-out register. It is possible to poll the status register to check the data-out and data-in
registers are full or empty. User may get the received character from data-in register when
bit-1 of status register is high, and may write the character to be transmitted into the dataout if bit-0 of the status register is high.
; This code reads received character into AL.
; If no character received then AL returns zero.
mov DX,332h
; status/control address
in AL, DX
; read status register
test AL,01h
; zero flag is set if AL .AND. 01h is nonzero
jz NotReceived
mov DX,330h
; data-in/data-out address
in AL, DX
; read received bits from data-in into AL.
shr AL,1
; Purge out the start bit, remaining bits are data.
NotReceived:
; Any code that process the received character shall be placed here.
Data transmission through USART is obtained by writing character into data-out register
after USART unit is ready for transmission of a character
; this code transmits the contents of AH register to USART.
WaitReady:
mov DX,332h
; status/control address
in AL, DX
; read status register
test AL,02h
; zero flag is set if AL .AND. 02h is nonzero
jz WaitReady
; Wait until flag is set
mov AL,AH
mov DX,330h
; data-in/data-out address
out DX,AL
; received character transferred into AL.
21
In most applications serial io is managed through an input and an output buffer. USART
generates an interrupt request whenever a character is received or transmission of data-out
buffer is over. The related interrupt service routine transfers the received character from
the data-in register to the input buffer, and it transfers any characters from the output buffer
to the data-out register.
Assemblers and Development Tools for 8086 and 8051 Microprocessors
3.3
Experimental Part
In this experiment you will write and assemble short programs using 8086 instructions in,
out, mov, add, jmp, test, jz, jnz instructions, and you will use EMU8086
assembler/emulator to obtain its executable code. Next, you will verify the executable code
by PROSIS simulation of a virtual simple 8086 educational development system.
At the first part of the experiment we will write a code to display either num1 or num2 on
the LED array depending on the bit-0 switch status of port UA. At the second part, we will
display the sum of the two numbers switch status
3.3.1.
Procedure:
-Start Emu8086, and close the welcome window. Write the following program into the
new-source window of the Emu8086 editor.
; Your Student Number, Name, Surname . . . . . .
; CMPE323 Lab-1 Simple I/O port with 8-bit addressing
.MODEL
SMALL
.8086
.CODE
mov ax,@DATA
mov DS,ax
W1:
mov dx,328h
in al,dx
test al,01h
mov al,num1
jz W2
mov al,num2
W2:
mov dx,324h
out dx,al
jmp W1
.stack
.data
num1 db 20
num2 db 30
END
-Save the file to your work-folder with the file name exp3A.asm
-Use the taskbar-button compile to assemble your source to exp3A.exe into your
working folder.
-Start ISIS and load the design file VSED_WA.dsn (drag and drop it into ISIS window).
- R-click (right click) on 8086 processor on the system diagram. 8086 will be selected
and turned to red, and a pop-up menu will appear. L-click (left-click) mouse on Edit
Properties to open Edit Component window. Change the program file browsing
exp3A.exe. R-click mouse on OK to close Edit Component window. R-click mouse
on any empty part of the diagram window to unselect the processor.
22
Assemblers and Development Tools for 8086 and 8051 Microprocessors
-From ISIS simulation bar
L-click on step button (2nd button) to
start debugging. From the ISIS menu-bar L-click on debug >> 8086 >> registers to
open register window. On the register window R-click >> set font >> Lucida
Console / Bold / 12 to make the font readable. L-clicking on step button will execute
each instruction and update the registers accordingly. Trace the program while PORT
UA A0 switch is at on position and at off position. On your report sheet write the
instruction pointer contents and the instructions for each step of execution until IP
becomes 0005 for the second time.
Reporting:
1- Start a text file with the name exp3.txt.
2- Write the Report Title in the following format
CMPE328 Experiment 3,
Part 1
3- Open the list file exp3A.exe.list and use copy-and-paste to copy it into your
report file.
4- Save exp3.txt to report the coming report item.
3.3.2.
This experiment uses a different board, VSED_BA.dsn, with an 8-bit IO address decoder
for port addresses
It may be obtained from the 16-bit IO addressed
UL
VSED_WA.dsn circuit by removing the AND
UA
and OR gates which are connected to ~E2 and
UB
USART
~E3 of 74HC138, and connecting A6 and A6 to
~E2 and ~E3 lines so that decoder is enabled
when (A7A6A5A4) is (001x).
A7
0
0
0
0
A6
0
0
0
0
A5
1
1
1
1
A4
0
0
0
1
A3
0
1
1
0
A2
1
0
1
0
A1
X
X
X
X
A0
X
X
X
X
hex
24h 27h
28h 2Bh
2Ch 2Fh
30h 33h
port
UL
UA
UB
USART
Procedure:
-Start Emu8086, and close the welcome window. Write the following program into the
new-source window of the Emu8086 editor.
; Your Student Number, Name, Surname . . . . . .
; CMPE323 Lab-1B Simple I/O port with 8-bit addressing
.MODEL
SMALL
.8086
.CODE
mov ax,@data
mov ds,ax
W1:
in al,28h ; first number from UA
mov ah,al
in al,2Ch ; second number from UB
add al,ah
out 24h,al
jmp W1
.stack
.data
23
END
-Save the file to your work-folder with the file name exp1B.asm
-Use the taskbar-button compile to assemble your source to exp1B.exe into your
working folder.
-Start ISIS and load the design file (simply drag and drop it into ISIS window.
- R-click (right click) on 8086 processor on the system diagram. 8086 will be selected
and turned to red, and a pop-up menu will appear. L-click (left-click) on Edit
Properties to open Edit Component window. Change the program file browsing
exp1B.exe. R-click on OK to close Edit Component window. R-click on any empty
part of the diagram window to de-select the processor.
L-click on step button (2nd button) to
-From ISIS simulation bar
start debugging. From the ISIS menu-bar L-click on debug >> 8086 >> registers to
open register window. If the font is too small to read then R-click on the register
window, select set font >> Lucida Console / Bold / 12 to make the font readable.
L-clicking on step button will execute each instruction and update the registers
accordingly. Trace the program to add the last two digit of your student number to
the third&fourth digits in hexadecimal format. For example if your student number is
123456, then you shall write 34h to port UA, and 56h to port UB. Read the result
from the LEDs of port UL.
Reporting
Write your observations into PART2 of your report file in full sentences. (i.e., I set
port UA to 34h by making (AD7..AD4)=0011, (AD3..AD2)=0100, and port UB to
56h by making (AD7..AD4)=0101, (AD3..AD2)=0110. Then, I read from port UL
Q0=0, Q1=1, Q2=0, Q3=1,Q4=0,Q5=0,Q6=0,
Q3=1,Q4=0,Q5=0,Q6=0, Q7=1, which makes
makes in binary 10001010
= 8Ah.)
3.3.3.
Procedure:
-Start Emu8086, and close the welcome window. Write the following program into the
new-source window of the Emu8086 editor.
; Your Student Number, Name, Surname . . . . . .
; CMPE323 Lab-1C Serial Communication
.MODEL
SMALL
.8086
.CODE
mov AX,@data
mov DS,AX
call InitUSART
; Convert all characters to Upper Case
MainLoop:
mov BX,offset inbfr
mov CX,0
Recv:
call RecvChar ; character is in AL
cmp AL,0
jz Recv
; no character
mov [BX],AL
; put chr into buffer
inc BX
; point empty byte in buffer
inc CX
; keep number of received chars
mov DX,324h
; LED-display
out DX,AL
cmp AL,0Dh
; is the character line feed
jnz Recv
; if not line feed receive next char.
24
proc
AL
332h
AL
AL
AL
40h
AL
04Dh
AL
05h
AL
RecvChar proc
; reads received character into AL.
; If no character received then AL returns zero.
push DX
mov DX,332h
; status/control address
in AL,DX
; read status register
and AL,02h
; zero flag is set if AL .AND. 01h is nonzero
jz NotReceived
mov DX,330h
; data-in/data-out address
in AL,DX
; received character transferred from data-in into AL.
shr AL,1
NotReceived:
pop DX
ret
endp
XmitChar proc
; transmits the contents of AH register to USART.
push DX
mov DX,332h
; status/control address
in AL,DX
; read status register
and AL,01h
; zero flag is set if AL .AND. 02h is nonzero
jz XmitChar
; Wait until flag is set
mov AL,AH
mov DX,330h
; data-in/data-out address
25
out DX,AL
; received character transferred into AL.
pop DX
ret
endp
.data
bptr dw 0102h
inbfr db 0 dup(32)
.stack 32
END
-Save the file to your work-folder with the file name exp1C.asm
-Use the taskbar-button compile to assemble your source to exp1C.exe into your
working folder.
-Start ISIS and load the design file VSED_WA.dsn (drag and drop it into ISIS window).
- Rclick (right click) on 8086 processor on the system diagram. 8086 will be selected
and turned to red, and a pop-up menu will appear. Lclick (left-click) on Edit
Properties to open Edit Component window. Change the program file browsing
exp1B.exe. Rclick on OK to close Edit Component window. Right-click on any
empty part of the diagram window to de-select the processor.
Lclick on run button (1nd button) to start
-From ISIS simulation bar
execution.
-If the terminal page does not appear on the screen then Lclick on ISIS-menu-bardebug >> virtual terminal to open terminal monitor window. Right-Click into the
terminal window and check Echo typed characters. -If the font is too small to read
then right-click on the terminal window, select set font >> Lucida Console / Bold /
12 to make the font readable.
- Click on terminal window, and then use keyboard to write Hello, and end the line
with return (enter-key). You shall see
Hello
HELLO
on the monitor. The first character of each character pair is what you entered from
keyboard echoed on the monitor, and the second character is the character sent from
8086 code.
- If you have the oscilloscope settings horizontal (sweep-time) at 1ms/div, ChannelA and Channel-B at DC 2V/div, trigger at DC with source A, at level 20, negative
edge, and Auto-mode then you may observe the received and transmitted waveform
of serial signal on the scope window.
Write your name in lower-case characters, set the trigger of scope to one-shot, and then
send the return character to catch the transmitted string from USART to terminal.
Reporting:
Use Oscilloscope to measure the total time period to transmit your name, and
write it in full sentence into PART3 of your report (i.e., I entered my name
Ali Veli and set the oscilloscope to oneone-shot trigger mode. After I
sent a return character I used cursor to measure total transmission
time T=34.25ms at timetime-base setting 5ms/div).
After you complete the procedures, please save and close exp3.txt file, and e-mail
it using your student e-mail account to [email protected] with the
subject line exp3 within the same day before the midnight.
27
29
4.
BIOS and DOS Services
4.1
Objective
4.2
Preliminary Study
4.3
Experimental Part
4.3.1.
30
start
buf= buf1, (di=buf)
Yes
buf1[1] = buf2[1]
No
Aligned
No
Yes
buf=buf2
Yes
bx
0
(some digits are not
processed)
No
(fill 0 to leftmost digit)
buf[2] = 0
(increment length of number in buf)
buf[1]= buf[1] + 1
mov ah,4ch
int 21h
end
------end of file---------In this program buf1 and buf2 are input string buffers. An input-string buffer
consists of three fields.
The first byte of the buffer is single byte buffer-size field.
The second byte is single-byte input-string-length field.
The remaining bytes are reserved for the ASCII-coded-input-string.
- You will use EMU8086 in tracing the assembly code. Open exp4p1.asm in
EMU8086.
31
- Ask to your Lab-assistant the first and second numbers to be used in tracing the
code. Start the emulation, and go in single steps until you will get the message
waiting for input on the emulator window.
- Switch to the screen by clicking the screen-button on the emulator window.
Then write the first number, and press enter-key to complete the string-input
service. In the emulator window waiting message will disappear.
Assemblers and Development Tools for 8086 and 8051 Microprocessors
is executed.
- Run the code to the end (use run button). Then, in the variable window find the
qword value of sum, and write it into exp4.txt.
sum:
4.3.2.
Objectives:
-to observe usage of macros in improving the readability of the assembly sources.
-to make and use an include file for the subroutines.
Procedure-1:
-The following assembly code finds the maximum and the minimum of an array
of two digit decimal numbers (i.e., numbers between 0 and 99). Write it into
exp4p2.asm in the exp4 folder. Dont forget to fill your name and number into
the first line of the file.
; exp4
exp4p2.asm student name and number :
.MODEL SMALL
.STACK 100h
.DATA
MESSAGE1 DB 13,10,'
The smallest is:
is: '
SMALLEST DB '
'
MESSAGE2 DB 13,10,"
The biggest is: "
BIGGEST DB '
$'
MESSAGE3 DB
?
32
NUMCOUNT EQU 6
NUMBERS DB 51,98,2,18,11,40
ROW
EQU 08
COLUMN
EQU 05
.CODE
MAIN PROC FAR
MOV AX,@DATA
MOV DS,AX
MOV SI,OFFSET MESSAGE3
MESSAGE3
CALL CLEAR
MOV DL,COLUMN
MOV DH,ROW
CALL CURSOR
MOV CX, NUMCOUNTNUMCOUNT-1
MOV DI, OFFSET NUMBERS
MOV SI, DI ; [SI] is smallest
MOV BX, DI ; [BX] is biggest
BACK: INC DI
; is [DI]<[SI]
MOV AL,[DI]
CMP AL,[SI]
JAE BIG
; skip if big
MOV SI, DI ; update if small
JMP SML
; is [DI]>[BX]
BIG: MOV AL,[DI]
CMP AL,[BX]
JB SML
MOV BX, DI
SML: LOOP BACK
mov AL,[SI]
mov AH,0
call HEX2ASCII
HEX2ASCII
xchg AH,AL ; ascii strings bigbig-endian
mov WORD PTR SMALLEST,ax
mov AL,[BX]
mov AH,0
call HEX2ASCII
xchg AH,AL ; ascii strings bigbig-endian
mov WORD PTR BIGGEST,ax
mov DX, OFFSET MESSAGE1
CALL
LL SCREEN
CA
MOV AH,4CH
INT 21H
MAIN ENDP
;------------------------------------------------HEX2ASCII PROC
; converts ah=0, al=binary_number to ax=ascii number
AGAIN:
CMP AL,10
JB CONVERTED
sub al,10
inc AH
jmp AGAIN
CONVERTED:
or ax,3030h
ret
HEX2ASCII endp
;------------------------------------------------CLEAR PROC
; clears 25rows,80cols screen
MOV
AX,0600H
;scroll the entire page
MOV
BH,0F0h
;normal attribute
MOV
CX,0000
;row and column of top left
MOV
DX,184FH
;row and column of bottom right
INT
10H
;invoke the video BIOS service
RET
CLEAR ENDP
;-------------------------------------------------CURSOR PROC
;SET CURSOR POSITION
; sets cursor to DH=row,DL=col.
MOV
AH,02
MOV
BH,00
INT
10H
33
RET
CURSOR ENDP
;-------------------------------------------------SCREEN PROC
; displays a $$-terminated string pointed by DH.
MOV
AH,09
INT
21H
RET
SCREEN ENDP
END MAIN
- You will use Emu8086 to trace this assembly code. Open exp4p2.asm in the
Emu8086, and replace the data entries NUMCOUNT and NUMBERS with the data
supplied to you by your lab instructor.
- Click the emulate button to start emulation. Then click the aux button and select
listing to open the list file. debug button in the emulator windows to open the
debug listing. Use Ctrl-A, and then Ctrl-C to copy the debug listing into
clipboard. Then paste them to the end of the reporting file exp4.txt. The added
text will look like the following text.
EMU8086 GENERATED LISTING. MACHINE CODE <<- SOURCE.
exp4p
exp4p2.exe_
4p2.exe_ -- emu8086 assembler version: 4.05
[ 3/23/2008 -- 23:18:53 ]
=================================================================
=================================================================
[LINE]
LOC: MACHINE CODE
SOURCE
=================================================================
[
[
[
[
1]
2]
3]
4]
:
:
:
0100: 0D 0A 20 20 20 54 68 65 20 73 6D 61
6C 6C 65 73 74 20 69 73 3A 20
. . . . . .
.MODEL SMALL
.STACK
ACK 100h
.ST
.DATA
MESSAGE1 DB 13,10,'
- Now, you shall build an include file with the name exp4p2b.asm.
First save the file exp4p2.asm twice with the new names exp4p2a.asm and
exp4p2b.asm.
In exp4p2a.asm, delete the procedures HEX2ASCII, CLEAR, CURSOR, SCREEN
and insert a line after MAIN ENDP that contains include
include exp4
exp4p2b.asm , i.e.,
MOV AH,4CH
INT 21H
MAIN ENDP
include myproc.asm
END MAIN
HEX2ASCII,
;------------------------------------------------------------------------------------------------HEX2ASCII PROC
; converts ah=0, al=binary_number to ax=ascii number
AGAIN:
CMP AL,10
. . .
. . .
RET
CURSOR ENDP
;-------------------------------------------------SCREEN PROC
; displays a $$-terminated string pointed by DH.
MOV
AH,09
INT
21H
RET
SCREEN ENDP
CLEAR,
CURSOR,
34
- Now open exp4p2a.asm in Emu8086, emulate and run. You will observe that it
runs the same as the single-file source code. In the listing of exp4p2a.asm, the
included code will appear missing. Copy all listing to exp4.txt.
Reporting:
After you complete the procedures, please save and close exp4.txt file, and e-mail
it using your student e-mail account to [email protected] with the
subject line exp4 within the same day before the midnight.
Late and early deliveries will have 20% discount in grading. No excuse acceptable.
Free time practice-1:
In your free time, convert the code exp4p2.asm to two files: File exp4p2c.asm that
contains source code invoking macros, and file exp4p2c.mac that contains
macro definitions. Instead of converting the procedures into parameterless
macros, try to include necessary calling parameters as well into the definition
of macro i.e.,
Table-1 Converting subroutines to macros with parameters.
CURSOR PROC
PROC
MOV
MOV
INT
RET
CURSOR ENDP
SCREEN PROC
MOV
INT
RET
SCREEN ENDP
AH,09
21H
CURSOR
MACRO ROW, COL
;SET CURSOR POSITION
MOV DH, ROW
MOV DL, COL
MOV AH,02H
MOV BH,00
INT 10H
CURSOR
ENDM
SCREEN MACRO STROFFSET
MOV DX,offset STROFFSET
MOV AH,09
INT 21H
SCREEN ENDM
Then, you need also modifications in exp4p2c.asm for invoking the macros
Table-2 Invoking macros with parameters instead of parameters passed in register.
MOV DL,COLUMN
MOV DH,ROW
CALL CURSOR
CURSOR ROW,COLUMN
SCREEN MESSAGE1
35
5.
Using Signed Numbers
and
LookLook-up Tables
5.1
Objective
5.2
Preliminary Study
5.3
Experimental Part
5.3.1.
Exp5.inc
36
buffer+1,al
buffer+1,30h
buffer+2,ah
buffer+2,30h
buffer+3,$
buffer+3,$
endm
37
macro
ah, 01h
16h
endm
setcurs
setcurs macro row, col
mov
ah,02
mov
bh,00
mov
dl,col
mov
DH,row
int
10H
setcurs endm
exitdos macro
mov ah,4ch
int 21h
exitdos endm
------end of file--------- In exp5 folder, create and edit exp5p1.asm to contain the following source text
; Source exp5
exp5p1
; student nr1:
; student nr2:
include exp5
exp5.inc
.model small
.stack 100h
.data
rowno
equ 08
colno
equ 05
Message1 db 'What is your last name? ','$'
Buffer1 db 24,?,24 DUP (0)
Message2 db CR, LF,'LetterLF,'Letter-count of your last name
name is: '
Message3 db '
$'
.code
mov ax,@data
mov ds,ax
dispclr
setcurs rowno,colno
dispstr Message1
getstr buffer1
; Mem[buffer1+1] contains the stringlength
mov al,Buffer1+1
al2asc Message3
dispstr Message2
waitkey:
keybch
keybch
jz waitkey
exitdos
end
- You will use EMU8086 in tracing the assembly code. Open exp5p1.asm in
EMU8086.
38
- Copy the listing lines corresponding to the code segment (starting from .code)
into your report file exp5.txt, as shown below:
CMPE328 Experiment 5 Report file
by <Name<Name-Surname> <number>
<Name-Surname> <number> and <Name
PartPart-1
.code
[ 16]
:
[ 17]
0160: B8 10 00
mov ax,@data
[ 18]
0163: 8E D8
mov ds,ax
dispclr
[ 19]
0165: B8 00 06 B7 F0 B9 00 00 BA 4F 18 CD
10
[ 20]
:
. . .
. . .
- Inspect carefully the first and the second occurance of invoking dispstr macro.
Are there any difference? Why are they different?
Reporting: Write your answer to report file
Dispstr macros are different because . . . . . .
- Close the listing, and trace the execution using single-step. When the emulator
warns you to enter the string, write your surname on the DOS window.
- Open vars window (click on vars button), and click on buffer1. Then fill in
to elements box 20.
Reporting: Write the array of bytes in the buffer1 to your report file exp5.txt
including the first zero byte.
BUFFER1: 18 05 62 . . .
75 72 0D 00
- Can you understand the length of the string from the second byte in buffer1? Is
it consistent with the remaining bytes?
- Close the emulator window. On the edit window, click on compile. A filesave browser will get opened to save the exe file. Save the exp5p1.exe file
into your exp5 folder. Then, execute the exp5p1.exe to observe how it works.
- Reporting: Save the report file, and start to the second part of the experiment.
5.3.2.
Objectives:
-to demonstrate signed arithmetic operations on a code finding the average of
signed numbers.
Procedure:
-The following assembly code finds the average of an array of bytes. Write it into
exp5p2.asm in the exp5 folder. Dont forget to fill your name and number into
the file.
; exp
exp5
5p2.asm
; Student name and number 1:
; Student name and number 2:
include exp5
exp5.inc
.model small
.stack 100h
.data
snum dw 4
sdata db -3, -12, 5, 2
aver dw ?
remn dw ?
MessageA db "Average is $"
MessageR db "Remainder is $"
NextLine db 13,10,"$"
dstr db 10 dup(20h),'$'
.code
mov ax,@data
mov ds,ax
39
- You will use Emu8086 to trace this assembly code. Open exp5p2.asm in the
Emu8086.
- Click the emulate button to start emulation. Observe carefully how the addition
and division operations are performed, how the result is converted to ascii, and
how it is written to display.
-Compile the executable file of the exp5p2.asm file. Execute and observe its
operation.
Reporting: In PART2 of your report file fill in the screen output to your report
after the program stops.
5.3.3.
Objectives:
-to demonstrate the input value search, and the output access for a Look Up table.
Procedure:
-The following assembly code finds the average of an array of bytes. Write it into
exp5p3.asm in the exp5 folder. Dont forget to fill your name and number into
the file.
; exp
exp5
5p3.asm
; Student name and number 1:
; Student name and number 2:
include exp5
exp5.inc
.model small
.data
Msg1
db 'I''ll find the square root using '
db 'a looklook-up table.',13,10
db ' Give me a number in the range [0, 255]: $'
Msg2
db 13,10,' SquareSquare-root is $'
lutcnt dw 15
lutin
db 0, 1, 4, 9, 16, 25, 36, 49, 64
db 81, 100, 121, 144,169,196, 225
lutout db 0, 1, 2, 3, 4, 5, 6, 7, 8,
db 9, 10, 11, 12, 13, 14, 15
buf
db 10h,?,10h dup(' ');
output db 5 dup(' '), '$'
.code
mov ax, @data
mov ds,ax
dispstr Msg1
getstr buf
asc2al buf
; find index
mov cx,lutcnt
lutlp:
mov bx,cx
40
- You will use Emu8086 to trace this assembly code. Open exp5p3.asm in the
Emu8086.
- Click the emulate button to start emulation.
- During the single-step emulation
- Enter string 200 when the emulator asks an input value.
- Observe carefully how the ascii input string is converted to 8-bit value by
asc2al macro.
- Observe carefully how the input array is searched from the last down to the
first until an entry is found smaller than the input value.
- Observe carefully how the output value is accessed once the index
corresponding to the input value is obtained.
- Generate the executable file (use compile), and run it to see the operation of the
program. Use input values 1, 5, 42, 64, 4Dh and 182 to see how it works.
Reporting: In PART3 of your report write what happens for each input.
- Hide the lines containing keybch and jz waitch. behind semicolons. Then
generate its executable and observe the difference in operation.
5.3.4.
Objectives:
-to demonstrate the input value search, and the output access for a Look Up table.
Fibonacci Numbers:
According to Wikipedia pages, the Fibonacci numbers first appeared, under the name mtrmeru (mountain
of cadence), in the work of the Sanskrit grammarian Pingala (Chandah-shstra, the Art of Prosody, 450
or 200 BC). Prosody was important in ancient Indian ritual because of an emphasis on the purity of
utterance.
In the West, the sequence was first studied by Leonardo of Pisa, known as Fibonacci, in his Liber Abaci
(1202). He considers the growth of an idealised (biologically unrealistic) rabbit population, assuming
that:
in the first month there is just one newly-born pair,
new-born pairs become fertile from after their second month
each month every fertile pair begets a new pair, and
the rabbits never die
Let the population at month n be F(n). At this time, only rabbits who were alive at month n2 are fertile and
produce offspring, so F(n2) pairs are added to the current population of F(n1). Thus the total is
F(n) = F(n1) + F(n2).
Procedure:
-The following assembly code finds the i-th Fibonacci number. Write it into
exp5p4.asm in the exp5 folder. Fill your name and number into the file.
; exp
exp5
5p4.asm
; Student name and number 1:
; Student name and number 2:
include exp5
exp5.inc
.model small
.data
luacnt
dw 12
lua db 1,1,2,3,5,8,13,21,34,55,89,144,233
fibnr db '
$'
buf db 20,?, 20
20 dup(' ')
msga db 'I have a looklook-up table to get'
41
- Use Emu8086 to trace this assembly code. Open exp5p4.asm in the Emu8086
and start single-step emulation.
- Generate the executable file (use compile), and run it to see the operation of the
program. Use input values 3, 6, Ah, 12 to see how it works.
Reporting:
After you complete the procedures, please save and close exp5.txt file, and e-mail
it using your student e-mail account to [email protected] with the
subject line exp5 within the same day before the midnight.
Late and early deliveries will have 20% discount in grading. No excuse acceptable.
Free time practice-1:
In your free time, write assembly code of a program to return 255 sin(180 i /32)
from a simple look-up table of 32 elements. (i.e., using a look-up table like
this one)
lutcnt db 32
lutout db 0, 25, 50, 74, , 0
43
45
6.
I/O and External Memory Interface
for 8051
6.1
Objective
6.2
Introduction
6.2.1.
Typical features
6.2.2.
Registers
46
Value
E0
E0
F0
82
83
A8
B8
80
90
A0
B0
87
D0
CA
CB
98
99
81
C8
88
8C
8A
8D
8B
CD
CC
89
Description
Accumulator
Accumulator
B register
Data Pointer Low byte
Data Pointer High byte
Port 0
Port 1
Port 2
Port 3
Program Status Word
Stack Pointer
Timer/Counter 0 High byte
Timer/Counter 0 Low byte
Timer/Counter 1 High byte
Timer/Counter 1 Low byte
Timer/Counter 2 High byte
Timer/Counter 2 Low byte
Label
P0
SP
DPL
DPH
PCON
TCON
TMOD
TL0
TL1
TH0
TH1
P1
SCON
SBUF
P2
IE
P3
IP
T2CON
RCAP2L
RCAP2H
TL2
TH2
PSW
A
ACC
B
Value
80
81
82
83
87
88
89
8A
8B
8C
8D
90
98
99
A0
A8
B0
B8
C8
CA
CB
CC
CD
D0
E0
E0
F0
Description
Port 0
Stack Pointer
Data Pointer Low byte
Data Pointer High byte
The predefined labels for bit addressable memory locations are limited by 8051
architecture. In Table 1.2, .x represents a value in the range of 0 to 7. For example P0.x
is short hand to represent P0.0, P0.1, P0.2, P0.3, P0.4, P0.5, P0.6 and P0.7.
With P0.0 = 80h, P0.1 equal to 81h, etc. Associated label values are given in
hexadecimal notation.
Table 1.2 Predefined Bit Labels
Label
ACC.x
B.x
P0.x
P1.x
P2.x
P3.x
PSW.x
SCON.x
IE.x
IP.x
TCON.x
T2CON.x
IT0
IE0
IT1
IE1
TR0
TF0
TR1
TF1
RI
TI
RB8
TB8
Value
E0 - E7
F0 - F7
80 - 87
90 - 97
A0 - A7
B0 - B7
D0 - D7
98 - 9F
A8 - AF
B8 - BF
88 - 8F
C8 - CF
88
89
8A
8B
8C
8D
8E
8F
98
99
9A
9B
Description
Accumulator (bits 0 through 7)
B register (bits 0 through 7)
Port 0 (bits 0 through 7)
Port 1 (bits 0 through 7)
Port 2 (bits 0 through 7)
Port 3 (bits 0 through 7)
Program Status Word (bits 0 through 7)
Serial Control register (bits 0 through 7)
REN
SM2
SM1
SM0
EX0
ET0
EX1
ET1
ES
ET2
EA
PX0
PT0
PX1
PT1
PS
PT2
P
OV
RS0
RS1
F0
AC
CY
9C
9D
9E
9F
A8
A9
AA
AB
AC
AD
AF
B8
B9
BA
BB
BC
BD
D0
D2
D3
D4
D5
D6
D7
Parity flag
Overflow flag
Register Select (bit 0)
Register Select (bit 1)
Auxiliary Carry flag
Carry flag
47
6.2.3.
Instruction Set
The 8051 instruction set contains data-transfer, ALU, bit-manipulation, and program
branching instructions. The complete instruction set is given in the following table.
Arithmetic Operations
Mnemonic
ADD A,Rn
ADD A,direct
ADD A,@Ri
ADD A,#data
ADDC A,Rn
ADDC A,direct
ADDC A,@Ri
ADDC A,#data
SUBB A,Rn
SUBB A,direct
Description
Add register to Accumulator (ACC).
Add direct byte to ACC.
Add indirect RAM to ACC.
Add immediate data to ACC.
Add register to ACC with carry.
Add direct byte to ACC with carry.
DEC Rn
DEC direct
DEC @Ri
INC DPTR
MUL AB
DIV AB
DA A
Size Cyc
1
2
1
2
1
2
1
2
1
1
1
1
1
1
1
1
1
1
2
1
1
2
1
1
1
2
1
1
1
1
1
1
1
1
1
1
1
2
1
A A / B (int.result); , B <- A%B (remainder) 1
Decimal adjust ACC.
1
4
4
1
Decrement register.
Decrement direct byte.
Decrement indirect RAM.
Increment data pointer.
result is 16-bit B:A A x B ;
Description
Size Cyc
Mnemonic
Move register to ACC.
1
1
MOV A,Rn
2
1
MOV A,direct Move direct byte to ACC.
Move indirect RAM to ACC.
1
1
MOV A,@Ri
2
1
MOV A,#data Move immediate data to ACC.
Move ACC to register.
1
1
MOV Rn,A
2
2
MOV Rn,direct Move direct byte to register.
2
1
MOV Rn,#data Move immediate data to register.
2
1
MOV direct,A Move ACC to direct byte.
2
2
MOV direct,Rn Move register to direct byte.
3
2
MOV direct,direct Move direct byte to direct byte.
2
2
MOV direct,@Ri Move indirect RAM to direct byte.
3
2
MOV direct,#data Move immediate data to direct byte.
Move ACC to indirect RAM.
1
1
MOV @Ri,A
2
2
MOV @Ri,direct Move direct byte to indirect RAM.
2
1
MOV @Ri,#data Move immediate data to indirect RAM.
2
MOV DPTR,#data16 Move immediate 16 bit data to data pointer register. 3
Move code byte rel. to DPTR to ACC (16 bit
MOVC
1
2
A,@A+DPTR
MOVC A,@A+PC
MOVX A,@Ri
MOVX A,@DPTR
MOVX @Ri,A
MOVX @DPTR,A
PUSH direct
POP direct
Logical Operations
Mnemonic Description
ANL A,Rn AND Register to ACC.
ANL A,direct AND direct byte to ACC.
ANL A,@Ri AND indirect RAM to ACC.
ANL A,#data AND immediate data to ACC.
ANL direct,A AND ACC to direct byte.
ANL direct,#data AND immediate data to direct byte.
ORL A,Rn OR Register to ACC.
ORL A,direct OR direct byte to ACC.
ORL A,@Ri OR indirect RAM to ACC.
ORL A,#data OR immediate data to ACC.
ORL direct,A OR ACC to direct byte.
ORL direct,#data OR immediate data to direct byte.
XRL A,Rn Exclusive OR Register to ACC.
XRL A,direct Exclusive OR direct byte to ACC.
XRL A,@Ri Exclusive OR indirect RAM to ACC.
XRL A,#data Exclusive OR immediate data to ACC.
XRL direct,A Exclusive OR ACC to direct byte.
XRL direct,#data XOR immediate data to direct byte.
Clear ACC (set all bits to zero).
CLR A
Compliment ACC.
CPL A
Rotate ACC left.
RL A
Rotate ACC left through carry.
RLC A
Rotate ACC right.
RR A
Rotate ACC right through carry.
RRC A
Swap nibbles within ACC.
SWAP A
Description
Exchange register with ACC.
Exchange direct byte with ACC.
1
1
1
1
2
2
2
2
2
2
2
2
1
1
1
1
3
1
2
2
1
1
1
2
2
1
1
1
3
1
2
1
2
1
1
1
2
2
3
1
1
1
1
1
1
1
1
2
1
1
1
1
1
1
Other Instructions
Mnemonic
XCH A,Rn
XCH A,direct
XCH A,@Ri
address).
Size Cyc
1
2
1
1
1
1
Mnemonic
CLR C
CLR bit
SETB C
SETB bit
CPL C
CPL bit
ANL C,bit
ANL C,/bit
ORL C,bit
ORL C,/bit
MOV C,bit
MOV bit,C
Description
Size Cyc
1
2
1
1
1
2
1
2
1
1
1
1
2
2
2
2
2
2
2
2
2
2
1
2
Program Branching
Description
Mnemonic
ACALL addr11 Absolute subroutine call.
LCALL addr16 Long subroutine call.
Return from subroutine.
RET
Return from interrupt.
RETI
AJMP addr11 Absolute jump.
LJMP addr16 Long jump.
Short jump (relative address).
SJMP rel
JMP @A+DPTR Jump indirect relative to the DPTR.
Jump if carry is set.
JC rel
Jump if carry is not set.
JNC rel
Jump if direct bit is set.
JB bit,rel
Jump if direct bit is not set.
JNB bit,rel
Jump if direct bit is set & clear bit.
JBC bit,rel
Jump relative if ACC is zero.
JZ rel
Jump relative if ACC is not zero.
JNZ rel
CJNE A,direct,rel Comp. direct byte to ACC and jump if not equal.
CJNE A,#data,rel Comp. imm. byte to ACC and jump if not equal.
CJNE Rn,#data,rel Comp. imm. byte to reg. and jump if not equal.
CJNE
Comp. imm. byte to ind. and jump if not equal.
@Ri,#data,rel
Size Cyc
2
3
1
2
2
1
2
3
2
2
2
2
2
1
2
2
3
3
3
2
2
2
2
2
2
2
2
2
3
3
3
2
2
2
2
2
3
2
2
48
Assemblers and Development Tools for 8086 and 8051 Microprocessors
8051 can access the program code ROM or Flash memory by MOVC instructions. External
RAM by MOVX instructions, and the internal RAM memory (locations 0 128 for MCS51,
0256 for MCS52) by MOV instructions.
6.2.4.
The 8051 microcontroller provides three ports for the users, denoted by symbols P0, P1, P2
and P3. 8051 i/o ports are memory mapped registers with input/output connection to the
external circuits. The addresses of these ports are available in Table 1.1.
The ports are bit addressable as seen in Table 1.2. Ports P1, P2 and P3 have weak
internal pull-up resistors, while the pins of P0 has no internal pull-ups, because it is also
used as AD0AD0-AD7 lines for external memory access. Therefore external pull ups are
necessary to interface a switch to a P0 pin, similar to resistors R00 and R01 in Fig. 2.
An i/o pin of the ports is suitable for
input only when it is set to high. For
example: CLR P1.3 makes P1.3 pin 0V, Figure 2 . Switch and LED interfacing configurations.
and it is not suitable for input, since P1.3
will sink external current strongly to the
ground. SET P1.3 makes P1.3 pin 5V
with a weak current source. The external
circuit can easily drive P1.3 below the
logic-threshold voltage, and make it read
0. A reset (RST high) starts the ports with
P0=P1=P2=P3=0x0FF, suitable for input.
An output pin can drive a LED
indicator in the common-cathode mode. In
Fig.2, the component pair {R30, DB1}
connected to P3.0 pin is a typical LED
Fig. 2 . Switch and LED interfacing configurations.
indicator. DB1 gets lighted when the
output pin P3.0 delivers low (=0V, or logic-0), and DB1 stays dark while P3.0 stays at
high (=5V, or logic 1).
In Fig.2, S1-RD1 forms a pull-up biased switch circuit. It gives high to the input P0.1
while switch is open (open-circuit = off), and makes P0.1 low while switch is closed
(closed circuit = on). In summary, P0.1 reads 0 if switch is turned on, and it reads 1
otherwise.
6.2.5.
Keil products supplies professional integrated development tools for 8051 family devices.
The currently available Keil student version can code up to 2-kBytes of hexadecimal
coding for any 8051 device. Keil-C (C51) and assembler (A51) are usually called by its
development environment UV3. However, we will use them calling in DOS-Command
environment through a batch file. Keil C is an almost-ANSI C compatible C-compiler for
writing programs in tiny-os operating system. Compiler C51 and assembler A51 produce
an object file, which needs linking into an absolute code using BL51. Absolute code is
further converted to INTEL HEX format by the code converter Oh51. The following listing
is the compile.bat batch file .
echo off
PATH=.\8051\C51\BIN
SET TMP=.\8051\TMP
del exp6.hex
49
The environment settings of the batch file is valid only if the folder 8052 is under the work
folder of the experiment. It works on desktop folder, or on the root folder of a flash disk.
6.2.6.
Keil products supplies professional integrated development tools for 8051 family
devices. The currently available Keil IDE mvision-3 (uv3), and a limited capacity trial
version can code up to 2-kBytes of hexadecimal coding for any 8051 device. UV3 is KeilC (C51) and assembler (A51) compatible. Keil C is an almost-ANSI C compatible C
compiler environment for writing programs in Tiny-OS operating system. Keil IDE
produces the hex file to transfer the program code into the target 8051 device. The free trial
version of Keil-IDE does not require any registration into Windows operating system. Its
initialization parameters are stored in tools.ini file, and can be edited by a text editor. The
software pack can be easily installed by copying the KC51 folder at the root of any drive,
and correcting the drive name in the tools.ini file.
UV3 environment does not need installation other than modification of the C51 path in
tools.ini file. A copy of KC51 is available on the C-drive, and you may use it also on your
flash-disk drive (about 50Mbytes).
Installation and starting a C or Assembly project with Keil-C51 are quite simple. If KC51
is not yet installed on your computer follow the steps to install it on your hard disk (C:) or
your floppy disk (E:).
- Installing KC51: Download the rarred KC51 IDE folder from the coarse web side, open
the rar-archive, and copy the folder KC51 to the root of your drive (C: ) or (E: ), so that
E:\KC51\ folder contains folders C51, UV3 and the file TOOLS.INI. Then edit path
statement of tools.ini to E:\KC51\C51. Your KC51 is ready for execution.
- Making a Work Folder: Start a working folder similar to E:\323\012345\ExpXX .
Copy all necessary C (-.C , -.H . and -.C51 files) and Assembler (-.ASM and -.A51
files) source files together with Proteus Circuit Simulation files (-.DSN) into your work
folder.
- Opening an existing Project: If a KC51project definition file (-.UV2) is available in the
work folder use (Project Open Project) to start the project with its settings.
- Starting a New Project: Start KC51\UV3\UV3.exe file. Close the initially opened
project file using menu ( Project Close Project) . Start a new project by (Project
New uVision Project ) browsing your work folder, and entering project name, lets say
proj. From the popped CPU-dialog-box, select Generic 8052 (all variants). Click
No if it asks to copy 8051 startup code to project folder . Click on
to
select it, and with right-click open the Options for Target-1 dialog window. Check
that Device is Generic 8052 and Linker is BL51. Set Target Xtal(MHz) as required for
the application, Memory Model Small, Code Rom Size Small, Operating System None,
and put check for Use On-chip ROM (0x0-0x1FFF).
50
Set Output to create both executable and hex file with debug information. You may
change the name of the executable and Hex-file by entering it into Name of Executable
box
- Generating a list file: List file contains debug messages and symbol tables. You can
generate -.lst file by putting a check into the Assembler Listing box in Listing window
of Options dialog.
After setting all of the above options click OK to close the Options dialog.
- Adding Assembly files to the project: Open the dependents list of
by clicking
on plus sign next to it. Right-click on Source Group 1 to get the quick menu for
adding source files to Group 1. Click it to start the file browser to add your source
file. First set the folder to your work folder that contains your -.asm file. Then set Files
of type field to asm source file. Your -.a51 file will appear in the browser window.
Select the file and click on add.
- Adding C files to the project: Apply the same procedure, but set Files of type field to
C source file. Your -.C file will appear in the browser window. Select the file and
click on add.
- Building the project: On the toolbar use the icons
(build and rebuild) to build the
project and generate the executable and -.hex file.
6.2.7.
Simulation in ISIS
Simulation is the best methodology to verify operation of the circuit and the program code
in a time-efficient manner. It is always a good idea to simulate the circuits and codes using
convenient simulation software instead of rushing to build the circuit and code the chip for
a real-life test.
ISIS is able to simulate many microcontrollers with their peripheral circuits. The circuit
diagrams are composed of components, and connections between the component terminals.
A component that needs a program code is linked to the program code file writing the code
folder and file name (.hex file name) into its configuration window. ISIS can simulate this
graphical circuit representation and update the appearance of the display elements in
regular periods of about 50ms.
6.3
Experimental Part
6.3.1.
51
1- Download the exp6.rar file which contains all necessary files and folders to a
convenient place i.e. onto the desktop. Extract and open the work folder Exp6.
2- Open the source file Exp6.a51. The file shall contain the following lines
Assemblers and Development Tools for 8086 and 8051 Microprocessors
52
6.3.2.
ISIS release 6.9 of Labcenter Electronics can successfully simulate the digital-analog
hybrid circuits including the PIC16, PIC18, 68HC11 and MCS51 family micro controllers.
Objective:
Our objective is getting familiar with the ISIS simulation environment.
Procedure
1- Start Proteus ProfessionalISIS 6 Professional in windows.
2- Use FileLoad design to open the file-browser, navigate to Exp6A folder, and load
Exp6A.DSN file to ISIS. You will get the design window seen in Fig.3.
3- Right click once on the 8051 processor. The processor will turn to red, indicating
that it is selected. Left click once on 8051 to open the edit component window of
8051 seen in Fig.4. The Program File shall contain the file name Exp5A.hex,
which is generated in Section 3.1. You can link a file using the file browser icon,
or directly by editing the file name. Do not forget to OK the new file name.
4- Close the edit-window, and right-click on the empty part of the design window to
deselect components. All red components will take their original colors.
5- Two kind of switches are shown in Fig.5 . These switches are active circuit
elements changing state by clicking on their control buttons.
6- Click on
button to start the component insertion mode. This mode supports
interaction to the active components (switches, buttons, and logic-states) using the
mouse.
push
button
switch
single pole
single throw
switch
control buttons
to turn the
switch on-off
3.2
B1=
B1=
S1=
S1=
B2=
B2=
Simulation section:
Pressed, P0.0 = low/high
?;
;
?;
; P3.1
Off, P0.1 = low/high
?;
; P3.1
Released,
?;
;
Released, P3.7 = low/high
53
P3.0 = low/high
?
?
P3.0 = low/high
= low/high
?
= low/high
?
P3.2 = low/high
?
P3.2 = low/high
?
All other bits initially start giving low output (near 0V). Then, a loop starts with the
label back,
back:
In the loop, P0 is copied to accumulator. An and-mask keeps bit-0 and bit-1, and
clears all other bits. Then, an or-mask sets bit-7.
; copy port0 switch B1,S1 states to acc
mov a,P0
anl a,#00000011b ; P0.1 and P0.0 are selected
orl a,#10000000b ; prepare P3.7 for input
Next, bit-7 (button B2 status) is copied to bit-2 of the acc register. Acc is copied to
P3 to display the new status on LED indicators.
; copy bit P3.7 to bit P2.2
mov C, p3.7
; copy P3.7 to Carry Flag
mov acc.2, C ; copy Carry to acc.2
mov P3,a
; apply result to P3
54
mov r1,A
dlylp1: mov r0,#(xtal*62/10)
dlylp2: djnz r0,dlylp2
djnz r1,dlylp1
ret
end
Reporting:
After you complete the procedures, please save and close exp6.txt file, and e-mail
it using your student e-mail account to [email protected] with the
subject line exp6 within the same day before the midnight.
Late and early deliveries will have 20% discount in grading. No excuse acceptable.
Free time practice:
Write a 8051 assembler source (file name Exp6P.a51) for the circuit of Exp6A, that
- initially turn off all three LED, and make P0.0, P0.l, and P3.7 input pins.
Clear R3 and R4.
- in the mainloop
call dly100u with acc=100 (for 10ms delay)
increment R3,
if R3 exceeds 10, reset R3=0, and increment R4.
turn off all LEDs
if R4=1, turn on the LED connected to P3.2 .
if R4=2, turn on the LED connected to P3.1 .
if R4=3, turn on the LED connected to P3.0 .
if R4=4, turn on all of LEDs, connected to P3.0, P3.1, and P3.2,
if R4=5, make R3=0; R4=0.
continue looping forever.
Assemble your source, and execute your code in ISIS. You shall edit compile.bat
file with a text editor to change exp6.a51 and exp6.lst to exp6P.a51 and
exp6P.lst.
After these changes compile.bat will generate exp6.hex file by assembling the
source file exp6P.a51.
Start execution of the code in ISIS and observe the LEDs.
Does it light the LEDs in a sequence at every 1 second?
55
7.
8051 Memory Decoders and
Memory Interface
7.1
Objective
The aim of this experiment is to observe the operation of a memory address decoder on a
8051 external memory circuit on the ISIS external memory interfacing simulation.
7.2
The 8051 microcontroller instruction set includes an external memory dedicated data
transfer instruction: MOVX, and the processor supports up to 64 kbytes external memory
addressing through the ports P0, P2 and P3. Accessing external memory occupies P0 to
carry AD[0..7] address-data lines, P2 to carry A[8..15] high address byte, and the pins
P3.6 and P3.7 to carry ~RD and ~WR control signals. The address latch enable ~ALE pin
supplies a negative-edge to trigger the D-FF register while 8051 delivers the lower address
byte A[0..7] through AD[0..7] lines, similar to the 8088 local bus. Total 16 address lines
provide 64kbytes address space for external memory. This address space is usable for
external code or data memory, and also for memory mapped i/o devices.
ISIS6.9 provides simulation of external memory addressing of the 8051 microcontroller,
which serves in this experiment for observing the operation of a 74LS138 decoder, 6116
RAM devices, and 2764 EPROM devices. The simulation power of ISIS is restricted to
only 8051bus devices with a limited memory options.
ISIS simulates a 2764 EPROM chip with its programmed contents by linking the contents
filename (.hex format) to its properties. In this experiment, we will have two program
projects: Exp7Bus.Uv2 to generate the program code file Exp7Bus.hex that runs in 8051
processor, and Exp7_2764.Uv2 to generate the data code file 2764.hex for the 2764 EPROM
chip.
7.3
Experimental Part
7.3.1.
Objective: preparation of a workfolder for KC51 IDE and generation of -.hex files for the
simulation. If KC51 is already installed on the computer skip steps 1 to 3 of Procedure-1.
Procedure-1:
1- Download the rarred KC51 IDE folder from the coarse web side, open the rararchive, and copy the folder KC51 to the desktop or to a flash-disk.
2- In the explorer, open M51 folder under the KC51 folder. Copy the folder address
\KC51\C51 to the clipboard.
3- Open tools.ini in notepad. Paste the folder address into PATH= \ at the
[C51] section of the ini file.
- If you plan to work on flashdisk (lets say drive E:\ ) then copy KC51 folder to
the root folder so that E:\KC51\ folder contains folders C51, UV3 and the file
TOOLS.INI. Then edit path statement of tools.ini to E:\KC51\C51.
56
4- On the root folder create folder x:\323\012345\exp7\, where 012345 stands for
your student number. In the folder \exp7\ start a txt file with the name
Exp7.txt for reporting. Write your student name and number on the first line of
the file similar to.
CMPE 328
number>
Exp7
Report
file
by
<your-name,
surname,
student
8- Build the project by clicking to Build-Target button ( ). You shall see the
following messages in the Build message window if the installation is
successful.
Build target 'Target 1'
assembling 2764.a51...
linking...
Program Size: data=8.0 xdata=0 code=17
creating hex file from "2764"...
"2764" - 0 Error(s), 0 Warning(s).
9- Open the project folder Exp7A in the explorer. From the date and time marks of
the files, you will see the following files created recently.
Reporting:
- Open the -.lst file in a text editor, and copy the first page (up to the end in the
source code) to your reporting file.
- Check whether the -.hex file in a text editor is generated. This file will be used for
the contents of the external EPROM chip.
- Save your reporting file for other report deliverables.
10- Open the project file Exp7Bus.Uv2 in Keil-IDE. You will find the following
source file in the project with the filename extmemread.a51 .
; Exp.7 8051 External Memory
; ( c ) 2008 Mehmet Bodur
;
org 0
mov p0,#0
start:
mov dptr,#0001h
mov a,#0x23
movx @dptr,a
mov p1,a
mov dptr,#2001h
mov a,#0x45
movx @dptr,a
mov p1,a
57
mov dptr,#0001h
movx a,@dptr
mov p1,a
mov dptr,#2001h
movx a,@dptr
mov p1,a
sjmp start
end
This program code writes two bytes to external memory locations, first 0x23 to
0x0001, then 0x45 to 0x2000. Next, it reads these two data bytes from the same
locations: 0x0001 and 0x2001. This program code displays on port-1 data bytes
after a read or write operation.
10- Build the project by clicking to Build-Target button ( ). You shall see the
following messages in the Build message window if the installation is
successful.
Build target 'Target 1'
assembling extmemread.a51...
linking...
Program Size: data=8.0 xdata=0 code=33
creating hex file from "Exp7Bus"...
"Exp7Bus" - 0 Error(s), 0 Warning(s).
the project folder Exp7A check the -.hex and -.lst
11- In
files to be sure that they are
generated. Copy the first page (upto the end line of assembly) into your reporting
file.
7.3.2.
Labcenter Electronics Portable Proteus 7.6 ISIS will simulate the extended memory of an
8051 micro controller.
Objective:
Our objective is getting familiar to the ISIS simulation environment.
Procedure
1- Start Proteus 7 PortableISIS
in windows.
2- Use FileLoad design to open
the file-browser, navigate to
Exp7A folder, and load
Exp7Bus.DSN file to ISIS.
You will get the design
window seen in Fig.3.
3- Right click, and then left
click once on the 8051
processor. The Program File
Fig. 2. Design window of Exp5A.DSN
in the edit component window
of 8051 shall contain the file
name Exp7Bus.hex, which is generated in Section 3.1. Check that its clock
frequency is 40. This frequency is selected because the animation display rate of
ISIS is frames per second, and it executes in 50ms steps at every click on the
button. Close the edit-window.
58
4- Apply the same procedure described in (3) on 2764 EPROM chip to link
2764.hex to this EPROM device. After this process close the edit-window.
6- Click on
button to start the component insertion mode. Click on step button
to start simulation. Start of
simulation will enable the memory
windows in the debug menu. Open
the memory windows, and observe
Fig. 3. The initial contents of
the initial contents of U3 (=2764)
the memory chips.
and U4 (=6116) memory chips.
Reporting:
Write the first 8 bytes of each memory contents to your reporting file.
3.2 Simulation section:
initial contents of U3: E0 E1 E2 E3 48 65 6C 6C
initial contents of U4: 00 00 00 00 00 00 00 00
Explanations:
You shall expect that EPROM is non-volatile, and it is a read-only memory.
Therefore the written bytes shall not change the contents of the EPROM memory.
On contrary, 6116 RAM will change the contents of the locations whenever a data
is written on its locations.
8- Click on the graph title Transient Analysis. A graph window will get opened.
are for EditWindow, AddTrace,
The control buttons
Execute, NavigateLeft, NavigateRight, ZoomIn, ZoomOut, ZoomAll, ZoomManuel,
and ViewLogFile. Clicking on Execute, and then ZoomAll will display the following
graph.
zoom in range
Explanations:
CLK frequency is too high to display the clock pulses individually. ~RD, ~WR, ALE,
A[8..15] are microcontroller outputs. AD[0..7] is multiplexed address-data
lines. A 74374 positive edge-triggered D-Latch stores address value A[0..7]
given from AD[0..7] lines at the positive . ~CE0 and ~CE1 are address decoder
outputs.
59
9- Use ManualZoom to zoom in to the first write cycle of the graph, as seen below.
Assemblers and Development Tools for 8086 and 8051 Microprocessors
Fig.4. Zoom in [1.35 , 1.75] seconds view showing the write 0x23
to the external memory location 0x0001.
Reporting:
Attach the blue start line to the start of the AD[0..7] valid period by left-clicking at
that point while you press the control-key. Now, measure the duration of the
AD[0..7]=0x01 and =0x23. Write the durations both in total number of clock
cycles and time in seconds.
Duration of AD[0..7]=0x01 is cc , =
Duration of AD[0..7]=0x23 is cc , =
seconds
seconds
Explanations:
One external memory write bus cycle starts from valid address on AD[0..7] , and
ends when AD[0..7] becomes floating.
10- Use manual zoom to display the first read bus cycle on the graph. This is a read
from 2764 EPROM device. An Intel 8051 external memory read bus cycle takes
exactly 12 clock cycles.
Reporting:
Explain in your report how you conclude that the memory cycle is a read cycle from
the EPROM (Use the status of ~WR, ~RD, and ~CE# lines). Explain what is value of
the data byte sent from the EPROM to the processor.
11- Use manual zoom to display the second read bus cycle. This is a read from 6116
RAM device. An Intel 8051 external memory read bus cycle takes exactly 12
clock cycles.
Fig.4. Zoom in [6.15 , 6.5] seconds view showing the read from the external memory location
0x2001.
Reporting:
Explain in your report how you conclude that the memory cycle is a read cycle from
the RAM (Use the status of ~WR, ~RD, and ~CE# lines). Explain what is value of the
data byte sent from the RAM to the processor. Is the data byte value the same
with the written data value?
60
Assemblers and Development Tools for 8086 and 8051 Microprocessors
Reporting:
After you complete the procedures, please save and close exp7.txt file, and e-mail
it using your student e-mail account to [email protected] with the
subject line exp7 within the same day before the midnight.
Late and early deliveries will have 20% discount in grading. No excuse acceptable.
61
8.
8051 Memory Mapped I/O
and
8255A Interfacing
8.1
Objective
8.2
The MOVX instruction of 8051 microcontroller offers a method to interface memory mapped
io devices using the ports P0, P2 and P3 for external memory addressing. P0 carries AD[0..7]
address-data lines, P2 carries A[8..15] high address byte, and the pins P3.6 and P3.7 provide
~RD and ~WR control signals. In contrast to external memory interfacing, we do not need to
latch A[0..7] since A[8..15] is sufficient to address up to 256 io devices.
In this experiment we will construct simple input and output ports using AD[0..7] lines
for only data transfer, and A[8..15] lines only for addressing the io devices. The address
will be decoded by an address decoder made of 74LS138 and 74LS139 decoders.
8.3
Experimental Part
8.3.1.
Objective:
To prepare a workfolder for KC51 IDE and generation of -.hex files for the simulation.
To observe the simulated circuit while it executes the assembled program code on 8051
with a memory mapped output and input interfacing to drive a 7-segment LED and to read
four switches.
Procedure-1.a : Preparation of the -.hex file
1- If C:\KC51\ folder is not available download KC51 from the course web page and
copy it on hard disk or your flash disk (lets say E: ). Correct the PATH statement
on the file E:\KC51\TOOLS.INI to PATH="E:\KC51\C51". Download and extract
EXP8A.rar into folder E:\323\012345\EXP8A.
62
2- Start a -.txt file with the name E:\323\012345\Exp8.txt for reporting. Write
your student name and number on the first line of the file similar to.
CMPE328 Exp8 Report file by <your-name, surname, student number>
5- Build the project by clicking to Build-Target button ( ). You shall see the
following messages in the Build message window if the installation is
successful.
Build target 'Target 1'
assembling Exp8A1.a51...
linking...
Program Size: data=8.0 xdata=0 code=107
creating hex file from "Exp8A1"...
"Exp8A1" - 0 Error(s), 0 Warning(s).
This project contains macros. In the target options, it needs the extended linker
and Ax51 instead of A51 assembler; and the output shall be set to create hex file.
The list file expands the macros only if listing is set to all-expansions. The macros
in this experiment can be handled both by standard and MPL macro processor.
6- Open the project folder Exp8 in the explorer. From the date and time marks of the
files, you will see the most recently created -.hex and -.lst files.
Reporting:
- Open the -.lst file in a text editor, and copy the first 35 lines (including main: ) to
your reporting file.
A51 MACRO ASSEMBLER
EXP8
EXP8A1
OBJ
REG
REG
REG
REG
REG
0080
0081
LINE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
SOURCE
; Exp8
Exp8A1.a51
; Student Name:
; Student Number:
;
; ( c ) 2008 Mehmet Bodur
;$ge
; Display value in RAM memory
; Old keys to detect negative edge.
; Hide/Display flag
Disp
equ R0
Keys
equ R1
Keys
OldKeys equ R2
Hide
equ R3
Tmr
equ R4
; simple
PA
equ
; simple
PB
equ
; portport-1
output port
80h
input port
81h
for debug
63
0000
0000 010C
0002
0002
0004
0006
0008
000A
3F06
5B4F
666D
7D07
7F6F
000C
;P1
equ 90h
; reset vector
org 0
ajmp main
lutcode:
gfedcba
;
db 00111111b,
db 01011011b,
db 01100110b,
db 01111101b,
db 01111111b,
gfedcba
00000110b
01001111b
01101101b
00000111b
01101111b
main:
;
db
db
db
db
db
lutcode:
egfcbda
egfcbda
01011111b, 00001100b
01100111b, 00101111b
00111100b, 00111011b
01111011b, 00001101b
01111111b, 00111111b
7- Get from your lab assistant a new combination of connections between port pins
and display pins (i.e., Q0 a, Q1 d, Q2b, Q3c, Q4f, Q5g, Q6e ).
You shall modify the connections between the 74LS374 and the display
accordingly as you see in Fig.2 . Then modify the display-code look-up table in
the assembly source for the correct display of the numbers on the display as
shown in Fig.3 .
Reporting:
Write the combination given to you by your assistant in a table form like
Q: 7 6 5 4 3 2 1 0
D: - e g f c b d a
Thereafter copy the first 35 lines of -.lst file obtained with your modified code i.e.
AX51 MACRO ASSEMBLER
EXP7B
64
OBJ
LINE
0083
0080
0081
000000
000000 0100
000002
000002
000004
000006
000008
00000A
3F06
5B4F
666D
7D07
7F6F
00000C 33323824
0002
000010
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
SOURCE
; ( c ) 2008 Mehmet Bodur
; Macro Definitions for 8088 style io
$ge
in macro al,p8
mov DPH,#p8
movx al,@DPTR
endm
out macro p8,al
mov A,al
mov DPH,p8
movx @DPTR,A
endm
ComR equ 83h
PA
equ 80h
PB
equ 81h
; start PPI in all output mode.
org 0
ajmp main
lutseg:
gfedcba
;
db 00111111b,
db 01011011b,
db 01100110b,
db 01111101b,
db 01111111b,
msg:
msglen
gfedcba
00000110b
01001111b
01101101b
00000111b
01101111b
db '328$'
equ 2
main:
Show that the simulation works properly for all numbers to your assistant to get
performance points of this experiment.
8.3.2.
Objective:
To observe the slow-motion simulation of the multiplexed 3-digit common-anode 7segment LED display, and to observe the simulation of a 6 digit common cathode 7segment LED display at full speed.
Procedure-2.a : Preparation of the -.hex file
1- Start UV3.exe . Close the projects (menuproject close project) if any project is
open. Open the project file Exp8B.Uv2 in the KC51/Exp8B folder. In the
Project-Workspace window, click on the target, and the source-group-1 folders to
turn on the project source file list. There must be Exp8B.a51 in your projects
sources. If the file is not yet open, open it by clicking on this item.
3- The file shall start with the following lines
; Student Name:
; Student Number:
; File: Exp8B.a51
; ( c ) 2008 Mehmet Bodur
; Macro Definitions for 8088 style io
$ge
in macro al,p8
mov DPH,#p8
movx al,@DPTR
endm
8- Build the project by clicking to Build-Target button ( ). You shall see the
following messages in the Build message window if the installation is
successful.
Build target 'Target 1'
assembling Exp8B.a51...
65
linking...
Program Size: data=8.0 xdata=0 const=0 code=87
creating hex file from "Exp7B"...
"Exp7B" - 0 Error(s), 0 Warning(s).
9- Open the project folder Exp8B in the explorer. From the date and time marks of
the files, you will see the -.hex and -.lst files created recently.
Reporting:
- Open the -.lst file in a text editor, and copy the first 11 lines (up to the line to your
reporting file.
AX51 MACRO ASSEMBLER
EXP7B
OBJ
LINE
1
2
3
4
5
6
7
8
9
10
11
SOURCE
; Student Name:
; Student Number:
; File: Exp7B.a51
; ( c ) 2008 Mehmet Bodur
; Macro Definitions for 8088 style io
$ge
in macro al,p8
mov DPH,#p8
movx al,@DPTR
endm
66
6- Before you complete your lab, modify the code to write your student number on
the display (at 12M clock frequency) to get the performance grade for this part of
the experiment.
8.3.3.
Objective:
The aim of this part is to demonstrate the operation of a stepper motor control by 8086
assembly code.
Procedure-3:
1- Create a subfolder E:\323\012345\Exp8D\ in the KC51 folder. Create a text
file in Exp8D folder with the name Exp8D2.ASM. Write the following program
into the Exp8D2.asm file:
;
;
;
;
;
;
;
;
;
;
else do nothing
looping in mainloop
.MODEL SMALL
.8086
.CODE
jmp Main
; Data in the code segment
rchr db 0
step db 0
smtb db 3, 6, 12, 9 ; double coil drive
; Code starts here
Main:
mov AX,CS
mov DS,AX
call InitUSART
MainLoop:
call RecvChar
; reads received character into AL.
; If no character received then AL returns zero.
cmp al,0
jz Mainloop
mov rchr,al
cmp rchr,'1'
jnz skipforward
; forward step
inc step
mov bx,0003h
and bl,step
mov al,[bx]+offset smtb
mov dx,324h
out dx,al
skipforward:
cmp rchr,'2'
jnz MainLoop
; backward step
dec step
mov bx,0003h
and bl,step
mov al,[bx]+offset smtb
mov dx,324h
out dx,al
jmp MainLoop
InitUSART
xor AL,
mov DX,
out DX,
out DX,
out DX,
mov AL,
out DX,
mov AL,
out DX,
mov AL,
out DX,
ret
proc
AL
332h
AL
AL
AL
40h
AL
04Dh ; 8-bit, no parity, baud=clock x1
AL
05h
; start both receive and transmit
AL
67
68
endp
RecvChar proc
; reads received character into AL.
; If no character received then AL returns zero.
push DX
mov DX,332h
; status/control address
in AL,DX
; read status register
and AL,02h
; zero flag is set if AL .AND. 01h is nonzero
jz NotReceived
mov DX,330h
; data-in/data-out address
in AL,DX
; received character transferred from data-in into
AL.
shr AL,1
NotReceived:
pop DX
ret
endp
.data
.stack 32
END
2- Use EMU8086 to assemble the source file to an exe file EXP8D2.exe. Start
Proteus-Professional 7.6 ISIS and open VSED_WA_SMOTOR.DSN in ISIS. Link the
8086 processors program file to EXP8D2.EXE file. Observe how the motor turns
when pressing to key 1 and key 2. Write your observation into your report
file.
Your report shall contain
EXP8D2:
-With SMTB 3, 6, 12, 9
on key 1 rotor rotates
on key 2 rotor rotates
when PA is 00000011
when PA is 00000110
when PA is 00001100
when PA is 00001001
. (ccw or cw?)
. (ccw or cw?)
the rotor alignes to ..
the rotor alignes to ..
the rotor alignes to ..
the rotor alignes to ..
degrees position.
degrees position.
degrees position.
degrees position.
. (ccw or cw?)
. (ccw or cw?)
the rotor alignes to ..
the rotor alignes to ..
the rotor alignes to ..
the rotor alignes to ..
degrees position.
degrees position.
degrees position.
degrees position.
Reporting:
After you complete the procedures, please save and close exp8.txt file, and e-mail
it using your student e-mail account to [email protected] with the
subject line exp8 within the same day before the midnight.
Late and early deliveries will have 20% discount in grading. No excuse acceptable.
69
9.
Design and Coding of
an Intelligent Restaurant
Service Terminal
9.1
Objective
The aim of this project is to use an A/D converter, four switches, an LCD and the serial
output port of an 8051 to construct an intelligent terminal for the restaurant service
stations.
9.2
Introduction
The file proj09.zip contains the C code, two header files, and the circuit design file of a
8051 system. The presented system reads an analog voltage and states of four switches,
displays these readings on LCD screen, and transmits the digital value through the serial
port with 4800 baud, 8-bit, no parity, one stop bit settings. The code is written with student
version Keil C compiler. The ISIS circuit schematics design file may be executed using
ISIS of the Portable PROSIS 7.6.
9.2.1.
KC51 does not support folder names longer than 32 characters. Therefore you shall copy
the proj09 folder to the root of a flash disk (E: ) or to your hard disk (C: ) drive. For a
trouble free operation we recommend to work in folder C:\323\012345\proj09\, where
012345 stands for your student number. Copy KC51 folder to C:\KC51\ so that the folder
C:\KC51\ contains folders C51, UV3 and the TOOLS.INI file. Edit the path line of the
TOOLS.INI file to change it to PATH="C:\KC51\C51\" so that KC51 programs can be
called while your source file is in folder C:\323\012345\proj09\. If you copy KC51
folder to another place do not forget to update the path statement accordingly. For
example, if KC51 is directly on the root of your flash disk E:, you shall make the path
statement PATH="E:\KC51\C51\".
9.2.2.
1. Extract proj09 folder to C:\323\012345\. If KC51 is not yet installed in your drive
the copy KC51 folder to file to C:\323\, and update PATH statement in the
TOOLS.INI file according to installation directives stated in previous subsection.
2 Start C:\323\KC51\UV3\Uv3.exe and start a New uVision project from project
menu. Use Generic and 8052 all variants, and click No for question Copy
standard 8052 startup code? .
70
Assemblers and Development Tools for 8086 and 8051 Microprocessors
3. With a right-click on Target 1 enter options
target: use on chip ROM (X);
Output
9.2.3.
LCD display
The sample code is written for LM016L (2-line by 16 column) LCD display in 4-bit data
transmission mode.
The following bit definitions assign symbols to the port pins for LCD.
71
#include <REG51.H>
#include <stdio.H>
// Special Function Bits declared for LCD
sbit RS = P1^0; // Control signal RESET of the LCD connected to pin P2.0
sbit EN = P1^1; // Enable
Enable (EN) LCD control signal connected to pin P2.2
sbit RW = P1^2; // Write (RW) Signal pin connected to pin P2.1
bit RSF,RSC ;// RS Flag,
where, RSF stores the state of control mode (1) or text mode (0). RS, EN and RW declares the
provides necessary delays for LCD and mainloop. The delay time is proportional to dd, and
it gives 1 ms delay for dd=100.
The LCDChar(char) procedure sends one character to LCD display by making enable
signal EN=high, and EN=low while the higher- and lower-nibbles of the character is applied
to the data lines. It also calls sufficient delay (1ms) after sending each control character.
void LCDChar(char ch ){
char Ct=ch;
P1= Ct&0xF0; if(RSF&&RSC){RS=1;}
EN=0; delay(10);
EN=1; delay(10);
EN=0; delay(5);
Ct= ch << 4 ;
P1= Ct&0xF0; if(RSF&&RSC){RS=1;}
EN=0;
EN=0; delay(10);
EN=1; delay(10);
EN=0; delay(5);
if(!RSF) delay(120); //1.2ms
}
The procedure PrintLCD(*char) sends the control and text characters to LCD. As a
feature of this procedure, printing a \x0FF toggles the text mode to control mode by
sending the characters with RS line high. The printed string must end with a null character
as usual in C language.
void PrintLCD(char *ch){
char Ct, n=0 ;
EN =0 ; RSF=1;
Ct=ch[n];
while(Ct){ RSC=1;
if(Ct&0x80) {RSC= 0;} // Ct>0x7F -> RSC=0
if(~Ct==0) {RSF= 0;} // Ct=0xFF -> RSF=0
else{ LCDChar(Ct);}
n++;Ct=ch[n]; }
}
72
Assemblers and Development Tools for 8086 and 8051 Microprocessors
The control characters valid for LM016L-LCD unit is given in the following Table.
Table of command codes for LCD displays
Hex
01
04
06
0C
10
18
28
80
81
8F
Action
Clear display screen
Decrement cursor (shift cursor left)
Increment cursor (shift cursor right)
Display on, Cursor hidden
Shift cursor position to left
Shift the entire display left
4-bit data, 2 lines, 5x7 matrix
Cursor Placement Commands row-1
Move cursor to 1st column of 1st row
Move cursor to 2nd column of 1st row
Move cursor to 16th column of 1st row
Hex
02
05
07
0F
14
1C
38
C0
C1
C1
Action
Return home
Shift display row right
Shift display row left
Display on, cursor blinking
Shift cursor position to right
Shift the entire display right
8-bit data, 2 lines, 5x7 matrix
Cursor Placement Commands row-2
Move cursor to 1st column of 2st row
Move cursor to 2nd column of 2st row
Move cursor to 16th column of 2st row
The placement of the cursor is achieved with the control codes { 80h, ,8Fh } for the
first line, and with the control codes { C0h, ,CFh } for the second line. For example,
to start the text Hello from the second line, third column you shall use
PrintLCD(\x0C2Hello), where \x0C2 sets the cursor to second line third column, and
the text Hello is written to the display. The cursor placement characters are over 0x7F,
and PrintLCD() process them as commands without needing a command mode character
\x0FF.
In the Init() procedure, PrintLCD sends a collection of commands (\xff) to LCD to
initialize it to 4-bit mode (\x02\x28), clear the display (\x01), hide the cursor (\x0c), and
with each written character shift the cursor to right (\x06).
void INIT(void){
// Initialization of the LCD by giving proper commands
// comm-mode,ret-home,4-bit,clr, hide-cursor, shift-cursor-right
PrintLCD("\xff\x02\x28\x01\x0c\x06\0"); // Initialize 4-bit LCD.
...
9.2.4.
Serial Port
The 8051 has an on-chip UART to implement serial communication with RS-232
communication protocol. RS232 communication may be useful for user interface as well as
in code development
a) to debug embedded applications, using a desktop PC;
b) to load code into flash memory for in circuit programming.
c) to transfer data from embedded data acquisition systems to a PC, or to other embedded
processors.
In our project, UART is used to transfer data to a PC at 4800 baud.
8051 UART can work in one of four modes, three of them being asynchronous and one of
them synchronous. For the simplicity of the project, we will give the receipt of how to
work in mode-1 at 4800 and 9600 baud rates.
In mode-1, the baud rate is determined by the overflow rate of Timer 1 or Timer 2. If we
use Timer 1, the baud rate is determined by the overflow rate and the value of SMOD as
follows:
73
(SMOD+1) Fosc
32 CPI (256 TH1)
BaudRate =
where SMOD is the double baud rate bit in the PCON register;
Fosc is the oscillator (or resonator) frequency (in Hz);
CPI is the number of machine cycles per instruction (e.g. 12 or 6)
TH1 is the reload value for Timer 1.
With SCON=0x50, Using TH1= FAh (=250 = 5 ), and oscillator frequency 11.06 MHz, the
baud rate becomes 4800. TH1=FDh (= 3) sets the baud rate to 9800. Thus, the
initialization procedure INIT() contains
void INIT(void){
. . .
// Serial port initialization
TMOD=0X20; TH1=0x0FA;
// select baud rate 4800
SCON=0x50;
// set mode-1
TR1=1;
// start timer.
TI=0;}
which sets Timer-1 to automatic load mode, and serial port to 4800 baud receive/transmit
mode so that writing a character to SBUF transmits the character. Further, the char
putchar(char) procedure in stdio.h is canceled, and then putchar is declared in the
program code as
char putchar(char ch){ // For serial output
SBUF=ch; while(!TI); TI=0; return 0;}
so that the int printf(*char, ) prints directly to the serial port by calling putchar.
9.2.5.
ADC interfacing
P2^0; //
P2^1; //
P2^2; //
P2^3; //
ADCVAL;
ADC
ADC
ADC
ADC
chip select
read enable
write enable
conversion over
The ADCRead ADC0801 conversion cycle starts by making the port P0 an input-port.
Then, the conversion starts after making ~CS low, and ~WR low. delay(2) is placed there
74
Assemblers and Development Tools for 8086 and 8051 Microprocessors
to observe the port easily on the digital analysis window. The code stays in a loop while
~INTR is high, which means conversion is not completed.
void ADCRead(void){ // Analog Digital Converter
// Reads ADC into ADCVAL
//Make the ADC port Input port
P0=0x0FF;
// start conversion
ADCS =0; ADWR =0; ADWR =1;
// wait till conversion is over
do{}while(ADINTR);
// read data of ADC into ADCVAL
ADRD =0; ADCVAL =P0; P2=0x0FF; }
Then, the reading of the conversion is written to the global variable ADCVAL. Parameter
transfer in global variables is frequently seen in microcontroller programming because it is
code-efficient.
9.2.6.
The lower four pins of P2 port are used for ADC interfacing. ADC read procedure makes
P2 an input port after it completes ADC read operation. The higher 4 pins of P2 are
interfaced to four pushbutton switches, SW1, SW2, SW3, and SW4. The detection of the
press and release instants are obtained by reading the switch states into SW, and keeping the
old switch states in SWP. Both SW and SWP are 8-bit unsigned global integers.
unsigned char
SW, SWP;
For the consistency of operation in the mainloop P2 is read into SW only once at the
beginning of the mainloop. For coding simplicity, the lower 4-bits are purged out by the
shift operation
SWP=SW; SW=P2>>4;
In these three cases, SW=0x0F must be initialized (all buttons are released) before the
mainloop.
The template code given for this project does the followings in its mainloop
void main (void) {
char num[16]; int i; char j[5];
delay(20000); // we need 200ms delay for LCD
INIT(); // LCD initialized
printf("Ready\r"); // This goes to UART
while(1) {
75
9.3
declares the ports, special function registers, and special function bits of the 8051
processor. STDIO.H provides declarations of the procedures _getkey getchar
REG51.H
The sbit type is used to declare single bits of special function registers such as EN, RS,
ADCS, ADRD. A bit variable declares bits in RAM (i.e., RSF). The char type is used for 8bit signed integers, int is used for 16-bit signed integers. The type qualifier unsigned
makes both char and int an unsigned number. The type qualifier const makes them
constants allocated in RAM area. They are initialized only once at the start of the program.
The qualifier code allocates the constants in ROM. For example:
code char test[] = "This is a text string in ROM";
allocates the character string test[] in ROM, along with the program code. The type
qualifier volatile allocates them in registers, and can be used for very short term
temporary purposes.
The _at_ keyword allows you to specify the address for uninitialized variables in your C
source files. It can be used to overlap a memory location for two different data types.
Keep the conditional tests as simple as possible. Use complement (~), and (&), or (|), and
ex-or (^) for bitwise operations between the char and int variables or constants. not (!)
operation complements a single bit, or a relational result. You can test the bits of a char
variable S by using a proper and-mask, i.e., S&0x40 is nonzero if bit-6 of S is high, and
similarly ~S&0x40 is nonzero if bit-6 of S is low.
9.4
Design Requirements
You will work in Keil C51 microVision-3 environment. You shall set the target options of
your microVision project to have
device: Generic 8051
target: Xtal 11.06 MHz ; Memory Small; Code ROM Size Small; Op.Sys. None.
76
Thus,
WeightCoeff =16*16*(GrPlate/NPlate)* 1.25 =20,
For example, the net weight of food-A can be obtained by calculating GrPlate for the
plate with food into GrFoodPlate, and then drop GrEmptyPlate from the calculated
value.
GrFoodA = GrFoodPlate GrEmptyPlate .
-Each food type will have a pre-determined constant (Kr (Kurus) per 10 gram) price
declared in integer form, typically A is 1.5 Kr/gram (KrPer10GrA =15) , B is 2.5 Kr/gram
(KrPer10GrB =25). The price of the plate shall be calculated depending on the food type.
For example, the food-B plate price will be
KrPlateA = GrFoodA KrPer10GrA /10 .
The following algorithm may be used in coding these requirements.
-Before the main loop your code shall initialize LCD print Ready\r\r to the terminal,
and set GrFoodA =0, GrFoodB =0, KrTotal =0.
In the main loop, it shall test the switches for the following actions:
77
-read ADC to get NPlate , calculate GrPlate , display it on the first line of the LCD (Add
some extra blanks to clear the previously written text, and set the cursor to the beginning of the
second line).
-if SW1 is pressed (it indicates that a plate of food-A is on the scale),
-Store GrPlate into GrFoodPlateA. Calculate GrFoodA.
Display GrFoodA on LCD, set NewCustomer,
-if SW2 is pressed, it points that a plate of food B is on the scale,
-Store GrPlate into GrFoodPlateB. Calculate GrFoodB.
Display GrFoodB on LCD, set NewCustomer,
-if SW3 is pressed, it means that the total price shall be reported to cashbox,
-Calculate KrPlateA using KrPer10GrA and GrFoodA. Also calculate KrPlateB
similarly. Find KrTotal =KrPlateA +KrPlateB , and print the following report to
9.5
Reporting
You shall write a very short report into the file proj.txt about :
- Goal of the developed system.
- Any difficulties you faced in writing your project code.
- Any explanations for the software coding.
- Any ideas to improve this project in hardware and in software.
- A conclusion about the contributions of each member to the project.
Enumerate the team leader and members, and denote each statement by (ideaowner, editor) in the following manner.
Team Leader: (1) Ibrahim Kisaparmak 012345
Members
(2) Rustem Habersiz 054321
(3) Hanefi Hamamci 053412
78
..
author
other supporters
..
Combining the LCD messages saved large amount of code memory (231).
The calibration of the weight might create problem because the sequence of the
multiplication and division operations are critical in calculating WFP (11).
.
Here, the statement Combining (23). is Rustems idea, and Hanefi is
author or editor of the statement. Next statement The calibr. WFP (11). is
owned by Ibrahim both in idea and in wording.
After you complete the project, please pack the -.txt report file C code (-.C and -.H
files), the -.hex file, the -.lst file, and the -.DSN file of your project into a zip file
with the name proj.zip and e-mail it using your student e-mail account to
[email protected] with the subject line proj before the Final Exam
Day.
Last day of delivery is Final Exam Day. No excuse acceptable.
79
10.
Design and Coding of
an Intelligent Human Weight Scale
10.1 Objective
The aim of this project is to use an A/D converter, four switches, an LCD and the serial
output port of an 8051 to construct an intelligent Body Mass Index (BMI) calculator.
10.2 Introduction
This project needs the hardware system and template files described in Chapter 9 for a
restaurant terminal design application. Please apply from Sections 9.2 to (including) 9.3 for
the preliminary of the project. The technical project specifications of the Body Mass Index
Calculator will start from Section 10.4.
10.2.1.
10.2.2.
10.2.3.
LCD display
10.2.4.
Serial Port
10.2.5.
ADC interfacing
10.2.6.
80
The LCD module of the unit shall display the following information
Line1: W=120 kg BMI= 53
Line2: H=150 cm *
where, the height H is the value set by switches SW1, SW2 and SW2, the weight Weight is
calculated from the ADC reading ADCVAL by the expression
Weight = (ADCVAL+80)/2 ,
which gives minimum 40 kg while ADCVAL=0, and maximum 167 kg while ADCVAL=255.
Considering the overflow of 16- bit integers, the BMI value shall be calculated as
BMI = 100*Weight /Height*100/Height;
The star *
* on line 2 shall be displayed only if StepSize =10, and shall be replaced by a
dot . if StepSize =1.
The switch SW4 shall print a report to the mini printer which is connected to the serial
terminal. The contents of the report shall be
Date:
Name:
W=120 kg
H=150 cm
BMI = 53
-----------
where the empty entries for date and name is going to be filled by the health officer who
places the report into the medical file of the person.
There are some challenges in this design. Student version of Keil-C51 compiles maximum
2.06k code. The template already consumes 1.4 k code. You shall code your program in
code efficient manner to complete the project in 2.1 k code. The followings are remedies
for code efficient programming:
1- Do not pass more than a single argument to a procedure, and do not return values from a
procedure. Instead, use all variables global, so that you can address them in the procedures
freely.
2- Write procedures for all repeating parts of the code, for example to test the switch
conditions.
3- PrintLCD, sprintf, and printf uses lots of code. Combine them to each other; i.e., instead
of
printf(W= %u kg\r,WW); printf(H= %u cm\r,HH); use
printf(W= %u kg\rH= %u cm\r,WW,BB);
4- Avoid using single letter variables A, B, since they are predefined for 8051 registers.
81
10.5 Reporting
You shall write a short team report into the file proj.txt . Each team member shall
have at least one or two sentences in the report. The report shall start with
- Team members, and team leaders name, surname and student numbers, in
enumerated listing.
i.e: Team leader:
098760 Kevin Kostner (1),
Members:
098761 Cameron Diaz (2),
098762 Robert Redford (3),
098763 Brad Pitt (4)
At the end of each sentence give the number of the author and other
supporters of that sentence, i.e.In this project we used a predesigned hardware for the development of a body weight scale
that calculates the Body Mass Index, BMI (134). The software is
written in Keil C for a 8051 processor (321). . . Here, the idea
of the first sentence has been proposed by Kevin (1), and supported
by Robert and Brad. Similarly, idea of the second sentence is owned
by Robert, and it is supported both by Cameron and Kevin.
The remaining part of the report shall contain
- Goal of the developed system.
- Any difficulties you faced in writing your project code.
- Any explanations for the software coding.
- Any ideas to develop this project in hardware and in software.
- A conclusion about the contributions of each member to the project.
After you complete the project,
- Please pack the report proj.txt, the C code (-.C and -.H files), the -.hex file, the .lst file, and the -.DSN file of your project into a zip file with the name proj.zip
and e-mail it using your student e-mail account to [email protected]
with the subject line proj before the June 15, 2010 midnight .
- Please submit a hardcopy of only proj.txt file (no code, only verbal report) to
your instructor, or to lab assistant.
Enjoy the project.
Last day of delivery is Final Exam Day. No excuse acceptable.
82
83
11.
APPENDIX
Complete 8086 instruction set
Mnemonics
AAA
AAD
AAM
AAS
ADC
ADD
AND
CALL
CBW
CLC
CLD
CLI
CMC
CMP
JA
JAE
JB
JBE
JC
JCXZ
JE
JG
JGE
JL
JLE
JMP
JNA
JNAE
JNB
CMPSB
CMPSW
CWD
DAA
DAS
DEC
DIV
HLT
IDIV
IMUL
IN
INC
INT
INTO
IRET
JNBE
JNC
JNE
JNG
JNGE
JNL
JNLE
JNO
JNP
JNS
JNZ
JO
JP
JPE
JPO
JS
JZ
LAHF
LDS
LEA
LES
LODSB
LODSW
LOOP
LOOPE
LOOPNE
LOOPNZ
LOOPZ
MOV
MOVSB
MOVSW
MUL
NEG
NOP
NOT
OR
OUT
POP
POPA
POPF
PUSH
PUSHA
PUSHF
RCL
RCR
REP
REPE
REPNE
REPNZ
REPZ
RET
RETF
ROL
ROR
SAHF
SAL
SAR
SBB
SCASB
SCASW
SHL
SHR
STC
STD
STI
STOSB
STOSW
SUB
TEST
XCHG
XLATB
XOR
Operand types:
immediate: 5, -24, 3Fh, 10001101b, etc...
Registers REG: AX, BX, CX, DX, AH, AL, BL, BH, CH, CL, DH, DL, DI, SI, BP,
SP
Segment Registers SREG: DS, ES, SS, and only as second operand: CS.
memory: [BX], [BX+SI+7], variable, etc....
Notes:
When two operands are required for an instruction they are separated by comma, i.e.,
REG, memory
When there are two operands, both operands must have the same size (except shift and
rotate instructions). For example:
registers
AL, DL
DX, AX
m1 DB ?
AL, m1
m2 DW ?
AX, m2
84
AAD No operands
AAM No operands
; AH = 01, AL = 05
; AH = 00, AL = 0Fh (15)
AAS No operands
; AH = 02, AL = 0FFh
; AH = 01, AL = 09
85
ADC op1,op2
REG, memory
memory, REG
REG, REG
memory, immediate
REG, immediate
ADD op1,op2
REG, memory
memory, REG
REG, REG
memory, immediate
REG, immediate
AND op1,op2
REG, memory
memory, REG
REG, REG
memory, immediate
REG, immediate
Add.
STC
; set CF = 1
MOV AL, 5 ; AL = 5
ADC AL, 1 ; AL = 7
Flags: r{C,Z,S,O,P,A}
CALL addr
procedure name
label
4-byte address
('A')
CBW No operands
CLC No operands
CLD No operands
86
CLI No operands
Flags: 0{I}
CMC No operands
CMP op1,op2
REG, memory
memory, REG
REG, REG
memory, immediate
REG, immediate
CMPSB No operands
Flags: r{C,Z,S,O,P,A }
CMPSW No operands
Flags: r{C,Z,S,O,P,A }
CWD No operands
DAA No operands
= 0
= 0
AX = 00000h:0FFFBh
AX = 0FFFFh:0FFFBh
DAS No operands
DEC op
REG
memory
Decrement.
operand = operand - 1
Example:
MOV AL, 255 ; AL = 0FFh (255 or -1)
DEC AL
; AL = 0FEh (254 or -2)
Flags: r{Z,S,O,P,A }, n{C} Carry flag is not changed.
DIV op
REG
memory
Unsigned divide.
when operand is a byte:
AL = AX / operand; AH = remainder (modulus)
when operand is a word:
AX = (DX AX) / operand ; DX = remainder (modulus)
Example:
MOV AX, 203
MOV BL, 4
DIV BL
; AX = 00CBh
; AL = 50 (32h), AH = 3
Signed multiply.
when operand is a byte: AX = AL * operand.
when operand is a word: (DX AX) = AX * operand.
Example:
MOV AL, -2
MOV BL, -4
IMUL BL
; AX = 8
Flags: 0{C, O }, u{ Z,S,P,A }
IN op1,op2
AL, im.byte
AL, DX
AX, im.byte
AX, DX
INC op
REG
memory
INT imm
immediate byte
INTO No operands
IRET No operands
87
88
JA addr
label
JAE addr
label
JB addr
label
JBE addr
label
JC addr
label
JCXZ addr
label
Jump if CX is Zero.
if CX = 0 then jump endif
Flags not changed
JE addr
label
JG addr
label
JGE addr
label
Jump if Greater than or Equal to. Short Jump relative to IP for Signed
compare. Jump if first operand is Greater than or Equal to second
operand when used after CMP instruction.
if SF = OF then jump endif
Flags not changed
JL addr
label
JLE addr
label
Jump if Less than or Equal to. Short Jump relative to IP for Signed
compare. Jump if first operand is Less than or Equal to second
operand when used after CMP instruction.
if SF <> OF or ZF = 1 then jump endif
Flags not changed
JMP addr
label
4-byte address
89
JNA addr
label
JNAE addr
label
JNB addr
label
JNBE addr
label
JNC addr
label
JNE addr
label
JNG addr
label
JNGE addr
label
JNL addr
label
JNLE addr
label
JNO addr
label
JNP addr
label
Short Jump if No Parity. Only 8 low bits of result are checked. Set by
CMP, SUB, ADD, TEST, AND, OR, XOR instructions.
if PF = 0 then jump endif
Flags not changed
JNS addr
label
Short Jump if Not Signed (positive). Set by CMP, SUB, ADD, TEST,
AND, OR, XOR instructions.
if SF = 0 then jump endif
Flags not changed
JNZ addr
label
Short Jump if Not Zero. Set by CMP, SUB, ADD, TEST, AND, OR,
XOR instructions
if ZF = 0 then jump endif
Flags not changed
JO addr
label
JP addr
label
Short Jump if Parity (even). Only 8 low bits of result are checked. Set
by CMP, SUB, ADD, TEST, AND, OR, XOR instructions.
if PF = 1 then jump endif
Flags not changed
JPE addr
label
90
JPO addr
label
Short Jump if Parity Odd. Only 8 low bits of result are checked. Set by
CMP, SUB, ADD, TEST, AND, OR, XOR instructions. Same as JNP
(jump if no parity) instruction.
JS addr
label
Short Jump if Signed (if negative). Set by CMP, SUB, ADD, TEST,
AND, OR, XOR instructions.
if SF = 1 then jump endif
JZ addr
label
LAHF No operands
LDS op,mem
REG, memory
LEA op,mem
REG, memory
LES op,mem
REG, memory
LODSB No operands
LODSW No operands
LOOP
label
addr
LOOPE addr
label
Decrease CX, jump to label if CX not zero and Equal (ZF = 1).
CX = CX 1
if (CX <> 0) and (ZF = 1) then jump else no jump, continue
endif
Flags not changed
LOOPNE addr
label
Decrease CX, jump to label if CX not zero and Not Equal (ZF = 0).
CX = CX 1
if (CX <> 0) and (ZF = 0) then jump else no jump, continue
endif
Flags not changed
LOOPNZ addr
label
LOOPZ addr
label
Same as LOOPNE
Flags not changed
Same as LOOPE
Flags not changed
MOV op1,op2
REG, memory
memory, REG
REG, REG
memory, immediate
REG, immediate
SREG, memory
memory, SREG
REG, SREG
SREG, REG
MOVSB No operands
91
MOVSW No operands
MUL op
REG
memory
Unsigned multiply.
when operand is a byte: AX = AL * operand.
when operand is a word: (DX AX) = AX * operand.
Example:
MOV AL, 200
; AL = 0C8h
MOV BL, 4
MUL BL
; AX = 0320h (800)
Flags r{C, O}. 0{CF,OF} when high section of the result is zero.
NEG op
REG
memory
NOP No operands
NOT op
REG
memory
OR op1,op2
REG, memory
memory, REG
REG, REG
memory, immediate
REG, immediate
OUT op1,op2
immediate-byte, AL
immediate-byte, AX
DX, AL
DX, AX
POP op
REG
SREG
memory
92
POPA No operands
(80186 +)
POPF No operands
PUSH op
REG
SREG
memory
immediate (80186 +)
PUSHA No operands
(80186 +)
PUSHF No operands
RCL op1,op2
memory, immediate
REG, immediate
memory, CL
REG, CL
RCR op1,op2
memory, immediate
REG, immediate
memory, CL
REG, CL
Pop all general purpose registers DI, SI, BP, SP, BX, DX, CX, AX
from the stack (SP value is ignored, it is Popped but not set to SP
register).
it works with 80186 and later
POP DI
POP SI
POP BP
POP xx (SP value ignored)
POP BX
POP DX
POP CX
POP AX
Flags not changed
Get flags register from the stack.
flags = SS:[SP] (top of the stack)
SP = SP + 2
Flags popped from stack
Store 16 bit value in the stack.
PUSH immediate works only on 80186 CPU and later!
Flags not changed
Push all general purpose registers AX, CX, DX, BX, SP, BP, SI, DI
in the stack. Original value of SP register (before PUSHA) is used.
Note: this instruction works only on 80186 CPU and later!
PUSH AX
PUSH CX
PUSH DX
PUSH BX
PUSH SP
PUSH BP
PUSH SI
PUSH DI
Flags not changed
Push flags register in the stack.
SP = SP - 2
SS:[SP] (top of the stack) = flags
Flags not changed
Rotate operand1 left through Carry Flag.
The number of rotates is set by operand2.
When immediate is greater then 1, assembler generates several RCL xx,
1 instructions because 8086 has machine code only for this instruction .
shift all bits left, the bit that goes off is set to CF and previous
value of CF is inserted to the right-most position.
Flags r{C,O} . 0{OF} if first operand keeps original sign.
Rotate operand1 right through Carry Flag.
The number of rotates is set by operand2.
When immediate is greater then 1, assembler generates several RCL xx,
1 instructions because 8086 has machine code only for this instruction .
shift all bits right, the bit that goes off is set to CF and previous
value of CF is inserted to the left-most position.
Flags r{C,O} . 0{OF} if first operand keeps original sign.
RET No operands
or even immediate
RETF No operands
or even immediate
ROL op1,op2
memory, immediate
REG, immediate
memory, CL
REG, CL
ROR op1,op2
memory, immediate
REG, immediate
memory, CL
REG, CL
SAHF No operands
93
94
SAL op1,op2
memory, immediate
REG, immediate
memory, CL
REG, CL
SBB op1, op2
REG, memory
memory, REG
REG, REG
memory, immediate
REG, immediate
SCASB No operands
SCASW No operands
SHL op1,op2
memory, immediate
REG, immediate
memory, CL
REG, CL
SHR op1,op2
memory, immediate
REG, immediate
memory, CL
REG, CL
STC No operands
STD No operands
STI No operands
STOSB No operands
STOSW No operands
SUB op1,op2
REG, memory
memory, REG
REG, REG
memory, immediate
REG, immediate
TEST op1,op2
REG, memory
memory, REG
REG, REG
memory, immediate
REG, immediate
XCHG op1,op2
REG, memory
memory, REG
REG, REG
XLATB No operands
XOR op1,op2
REG, memory
memory, REG
REG, REG
memory, immediate
REG, immediate
95
Subtract.
operand1 = operand1 - operand2
Flags: r{C,Z,S,O,P,A}
Logical AND between all bits of two operands for flags only.
These flags are effected: ZF, SF, PF. Result is not stored anywhere.
96
Assembler Directives
.model [tiny|small|compact|medium|large|huge]
.data (defines the start of data segment)
.code (defines the start of code sector)
.stack n (defines the size of stack segment)
@data (data segment allocated by OS.)
<name> equ value (assigns name=value)
db value (allocate byte with value)
dw, dd, dq alloc.word, double-word, quadword
dt (allocate 10 digit unpacked-BCD.)
n dup(value) (duplicate value for n times.)
<proclabel> proc [short|near|far]endp
(define procedure)
end (end of assembler source.)
<macrolabel> macro argumentlistendm
(define macro).
include filename.extension (include a file)
call procaddr (calls near subroutine procaddr)
ret [n] (removes n bytes from stack and
returns from subroutine)
push rx - pop rx (push - pop16-bit reg. on
stack.)
pushf - popf (push - pop flags onto stack)
xchg dst,src (swaps registers dst and src)
8255 PPI
Mode-0 Control Byte:
(for PA, PCH, PB, PCL use 0:output, 1:input)
b7
b6
b5
b4
b3
b2
b1
b0
PA
PCH
PB
PCL
8251 USART
Mode Register format for asynchronous mode:
b7 b6 = { S2S1: nr.of stop bits
00: invalid / 01:1stop / 10: 1.5stop / 11: 2stop },
b5
= { EP:
parity type
0: odd / 1: even },
b4
= { PEN: parity enable
0: no-parity-bits / 1: parity-bits-present },
b3 b2 = { L2L1: nr.of data bits
00: 5-bit / 01: 6-bit / 10: 7-bit / 11: 8-bit },
b1 b0 = { B2B1: baud rate factor 00: sync-mode / 01: /1 / 10: /16 / 11: /64 }
b7
b6
b5
b4
b3
b2
b1
b0
b7
b6
b5
b4
b3
b2
b1
b0