Systems Design and The 8051
Systems Design and The 8051
Design
and the 8051
The hardware, firmware, and software
design of microprocessor systems
Second Edition
exit
TechnoPress
Tulsa
Systems Design and the 8051
Contact:
THEWAY Corp.
P.O. Box 33124
Tulsa, OK 74153
www.ThewayCorp.com
[email protected]
Edited by:
Cover Design: Marcus O. Durham, PhD
Printed in United States of America
First printing by Fidlar Doubleday, August 2003
Second edition by Fidlar Doubleday, August 2004
ISBN: 0-9719324-6-8
2
TO
Russ Sanders, a former student who has taken his early training and
made a business of it. Ron Sanders, a colleague, who has worked on
my various designs for many years.
⇐⇑⇒
3
Table of Contents
Title Page................................................................................... 1
Table of Contents...................................................................... 5
Section I – Foundations ....................................................................4
Section II – Systems .........................................................................6
Section III – Applications...............................................................10
Section IV – Hardware ...................................................................11
Section V – Architecture ................................................................12
Section VI – Communication .........................................................13
Section VII – Documentation ........................................................14
SECTION I - FOUNDATIONS 15
1. Introduction ............................................................................ 16
Why this book, now 16
Development environments 18
Book structure 18
Class structure 19
Credit where credit is due 20
2. Fundamental circuits.............................................................. 21
Fundamentals 21
Output 22
Input 23
Computer vs. microcontroller 24
History 101 24
Microcontroller 25
Microcontroller input/output 26
Sink or source 27
Propagation delay and power consumption 28
External input/output 29
3. Memory devices ...................................................................... 31
Where do you keep it 31
Table of Contents 5
Program 31
Data 32
Dual in-line package 32
Connections 33
How it works 34
Other uses 34
4. Project 0 - Memory................................................................. 36
Project 0: Math using ROM 36
5. Micro primer........................................................................... 38
Its all in the family 38
On-board data memory 39
Arithmetic 39
Other packages 40
Flash microcontroller 40
Program memory locks 40
Features 41
The extended family 42
6. Address and interface............................................................. 43
What is the connection 43
Power 43
Clock 43
Reset 45
Ports 45
Port 0 46
Port 2 46
External memory 47
External program 47
External data 48
External 64K 48
Port 1 49
Port 3 49
7. Minimum system..................................................................... 50
Minimalist 50
Project 51
Minimum software 51
Opcodes, mnemonics, comments 52
Classes of instructions 53
Schematic 53
8. Machine cycle time ................................................................. 55
First computer circuit 55
6 Systems Design and the 8051 Durham
Cycle time 56
Machine cycles 57
Long precise wait 58
In from out 58
Switch a bit 59
Circuit: led metronome 60
9. Project 1 – Output & time delay ........................................... 61
Project 1: Metronome 61
Program sample example 63
10. Software development ............................................................ 66
The here and now 66
Instructions 67
Assembler directives 69
Step by step 71
Program with comments 71
Listing 73
Intel hex 75
Commentary 76
The top placement 77
The subs 78
Your comments, please 78
The bottom placement 79
Structure 79
11. Design practices ...................................................................... 81
Top down 81
Extreme programming (XP) 82
Steps for success 83
Process diagram 85
SECTION II - SYSTEMS 86
12. Switch, logic, and subs............................................................ 87
Switch hitter 87
Debounce 88
Bit manipulation 88
Masking logic 89
Rotate and exchange 90
Conditional branch 91
Subroutines 92
Stack 93
Circuit: led and switch 95
Table of Contents 7
Serial 385
SCON: Serial control register 385
50. SFR extended ........................................................................ 387
Enhanced registers 387
Timer/counter 2 387
T2CON: Timer/counter 2 control register 389
T2MOD: Timer 2 mode register 390
Timer 2 data registers 390
Serial peripheral interface 391
SPCR: SPI control register 392
SPSR: SPI status register 393
SPDR: SPI data register 394
WMCON: Watchdog 394
Using onboard EEPROM 395
⇐⇑⇒
SECTION I - FOUNDATIONS
⇐⇑⇒
1
INTRODUCTION
Thought
Engineering is the tradeoff
between quality, time, and money
You can have two, but you cannot have all three.
MOD
Why use the 8051 architecture? The core of the 8051 arguably is
used more than any other device. It is an expansion of the i8042
architecture, which is the fundamental processor used in keyboards
for personal computers. Phenomenally, the architecture has been
around for over 25 years. It is constantly being enhanced by various
vendors to perform tremendous tasks.
This work, Systems Design and the 8051, takes a different tack. It is
based on engineering design principles that are elucidated as
required. Extreme programming (XP) approach to compatibility
allows each new project to be integrated as a separate, but
interactive module.
The book begins with the fundamentals and sequentially adds new
projects. This is accomplished by integrating a straightforward and
concise application explanation for all software commands. That is
followed by a circuit representation of the new components. The
project requirements are laid out. Finally, an exemplar program
shows a similar system that the designer can modify to complete the
project.
18 Systems Design and the 8051 Durham
The procedure can obviously work. For many years, I have had
students step-by-step build a functioning, integrated computer
system around 10 projects. They start with a parts list, obtain the
parts, and build the projects into a working system. This is done in a
single semester. What an accomplishment!
Development environments ________
The projects will begin with using a memory device as a table for
arithmetic functions. A number of projects will be constructed for
performing common control tasks. The epitome of control will
entail communications between two computers.
You can accomplish the tasks. The projects should prove both
challenging and enjoyable. Occasionally, you may be frustrated but
persevere. As a result, the completion of the task will be most
rewarding.
The material comes with a guarantee. If you complete all the tasks,
you will have the tools to design a computer system for any
purpose. Good Computing!
FUNDAMENTAL CIRCUITS
Thought
Tell me the input, output, and
what to do in between, then
I can write a computer program.
Capt. Ed Fischel, USAF
Fundamentals ___________________
What are the fundamentals? Is it not input, output, and how these
are related? A mechanical switch represents every type of input
there is in a digital world. Similarly, a lamp or light emitting diode
(LED) is a surrogate for every possible output.
These two simple devices can effectively interface to any real world
circumstance by placing a buffer between the digital components
and the external items. Hence, a transistor or gate can substitute for
the switch and LED.
The power for most digital computer devices historically has been 5
volts DC referenced to ground. In many of the newer technologies,
this level is dropping below 2 volts. Regardless, the power voltage
is called VCC and has a digital value of 1 or True. Similarly, the
reference ground is zero volts, is called VSS, and has a digital value
of 0 or False.
22 Systems Design and the 8051 Durham
Output _________________________
VCC Ground
R = V / I = 1.5 V/ 5 mA = 300 Ω
Typical values are 270 to 330 Ohms. If the lamp is not bright
enough, the specifics should be verified, and a different resistor
should be calculated.
Chapter 2 Fundamental Circuits 23
Input ___________________________
A switch must represent two states, both off and on. Therefore, it
must be connected to both power and ground. To prevent a short
circuit when the switch is closed, a resistor is placed between the
power and the switch. This is called a pull-up resistor. The other
side of the switch is connected to ground.
The output of the switch is taken between the resistor and the
switch. The other side of the output is ground.
VCC
Out
Ground
The computer was originally developed during World War II. These
machines were physically very large, but had limited memory.
Large computers continued to develop until the very powerful
mainframe systems of the 1960’s. These machines still had discrete
magnetic core memory, transistors, and diodes.
At that time, the first integrated circuits (ICs) were being developed.
From the earliest days of the IC, microcomputers have been a major
component. A brief chronology of the microcomputer shows the
rapidity of the development.
Microcontroller _________________
The basic computer circuit is actually very simple. First power and
ground are connected to the upper right and lower left pins
respectively. Next, a crystal is connected to the XTAL pins to
provide stimulus for the internal oscillator. An 11.059 MHz crystal
will provide good performance and excellent communications.
Other choices are available and can be found in later sections. A
very small coupling capacitor of 10 – 40 pf is connected from each
side of the crystal to ground.
Third, pulling the RESET line high restarts the processor. The
RESET line can float low during normal operation. A power-on
reset circuit is often connected to the pin to automatically perform
the start function.
VCC
Xtal2
Xtal1
Ground
Any bit of the port can be converted to input. Simply send a one to
the bit of the port. Then that bit can be read or input. If all ones are
sent to a port, then the entire byte becomes an input.
The internal circuitry for one bit of a port is shown. A latch holds
the output to the pin. A separate line provides the input.
For output, data is written to the port. The result is displayed on the
pin. For input, a one is sent to the port. This enables the line and
Chapter 2 Fundamental Circuits 27
pulls the pin high. Therefore, with no other connection to the pin,
input from the port bit will be one. If the pin is pulled low by an
external switch, then the input is a zero.
VCC
Q
Latch
pin
Q’
port in
Sink current is the amount of current that will flow into an output,
IOL, at low state. Source current is the amount of current that will
flow out of a gate, IOH, at the high state.
tPLH tPHL
The table below gives the performance for various logic families. A
minus sign indicates current is flowing out of the gate.
A later chapter on circuit time and phase shift addresses the timing
and propagation delay in more detail.
Chapter 2 Fundamental Circuits 29
Vcc
port
Vcc
port
ground
Port Ground
Vcc
port
30 Systems Design and the 8051 Durham
When the switch is closed, the lamp will be on. Therefore, the
switch must be open for the lamp to be controlled by the port. When
the port sends a zero, the lamp is on. When the port sends a one, the
lamp is off, and the switch can be read.
⇐⇑⇒
3
MEMORY DEVICES
Thought
Memory is the second thing to go.
He just does not remember the first.
Old quip
Program ________________________
Data ___________________________
Connections _____________________
Like most other DIP packages, power is supplied to the upper right
(pin 28), and ground is supplied to the lower left (pin14).
* V
A14 1 28 VCC
A12 2 27 /WE
A7 3 26 A13
A6 4 25 A8
A5 5 24 A9
A4 6 23 A11
A3 7 22 //OE
A2 8 21 A10
A1 9 20 //CE
A0 10 19 DQ7
DQ0 11 18 DQ6
DQ1 12 17 DQ5
DQ2 13 16 DQ4
Ground 14 15 DQ3
Memory 256K
When sending data to the chip, the Write Enable not (/WE) line
must be pulled low. When obtaining data from the chip, the Output
Enable not (/OE) line must be pulled low. Obviously, the two lines
should not be pulled low simultaneously.
34 Systems Design and the 8051 Durham
Addresses = 2m
For eight (8) address connections, there are 256 addresses. The first
address is zero (0) and the last would be 255.
2m * 8 = 28 * 8 = 2048
Since the chip will have an output based on the status of the address
lines, it can be used to represent a conventional logic network.
There are ‘n’ outputs and each output can have 2m maxterms.
Chapter 3 Memory Devices 35
The ROM has fixed values, which makes it well suited for projects
that require a table lookup. This is particularly appropriate for
mathematics problems that are repeated frequently.
Consider an example.
Given: y = 2 x2 – 1
Allowable range: 0 ≤ x ≤ 3
⇐⇑⇒
4
PROJECT 0 - MEMORY
Thought
Skip this project,
if not using external memory.
Purpose: Skip this project if you are not using external memory.
To show the function of a ROM.
To program an EPROM.
Preamble:
The function of address and data lines is exactly the same as the
ones on a ROM. Placing information in an EPROM is called
Chapter 4 Project 0 - Memory 37
Plan:
Preparation:
Procedure:
Presentation:
MICRO PRIMER
Thought
Prim and proper
is an old Southern saying for
‘You have got it together.’
A & B accumulators
Timer/counter mode and control
Serial port mode and control
Stack pointer
Data pointer
Program status word for flags
Interrupt enable and priority
Parallel ports 0, 1, 2, and 3 for data I/O
Arithmetic ______________________
One of the variations of the 8051 which has almost everything but
the kitchen sink is an Atmel design. Other than part of this section,
the section on in-system programming, and the chapter on extended
special function registers, all the remaining information in this book
is generic and applicable to the entire family of microcontrollers.
Some versions have three lock bits that can be left unprogrammed
(U) or can be programmed (P) to obtain security and prevent further
programming or fetching of the program. In prototyping, these are
left unprogrammed.
Features ________________________
The data sheet for the device provides very substantial design
information. Much of this is similar to generic controllers.
A primer provides all the details about how to use the features that
are special to this machine. Both these data sheets are available from
the manufacturers and on the web.
EXTERNAL
INTERRUPTS
4K 128
ROM RAM
TIMER 2
CPU
RD WR P0 P2 P1 P3 TXD RXD
ADDRESS
⇐⇑⇒
6
Thought
Education:
Learn - Do -Teach
Power __________________________
Before anything can work, power must be applied. The upper right
(pin 40) is connected to VCC, which is usually 5 volts. The lower left
(pin 20) is connected to the ground reference.
Clock __________________________
* V
P1.0 1 T2 40 VCC
P1.1 2 T2 EX AD0 39 P0.0
P1.2 3 AD1 38 P0.1
P1.3 4 AD2 37 P0.2
P1.4 5 SS/ AD3 36 P0.3
P1.5 6 MOSI AD4 35 P0.4
P1.6 7 MISO AD5 34 P0.5
P1.7 8 SCK AD6 33 P0.6
Reset 9 AD7 32 P0.7
P3.0 10 RXD VPP 31 /EA
P3.1 11 TXD PROG/ 30 ALE
P3.2 12 INT0 29 /PSEN
P3.3 13 INT1 A15 28 P2.7
P3.4 14 T0 A14 27 P2.6
P3.5 15 T1 A13 26 P2.5
P3.6 16 /WR A12 25 P2.4
P3.7 17 /RD A11 24 P2.3
Xtal2 18 A10 23 P2.2
Xtal1 19 A9 22 P2.1
Ground 20 A8 21 P2.0
MCS 51 / 8051
Reset ___________________________
Reset is connected to pin 9. The machine runs when the line is low.
Reset occurs if the pin is pulled high for two machine cycles. In the
simplest realization, a switch performs this function. The switch
should be open for normal operations and momentarily closed for
reset.
The most elegant circuit occurs with power on. This circuit will
automatically reset the computer whenever power is applied. The
circuit consists of a 10 microfarad capacitor connected to Vcc and a
10 K Ohm resistor connected to ground.
Ports ___________________________
Ports are parallel locations within the processor. Each port includes
eight bits that are individually addressable. Three different notations
are used to represent a bit on a port, as shown in the diagram. These
include pin number, port number followed by the bit number, and
function such as address / data.
The maximum output currents that the chip can handle are shown in
the table.
46 Systems Design and the 8051 Durham
Condition IOL
Max per port pin 10 mA
Max for eight bit, port 0 26 mA
Max for eight bit, port 1,2,3 15 mA
Max total for all output pins 71 mA
Port 0 __________________________
Port 2 __________________________
Two pins control the data capture and transfer. The chip or latch
enable (pin 11) is asserted high, the gates receive and pass
information. When the pin is asserted low, the flip/flops trap and
hold the information. The output enable not (pin 10) is hardwired
low to permanently activate the output.
When the 8 address bits are on the port, the Address Latch Enable
line (pin 30) is toggled. This pin is connected to the chip enable pin
of the external latch. Therefore, when the address is superimposed,
the latch will capture and hold the location.
Do not allow input address pins on any memory device to float. Pull
the pin low if it is not connected to the processor.
Data is read from external memory when the read not (/RD) pin 17
is pulled asserted low by the processor. This is connected to the read
not (/RD) or output enable not (/OE) pin 22 on the memory device.
Address = 28 – 1 = 255
Chapter 6 Address & Interface 49
Since the port is bit accessible, any bits not used for addressing are
available for use as general purpose I/O. Often the upper bit (A15)
is used to select memory or memory-mapped input/output.
Port 1 __________________________
Port 1 is the most used general purpose I/O (pins 1-8) on the
processor. The internal pull-ups operate like port 2. Most devices
are connected through these pins.
Port 3 __________________________
⇐⇑⇒
7
MINIMUM SYSTEM
Thought
Elegantly simple
Minimalist ______________________
Although the software code is very simple for this type project, the
implementation will be in a structure that can support very complex
problems. As systems grow, more interaction is needed. A later
software illustration identifies issues of compatibility, particularly
for variable descriptions.
wires. Red should be used for power. Black is preferred for ground.
A variety of other colors for inter-connections will help
construction. Keep the board neat, since this will aid
troubleshooting and improve your attitude about the project.
Project _________________________
The project is to apply one switch and two LED’s to the computer.
One LED is on while the other is off. Change the state of the switch
and the LEDs will change state.
Addresses 0000 – 0002h are the power on reset vector and are
reserved to send the program to another location. Addresses 0003 –
002Ah are reserved for interrupt processing in a standard processor.
Many enhanced processors reserve the next 8 bytes for expansion
interrupts. Additional explanation is given in the architecture section
covering memory organization.
Schematic _______________________
The illustration should show the circuit so that another builder can
construct it. This particular example also shows the in-system
programming connections, although that is not normally shown. It is
provided so the novice can start from scratch and build it.
54 Systems Design and the 8051 Durham
VCC
Vcc
Xtal2
Xtal1
Ground
⇐⇑⇒
8
Thought
Engineers do not run the world,
But make the world run.
hold the address while the data/program is fetched from the ROM.
If the program memory is internal, then the system is very simple.
In the latter case, a connection for programming the in-system
memory is needed.
To obtain less time, remove the outer loop that includes register R3.
To obtain greater time, add another loop outside the shown code.
The machine cycles for each instruction are gathered from the
instruction table toward the back of the book.
mov = 1 cycle
nop = 1 cycle
djnz = 2 cycle
ret = 2 cycle
The time for each loop is calculated by counting the total number of
cycles in the loop. The inner loop includes just three instructions.
mov =1
nop = 1* loop count
djnz = 2* loop count
The total cycles depend on going through the inner loop as many
times as the outer loop counter.
Determine the total cycles for the example given above. The inner
count is one (1), while the outer loop is two (2).
Inner loop = (3 * 1) + 1 =4
Outer loop = [(4 + 2) * 2] + 1 = 17
Plus = 4 for call & return =4
58 Systems Design and the 8051 Durham
Total cycles = 25
The elapsed time is the total cycles multiplied by the time for each
cycle.
Some routines for display require a longer wait string than typically
used. These can be developed by multiple calls to a precise delay.
One-tenth second is a good base counter.
;-------------------------------------------------
WAIT:
;-------------------------------------------------
; Create a 0.1 second wait.
; Count = 0.1/1e-6 = 100000
; Loop = 192 = C0H
The four ports are four bytes of the special function registers. These
bytes are used as the input and output connections to the computer.
Each of the ports is bit accessible. The operation of the ports was
explained in an earlier chapter. This discussion is how to program
the ports.
The output is quite simple. Place the value in the register that
represents the port. This triggers a latch, which holds the value on
Chapter 8 Machine Cycle Time 59
the external pins. A simple mov to the location will implement the
transfer of data to the external pins. No other action is required.
;ILLUSTRATE OUT/IN
mov 90h,#0FFh ;set port1 for input
mov A,90h ;read port status
mov 0B0h,#01 ;output port3,bit 1
;ILLUSTRATE OUT/IN
setb 0B0h ;set port3 for input
jb 0B0h,EXIT ;bit=1,then go end
;else do this instr.
60 Systems Design and the 8051 Durham
Port
⇐⇑⇒
9
Thought
You see what you seek.
Yakov Smirnoff
Preamble:
This makes one flash. The cycle is repeated for multiple flashes. A
cpl command is easily used to toggle a bit.
Plan:
Preparation:
Procedure:
Check the system that has just been built. Implement a metronome
on the computer. Since ports 0 and 2 are used for memory
addressing, ports 1 and 3 are free for direct input/output. Put an
LED on one of the free I/O port bits. The LED must blink at a
specific rate. The cycling output implementation is a metronome.
Writing a 1 and 0 sequentially to a bit of the output port is the actual
task.
Presentation:
⇐⇑⇒
;-----------------------------
;Program: MODDelay.asm
;Update: 29 January 2003
;Initial: 17 October 1991
;
64 Systems Design and the 8051 Durham
;-----------------------------
0080 org 0080H
INITIAL:
MAIN:
;-----------------------------
0080 D2B4 setb 0B4h ;turn on
0082 12008A lcall DELAY ;wait
0085 D2B5 setb 0B5h ;turn on
;-----------------------------
DELAY:
;-----------------------------
Chapter 9 Project 1 - Output & Time Delay 65
end
⇐⇑⇒
10
SOFTWARE DEVELOPMENT
Thought
God is in the details.
Instructions _____________________
The source code consists of the information on each line that starts
with the label. The assembler adds the address and op codes to each
line.
The third is db and its related types. This defines byte values in code
memory. It often involves table values and ASCII messages. Include
a line with a copyright message. If it is not copyrighted, use
70 Systems Design and the 8051 Durham
Several assemblers are available for the 8051. The major differences
are in the syntax of the directives. Three commonly used formats are
compared.
The major directives are listed in the table. Each assembler has a
different set, but these are the most common. There is an overlap
Chapter 10 Software Development 71
; www.ThewayCorp.com
;Copyright (c)1990, 2003. All rights reserved
;
;Purpose:
; The LED on P3.4 will come on.
; The LED on P3.5 will go off.
; The LEDs will change state if P3.3 is at ground
;#################################################
;
; ASSIGNMENTS
;
;#################################################
;PORT USE
P33 equ 0B3H ;Port3.3, switch input
P34 equ 0B4H ;Port3.4, LED
P35 equ 0B5H ;Port3.5, LED flashing
;#################################################
;
; PROGRAM
;
;#################################################
START:
;-------------------------------------------------
; When processor is reset, program control comes
; here. Jump to the first executable address
; after all interrupts reserved locations, etc.
org 00H
ljmp INITIAL
Chapter 10 Software Development 73
org 33H
db 'Marcus O. Durham, PhD, PE'
;-------------------------------------------------
org 80H
INITIAL:
;-------------------------------------------------
;-------------------------------------------------
MAIN:
;-------------------------------------------------
;*************************************************
end
Listing _________________________
The first information is the memory location of the first byte of the
instruction. The next information is the machine code translation of
the instruction.
After the program, the listing shows the value of every variable in
the code.
An edited version of the listing is shown to save space and fit within
the page size. Comments have been truncated in addition to removal
of header information.
75 ;-------------------------------
83
0086 20B304 84 jb P33,MAIN9
0089 B2B4 85 cpl P34
008B B2B5 86 cpl P35
87
008D 80F7 88 MAIN9: sjmp MAIN
89
90 ;*******************************
91 end
N A M E T Y P E V A L U E A T T R I B U T E S
Each line begins with a colon (:). This is followed by the number of
bytes on the line, the address of the first byte, a directive, then the
machine instructions in that block. The line concludes with the
checksum for the line.
76 Systems Design and the 8051 Durham
Commentary ____________________
The first item that should be used is a header which gives the name
of the program and who wrote the document. Remember, there are
laws against plagiarism. The use of a version number of a program
(e.g. V1.3, V2.2) is strongly recommended. Update or increase the
number of the version every time you edit a file. This helps to keep
track of each change made to the files.
Chapter 10 Software Development 77
The next major item that should follow is a short description of the
program. This should be long enough to give the user a general idea
of what the program does. The user should be able to use the
software without having to figure it out the hard way. Avoid going
into endless detail. Depending on the program, the description may
be anywhere from 2-3 paragraphs to about one page. A page and a
half may be required for BIG programs.
Assume that the user does not have your hardware available, but
that (s)he is intelligent enough to put together a system to run your
software. Therefore, state such things as where to hook-up port-pins
and what parts of the software to modify if a different crystal is
used. Similarly, the documentation should be good enough that the
user can modify the code or add to the program. (S)he should not
have to spend weeks trying to figure out whether the
additions/changes will affect the old code.
Place all the equate statements in one place such as at the top of the
file. Typical equates include ASCII codes, RAM locations, and
external locations in the memory map. This item can save you and
the user substantial time when digging for a particular item.
Remember to update these addresses when you change locations.
Often the equate list can save substantial amounts of time when
determining which items may adversely affect the program. This is
especially important if you are writing only one module of a large
program.
78 Systems Design and the 8051 Durham
Document any test pin or port bit assignments. Note the uses for all
the registers dedicated to only one or two uses. If a register is used
as a general-purpose register, it can be so stated.
If you do not write the comments until after you have finished
writing the program, often you will have forgotten what a particular
Chapter 10 Software Development 79
line of code does. Alternatively, you will run out of time and skip
the comments altogether. In that case, the client will not even bother
to look at the program.
Structure _______________________
Second, the structure forces you to think about what you are trying
to accomplish with the program. Hence, the program can be broken
down into distinct sub-tasks, which can be more easily tackled.
Often these subroutines can be used in several different parts of the
program, thus saving ROM space. If subroutines are well written,
they can also be used in other programs calling for similar
functions.
⇐⇑⇒
11
DESIGN PRACTICES
Thought
One small step for man
One giant leap for mankind.
Commander Neal Armstrong
1. Entry
The point where the procedure starts arises from a reset or from
a decision.
2. Initialize
A sequence of events or conditions are involved in the planning
and set-up.
3. Input
The loop first must gather data from other sources.
4. Process
The core of the loop is manipulation of the data until a final
value is obtained.
5. Output
The defined results are displayed or become input to another
procedure.
6. Limit
A test or decision is performed to determine if the loop is
completed. The test may occur at three different places.
a. The test may be implemented before the input if there is a
predefined loop range. This is a If-Then-Else or For-Next
structure.
b. A decision is made after the input based on the input. This
is a data comparison structure.
c. A decision is made after the process is complete. This is a
Do-While some condition exists.
7. Exit
The point to leave the project causes transfer to another
procedure or task.
Chapter 11 Design Practices 85
exit
⇐⇑⇒
SECTION II - SYSTEMS
⇐⇑⇒
12
Thought
People are where they are,
because of choices they make.
MOD
Debounce _______________________
;-------------------------------------------------
DEBOUNCE:
;-------------------------------------------------
;CHECK CHANGE BY xrl
mov B,A ;hold the input
xrl A,CharP ;exclusive or
jnz DEBN1 ;<>0, so a change
;KEEP DEBOUNCED
mov CharD,B ;0=no change,debounc
DEBN1: mov CharP,B ;not debounce
ret
The routine compares bytes. The value enters in the A register. The
previous value is kept in CharP. By using an EXCLUSIVE-OR, bits
that have changed are easily found. If bits have not changed, keep
the debounced value in CharD.
In addition the internal data locations 20 – 2Fh (32 – 47d) are bit
addressable. The bit address is sequential. Address 20h, bit 0 has a
bit address of 00h. Bit 7 has an address of 07h. Address 2Fh, bit 7
has a bit address of 7Fh.
;bit MANIPULATION
CLEAR: clr 93h ;clear port1,bit3
SETCARRY: setb C ;1→Carry
Not all the values that exist in a byte are always necessary for
evaluation. If only some of the bits are used, the others can be
removed from the byte. The process of selectively modifying some
of the bits is called masking.
The logical AND (anl) of a bit with a 0 clears the bit, while using a
1 leaves the bit unchanged.
The logical OR (orl) of a bit with 1 sets the bit, while using a 0
leaves the bit unchanged.
;ILLUSTRATE LOGIC
ZERO: anl A,#11110111b ;A bit3 becomes 0
ONE: orl A,#00001000b ;A bit3 becomes 1
INVERT: xrl A,#00001000b ;A bit3 complemented
Logical orl and anl should be used to selectively set bits on output
ports. This will change the status of bits without impacting the other
functions. If there are multiple functions on the port, avoid mov
instructions.
Data bits can be moved one position to an adjacent bit location. The
data must be in the accumulator or A register.
If the register is rotated to the right, the least significant bit (LSB) is
rotated to the most significant bit (MSB). Conversely, if the register
is rotated to the left, the MSB is rotated to the LSB. No data is lost
in the transaction.
The machine does not have a shift instruction since it has hardware
multiply and divide. A shift is similar to a rotate, except a bit falls
off the end with each shift. If a shift is required the rotate with carry
can be used.
Chapter 12 Switch, Logic & Subs 91
;CONDITIONAL BRANCH
BEFORE: ;an entry
Subroutines _____________________
;SUBROUTINE
MAIN: lcall SUB ;SUB=label
ONE:
Only four bytes and four clock cycles are required for the two
instructions that create a subroutine. The lcall uses 3 bytes and 2
clock cycles, while ret uses 1 byte and 2 clock cycles.
Stack ___________________________
The subroutine instructions, lcall and ret, places and retrieves the
two program counter bytes on the stack.
There are two instructions that move a byte between direct internal
memory and the stack. push places the direct value into the next
memory address above the location in the stack pointer. pop moves
the value at the stack pointer location to the direct internal memory.
Although other instructions may be between them, always pair stack
operations.
;STACK
INITIAL: mov SP,#5Fh ;move stack to 5Fh
;other commands
SUB: push Direct ;direct to stack
;other commands
pop Direct ;stack to direct
The stack can use the entire internal data memory. The large stack
makes the machine capable of pseudo-reverse polish operations. In
many ways the machine appears to be a stack processor.
Chapter 12 Switch, Logic & Subs 95
Port
⇐⇑⇒
13
Thought
Sell to people that are buying.
Jim Stovall
Preamble:
Preparation I:
Procedure I:
Presentation I:
Preparation II:
Wire 6 LEDs on one port and 2 switches on the other bits of the
port. The input port switches will represent brake, idle, turn left, and
turn right signals. A two-bit input will be sufficient. The LEDs will
represent the taillights. When the switch combination is selected, the
LEDs should have the following display:
Procedure II:
There are no restrictions in choosing the port for your I/O system.
Remember to use proper software documentation. Then, the port
used will be obvious to the customer.
Presentation II:
⇐⇑⇒
Chapter 13 Project 2 – Input & Decisions 99
;Program: ModTbird.asm
;Initial: 7 February 2003
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.ThewayCorp.com
;Copyright (c)2003. All rights reserved
;Purpose:
; Check switches for status and display
; results in pattern of old T-Bird car
; P3.0-P3.1 used as direction input
; 00-idle, 01-right, 10-left, 11-brake
; P3.2-P3.4 left lights
; P3.5-P3.7 right lights
; P1.2 start switch
;
;Processor: 8031 family
;PROM: 8k (2000H) onboard
;Crystal: 11.059 MHz
;Assembler: Intel ASM51
;
;#################################################
; ASSIGNMENTS
;#################################################
Pio equ 0B0h ;port for input output
Switch equ 092h ;switch input
;#################################################
; PROGRAM
;#################################################
org 00H
100 Systems Design and the 8051 Durham
org 0033h
db 'Marcus O. Durham, PhD, PE'
;-------------------------------------------------
org 0080H ;get past interrupt
INITIAL:
;-------------------------------------------------
setb Switch ;make switch input
mov Pio,#03h ;make bits 0&1 input
;-------------------------------------------------
MAIN:
;-------------------------------------------------
jb Switch,MAIN ;use as start,1=open
lcall INPUT ;get switch input
;-------------------------------------------------
INPUT:
;-------------------------------------------------
; Check bits for input.
;-------------------------------------------------
OUT:
;-------------------------------------------------
Chapter 13 Project 2 – Input & Decisions 101
;-------------------------------------------------
DELAY:
;-------------------------------------------------
; Create a short time delay
;-------------------------------------------------
RIGHT:
;-------------------------------------------------
; Flash right lights.
ret ;exit
;-------------------------------------------------
LEFT:
;-------------------------------------------------
; Flash left lights.
ret ;exit
;-------------------------------------------------
102 Systems Design and the 8051 Durham
BRAKE:
;-------------------------------------------------
; Turn all lights on.
; Ensure port input is not cleared.
ret ;exit
;-------------------------------------------------
IDLE:
;-------------------------------------------------
; Turn all lights off.
; Ensure port input is not cleared.
lcall DELAY ;
ret ;exit
;*************************************************
end ;Program end
⇐⇑⇒
14
Thought
Everyone is given the same 24-hours.
What you do with it makes the difference.
MOD
One of the more useful features is the built-in timer counters. These
can be used to count events or to count machine cycles. The
machine cycles then translate into time.
The counting register is sixteen bits. The low byte is TL0, while the
high byte is TH0.
Timer __________________________
One machine cycle consists of six states. Each state lasts for two
oscillator periods. Hence one machine cycle takes 12 oscillator
periods.
Interrupts _______________________
Interrupts can arise on two pins of port3. These are INT0 (0B2h)
and INT1 (0B3h). The interrupts are initialized in the interrupt
enable (IE) register. The precedence can be set in the interrupt
priority (IP) register. Detailed explanations are provided in the
section on special function registers.
106 Systems Design and the 8051 Durham
;-------------------------------------------------
COUNT0:
;-------------------------------------------------
setb 0B4h ;set T0 for input
mov TMOD,#00000101b ;T0,Mode1,counter
setb TR0 ;start the count
ret
;-------------------------------------------------
COUNTS:
;-------------------------------------------------
;COUNT 5 EVENTS
lcall COUNT0 ;set up timer
mov A,#5 ;preload the limit
HERE: cjne A,TL0,HERE ;T0 count low byte
Chapter 14 Timers & Interrupt 107
;-------------------------------------------------
COUNTINT:
;-------------------------------------------------
;INITIAL
setb 0B4h ;count 1 as input
mov TMOD,#00000101b ;counter=0, mode1
mov TH0,#0FFh ;minus leading ones
mov TL0,#0FBh ;-5
setb TR0 ;start counting
;OPTIONAL INTERRUPT
orl IE,#10000010B ;enable all & T0
;HERE: jnb TF0,HERE ;optional polling
ret ;get outta here
;-------------------------------------------------
TIMEINIT:
;-------------------------------------------------
; The preset time is calculated. The crystal osc.
; frequency is 11.059 MHz.
108 Systems Design and the 8051 Durham
;
; Preset= (Sec * Osc freq)/12 osc/machine cy
;
; for 1 msec, THxTLx= -921.583= -400h = 0FC66h
; for 1/20 sec, THxTLx= -45954.167 = 4C7Eh
; for 1/30 sec, ThxTlx= -30719.444 = 8801h
; ;INITIAL
mov TMOD,#00000001b ;timer=0, mode=1
TIMERUN: mov TH0,#88h ;4C7Eh = 1/20 sec
mov TL0,#01H ;lo count
setb TR0 ;start counting
;OPTIONAL INTERRUPT
orl IE,#10000010b ;enable all & T0
ret ;MrButler to Atlanta
Port
⇐⇑⇒
15
Thought
Objectivism
is rational self-interest.
Ayn Rand
Preamble:
To receive an interrupt signal from the pins, make sure that the bits
corresponding to each pin are enabled. Set the bit to one, since the
ports are bit addressable.
Create a project to show that both interrupt pins work properly with
either a level or an edge-triggered signal.
Procedure I:
A more elegant design will count the number of times that the INTx
pin is triggered. Then, after a preset number of events, an LED will
illuminate.
Presentation I:
Procedure II:
Toggle the same LED every second. After each minute, illuminate
another LED. It is advisable to write the clock routine inside the
interrupt program and the display routine as the main program. This
will provide a more precise clock.
Presentation II:
Demonstrate the operation of the clock. Ensure all LEDs are off
before time start.
⇐⇑⇒
;-------------------------------------------------
;Program: MODTime.asm
;Update: 07 February 2003
;Initial: 17 October 1991
;
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.ThewayCorp.com
;Copyright (c)1991, 2002. All rights reserved
;
;Purpose:
; A set of routines are provided to perform the
; basic functions of a clock.
;
;Processor: 8031 family
;PROM: 8k (2000H) onboard
;Crystal: 11.059 MHz
112 Systems Design and the 8051 Durham
;#################################################
;
; ASSIGNMENTS
;
;#################################################
;#################################################
;
; PROGRAM
;
;#################################################
org 00H
START: ljmp INITIAL
;-------------------------------------------------
;INTERRUPT-Timer 0
;-------------------------------------------------
; The procedure provides direction when timer
; completes count.
org 0BH
ljmp TIMECAL ;interrupt processor
;-------------------------------------------------
org 0033H
db 'Marcus O. Durham, PhD, PE'
;-------------------------------------------------
org 0080H
INITIAL:
;-------------------------------------------------
mov SP,#5Fh ;start stack @ 5f+1
lcall TIMEINIT ;start timer0
;-------------------------------------------------
MAIN:
;-------------------------------------------------
;PROCESS
jnb TimFlag,Man9 ;time cycle at end?
Chapter 15 Clock & Interrupt 113
;-------------------------------------------------
TIMEINIT:
;-------------------------------------------------
;INTERRUPT
orl IE,#10000010b ;enable all & T0
; ;INITIAL
mov TMOD,#00000001b ;timer=0, mode=1
lcall TIMERUN ;preset & start T0
ret ;MrButler to Atlanta
;-------------------------------------------------
TIMERUN:
;-------------------------------------------------
; The routine preloads values and starts the
; timer.
;
; The preset time is calculated. The crystal osc.
; frequency is 11.059 MHz.
;
; Preset= (Sec * Osc freq)/12 osc/machine cy
;
; for 1 msec, THxTLx= -921.583= -400h = 0FC66h
; for 1/20 sec, THxTLx= -45954.167 = 4C7Eh
; for 1/30 sec, ThxTlx= -30719.444 = 8801h
;INITIAL
clr TR0 ;stop counting
mov TH0,#88h ;8801h = 1/30 sec
mov TL0,#01H ;lo count
setb TR0 ;start counting
;-------------------------------------------------
TIMECAL:
;-------------------------------------------------
; This routine is called from the interrupt
114 Systems Design and the 8051 Durham
;INITIAL
lcall TIMERUN ;preset & start T0
;*************************************************
end
⇐⇑⇒
16
BOARD CONSTRUCTION
Thought
Moral economics:
Maximizing personal benefit,
without compromising integrity.
Professor Durham
Improper soldering will keep the board from working and can be
nearly impossible to find. If you are uncomfortable with soldering,
ask for instructions or help. There are a few training videos that are
excellent tools. It is better to start correctly than to redo much of
your work.
Basics __________________________
Build the board the way you are learning the projects. Begin with
the basics, get it working, and then move to things that are more
complicated.
The first step is to get power to the board. If you do this first, you
can test the board without concern for damaging expensive
electronics. Install the voltage regulator, filtering capacitor, and the
power plug connector.
Then apply power. Verify that there is VCC (5V) and ground where
it is required on the board.
Socket to me _____________________
The memory expansion has a special socket that will allow a 0.3” or
0.6” wide memory chip. To install the socket, cut the connecting
bars that hook the sides of the socket together. Install the 14-pin SIP
header in the center row of the socket.
Initially, connect EA’ to 5V, since external memory is not used. The
others can be connected if the components are added.
⇐⇑⇒
17
Thought
A liberal selectively
acts the way he wants without regard for
accountability, absolutes, or consequences.
MOD
Preamble:
Several chapters refer to board construction. One has a parts list and
pin-out diagrams. The board schematic and specifications are
included. Another has details for construction practices.
For the most basic computer, only the processor, crystal oscillator,
memory, and power supply are required. If the program memory is
internal, then the system is very simple.
Plan:
Preparation:
Procedure:
Presentation:
⇐⇑⇒
18
EXTERNAL MEMORY
Thought
A conservative
is constrained by
accountability, absolutes, or consequences.
MOD
Since only one page of memory is available, any addresses that are
used for internal memory are not available in the external memory
chip.
Control lines are used to segregate data and program memory and to
isolate internal and external operation. On Reset, program control
transfers to program memory address 0000h.
If the external address not (/EA) line is low, the address points to
external memory. If /EA is high, the program counter points to
Chapter 18 External Memory 123
The addressing is handled the same for both data and program
memory. The sixteen-bit address for external memory is placed on
two ports. Port 0 has the low byte and port 2 has the high address
byte. The eight bit data is transferred via port 0.
The data for the latch is setup when the latch enable (LE) pin is
driven high. When the pin is pulled low, the data is trapped by the
latch.
The ALE line is connected to the latch enable pin of the latch. When
the ALE line is asserted, the address is setup. The address is trapped
on the trailing (falling) edge of ALE. The latch holds the low
address. Port 2 holds its high address until the information byte
from memory is received.
124 Systems Design and the 8051 Durham
Port 0 must be set for input to receive data. The CPU automatically
sets port 0 for input during a memory fetch. However, it does not
retain special function settings. Therefore, that information is
destroyed during a program fetch.
Since there is not input on port 2 during a fetch, it does not have to
be configured. Therefore, port 2 special function register data is
preserved during an external program fetch. The data reappears on
the port during cycles, which are not a part of external program
fetch.
The data pointer register is also sixteen bits. The program must fill
the register. It will point to program memory when the movc
instruction is used. It will point to data memory when the movx
instruction is used. This is called indirect addressing
There are a few one-byte, two-cycle instructions, such as ret and inc.
The sequence is read instruction at S1, read and discard next byte at
S4, S1, S4.
RAM is written on write enable not (/WE) on pin 27. Address A14
is connected on pin 1. RAM is read via output enable not (/OE) on
pin 22. RAM read is activated by read not (/RD) and write not
(/WR).
A map clearly illustrates how the connections to the chip socket are
interrelated. A programmable logic device (22CV10) can be used as
the logic to switch the appropriate lines to the socket.
⇐⇑⇒
19
BIOS
Thought
An anarchist
is unconstrained by
accountability, absolutes, or consequences.
MOD
Definition ______________________
This chapter and the associated project will only be used if your
design includes both an external EPROM and SRAM and the
program is loaded via the serial port. Otherwise, the topics can be
skipped with no loss of ability to build a workable system.
What is bios? Bios is an acronym for basic input output system. The
program begins when the computer is initialized. The procedure is
typically stored in read-only memory and cannot be changed.
Because of the permanent nature of the software, it is often called
firmware.
The bios for the microprocessor system would include the firmware
implementation of the serial, seven-segment or liquid crystal
display, and keypad. That is what is commonly used as a backbone
for developing applications software.
The code is for use with the most fundamental derivatives of the
Intel 8031. Many variations of the microprocessor have this or
similar capabilities as an integral part.
;-------------------------------------------------
BIOSMAIN:
;-------------------------------------------------
;INITIALIZE
mov SP,#5Fh ;start stack @ 5f+1
lcall UART ;Config & start UART
;PROCESS
lcall RAMTEST ;Test RAM & interfac
mov DPTR,#SerGreet ;get start addr
lcall BIOSSER ;Send message on ser
lcall DOWNLOAD ;Serial DOWNLOAD Ram
lcall P35DONE ;Flash P35=done dnld
;TERMINATE
ljmp MEMSWIT ;Switch prog storage
;to RAM from EPROM
If any one of the values read does not equal the value written, then
the test fails. A failed test can result from a bad interface or a bad
RAM chip. The message LED on P3.5 cycles off/on 128 times.
The message LED at P3.5 turns on at the start of the test and turns
off at end of a successful test. The memory subroutine returns to the
main calling routine upon test completion.
;-------------------------------------------------
RAMTEST:
;-------------------------------------------------
;TURN ON LED & INIT
setb P3.5 ;Set LED on/uC Busy
mov TmpA,#02 ;two wr/rd passes
mov TmpC,#0AAH ;First wr=10101010
;LOOP
RAMT1: mov TmpB,TmpC ;Start write pass
mov DPTR,#0000H ;First RAM address
;WRITE
RAMT2: mov A,TmpB ;Value to write
movx @DPTR,A ;Write to RAM
cpl TmpB ;Flip bits
inc DPTR ;Increment address
mov A,DPL ;} Continue write
cjne A,#00H,RAMT2 ;} loop until each
mov A,DPH ;} RAM address has
cjne A,#80H,RAMT2 ;} been written to.
;SUCCESSFUL TEST
clr P3.5 ;LED off/uC not Busy
sjmp RAMT9 ;Return to call
;FAILED TEST
RAMT7: mov TmpA,#0FFH ;Init loop counter
RAMT8: cpl P3.5 ;Toggle LED
lcall DELAY ;Delay to see LED
djnz TmpA,RAMT8 ;Loop 256 times
setb P3.5 ;Set LED on/uC Busy
RAMT9: ret ;Return to call
Download ______________________
The routine waits for a colon byte. Then the next byte determines
the number of hex values in one line or record. The stream next has
a two-byte value for the beginning program address where the data
will be stored. The following byte is to check end-of-file. Finally,
the stream of hex contents follows and is transferred to RAM.
;-------------------------------------------------
DOWNLOAD:
;-------------------------------------------------
;NO HANDSHAKE
clr P3.5 ;Hndshak-uP not BUSY
;RECEIVE READY
jnb RI,DOWNLOAD ;Wait for rec'd byte
lcall SERIN ;Input byte
cjne A,#3AH,DOWNLOAD ;Wait for : input
;COUNTER BYTES
DOWN1: lcall DOWNBYTE ;':' rec'd, get byte
mov R5,A ;Put in R5 for cntr
mov R4,A ;Init CHEKSUM in R4
Chapter 19 Bios 133
;ADDRESS
DOWN2: lcall DOWNBYTE ;Get next byte which
mov DPH,A ;is high order addrs
lcall CKSUMINC ;Update checksum
lcall DOWNBYTE ;Get next byte which
mov DPL,A ;is low order addrs
lcall CKSUMINC ;Update checksum
;NEXT byte
DOWN4: lcall DOWNBYTE ;Input HEX file
movx @DPTR,A ;Output to RAM
inc DPTR ;Next address
lcall CKSUMINC ;Update checksum
djnz R5,DOWN4 ;Repeat if more byte
;CHECK IF ERRORS
DOWN5: mov A,R4 ;Verify CKSM of recd
cpl A ;byte & HEX file.
inc A ;Complement, add 1 &
mov TmpA,A ;compare with in
lcall DOWNBYTE ;file. If OK,
cjne A,TmpA,DOWN7 ;continue, else err
ljmp DOWNLOAD ;Continue receiving
;end-OF-FILE
DOWN6: lcall DOWNBYTE ;Input file chksm.
cjne A,#0FFH,DOWN7 ;If not FF, error
ret ;Return to call
;FAILED
DOWN7: mov LoopC,#3CH ;Loop counter
DOWN8: cpl P3.5 ;Toggle LED/uP BUSY
lcall DELAY ;Delay to see LED
lcall DELAY ;Delay to see LED
lcall DELAY ;Delay to see LED
djnz LoopC,DOWN8 ;Loop 60 times
setb P3.5 ;LED on/uP BUSY
ret ;Return to call
134 Systems Design and the 8051 Durham
Downbyte ______________________
This routine inputs two sequential ASCII values and converts them
to a corresponding binary value. The binary format is a nibble. The
low order and high order nibble are combined to yield the
hexadecimal Intel-hex format. Register A is used for input, R3 for
output, with R1 and R2 for processing.
;-------------------------------------------------
DOWNBYTE:
;-------------------------------------------------
;RECEIVE READY
jnb RI,DOWNBYTE ;Wait for full byte
lcall SERIN ;Input when rec'd
mov R1,A ;Put byte in R1
anl A,#40H ;Ck lead nibble, if
jz DOWB2 ;above 9, convert.
;
;HEX TO DECIMAL
DOWB1: mov A,#09D ;Conv ASCII A to F
add A,R1 ;by adding 9 then
sjmp DOWB3 ;adjust lead nibble
;
;DECIMAL
DOWB2: xch A,R1 ;Xchg ASCII value
;
;ADJUST
DOWB3: swap A ;Swap nibbles then
anl A,#0F0H ;strip unused nibble
mov R3,A ;Put hi nibble in R3
;
;GET NEXT byte
DOWB4: jnb RI,DOWB4 ;Wait for next byte
lcall SERIN ;Input when rec'd
Chapter 19 Bios 135
Checksum ______________________
;-------------------------------------------------
CKSUMINC:
;-------------------------------------------------
add A,R4 ;add new byte to sum
xch A,R4 ;put sum into accum
ret
The procedure calls the serial input routine that was discussed in the
serial project. It also calls a routine to convert ASCII data to a
binary byte.
136 Systems Design and the 8051 Durham
;-------------------------------------------------
ASCIBYTE:
;-------------------------------------------------
;RECEIVE READY
jnb RI,ASCIBYTE ;Wait for full byte
lcall SERIN ;Input when rec'd
mov R1,A ;Put byte in R1
anl A,#40H ;Ck lead nibble, if
jz ASCB2 ;above 9, convert.
;
;HEX TO DECIMAL
ASCB1: mov A,#09D ;Conv ASCII A to F
add A,R1 ;by adding 9 then
sjmp ASCB3 ;adjust lead nibble
;
;DECIMAL
ASCB2: xch A,R1 ;Xchg ASCII value
;
;ADJUST
ASCB3: swap A ;Swap nibbles then
anl A,#0F0H ;strip unused nibble
mov R3,A ;Put hi nibble in R3
;
;GET NEXT byte
ASCB4: jnb RI,ASCB4 ;Wait for next byte
lcall SERIN ;Input when rec'd
mov R2,A ;Put ASCII byte n R2
anl A,#40H ;Strip lead nibble
jz ASCB6 ;If ASCII above 'A'
;
;HEX TO DECIMAL
;then adjust by + 9
Chapter 19 Bios 137
All register values retain their value during this switch since no reset
occurs. Therefore, the new program must initialize the register
values it uses.
For example, consider the bios starts at address 0000h. It has the
requisite jump past the interrupts. It begins operation at address
0080h. Then the download procedure occupies the next few hundred
138 Systems Design and the 8051 Durham
bytes. If the memory switch routine is org 007Ah (80h – 6h) in the
ROM, then the new program will also start at 0080h in the RAM.
;-------------------------------------------------
007A org 007AH ;After interrupt
MEMSWIT:
;-------------------------------------------------
007A 90FFFF mov DPTR,#0FFFFH ;Mode latch address
007D 7401 mov A,#1 ;Mode =1
007F F0 movx @DPTR,A ;Make switch to RAM
The process just described works fine if the ROM and RAM are
both external. However, if the ROM is internal, /EA will not be
configured for external operation. As a result, it is necessary to be a
little more creative with the software.
;-------------------------------------------------
org 1FFAh ;After interrupt
MEMSWIT:
;-------------------------------------------------
Then the next program code line will execute at 2000h. In order for
the new program that has been downloaded to execute properly, it
must have the program organized to org 2000h.
;-------------------------------------------------
org 2000h ;start address
START:
;-------------------------------------------------
Chapter 19 Bios 139
Create a routine that will display the location of all the routines that
may be called. Use the data to define the location to the SRAM
program. The SRAM procedure will require an equ for the name
and address of each routine that is called. Alternately, an org
directive can be set for the same location.
⇐⇑⇒
20
Thought
Perfect practice makes perfect.
Proverb
Preamble:
Plan:
The interface used to download INTEL HEX files from the host to
the microcontroller system is simple RS-232 serial communication
without any control (handshake) lines.
Preparation:
There are two other pins that are used for chip control. These are the
chip select and the output enable. Functionally, since there is only
one memory device, the chip select can be left active by connection
to ground. The output is determined by the function.
142 Systems Design and the 8051 Durham
EPROM: /OE=/PSEN
SRAM: /OE=/RD
The indicator for the download process will use port P3.5. Connect
an LED with proper buffering to this port.
Finally, program the code memory with the BIOS program that was
discussed in the previous chapter.
Procedure:
The BIOS program will operate as a RAM tester. If P3.5 turns on,
then off, the right connections have been made. If the LED flashes
128 times, hardware debugging of the SRAM system is required.
The monitor program constantly scans for the incoming serial data.
The host PC computer will execute a download file transfer
program. This program transmits an INTEL HEX file from the host
to the development board. If P3.5 flashes 30 times, the download
process was not successful. Otherwise, the download was
completed.
The BIOS changes control to execute the program from RAM. The
application program should begin at an address above all interrupts
and other reserved spaces.
Presentation:
SERIAL COMMUNICATIONS
Thought
For lack of a nail…
the kingdom was lost.
Benjamin Franklin in
Poor Richard’s Almanac.
Background ____________________
With his system, Krum also developed a code for the sequence of on
and off bits. This code is the predecessor of the present day
American Standard for Information Interchange (ASCII) characters.
That standard was adopted in 1966.
Microcontroller _________________
Separate buffers are used for transmit and receive, therefore they
can occur simultaneously as true duplex communications. Since the
micro code is structured for communications, software
implementation is very simple. The speed is setup, a message is
transferred via the buffer, and a flag is checked for completion of
the message.
Mode 0 _________________________
Oscillator Frequency
Baud Rate = {--------------------}
12
Mode 1 _________________________
Mode 1 has a variable baud rate for eight bit data. Either Timer 1 or
Timer 2, if available, can generate the baud rate. The generic
procedure uses Timer/Counter 1.
K * Oscillator Frequency
Baud Rate = {------------------------}
32 * 12 * [256 – TH1]
The reload time for the baud rate is placed in the high byte of Timer
1 (TH1). The equation to calculate TH1 can be written as follows.
K * Oscillator Frequency
TH1 = 256 – {------------------------}
32 * 12 * Baud Rate
148 Systems Design and the 8051 Durham
Mode 2 _________________________
In Mode 2, the baud rate is fixed for 9-bit data. It is 1/32 or 1/64 of
the oscillator frequency, depending on the value of the SMOD bit in
the PCON register. In this mode, none of the timers is used, and the
clock comes from the internal phase-2 clock.
SMOD = 1, Baud Rate = 1/32 Osc Freq.
SMOD = 0, Baud Rate = 1/64 Osc Freq.
To set the SMOD bit, use orl PCON,# 80H. The address of PCON is
87H.
Mode 3 _________________________
The baud rate in mode 3 is variable and sets up exactly the same as
in mode 1. This allows 9-bit data transfer.
Oscillator Frequency
Baud Rate = {------------------------------}
32 * [65536 – (RCAP2H,RCAP2L)]
To obtain the reload value for RCAP2H and RCAP2L the previous
equation can be rewritten as follows.
Oscillator Frequency
RCAP2H,RCAP2L = 65536 – {-------------------}
32 * Baud Rate
burst crystal. Although odd for computers, the frequency is the very
common 3.5795 MHz.
1 * 3579500
TH1 = 256 – {--------------}
32 * 12 * 300
TH1 = -31.07
Interestingly, this slow rate of 300 Baud is still frequently used with
long range radio communications such as amateur or “ham” radio.
The set-up for serial communication has many options that require
substantial details. Nevertheless, the actual code used is quite small.
A complete serial initialization contains a very limited number of
lines.
Register PCON, bit SMOD can be used to double the baud rate. If
the bit is clear, the rate multiplier is K=1. If the bit is set, then the
multiplier is K=2. However, the speed multiplier is not used for
these examples.
Chapter 21 Serial Communications 151
For a 11.059 MHz oscillator, and 9600 baud operation, the value
placed in TH1 is 0FDHh (-3d).
;-----------------------------
UART:
;-----------------------------
mov TMOD,#00100000b ;Timer 1 Mode 2
mov TH1,#0FDH ;9600 BAUD @11.05MHz
mov SCON,#01010010b ;Set SM1, REN & TI
setb TR1 ;Start timer
ret ;Return to call
Many options are available for data protocol. The SCON register is
configured for eight-bit or nine-bit data transfer. This will then
determine the hardware communications sequence. Eight bits are
normal communications. Nine are used when additional control bits
are required.
If parity is used, the bit is placed as the last bit in the transmission.
For eight-bit exchange, this would be the most significant bit in the
accumulator. However, because of the difficulty in managing eight
bits of data, plus a parity bit, the parity is often not used.
The standard data format for interchange with most serial devices is
ASCII. This is a 7-bit code for characters. The table is shown in the
reference chapter on ASCII.
The serial line is normally held high. When data is ready to be sent,
the line is pulled low for one bit time, the start bit. Then the eight bit
string is sent. This is followed by a high stop bit that allows the
receiver to process the character.
Chapter 21 Serial Communications 153
0 1 2 3 4 5 6 7
Wait Start Stop
The exchange of data using the internal serial buffers is very simple.
First, verify that the last process is complete. Then clear the process
interrupt flag. Next, transfer the data between the accumulator and
the buffer.
Once the data is in the buffer, the program can go on to other things.
The hardware micro code will complete the exercise of shifting the
data between the port 3 pins and the buffer.
;-----------------------------
SERIN:
;-----------------------------
jnb RI,$ ;rcv busy so wait.
mov A,SBUF ;Get byte from SBUF
clr RI ;Clear RI
ret ;Return to call
;-----------------------------
SEROUT:
;-----------------------------
154 Systems Design and the 8051 Durham
* V
1 20
2 T1IN 19
3 R1OUT 18
4 R1IN 17
5 T1OUT C2- 16
6 GND C2+ 15
7 Vcc 14
8 13
9 GND 12
10 C2- C2+ 11
P3.0 Rx P3.1 Tx
⇐⇑⇒
22
Thought
Serial is for communicating.
Cereal is for eating.
Preamble:
The processor has a built-in serial circuit that can be used for
communications. The computer has its own baud rate generator,
which uses a timer. Several bits in various registers must be set
before opening serial communications. The timer interrupt registers
are a necessary component, since Timer 1 determines baud rate. The
details of setting registers, interrupts, and the baud rate generator
can be observed from the reference section.
Plan:
Preparation:
Procedure:
If the code is valid, turn on or off an LED. This can represent a relay
that opens / closes a door. Alternately, it can be a signal to another
device.
Presentation:
⇐⇑⇒
158 Systems Design and the 8051 Durham
;-----------------------------
;Program: MODRs232.asm
;Update: 29 January 2003
;Initial: 17 October 1991
;
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.ThewayCorp.com
;Copyright (c)1991, 2002. All rights reserved
;
;Purpose:
; A routine to demonstrate serial communication.
; A single character message will be displayed on
; the HyperTerminal or PC serial display.
;
;Processor: 8031 family
;PROM: 8k (2000H) onboard
;Crystal: 11.059 MHz
;Baud: 9600
;Assembler: Intel ASM51
;#################################################
;
; PROGRAM
;
;#################################################
org 00H
START: ljmp INITIAL
org 0033H
db 'Marcus O. Durham, PhD, PE'
;-----------------------------
org 0080H ;Addres past reserve
Chapter 22 Project 6 – RS232 Communications 159
INITIAL:
;-----------------------------
;INITIALIZE
mov SP,#5Fh ;start stack @ 5f+1
lcall UART ;config & start UART
;-----------------------------
MAIN:
;-----------------------------
;PROCESS
mov A,#3Fh ;ASCII ?
lcall SEROUT ;send character
MAN9: ljmp MAIN ;Repeat
;*************************************************
;
; SERIAL RS232
;
;*************************************************
UART:
;-----------------------------
;
; Initialize the registers that control the
; serial communications process.
;
; Timer 1 is used in eight bit auto-reload mode.
; So TMOD bit M1 is set and bits
; M1, C/T' and GATE are clear.
; With GATE set, INT1' & INT0' control the timer.
;
; Bit SMOD in register PCON can be used to double
; the baud rate when set. It's clear here, K=1.
; If set, then K=2.
;
; SCON is used to define serial communication
; mode 1, eight bit UART, by setting bit SM1,
; and enable reception with bit REN set.
;
; Bit TR1 in register TCON is set to enable
; timer.
;
; Set TI to indicate serial transmission is
; complete.
160 Systems Design and the 8051 Durham
;
; Register TH1 contains the count for baud rate.
; TH1 = 256-(K * Osc Freq / 384 * baud rate)
;
; For 11.059 MHz oscillator,
; TH1 is 0FDH (-3D) for 9600 baud.
; TH1 is 0E8H (-24D) for 1200 baud.
;-----------------------------
SERIN:
;-----------------------------
;
; General purpose serial receiver routine. It
; gets a byte from the serial buffer, SBUF,
; converts to the needed binary form by removing
; the leading bit, and clears the RI (receive
; interrupt) flag that is set by the uP after a
; full byte is received.
;
; Clearing RI allows next byte to be received.
; SBUF is the input and register A is the output.
;-----------------------------
SEROUT:
;-----------------------------
;
; Transfer one byte out to the serial port.
; TI is high while a transmission is happening.
Chapter 22 Project 6 – RS232 Communications 161
;*************************************************
;Program end
end
⇐⇑⇒
23
EXPANSION LATCHES
Thought
The process of success:
Dream – overcome – success.
MOD
One choice is to place latches on one of the ports and select the
latches with control lines. This is very straightforward, but three
design constraints must be considered.
Two latches are inherent for an effective system. The key latch has
lines for output of column and input of row lines. The display-out
latch has eight data lines for display devices. The routines for these
latches are common to many procedures.
When the latch enable (LE) is asserted high, the flip/flops are
transparent. The data is simply received by the flip/flops and
clocked through to the output. When the latch enable (LE) is
asserted low, the data on the input is trapped in the latch.
When the output enable not (/OE) is asserted low, the data on the
flip/flops is placed on the output terminals. When the /OE line is
asserted high, the output pins of the latches are high impedance.
Therefore, it does not interfere with other lines connected to the
same terminal pins.
When doing an output from the processor through the latch, the
output enable not (/OE) can be permanently wired low. When doing
an input from the latch to the processor, the latch enable (LE) line
can be permanently wired high.
The programmable logic must make the latch enable line high then
low. This may be done with hardware, but it is preferably done in
software using the select lines. The pins must be set high, then
cleared low for the latch to hold.
‘573
LE /OE
An input latch uses the output enable not (/OE) line. The line must
be asserted low by the processor before the value is read. So that
data is always available, the latch enable line is wired high, making
the latch transparent.
‘573
LE /OE
Chapter 23 Expansion Latches 165
Function Select
B4B3
unused 00
Keypad 01
Display out 10
ADC 11
;-------------------------------------------------
LKEY:
;-------------------------------------------------
; Latch for keys. Select as #01 on B4,B3.
;-------------------------------------------------
LOUT:
;-------------------------------------------------
; Latch for output. Select as #00 on B4,B3.
;-------------------------------------------------
LDISPLAY:
;-------------------------------------------------
; Latch for display out. Select as #10 on B4,B3.
;byte OUT
mov P1,A ;data to display
clr 0B3h ;display-out latch
setb 0B4h ;LE hi
clr 0B4h ;LE lo
ret
⇐⇑⇒
24
Thought
Doing the same thing and
expecting different results is ignorance.
Uncle Albert Einstein
Eight-bit addressing can be use to access the lower 256 bytes. The
address is stored in R0 or R1. There are four banks selected by the
process status word (PSW) register. Therefore, up to eight banks
can have an address.
The same register is employed for data memory and code memory.
Therefore, it must be changed frequently. That requires additional
temporary locations to hold the last values.
The instruction activates either the read not (/RD) or the write not
(/WR) line. These lines are active low when the data is available at
the port.
When using the bank registers, the bank must be selected first. Next,
the address is placed in the register. Then the transfer is made with
the external location.
When read or write lines are used for the latch enable (LE), the
process is very simple. The control line must be high during setup.
However, the read or write line is asserted low. Therefore, it must
be inverted before connecting to the latch enable. Then the latch
170 Systems Design and the 8051 Durham
traps the data when the read or write line is released to high, which
makes the LE go low.
When doing an output to the latch, the output enable not (/OE) can
be permanently wired low. The latch enable (LE) is controlled by
the and of the address with the inverted write not (/WR) line.
‘573
D0 – D7
Address
LE /OE
/Wr
When doing an input from the latch, the process is slightly more
complex. The output of the latch is not permitted on the port except
when the port is ready to read. Otherwise, the load of the latch
would influence other inputs.
‘573
D0 – D7
Address
/OE LE
/Rd 5V
The connection of the addresses with the read not or write not line is
accomplished in a programmable logic device (PLD). Therefore,
each of the two diagrams simply become an equation line of code in
firmware. The firmware latch is illustrated in the chapter on
programmable logic devices.
When the control is to the latch enable (LE) line, the device is self
latching simply by the transition of the read not (/RD) or write not
(/WR) line that is connected to the latch.
Chapter 24 Memory-mapped I/O 171
Function Address
Memory map 8000h
Key Oen & Key LE 8001h
Display LE 8002h
8003h
8004h
The latch controls circuits can be glue logic. However, to save space
and increase flexibility, a programmable logic device is preferred.
The latches that require the data to be held can be locked or gated
with firmware in the PLD.
;-------------------------------------------------
LKEYIN:
;-------------------------------------------------
; Latch for key in.
;-------------------------------------------------
LDISPLAY:
;-------------------------------------------------
; Latch for display out.
;byte OUT
172 Systems Design and the 8051 Durham
⇐⇑⇒
25
Thought
Listening is
asking open ended questions.
MOD
Preamble:
The I/O ports are already built within the chip. Moreover the ports
are an internal memory-mapped type.
Plan:
For this project, implement the T-Bird Tail Light System at the
memory-mapped locations.
Preparation:
In this project, the I/O system will be changed, rather than using an
individual I/O port. Decode the input and output system as a
memory location on the same lines as the external SRAM. Memory
mapping is accomplished by wiring a latch to the address / data
lines.
Procedure:
Use the 74573 as a latch to hold the data for the display. Rewrite the
previous display program so that it will run at the new addresses.
Remember, the previous display was handled as a port location. If it
were written with appropriate subroutines, only two lines of code
will change.
Chapter 25 Project 7 - I/O Expansion 175
Presentation:
⇐⇑⇒
;Program: MODmmio.ASM
;Update: 2 August 2004
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.ThewayCorp.com
;Copyright (c)1991 - 2004. All rights reserved
;#################################################
; ASSIGNMENTS
;#################################################
AdSeven equ 8002h;MMIO address for Seven Seg
;#################################################
; PROGRAM
176 Systems Design and the 8051 Durham
;#################################################
org 00H
START: ljmp INITIAL
org 0033h
db 25, 1,'Marcus O. Durham, PhD, PE'
;-------------------------------------------------
org 0080h ;get past interrupt
INITIAL:
;-------------------------------------------------
mov SP,#5Fh ;start stack @ 5f+1
;-------------------------------------------------
MAIN:
;-------------------------------------------------
;DISPLAY
MAN1: mov A,#55h ;turn on
MAN2: lcall OUT ;output seven seg
mov A,#0AAh ;alternate segments
lcall OUT
sjmp MAIN
;-------------------------------------------------
OUT:
;-------------------------------------------------
; Create a loop to display latch.
;*************************************************
end
⇐⇑⇒
26
TABLES
Thought
A project has four seasons-
plan, act, reap, reward
MOD
What are these kinds of data? Message strings are one common
example. Tables are another. Tables can be used to quickly translate
values. For example, numbers shown on a seven-segment display
have a unique pattern. The pattern can be stored in the table to
correlate with a number.
In reality, the Define Byte (db) has become the directive that all
assemblers use and is the only one required for programming. By
placing a string of bytes, words are automatically defined. If
numbers are used with the byte, they are stored directly. If ASCII
characters are stored, they are included in a single quote.
Chapter 26 Tables 179
To load the data, the corresponding number must be loaded into the
accumulator (A) register. The base determined by the org must be
loaded into the data pointer register (DPTR).
The following table illustrates the available letters and numbers that
can be built.
180 Systems Design and the 8051 Durham
Character Pattern
0 3F
1 06
2 5B
3 4F
4 66
5 6D
6 7D
7 07
8 7F
9 6F
A 77
C 39
E 79
F 71
H 76
I 06
J 1E
L 38
O 3F
P 73
S 6D
U 3E
Y 6E
b 7C
c 58
d 5E
g 6F
h 74
i 04
n 54
o 5C
r 50
t 78
u 1C
? 53
- 40
_ 08
Chapter 26 Tables 181
f b
g
e c
;EXTERNAL CODE
mov DPTR,#1000h ;base of table
mov A,#02h ;number seeking 7seg
movc A,@A+DPTR ;[1002h]= 5bh →A
;EXTERNAL data
mov DPTR,#08000h ;memory-mapped I/O
movx A,@DPTR ;[8000h] →A
182 Systems Design and the 8051 Durham
;-------------------------------------------------
DISPLAY:
;-------------------------------------------------
BIOSSER:
;-------------------------------------------------
;Send a string to the serial port.
ret
;-------------------------------------------------
SERCOMM:
;-------------------------------------------------
; Send byte on serial line.
; Convert byte to 2 ASCII characters.
;
;SAVE byte & SEGMENT
mov R0,A ;hold data
;#################################################
; CODE-STORED CONSTANTS
;#################################################
TABASCII:
;-------------------------------------------------
;look-up table for hex to ascii conversion:
db '0123456789ABCDEF'
;-------------------------------------------------
;Canned message to confirm serial port activation:
Online: db 6, 80h ,'Value=', CR, LF, 0
;#################################################
⇐⇑⇒
27
MULTIPLEXING
Thought
Our perception is an analog world,
the reality is discrete sampling.
Professor Durham
Perception ______________________
A phenomenal tool is the eye – brain sensory system. The eye sees
an object and translates the image to the brain. Actually, the eye is a
sampling system rather than a continuous analog network. The brain
processes the samples and gives the impression of continuous,
smooth information. Technology takes advantage of this visual
perception to reduce the quantity of information that must be
provided.
Consider some of the sampling to which the eye is exposed, but the
perception considers the data as stable. The tests are performed in
frames per second. The duration of the sampling is the reciprocal of
the frame rate.
186 Systems Design and the 8051 Durham
Frame/sec Image
<18 Movie has flicker
18 Motion appears fluid
24 Movie picture rate
25 Television image rate
60 Fluorescent lamp
75 Computer monitor refresh
100 Cannot detect any flicker
220 Air Force pilots identify a plane
500 No detection, but sense something not as it should be
When there are small changes near 20 frames per second, the
changes appear to be fluid motion. Near 100 frames per second, the
eye cannot see any transitions. However, trained pilots can detect an
airplane when it is flashed before their eyes for 1/220 second. If an
image is flashed occasionally, in the order of 500 frames per second,
the mind never detects it. However, the brain does sense something
is not quite right.
Multiplex _______________________
Similarly, displays that are updated more often than 25 times per
second will appear to be on continuously.
D0-D6 ‘573
data
PLD LE /OE
D0-D2 ‘573
SELECT
PLD LE /OE
188 Systems Design and the 8051 Durham
The select line drivers are open collector inverters, such as 7406.
These require a pull-up resistor on the output. This permits the chip
to supply much more current. Alternately, field effect transistors
(FETs) can be used as drivers. When all seven-segments are on,
then substantial current is required through the common pin.
When a one is sent to the inverter, the output is low. If the seven-
segment is common cathode, this is proper. However, if the display
is common anode, the data to the inverter must be complimented.
Latches are shown on the data lines. The devices should be ALS or
CMOS type, since they are less fan-out load. These latches may be
connected as memory-mapped I/O. They may also be expansion
latches on a port. The only difference is the control logic in the
programmable logic device.
The latches setup the output when the latch enable (LE) line is high.
When the line is then asserted low, the data is trapped in the latch.
That data is displayed as long as the output enable not pin is low.
Therefore, the programmable logic must make the latch enable line
high then low. This may be done with hardware in the case of
Chapter 27 Multiplexing 189
Code requirements________________
The display is a routine that operates in three steps that are repeated
for each digit to be displayed.
1. Select the digit display line.
2. Send the data byte to the display.
3. Wait briefly for persistence of display.
The first routine (SEVEN) sets the bit that activates the common
line on one of the seven-segment displays. These lines of code
would be repeated for as many displays as shown. The output
routine gets the byte to display, shows it and waits. The information
to be displayed is stored at the location referenced by R0.
For the examples, the select lines are on port 1, but this is easily
changed in the equate directives. Display A is bit 0 (P1.0), display B
is bit 1 (P1.1), and display C is bit 2 (P1.2). The output is either on a
port or memory mapped.
;-------------------------------------------------
SegA equ 90h ;address
SegB equ 91h ;address
SegC equ 92h ;address
;-------------------------------------------------
SEVEN:
;-------------------------------------------------
;DIGIT 1
clr SegA ;turnoff select line
190 Systems Design and the 8051 Durham
;-------------------------------------------------
SEVOUT:
;-------------------------------------------------
;byte OUT
mov A,@R0 ;data byte
inc R0 ;next info to show
;PERSISTENCE WAIT
mov R2,#200 ;Nested loop counter
ZDEL1: mov Pio,A ;display digit
djnz R2,ZDEL1 ;Nested loop, 256 x
ret
;-------------------------------------------------
SEVOUT:
;-------------------------------------------------
Chapter 27 Multiplexing 191
;byte OUT
mov A,@R0 ;data byte
inc R0 ;next info to show
;PERSISTENCE WAIT
mov DPTR,#8002h ;addr for disp latch
Simply do what your third grade teacher told you. Divide by the
place value to get the number for that place. The maximum number
is 255. So, first divide by 100 to get the number of hundreds. Take
the remainder and divide by the next place value of 10 to get the
number of tens for that place. Then remainder is the units.
;-------------------------------------------------
BINBCD:
;-------------------------------------------------
;byte BINARY TO BCD
mov A,GapD ;count 2
mov B,#100 ;divisor
div AB ;A/B, Quo= A, Rem= B
mov GapA,A ;# of 100's
mov A,B ;remainder
mov B,#10 ;divisor
div AB ;A/B, Quo= A, Rem= B
mov GapB,A ;# of 10's
192 Systems Design and the 8051 Durham
⇐⇑⇒
28
Thought
You are looking,
but are you seeing?
Dr. Eden Ryl
Preamble:
In this project build a 3-digit, 7-segment display. Only one byte may
be used to display LEDs. To display all the digits, use time
multiplexing.
The multiplex cycle must be very short, so that the human eyes will
not be able to see the blinking. The eye can discern any frequency
slower than 17 frames per second. Therefore, refresh the display
faster than 20 times a second. This task can be easily achieved, since
the uC is fast enough to process the output.
194 Systems Design and the 8051 Durham
Plan:
Preparation:
To drive the 7-segment displays, use a 74573 latch for the data
buffer. Connect the output of the latch to the seven pins of the
display. Repeat with a parallel connection to all other 7-segment
displays.
One option is to use an open collector driver. The 7406 hex inverter
is a popular open collector chip. The open collector must be
connected to 5 volts through an external pull-up resistor. Typically
Chapter 28 Project 8 - Seven-segment Displays 195
use 2.2 kOhm resistor with adequate power rating to handle the full
load current.
The driver input is a single bit that can come from any port or
memory-mapped I/O location. This becomes the digit select line.
Procedure:
Separate the hex number into two bytes or digits. Do a table lookup
to convert the digits to 7-segment values. Send the digits to the
multiplex display program. Display the value for about two seconds.
Presentation:
⇐⇑⇒
The latch key out and latch display routines are given in the chapter
on expansion latches.
;Program: ModSeven.ASM
;Update: 20 February 2003
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.ThewayCorp.com
;Copyright (c)1991, 2003. All rights reserved
;Purpose:
; Data is stored in GapA, GapB, GapC.
; Data is displayed on 3 7-segment displays.
; Display-out latch shows the data.
; The 3 displays are selected by port 3.2, 3.3, &
; 3.4
;
;#################################################
; ASSIGNMENTS
;#################################################
GapD equ 37H ;general purpose variables
GapC equ 36H
GapB equ 35H
GapA equ 34H
;#################################################
; PROGRAM
;#################################################
org 00h
START: ljmp INITIAL
org 0033h
db 25, 1,'Marcus O. Durham, PhD, PE'
;-------------------------------------------------
org 0080H ;get past interrupt
INITIAL:
;-------------------------------------------------
mov SP,#5Fh ;start stack @ 5f+1
setb P35 ;make input
;-------------------------------------------------
MAIN:
;-------------------------------------------------
lcall SEVSEG ;output seven segmen
;-------------------------------------------------
HELLO:
;-------------------------------------------------
; Preload a value into the general purpose bytes.
;PRELOAD
mov GapA,#0Fh ;data byte
mov GapB,#0Ah
mov GapC,#0Bh
ret
198 Systems Design and the 8051 Durham
;-------------------------------------------------
SEVBCD:
;-------------------------------------------------
; Convert the binary coded decimal to seven seg.
; Use a table look up.
;INITIAL
mov DPTR,#TabSeven ;seven seg table
;CONVERT
SBCD1: mov A,@R0 ;get BCD
movc A,@A+DPTR ;table offset to A
mov @R0,A ;replace w/ 7 seg
;NEXT DIGIT
inc R0 ;next
djnz LoopC,SBCD1 ;>=0, repeat process
;-------------------------------------------------
SEVSEG:
;-------------------------------------------------
; Seven Seg is a routine that operates in 4 steps
; 1. Select the digit stored in GapS
; 2. Select the digit to turn on
; 3. Send the data
; 4. Wait briefly for persistence of the led.
; 5. Repeat
;SELECT LINES
clr SegA ;turnoff all selects
clr SegB
clr SegC
;DIGIT 1
setb SegA ;Bit is hi, select A
Chapter 28 Project 8 - Seven-segment Displays 199
;DIGIT 2
;DIGIT 3
;TERMINATE
ret ;back to Hotlanta
;#################################################
; TABLES
;#################################################
TabSeven:
;-------------------------------------------------
; Seven-segment display
db 3Fh ;0
db 06h ;1
db 5Bh ;2
;complete the table
;*************************************************
end ;Program end
⇐⇑⇒
29
MATRIX SCANNING
Thought
Integrity is
recognizing someone’s short coming
and saying nothing about it to anyone.
Rosemary Durham
# wires = # keys + 1
This technique would require way too many wires, a huge cable,
and an excessive number of pins on the microprocessor. An
alternative is to use a matrix. A wire is connected to each row and a
wire is connected to each column.
A 4 x 4 keypad will add four more keys put will require only one
more wire. That is a huge gain.
VCC Output
Input
Conflicts ________________________
If the project were only that easy, anyone could do it and there
would be no need for a design engineer. However, there are several
opportunities for improvement.
First, switches will bounce when they are exercised. This will cause
the impression of multiple key depressions. Hardware triggers can
be used, but they are expensive. Software is the best solution. The
logical exclusive-or instruction makes the problem almost trivial.
The chapter on switch inputs and logic gave an illustration of the
procedure.
2. n-key lockout on last. The last key released is recognized and all
others are locked out.
3. n-key rollover. All keys are recognized and placed in a first in-
first out (FIFO) memory until the computer can accept the data.
real estate and investment. Although the topic was introduced with
switches, more detail is investigated now.
;-------------------------------------------------
DEBOUNCE:
;-------------------------------------------------
;CHECK CHANGE BY xrl
mov B,A ;hold the input
xrl A,CharP ;exclusive or
jnz DEBN1 ;<>0, so a change
;KEEP DEBOUNCED
mov CharD,B ;0=no change, CharD
DEBN1: mov CharP,B ;not debounce
ret
Decipher _______________________
The row lines are connected through a pull-up to give a one from
the 5 volts. Columns are used to output a zero from the processor.
These are not connected to a pull-up.
After a zero is sent to a column, the row is read. If the row is one,
then a key is not pressed. If the row is zero, then a key has been
pushed.
Connections _____________________
for the latches. The remainder of the process remains the same,
regardless of the I/O connection.
For the particular process at hand, the row lines connect to a latch
that uses memory mapping. The technique has been discussed
extensively in other sections. Columns are connected to a separate
latch.
Memory mapped I/O shares space with the upper byte of memory
addressing. However, because of the connection configuration, there
is not a conflict. Address A15 selects the MMIO, so this line is not
connected to memory.
The read and write address can be the same, since the address is
ANDed with the read not or write not line from the processor. The
addresses are selected using the data pointer register (DPTR). DPTR
is a sixteen-bit location that is comprised of a high (DPH) and low
(DPL) register. The high is associated with port 2 while the low is
allocated to port 0.
;-----------------------------
KEYTEST:
;-----------------------------
; Output '0' to columns.
; Read rows, if any is '0', a key is pressed.
;COLUMN OUT
mov DPTR,#8001h ;keypad address
mov A,#0 ;key enable
movx @DPTR,A ;output columns
movx A,@DPTR ;read rows
;DECIPHER push
anl A,#0Fh ;mask hi nibble
cjne A,#0Fh,KEYT2 ;<>1, so key pushed
sjmp KEYTEST ;no key
16. Add row number to get assigned number for key pushed.
17. Continue loop for next column.
18. Check if number is in legitimate range.
19. Convert key number to ASCII value, via table lookup.
20. Set flag for key is held.
21. Return
initialize variables
loop entry
Read row
column value=col # * 4
last column?
yes
column number<0Fh?
CharK = None
convert key # to ASCII
Serial input
Set key held flag
return
210 Systems Design and the 8051 Durham
The Keys routine directs the traffic for determining the key that is
pressed. The first task is to check if any key is pressed. To do so,
read the row and debounce the value. Enter the routine with the
value in the accumulator. Perform an exclusive-or with the previous
value, CharP. Exit the task with the debounced value in CharD.
Then use the procedure in the flow chart to decode the row and
column value. The routine waits until a key is pushed before
returning.
Row lines are connected to a pull-up to give 5V. The routine outputs
a zero to the columns. Then read the rows to determine if any key is
'0'. If so, it is pressed.
A = KeyCol * 4
For example, the key associated with the number “8” is pushed.
This is in column 1, row 2. The deciphering will return a column
location of 4 plus a row location of 2 for a key location of 6. The 6
is the offset pointer into a table location that will return andASCII 8.
;#################################################
;CONSTANTS
;-------------------------------------------------
None equ 0FFh ;blank key
AdKey equ 8001h ;mmio latch
;-------------------------------------------------
;DEFINED VARIABLES
;-------------------------------------------------
;KEYS
KeyCol equ 17h ;present column number
;*************************************************
; KEYPAD
;*************************************************
KEYS:
;-------------------------------------------------
; Keypad is used to decode a matrix set of keys.
; A 4X3 keypad can be used.
;
; Columns connect to a latch, in the upper bits
; Rows connect to a latch, in the low bits.
;
; Column latch bits |7|6|5|4|3|2|1|0|
; Key column |0|1|2|3|-|-|-|-|
;
212 Systems Design and the 8051 Durham
;COL 1
mov A,#10111111b ;Column 1
mov KeyCol,#4 ;column location
lcall KEYROWRD ;input row
cjne A,#0Fh, KEYP7 ;<> F, so pushed
;COL 2
mov A,#11011111b ;Column 2
mov KeyCol,#8 ;column location
lcall KEYROWRD ;input row
cjne A,#0Fh, KEYP7 ;<> F, so pushed
;COLUMN VALUE
KEYP7: add A,KeyCol ;A=KeyCol*4 + KeyRow
;TERMINATE
KEYP9: ret ;back to message
;-------------------------------------------------
KEYROWRD:
;-------------------------------------------------
; Output column, read row
; Determine row number
;INITIALIZE
clr C ;initialize test bit
mov B,#0 ;row number
;TERMINATE
KEYR9: ret ;back to message
;-------------------------------------------------
TabKey:
;-------------------------------------------------
; Three column keyboard
db ‘147*2580369#’
214 Systems Design and the 8051 Durham
D0
Row0
D1
Row1
D2
Row2
D3
Row3
Row
Latch
⇐⇑⇒
30
PROJECT 9 - KEYPAD
Thought
The key to success?
The Golden Rule
Preamble:
Plan:
Preparation:
Procedure:
Send a 4-bit output to the keyboard. Then read another 4-bits from
the keyboard to determine which key is pressed.
Presentation:
⇐⇑⇒
Most projects have been presented with an example code that had
additional items to be developed. In contrast, this section of code is
complete. It is necessary because of the involved process.
;-------------------------------------------------
;Program: MODkey.ASM
;Update: 26 July 2004
;Initial: 17 October 1991
;
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.DrMod.com
;Copyright (c)1991, 2004. All rights reserved
;
;Purpose:
; A set of routines are provided to perform the
; keypad input.
;
;Processor: 8031 family
;PROM: 8k (2000H) onboard
;Crystal: 11.059 MHz
;Baud: 9600
218 Systems Design and the 8051 Durham
;#################################################
;
; ASSIGNMENTS
;
;#################################################
;CONSTANTS
;-------------------------------------------------
;SYMBOLS
None equ 0FFH ;blank key
AdKey equ 8001h ;mmio latch
;-------------------------------------------------
;DEFINED VARIABLES
;-------------------------------------------------
;KEYS
KeyCol equ 17H ;present column number
KeyBit equ 16H ;byte moves a bit w/ column
KeyRow equ 15H ;row number pushed
KeyMul equ 14H ;multiple key count
CharK equ 13H ;key input character
CharD equ 12H ;debounced
;-------------------------------------------------
;BITS ASSIGNMENTS
;-------------------------------------------------
;AT RAM byte 20H
FgKeyH bit 00H ;flag key held down
;#################################################
;
; PROGRAM
;
Chapter 30 Project 9 - Keypad 219
;#################################################
org 00H
START: ljmp INITIAL
org 0033h
db 25, 1,'Marcus O. Durham, PhD, PE'
;-------------------------------------------------
org 0080H ;Addres past reserve
INITIAL:
;-------------------------------------------------
;INITIALIZE
mov SP,#5Fh ;start stack @ 5f+1
lcall UART ;config & start UART
;-------------------------------------------------
MAIN:
;-------------------------------------------------
; The procedures are to input a key, send it on
; serial, and do a line return.
;PROCESS
lcall KEYS ;check keys
mov A,CharK
lcall SEROUT ;A =message value
MAN9: ljmp MAIN ;Repeat
;*************************************************
; KEYPAD
;*************************************************
KEYS:
;-------------------------------------------------
; Keypad is used to decode a matrix set of keys.
;LAST KEY
mov A,CharK ;last key
cjne A,#None,KEYS9 ;<>none, have a key
sjmp KEYS ;=none, get a key
;TERMINATE
KEYS9: ret ;back to message
;-------------------------------------------------
KEYPAD:
;-------------------------------------------------
; KEYPAD is a routine to input buttons pressed on
; keyboard. A 4X4 keypad can be used.
;
; Columns connect to a latch, in the upper bits
; Rows connect to a latch, in the low bits.
;
; Column latch bits |7|6|5|4|3|2|1|0|
; Key column |0|1|2|3|-|-|-|-|
;
; Row latch bits |7|6|5|4|3|2|1|0|
; Key row |-|-|-|-|3|2|1|0|
;
; Row lines are connected to a pull-up to give 5V
; Output '0' to columns.
; Read rows, if any key is '0' it is pressed.
;
; A table is used to decode the value of
; each key to ASCII.
;
; If a key has not been selected, try for a
; serial input.
;INITIALIZE
KEYP3: jb FgKeyH,KEYP8 ;key held, exit
lcall KEYINIT ;initialize
;COLUMN VALUE
lcall KEYCOLQ ;query, KeyCol=col
add A,KeyRow ;A=KeyCol*4 + KeyRow
mov CharK,A ;upgrade the charac
;NEXT COLUMN
KEYP6: djnz KeyCol,KEYP4 ;remain col to write
;CONVERT TO ASCII
mov A,CharK ;lookup last value
mov DPTR,#TabKey ;start of table
movc A,@A+DPTR ;conversion
mov CharK,A ;save key
;NULL RESPONSE
KEYP8: mov CharK,#None ;nothing pushed
;TERMINATE
KEYP9: ret ;back to message
;-------------------------------------------------
KEYINIT:
;-------------------------------------------------
; Initialize is a routine to set variables.
; A 4X4 keypad can be used with a single byte.
;
; KeyCol present column number
; KeyMul multiple key count
; KeyRow row number pushed
; KeyBit byte moves a 0 bit for the column move
;TERMINATE
ret ;back home
;-------------------------------------------------
KEYALLRD:
;-------------------------------------------------
; Row Read is a routine that sends a 0 to columns
; It reads the row.
; For ALLRD, 0 is sent to all columns.
; For ROWRD, 0 is sent to each column
; successively
;
;SEND ALL 0
mov A,#00001111h ;all col=0
sjmp KEYROW1 ;COL OUT, ROW IN
;
;bit TO SEND
KEYROWRD: mov A,KeyBit ;0 bit is column
;TERMINATE
ret ;back to message
;-------------------------------------------------
KEYROWQ:
;-------------------------------------------------
; Row Calculate determines the row number that is
; pressed. RowNum = 0,1,2,3
;
; A counter is set if multiple rows are pushed.
;
; The routine can handle 4 rows.
; If fewer rows are used, simply change the jump
; to the corresponding number of rows.
; If a 1 row pad is used, sjmp to ROW1.
;INITIALIZE
clr C ;initialize test bit
;; sjmp KEYR3 ;pad has only 3 rows
;TERMINATE
KEYR9: ret ;back to message
;-------------------------------------------------
KEYCOLQ:
;-------------------------------------------------
; Column calculate determines the column that is
; pressed, KeyCol. Then it calculates the value
; for the key.
;
; Rows are numbered 0,1,2,3
; Columns are numbered 0,1,2,3
; Columns are valued 0,4,8,12.
; Columns value = column number * number of rows
; With four rows A = KeyCol * 4
;CALCULATE
mov A,KeyCol ;column w/ 0
dec A ;column # inc by 1
mov B,#4 ;qty of rows
mul AB ;A = column value
;TERMINATE
ret ;back to message
;+++++++++++++++++++++++++++++++++++++++++++++++++
;TABLE SETUP - KEYPAD CONVERSION
;-------------------------------------------------
; Tables are used to convert between formats.
; These include keypad & ASCII.
; The table pointer will show a decimal result
; that corresponds to a column/row location.
;-------------------------------------------------
TabKey:
Chapter 30 Project 9 - Keypad 225
;-------------------------------------------------
; Three column keyboard
db ‘147*2580369#’
;*************************************************
⇐⇑⇒
31
Thought
3C procedures:
Command, control, communications.
High end systems will use a cathode ray tube (CRT) for imaging.
The size makes them very useful for showing large amounts of data.
However, the size and power consumption is a serious drawback for
many projects.
Connections _____________________
The LCD has fourteen pins for connecting power, controls, and
data.
228 Systems Design and the 8051 Durham
Pin Function
1 Vss, ground
2 Vdd, 5 V
3 Vo, power for contrast
4 Reg. Select (RS) 0= instruction, 1= data
5 RW, 0= Write, 1= Read
6 Enable
7-14 DB0-DB7 data bits
Control ________________________
The liquid crystal display has three control lines- enable (pin 6),
read/write not (pin5), and register select (pin 7). It is wise to have
the enable line asserted low before the other control lines are
asserted. The register select and the read/write are activated by
software control. The commands are executed on the low to high
transition of the enable line. The high also allows data to be set-up.
Data is transferred with the enable line high.
D0-7
Port 0 Data
AD0-7
P1.0 4 RS
P1.1 5 RW
P1.2 6 En
microprocessor LCD
The enable line is first pulled low before the control lines are
asserted. Then the register select line is asserted high or low,
depending on the function for the LCD. Next the write line is pulled
230 Systems Design and the 8051 Durham
The controls are activated when the enable line transitions to high.
The data is transferred between the microprocessor and the LCD on
the high to low transition of the enable line.
The register has 8 lines that are configurable. The lines may be
shared with other output controls One arrangement that has been
used is illustrated. The upper four bits are for columns on a keypad.
The lower 3 bits are for the display select. Bit three is for RS485
select.
Other bits are on the latch (register) which will not be part of the
present operation. The value to the latch must be changed with
anl/orl or setb/clr to prevent these other bits from changing.
Chapter 31 Liquid Crystal Display 231
To ensure that other lines are not affected, the value placed on the
register can be maintained in temporary storage. However, since no
other output on the latch is processed while the LCD is being
driven, seldom is it necessary to hold the values. The exception
would be if other tasks were performed during the delays for the
LCD.
So look at a review of the process. The bits for the LCD control
lines are selected. The value may be saved in temporary storage.
The value is presented to the latch/register. The latch enable is made
active. The LCD then responds.
The next section illustrates the procedure that will be used for the
project implementation.
The LCD can be wired directly from a PLD a latch for the control
lines. The enable and register select lines are encoded in the PLD.
These are simply chosen based on a memory-mapped address.
D0-7
For most LCDs there must be a delay of at least 140 ns after the
controls are selected before the enable can be taken high. A RC
circuit is placed in the enable line to delay the response to the LCD
enable. Typical component values are 1 K Ohm and 200 pF.
232 Systems Design and the 8051 Durham
Command ______________________
The LCD has a number of commands and instruction codes that are
required for display. The LCD can receive instructions for set-up,
send status, receive display data, or send the data currently in the
display back to the microcontroller. Two address lines (XX) select
the function.
Code Function
01 clear and home
02 home
04 cursor increment w/ data display
06 cursor decrement w/ data display
0A cursor on, flash off
0B cursor on, flash on
10 move cursor left
14 move cursor right
38 function set -8bit, 2line, 5x7dot
8X cursor position= DDRAM address
81 1st line, 1=home
C1 2nd line home
A1 3rd line home
E1 4th line home
The next table has the codes for the status response from the LCD to
the microprocessor.
Code Function
8X busy flag, X=current address
0X clear, ready to accept data
The LCD busy flag (BF) is clear when the module is ready to accept
another instruction. However, the busy flag (BF) cannot be read
until the first 3 LCD initialization bytes have been processed by the
module. Thus BF cannot be tested in the initialization subroutine.
Initialization ____________________
First, after VCC is applied, allow 15ms for the module internal
initialization to be completed. The instruction mode is used for all
initializing. The instruction is sent, then there is a delay before the
next instruction.
The instruction codes contain items that are used for cursor
positioning. The first three bits of the message define the cursor line
that will be used. The remainder of the line contains the character
location on the line.
If using a 2 line display, send 80h to access the first space. Then
follow with the 16 or 20 characters for the length of the line. The
second line is accessed by sending 0C0h. Then the characters for the
length of the line.
⇐⇑⇒
32
Thought
Confidence is
the mental assurance
that something is true.
MOD
Preamble:
The data pin outs and the control pin outs are standard among most
manufacturers. Some have a different power pin arrangement. There
are also lines for controlling the contrast. However, these are often
fixed. The board has an automatic circuit for contrast control. No
software is required for the contrast control. If the automatic feature
is not desired, it may be bypassed by grounding the contrast control
pin.
Plan:
Preparation:
Connect the data lines through one latch. Connect the control lines
through another.
Procedure:
Next send data to the LCD. The information can come from the
keypad, serial line, or from internal tables.
238 Systems Design and the 8051 Durham
Presentation:
⇐⇑⇒
;-------------------------------------------------
;Program: BiosLcd.ASM
;Update: 27 July 2004
;Initial: 17 October 1991
;
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.ThewayCorp.com
;Copyright (c)1991-2004. All rights reserved
;
;Purpose:
; A set of routines are provided to initialize
; and operate a liquid crystal display.
;
;Processor: 8031 family
;PROM: 8k (2000H) onboard
;Crystal: 11.059 MHz
;Baud: 9600
;Handshake: not used at this speed
;Assembler: Intel ASM51
;
;#################################################
;
; ASSIGNMENTS
Chapter 32 Project 10 – Text Display 239
;
;#################################################
;CONSTANTS
;-------------------------------------------------
;
;CHARACTERS, HOLD, COUNT
CharL equ 0EH ;character to LCD & Serial
LoopC equ 07H ;loop counter
;#################################################
;
; PROGRAM
;
;#################################################
org 00H
START:
;-------------------------------------------------
ljmp INITIAL
;LCD INITIALIZE
lcall SCRINIT ;initialize screen
;-------------------------------------------------
MAIN:
;-------------------------------------------------
;
; The main procedure directs traffic.
; The main orchestrates execution of the
; subroutines.
240 Systems Design and the 8051 Durham
;PROCESS
mov DPTR,#SerGreet ;get address
lcall BIOSLCD ;message headr RS232
lcall BIOSLCD ;second line
;-------------------------------------------------
BIOSLCD:
;-------------------------------------------------
;
; Send LCD message
; The first byte is the # of characters to send.
;LCD data
lcall DLYMIC ;wait for next byte
lcall SCRDATA ;send out byte
inc DPTR
inc DPTR
ret
Chapter 32 Project 10 – Text Display 241
;*************************************************
;
; LCD SETUP
;
;*************************************************
;
; Because of the control sequence, the LCD
; appears somewhat tedious.
;
; There are three groups of routines.
; 1. LCD control lines
; 2. LCD initialize, instruction, data, & busy
; 3. Message to display info.
;
; The LCD has 14 pins.
; 1 = Vss, ground
; 2 = Vdd, 5 V
; 3 = Vo, power for liquid crystal drive
; 4 = RS, 0= instruction, 1= data Reg. Select
; 5 = RW, 0= Write, 1= Read
; 6 = Enable
; 7-14 = DB0-DB7 data bits
;
; The LCD control lines are programmed as bits
; LcdRS = bit
; LcdRW = bit
; LcdEn = bit
;
;-------------------------------------------------
;SCREEN INSTRUCTION CODES
;-------------------------------------------------
; The following codes are required by the LCD
; display. The LCD can receive instructions for
; set-up, send status, receive display data, or
; send the data currently in the display back to
; the microcontroller.
; Two address lines (XX)select the function.
;
; Instruction Codes
; 01 ;clear and home
; 02 ;home
; 04 ;cursor increment w/ data display
242 Systems Design and the 8051 Durham
;-------------------------------------------------
SCRINIT:
;-------------------------------------------------
;--SUBS CALL -
; The routine initializes the Liquid Crystal
; Display. The busy flag stays busy until
; initialization is complete. The time is 15ms.
; Therefore delays must be built into the init
; routine before Busy can be used.
;
; Allow 15ms for Hitachi 44780 internal initial
; to complete after Vcc is applied.
; (Re: Standish document A93531B p. 2 &
; Hitachi document CD-E613P 0591 p. 90).
;
; The series of instructions are as required by
; Philips mfg data sheet.
;
; Instruction mode is used for all initializing.
;
; 232 must be on for LCD contrast control
; to get 10 volts.
;
; Delay is used rather than test for Busy line.
; If LCD is not plugged-in, then there is only
; a small delay. If Busy were checked, the
; process would hang.
;POWER ON RESET
mov LoopC,#20 ;20ms delay
SCRNI1: lcall DLYMIL ;1 ms routine
djnz LoopC,SCRNI1 ;loop
;CLEAR REGISTERS
mov CharL,#30H ;#1function set=8bit
lcall SCRINST ;send command
;SET CURSOR
mov CharL,#38H ;#4funct set=8bit,2l
lcall SCRINST ;send command
lcall DLYMIC ;>100 microsec
;CHANGE MODE
mov CharL,#06H ;entry mode set
lcall SCRINST ;send command
ret
;-------------------------------------------------
DLYMIL:
;-------------------------------------------------
; Delays shorter than the interrupt cycle are
; required. Since this is outside the normal
; program polling, hard calculated delays are
; used.
;
; The delay is based on clock cycles.
; mov=1, nop=1, djnz=2.
;
; The cycles in the loop are calculated.
; (1) for mov
; (2* count ) for both nop's
; (2* count-1) for djnz
; (2) for last jump
Chapter 32 Project 10 – Text Display 245
; = Total cycles
;
; Old crystal frequency was 7.3728Mhz
;
; Time = #states(12) * Total cycles/crys freq
; 11.059 MHz = 1.085 microsecond
;
; The inside loop has 925 cycles.
; At 11.059MHz this represents 1.003 ms
;-------------------------------------------------
DLYMIC:
;-------------------------------------------------
; Delay = 50 microsecond
;
; Delays shorter than the interrupt cycle are
; required. Since this is outside the normal
; program polling, hard calculated delays are
; used.
;
; The inside loop has 49 cycles.
; At 11.059Mhz,
; 1.085 microsec * this represents 53 microsec
;-------------------------------------------------
SCRINST:
;-------------------------------------------------
; The routine writes instructions to LCD.
; Write an instruction to the LCD requires
; control line RS= 0
; control line RW= 0
; Enable must be low before change R/W' or RS.
246 Systems Design and the 8051 Durham
;
; CAUTION: A delay after data, before deselect
; can be interrupted and cause erratic data.
; disable interrupts until complete.
;CONTRL INSTRUCTION
clr LcdEn ;clr enable lo
clr LcdRW ;instruction& write
clr LcdRS
setb LcdEn ;set enable
;DISABLE INTERRUPTS
; anl IE,#7Fh ;disable main inter
;SEND INSTRUCTION
mov A,CharL ;select LCD data
mov DPTR,#8002h ;display latch
mov @DPTR,A ;send out
;CONTROL INSTRUCTION
clr LcdEn ;clr enable lo
;ENABLE INTERRUPTS
; orl IE,#80h ;enable all
ret
;-------------------------------------------------
SCRDATA:
;-------------------------------------------------
; The routine writes output data to LCD.
;
; Write data to the LCD requires
; control line RS= 1, data display on HD44780
; control line RW= 0, to write
; Enable must be low before change R/W' or RS.
;
; CAUTION: A delay after data, before deselect
; can be interrupted and cause erratic data.
;CONTRL INSTRUCTION
clr LcdEn ;clr enable lo
Chapter 32 Project 10 – Text Display 247
;DISABLE INTERRUPTS
; anl IE,#7Fh ;disable main inter
;SEND INSTRUCTION
mov A,CharL ;select LCD data
mov DPTR,#8002h ;display latch
mov @DPTR,A ;send out
;CONTROL INSTRUCTION
clr LcdEn ;clr enable lo
;ENABLE INTERRUPTS
; orl IE,#80h ;enable all
ret
;#################################################
;
; TABLES
;
;#################################################
;
; Tables are used to convert between formats.
; These include kepad & ASCII.
;
; Tables are also used to carry display messages.
;
;
;+++++++++++++++++++++++++++++++++++++++++++++++++
;TABLE SETUP - MESSAGES
;-------------------------------------------------
; Predefined messages are in code memory.
; These are used in BIOSSER.
; Place at end of program code or org out of way
;
; The first byte is the number of characters.
; The second byte is the cursor location for LCD.
248 Systems Design and the 8051 Durham
;-------------------------------------------------
TABMESSG:
;-------------------------------------------------
;*************************************************
end
⇐⇑⇒
SECTION III - APPLICATIONS
⇐⇑⇒
33
INFRARED COMMUNICATIONS
Thought
Think excellent, do right,
obtain peace.
MOD
There are four basic technologies that are used. Sony uses a bit
width technology. The four - NEC, Apex, Hitachi, and Pioneer - all
use the same technology, which is another version of bit width. JVC
uses a complementary system which is a space width technology.
The major departure is the European model by Philips. It has a fixed
bit width and a fixed quantity of bits.
A data bit is both positive and negative. The first half cycle is setup,
then the second half is the state. On is 0 in the second half, while off
is 1 in the second half.
1 bit
RX data
0 bit
When the first falling edge is detected, this is used as the timer
frame. Wait 3/ 4 bit time to sync in the middle of the next bit.
This program has a wait cycle at the start. It is looking for the first
transition in the bit stream. A better approach would be to activate
the interrupt on INT1.
The first or start bit is always on (0). The second is also on (0).
These are the automatic gate control (AGC).
The third bit is a check (CHK). It toggles each time a new key is
pushed.
Chapter 33 Infrared Communications 253
Check the first two bits for on. If not, wait more than 15 bit times to
begin a new sample.
Address Equipment
0 Television
2 Tele text
5 Video recorder
7 Experimental
16 Preamplifier
17 Receiver / tuner
18 Tape / cassette recorder
19 experimental
;-------------------------------------------------
IRRC5TAB:
254 Systems Design and the 8051 Durham
;-------------------------------------------------
; The command code determines the function.
;
; VALUE TO P1 REMOTE KEY COMMAND
; ----------- ---------- -------
db 01111111b ; 0 ; 0
db 01111110b ; 1 ; 1
db 01111101b ; 2 ; 2
db 01111100b ; 3 ; 3
db 01111011b ; 4 ; 4
db 01111010b ; 5 ; 5
db 01111001b ; 6 ; 6
db 01111000b ; 7 ; 7
db 01110111b ; 8 ; 8
db 01110110b ; 9 ; 9
db 11111111b ; ; A
db 11111111b ; ; B
db 01110011b ; ON/OFF ; C
db 01110010b ; MUTE ; D
db 01110001b ; PP ; E
db 01110000b ; OSD ; F
db 01101111b ; Volume+ ; 10
db 01101110b ; Volume- ; 11
db 01101101b ; Bright+ ; 12
db 01101100b ; Bright- ; 13
db 01101011b ; Color+ ; 14
db 01111010b ; Color- ; 15
db 11111111b ; ; 16
db 11111111b ; ; 17
db 11111111b ; ; 18
db 11111111b ; ; 19
db 11111111b ; ; 1A
db 11111111b ; ; 1B
db 01100011b ; Contrast+ ; 1C
db 01100010b ; Contrast- ; 1D
db 11111111b ; ; 1E
db 11111111b ; ; 1F
db 01011111b ; Program+ ; 20
db 01011110b ; Program- ; 21
db 11111111b ; ; 22
db 11111111b ; ; 23
db 01011011b ; Timer ; 24
db 01010111b ; Special 1 ; 25
db 01000001b ; Special 2 ; 26
Chapter 33 Infrared Communications 255
db 01000111b ; Special 3 ; 27
db 01001110b ; Special 4 ; 28
db 01000101b ; Special 5 ; 29
db 01010010b ; Special 6 ; 2A
Connections _____________________
Only three pins are required by the software. The data is input on
one pin.
The third pin shows a pulse generated by the software. This triggers
with each new bit. Therefore, a scope can look at the incoming
timing. This will ensure the code is sensing at mid bit.
---___---___------______---___---___--- IrInput
_|_____|_____|_____|_____|_____|_____|_ IrScope
Port3.3 13 1 IR
P3.4 14 2 Gnd
P3.5 15 3 Vcc
⇐⇑⇒
34
PROJECT 11 - WIRELESS
Thought
Peripheral vision or tunnel vision,
its your choice.
MOD
Preamble:
Plan:
Preparation:
Procedure:
If the data is valid, decode the pulses according to a table. Use the
results to initiate a control action. As a minimum, turn an LED on
and off, based on the infrared remote signal.
Presentation:
⇐⇑⇒
258 Systems Design and the 8051 Durham
;-------------------------------------------------
;Program: MODInfra.ASM
;Update: 16 February 2003
;Date: 17 August 2002
;
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.ThewayCorp.com
;Copyright (c)2002, 2003. All rights reserved
;
;Purpose:
; A set of routines are provided to perform
; infrared receive functions. The code can be
; easily modified.
;
; This code has timing based on 11.059 MHz
; crystal. If another crystal is used, the delay
; routines must be modified.
;#################################################
; PROGRAM
;#################################################
org 00H
START: ljmp INITIAL
;*************************************************
; INITIAL & MAIN
;*************************************************
org 0080H ;Addres past reserve
INITIAL:
;-------------------------------------------------
Chapter 34 Project 11 - Wireless 259
;INITIALIZE
mov SP,#5Fh ;start stack @ 5f+1
;-------------------------------------------------
MAIN:
;-------------------------------------------------
;PROCESS
lcall IRRECV ;infrared:A=IrComd
lcall SEROUT ;display IrComd
MAN9: ljmp MAIN ;Repeat
;*************************************************
; INFRARED REMOTE
;*************************************************
; PHILIPS RC5 remote receiver.
; Adopted from code by Wagner Lipnharski 11/99
;-------------------------------------------------
;Ir Receiver Assignments
;-------------------------------------------------
IrOut equ 0B5h ;LED out
IrInp bit 0B3h ;IR serial input stream
IrScope bit 0B4h ;soft generate pulse for each bit
IrComd data 41h ;IR code received
;-------------------------------------------------
IRRECV:
;-------------------------------------------------
; Receive IR string of 14 bits.
;INITIAL
IRRE0: setb IrOut ;Turnoff IR Indicate
setb IrInp ;Input bit
;-------------------------------------------------
; Interrupt entry on first falling edge.
; The code must be activated and the processor
; set up to jump to here.
; anl IE,#11111011b ;turn off ExtInt1
;-------------------------------------------------
260 Systems Design and the 8051 Durham
;ADDRESS STREAM
IRRE31: lcall DLYPHI ;1 bit time delay
clr A ;IR Rx first low lev
mov B,#6 ;6 more bits
;DECODE ADDRESS
anl A,#00011111b ;mask CHK (flip) bit
cjne A,#0h,IRRE8 ;<> Address 00
;COMMAND STREAM
mov B,#6 ;6bit command stream
IRRE5: setb IrScope ;*scope pulse
mov C,IrInp ;IR state to Carry
clr IrScope ;*scope pulse
rlc A ;Insert IR into A
;SAVE COMMAND
mov IrComd,A ;Save Command
sjmp IRRE9 ;good stuff
;*************************************************
; DELAY
;*************************************************
; Delay routine using NOPS and a nested loop.
; Registers R2 & R3 are used for counting loops.
; Count the machine cycles for each instruction.
;
; This code has timing based on 11.059 MHz
; crystal. If another crystal is used, the delay
; routines must be modified.
;-------------------------------------------------
DLYPHI:
;-------------------------------------------------
; For time interval at 1 bit cycle, need
; time interval of 1.728 ms, so need
; .001728 * 11059000/12 = 1592.5 machine cycles
; Use 1.72, need 1585 machine cycles.
;-------------------------------------------------
DLYPHI34:
;-------------------------------------------------
; For interval at 3/ 4 of a bit cycle, need
; time interval of 1.728 * .75= 1.296 ms, so need
; .001296 * 11059000/12 = 1194.3 machine cycles
; Use .75 * 1.72 gives 1188 machine cycles.
;-------------------------------------------------
262 Systems Design and the 8051 Durham
DLYPHI15:
;-------------------------------------------------
; For time interval at 15 bit cycle, need
; time interval of 1.728 * 15= 25.92 ms, so need
; .02592 * 11059000/12= 23,887.44 machine cycle
;
;-------------------------------------------------
end ;Program end
⇐⇑⇒
35
Thought
You can not serve two masters.
Jesus of Nazareth, ~AD 30
The major differences are in the connections. SPI has a common bus
of three wires, but it requires a separate select line for each device.
264 Systems Design and the 8051 Durham
IIC has only two wires for all communications. Although the wiring
is simpler for the IIC, the software is considerably more complex
than that for the SPI.
There are several other protocols that are very powerful and will be
mentioned only briefly. Since they are not used for on-board
connections, they will not be addressed in detail.
The IIC is a multiple master bus. More than one integrated circuit
can initiate data transfer. The chip initiating the transfer is the bus
master, during which the others are bus slaves. A microprocessor is
typically the master.
2. Then the master sends the Address of the slave along with a
read or write flag.
3. All slaves compare the address with their address. If the address
does not match, the slave waits for the Stop message.
4. If there is a match, the slave sends an Acknowledge.
5. When the master detects the acknowledge, it will write or read
the Data.
6. After completion, the master will send a Stop. This is a signal
the bus is released and a different transmission can take place.
P1.7 P1.6
SDA SCL
Notice that these occupy the same space as the SPI protocol.
Therefore, both will not exist on the same chip. If both are required,
it is relatively easy to select another pin location for either protocol.
Then bit bang the pins for data transfer. Several bit bang examples
are provided in this and the next chapter.
The device addresses are listed. Since the microprocessor does not
have the capability for IIC internally, the data must be bit-banged.
Data is sent MSB first. Any number of bits can be sent. The slave
address is a unique seven-bit number. This is followed by a
direction bit. Acknowledge (Ack) is sent by the receiver after each
byte.
The slave address has a device number as the four most significant
bits. Then three bits allow the address to select a particular device.
The final bit is 0 for write and 1 for read.
Since all devices share a common line, one method of assuring the
bus is not busy is to check the clock. The problem is this causes a
hang-up until the lines are clear.
A good practice is to leave the start and data transfer routines with
the clock low so the next transfer is ready.
The sequence of subroutines has two layers of calls. The calls are
read, write, and acknowledge. Then these call other routines.
IICREAD:
lcall IICSTART ;start
lcall IICMSBOT ;MSB out
lcall IICMSBIN ;MSB in
lcall IICACK ;acknowledge
lcall IICNACK ;not acknowledge
lcall IICSTOP ;stop
IICWRITE:
lcall IICSTART ;start
lcall IICMSBOT ;MSB out
lcall IICSTOP ;stop
IICDACK:
lcall IICSTART ;start
lcall IICMSBOT ;MSB out
lcall IICSTOP ;stop
A short time delay is required for the IIC bus setup time. Four NOPs
are all that is required with 7 MHz crystal. Five are adequate with
the 11 MHz crystal.
268 Systems Design and the 8051 Durham
The bit-banging routines are shown below. These include start, stop,
acknowledge, and not-acknowledge. These routines can be used
with any two bits on the processor, since they do not rely on the IIC
registers of special processors.
;-------------------------------------------------
IICSTART:
; Send IIC start sequence.
; Start M/M Hold-Scl=1 Change-Sda=1 to 0
;
; ;START SEQUENCE
setb IicSda ;Sda=1
setb IicScl ;Scl=1
%iicdly ;mac setup time wait
clr IicSda ;transition 1 to 0
%iicdly ;mac setup time wait
clr IicScl ;end clock pulse
ret
;
;-------------------------------------------------
IICSTOP:
; Send IIC stop sequence.
; Stop M/M Hold-Scl=1 Change-Sda=0 to 1
; Leave with clock HI so the line is released.
;
; ;STOP SEQUENCE
clr IicSda ;Sda=0
setb IicScl ;Scl=1
%iicdly ;mac setup time wait
setb IicSda ;transition 0 to 1
ret
;
;-------------------------------------------------
IICACK:
; Send IIC Acknowledge sequence.
; Acknow R/M Hold-Sda=0 Change-Scl=0 to 1
; Scl=0
; This is to follow each byte received.
;
; ;ACK SEQUENCE
Chapter 35 Serial Chips - IIC 269
⇐⇑⇒
36
Thought
Don’t walk around with a chip
on your shoulder.
Grandpa
The master creates the clock by asserting the strobe pin low and
high. The SPI standard allows either positive or negative clock
polarity. Two different protocols can be used for clocking 8-bit data.
272 Systems Design and the 8051 Durham
The MOSI pin is the data output from the master, so it is the input to
all the slaves. Conversely, the MISO pin is the data input to the
master, so it is the data output from one of the slaves.
The slave select is a chip select for each slave. Therefore, several
lines are required for multiple slave integrated circuits. The slave
selected is the only one that responds to activity on the bus. The
others are high impedance, so they do not interfere.
analog data, holds the value, and converts it to a digital signal. The
number of bits used for the conversion determines the sensitivity.
Sensitivity is voltage range divided by digital range. An eight-bit
converter has a range of 0 to 255. Therefore, each bit has a
sensitivity of 5/256 = 0.0195 volts per bit.
Even with good design, often the low order bits of the conversion
results are noisy and unstable. On an eight bit converter, this may be
one or two bits. On twenty-four bit converters, it may be 4 bits.
These bits represent the noise threshold. Several techniques are used
to manage the unstable variations.
The simplest is to truncate the noise bits. Rotate the value right, then
left with zero fill for the number of unstable bits. The disadvantage
is this effectively reduces the sensitivity by a power of two.
The master triggers the clock bit. Data comes into a device on rising
edge and out from the device on a falling edge.
The sequence for reading the ADC is very dependent on the clock.
1. Start: Assert SCK high.
2. Select: Chip select high, chip select low.
3. Command: SCK low, assert data bit, wait, SCK high, wait,
repeat the cycle for each bit.
4. Ready: SCK low
5. Input: SCK high, SCK low, read data bit, repeat the cycle for
each bit.
6. Stop: SCK high
7. Deselect: Chip select high
After the four bits are output on the serial peripheral interface, the
master is configured to read twelve bits of data. If the system is
using a 10-bit or 8-bit device, the extra bits read will return a 0.
Data is written to the chip on a rising clock edge. Set the data on
the pin, then pulse the clock high followed by a low to complete the
cycle.
Read data from a chip on a trailing edge. Pulse the clock high
followed by a low, then read the data.
The LTC 1098 needs at least 10us after enabling, before the first
data bit is output. This is a relatively slow device for use as a
physical sensor. It has a 40Hz serial clock limit.
The twelve bits of data are read MSB first. When this is placed
directly in a register, it appears as sixteen bits with zero fill. This
appears to be a multiply by 24 or sixteen. Therefore, it is necessary
to shift the data to get the desired precision. This is a bit bang
procedure that can be used with any version of the processor.
;#################################################
; ASSIGNMENTS
;#################################################
;CONSTANTS
;-------------------------------------------------
;LATCH & SPI
Mosi equ 95h ;SPI Mosi from uC to slave
Miso equ 96h ;SPI Miso from slave to uC
Sck equ 97h ;SPI Clk
;-------------------------------------------------
;DEFINED VARIABLES
;-------------------------------------------------
QikB equ 19H ;Interrupt HEX value, msb
QikA equ 18H ;Interrupt HEX value, lsb
;#################################################
; PROGRAM
;#################################################
org 00h
START: ljmp INITIAL
;-------------------------------------------------
org 0080h ;Address past reserve
INITIAL:
MAIN:
;-------------------------------------------------
;PROCESS
lcall ADCIN ;read adc on spi
mov A,QikB ;MSB, channel 1
lcall SEROUT ;send to serial
mov A,QikA ;LSB, channel 1
lcall SEROUT ;send to serial
------------------------------------------------
Chapter 36 Serial Chips - SPI 277
ADCIN:
;-------------------------------------------------
; LTC1098, 2channel, 12-bit analog-digital convt
; Write 4 bit control message. Then do input.
;
; Write data to chip on rising edge:
; Set data, pulse hi, pulse low.
; Read data from chip on trailing edge:
; Pulse hi, pulse lo, read data.
;
; The LTC needs at least 10us after enable
; before first data bit is output.
; There is a 40Hz serial clock limit.
;STOP CLOCK
setb SpiClk ;clock low for null
;DESELECT
setb SpiClk ;hi before deselect
; lcall ADCDES ;disable & shutdown
278 Systems Design and the 8051 Durham
;NEXT CHANNEL
; lcall ADCSEL ;enabl falling edge
ADCI9: ret
;-------------------------------------------------
SPIMSBIN:
;-------------------------------------------------
; Read serially from the SPI starting
; with the most significant bit (MSB). Data is
; clocked from the device on falling clock edge.
;-------------------------------------------------
SPIMSBOT:
;-------------------------------------------------
; Send B-bits. Most significant bit(MSB) first
; Data is clocked in device on rising clock edge.
;-------------------------------------------------
end
This turns off interrupts (SPIE) and enables the SPI channel (SPE).
The order of bits is MSB first (DORD). The processor is the master
(MSTR). The serial clock polarity is low when idle (CPOL). The
slave may remain selected between samples (CPHA). The
microprocessor frequency is divide by 16 to provide a clock
frequency of less than 1 MHz.
;-------------------------------------------------
;Program: MODonspi.ASM
;Initial: July 28, 2003
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.ThewayCorp.com
;Copyright (c) 2003. All rights reserved
; Original adapted from Atmel.
;
;Purpose:
; A set of routines are provided to write and
; read from a serial peripheral interface.
; The device is an eeprom.
;
;Processor: 8031 family
;PROM: 8k (2000H) onboard
;Crystal: 11.059 MHz
;Assembler: Intel ASM51
;#################################################
; ASSIGNMENTS
;#################################################
;CONSTANTS
;-------------------------------------------------
;SPI REGISTERS
Spcr data 0d5h ;SPI control register
Spsr data 0aah ;SPI status register
Spdr data 86h ;SPI data register
Spif equ 10000000b ;interrupt flag
;SPI ASSIGNMENTS
Mosi bit 95h ;SPI Mosi from uC to slave
Miso bit 96h ;SPI Miso from slave to uC
Sck bit 97h ;SPI Clk
CSn bit 94h ;device slave select
Chapter 36 Serial Chips - SPI 281
;DEVICE COMMANDS
Rdsr equ 05h ;Read Status Register
Wrsr equ 01h ;Write Status Register
Read equ 03h ;Read Data from Memory
Write equ 02h ;Write Data to Memory
Wren equ 06h ;Write Enable
Wrdi equ 04h ;Write Disable
;bit DEFINITION
A8 bit acc.3 ;MSB of address
NRDY bit acc.0 ;hi= write cycle in progress
;#################################################
; PROGRAM
;#################################################
org 00h
START: ljmp INITIAL
;-------------------------------------------------
org 0080h ;Address past reserve
INITIAL:
;-------------------------------------------------
; SPI master mode initialization code.
; SPCR is setup as interrupt disable,
; pin enable, MSB first, polarity 0, phase 1
; clock rate /16
;-------------------------------------------------
MAIN:
;-------------------------------------------------
lcall SPIEEROM ;write/read eeprom
;-------------------------------------------------
SPIEEROM:
;-------------------------------------------------
; Write/Read AT25C040 EEPROM via the Serial
; Peripheral Interface (SPI).
; Completion of programming is checked by polling
; SPI interrupt is not used.
; Works w/ microcontroller clk of 24 MHz or less.
;
; Write one byte to AT25040 and verify
; (read and compare).
; Code to handle verification failure not shown.
; Needs timeout to prevent write error from
; causing an infinite loop.
;
; Information to write has value of Data.
; Address to write has 16-bit value of Address.
; if not valid write & read go to
;-------------------------------------------------
SRDSTAT:
;-------------------------------------------------
; Read device status. Returns status byte in A.
ret
;-------------------------------------------------
SWRENAB:
;-------------------------------------------------
; Enable write.
; Does not check for device ready before sending
; command. Returns nothing. Destroys A.
ret
;-------------------------------------------------
SRDBYTE:
;-------------------------------------------------
; Read one byte of data from specified address.
; Does not check for device ready before sending
; command. Called with address in DPTR.
; Returns data in A.
ret
;-------------------------------------------------
SWRBYTE:
;-------------------------------------------------
; Write one byte of data to specified address.
; Does not check for device ready or write enable
; before sending command. Does not wait for write
; cycle to complete before returning.
; Called with address in DPTR, data in A.
; Returns nothing.
ret
;-------------------------------------------------
SPIIO:
;-------------------------------------------------
; Send/receive data through the SPI port.
; A byte is shifted in as a byte is shifted out,
; receiving and sending simultaneously.
; Waits for shift out/in complete before return.
Chapter 36 Serial Chips - SPI 285
When the chip select line is asserted low, the most significant bit
(MSB) is placed on the data line. The next bits (A6-A0) are placed
on the data line with the falling edge of the clock line.
The hold function begins with the eighth clock cycle. After the eight
clock cycle, chip select must go high, or the clock line must remain
low for at least 36 internal system clock cycles to allow completion
of the conversion.
If the chip select is kept low for multiple conversion, the clock line
(SCK) must remain glitch free or the microprocessor and the device
will lose synchronization.
The clock line must maintain each state for more than 404 ns. The
conversion time takes a maximum of 17 microseconds. The
maximum clock frequency is 1.1 MHz.
Circuit: SPI_____________________
Port1 1 Ref+ 8
SCK 8 3 Ref- 6
/SS 5 4 CS 5
microprocessor ADC
⇐⇑⇒
37
PROJECT 12 - A TO D CONVERTER
Thought
The whole world is an analog stage,
digital only plays bit parts.
Preamble:
Several protocols are used for serial interfacing. One of the simplest
to implement is the serial peripheral interface (SPI). It requires four
lines – a data out line, a data in line, a clock line, and a select line.
288 Systems Design and the 8051 Durham
The data and clock lines can be common with other SPI devices.
However, each requires its own select.
Plan:
Preparation:
Use the power supply as the reference voltage. Connect the three
control lines to a port or memory addressed latch on the processor.
Connect a variable voltage source for the input signal.
Procedure:
Next, write a routine to select the ADC chip and the appropriate
channel. Call the SPI routine to perform the transfer.
Presentation:
⇐⇑⇒
;-------------------------------------------------
;Program: MODadc.ASM
;Initial: 13 November 2003
;By: Dr. Marcus O. Durham, PhD, PE
290 Systems Design and the 8051 Durham
;Purpose:
; A set of routines are provided to read from
; a serial peripheral interface. The device is
; an 8-bit analog to digital converter. This uses
; the SPI registers
;
;Processor: 8031 family
;PROM: 8k (2000H) onboard
;Crystal: 11.059 MHz
;Assembler: Intel ASM51
;#################################################
; ASSIGNMENTS
;#################################################
;CONSTANTS
;-------------------------------------------------
;SPI
SpCr equ 0D5h ;SPI control register
SpDr equ 86h ;SPI data register
SpSr equ 0AAh ;SPI status register
AdCs equ 94h ;adc chip select
;#################################################
; PROGRAM
;#################################################
org 00h
START: ljmp INITIAL
;-------------------------------------------------
MAIN:
Chapter 37 Project 12 – A to D Converter 291
;-------------------------------------------------
;PROCESS
;-------------------------------------------------
SPIINIT:
;-------------------------------------------------
; Setup SPI:
; Disable interrupts; enable spi; msb first;
; master; clk low when idle; cpha=1; f=osc/64
mov SPCR,#01010110B
ret
;-------------------------------------------------
SPIREAD:
;-------------------------------------------------
; Read byte from ADC.
;
;CHIP SELECT LOW
clr AdCs ;enable chip select
;CHECK STAUS
SPR1: mov A,Spsr ;read status reg
rlc A ;move spif to carry
jnc SPR1 ;<>1, so no data
;------------------------------------------------
end ;Program end
⇐⇑⇒
38
WAVEFORM SYNTHESIS
Thought
Quality = excellence.
Professor Durham
The magnitudes can be held constant and the time interval between
outputs can be adjusted to vary the frequency. Alternately, the time
interval can be held constant and the table value multiplied by a gain
or scaling value to provide varying magnitude for the signal.
Sensitivity ______________________
Software ________________________
The table that is created contains the wave value. Take the
waveform and divide into as many entries as necessary to
adequately describe the wave. Calculate the value at precise
intervals, then place these entries in the table.
A sawtooth wave can be defined with just two points. Other wave
forms are similarly calculated.
⇐⇑⇒
39
PROJECT 13 – D TO A CONVERTER
Thought
Aphorism:
A concise formulation of a
principle, truth, or sentiment.
Definition
Preamble:
The D/A converter allows the output of a precise voltage level from
a digital signal. Coupling with a microprocessor allows the output of
this voltage to appear at a precise time. Thus the system allows the
output of voltage as a function of time.
Use an op-amp on the output. Set the range of the op-amp to yield 0
volts when a digital 00 is applied. Adjust the output to +5 volts
when 255 is sent to the DAC. The +5 level can be adjusted by a
potentiometer. Use an oscilloscope to make voltage measurements.
298 Systems Design and the 8051 Durham
Plan:
Procedure:
Notice that the values of the sine need only be known for one
quadrant of the waveform. The other segments may be formed
based on these values.
Presentation:
The routine should be such that it can be easily modified to vary the
frequency. Vary the frequency by changing the delay time between
successive outputs to the D/A converter.
⇐⇑⇒
Chapter 39 Project 13 – D to A Converter 299
;-------------------------------------------------
;Program: MODDac.ASM
;Update: 28 February 2003
;Initial: 17 October 1988
;
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.ThewayCorp.com
;Copyright (c)1988, 2003. All rights reserved
;
;Purpose:
; Use digital to analog converter for waveform
; synthesis.
;
;Processor: 8031 family
;PROM: 8k (2000H) onboard
;Crystal: 11.059 MHz
;Assembler: Intel ASM51
;#################################################
;CONSTANTS
;#################################################
;OUTPUT
Pio equ 90h ;port for i/o
;#################################################
; PROGRAM
;#################################################
org 00H
START: ljmp INITIAL
org 0033h
db 'Marcus O. Durham, PhD, PE'
300 Systems Design and the 8051 Durham
;-------------------------------------------------
org 0080H ;Addres past reserve
INITIAL:
;-------------------------------------------------
;INITIALIZE
lcall DACINIT ;initialize counters
;-------------------------------------------------
MAIN:
;-------------------------------------------------
; Display a wave form.
;PROCESS
lcall DACWAVE ;display a wave
MAN9: ljmp MAIN ;Repeat
;*************************************************
; DIGITAL ANALOG CONVERTER
;*************************************************
DACINIT:
;-------------------------------------------------
; Initialize waveform pointers.
;INIT
mov R2,#0 ;table entries pntr
mov R3,#0 ;+half wave=0,neg=1
ret
;-------------------------------------------------
DACWAVE:
;-------------------------------------------------
; Produce a wave.
;PROCESS
mov DPTR,#TabWave1;table with wave
DACW1: mov A,R2 ;table pointer
movc A,A+DPTR ;get wave value
DACW9: ret
;-------------------------------------------------
TabWave1:
;-------------------------------------------------
; Make entries for half cycle.
db 01h ;first entry
;-------------------------------------------------
end
⇐⇑⇒
40
PROJECT 14 - PHOTOSENSOR
Thought
Principle 1:
Never criticize, ever.
Dale Carnegie
Preamble:
Sensors are the most important part of data acquisition systems used
in real-time computing. The photosensor is a widely used detector.
Interfacing a sensor system to the uC depends on the application. As
with any engineering problem, each method has its advantages.
Plan:
Write a program that will utilize a software design for the reader.
The sensor uses a simple photo-detector device.
Chapter 40 Photosensor 303
Preparation:
Procedure:
The sensor input is a bit from the port of your choice. The software
will count the width of dark and bright bars in the bar codes. The
width is determined by counting the number of samples while the
input bit is at a one-state. The program must calibrate the width of
the entire bar code. Next, group the number of dark & bright bars
into wide & narrow categories. There will be four groups. These are
dark wide, dark narrow, bright wide, and bright narrow. Use this
data with an encryption algorithm.
Presentation:
⇐⇑⇒
41
Thought
Principle 2:
Give positive affirmation.
Dale Carnegie
Preamble:
There are many analog devices that are controlled by a digital based
system. Variable speed motor control is one popular example. The
digital control of a physical variable such as speed can be
implemented in several ways.
In one approach, the digital signal is used with a D/A converter. The
converter is followed by a linear power amplifier to produce voltage
with a variable amplitude. The voltage is applied to the motor. The
cost of the D/A converter and linear amplifier are significant
disadvantages of this scheme.
amplitude voltage to the motor. The modulation can take two forms:
(1) on-off pulses of constant duration but with a variable number of
pulses per second, and (2) on-off pulses at a constant repetition rate
but with a variable width for each pulses.
In order to time the trigger pulse, the beginning of the cycle must be
known. An additional circuit called a zero crossing detector (ZCD)
takes care of this task. The ZCD output is a TTL level square wave
whose transitions indicate a zero crossing of the AC line. Note that
306 Systems Design and the 8051 Durham
the trigger pulse to the SCR must be turned-off before the next cycle
begins or the SCR will turn-on again at the beginning of the cycle.
Plan:
This project uses both types of modulation for the control of light
intensity to 6 V DC and 120 V AC lamps.
Preparation:
8 full on
7
6 .
. .
. .
. .
1 .
0 off
Procedure:
Presentation:
Change the intensity of the light when a keypad key is selected for
each procedure.
⇐⇑⇒
42
Thought
Principle 3:
Find out what the other person wants
and help them get it.
Then you will get what you want.
Dale Carnegie
Preamble:
A simple driver for the motor can establish the total current applied
in a certain period of time. This driver is easily turned on and off. A
driver that can be interfaced to a digital system will be able to detect
digital signals (hi-lo or on-off).
Plan:
Preparation:
Procedure:
Presentation:
⇐⇑⇒
43
MATH FUNCTIONS
Thought
1+1 = 10
Binary thinking
Arithmetic ______________________
All the operations are structured for eight bits. In most calculations
that is too limited. The following routines were developed to expand
to a larger quantity of bits. These are based on routines in very early
versions of Intel applications notes. These routines were modified to
fit my applications, so the original copy is no longer available to
identify as a reference.
312 Systems Design and the 8051 Durham
; R6 = size, mul
; R5 = carry, mul
; R4 = mul
; R3 = loop control iteration
; R2 = loop control & size number of bytes
; R1 = @ source
; R0 = @ destination
;
; To enter the basic routines, place variables
; and size to count info in R0, R1, R2
; using something like the JHEX4 subroutine.
;-------------------------------------------------
JHEX4:
;-------------------------------------------------
; Standard arrangement for most math.
; Do this or a similar procedure before calling
; the math manipulation process.
;-------------------------------------------------
JCLEAR:
;-------------------------------------------------
; Clear variables @ R0.
; R2 = # bytes
;ZERO GOES IN
mov @R0,#0 ;clear register
inc R0 ;next bit
djnz R2,JCLEAR ;continue loop
ret
;-------------------------------------------------
JCOPY:
;-------------------------------------------------
; Copy source to destination.
; Do not change source.
inc R1
mov @R0, A ;move to destination
inc R0 ;next
djnz R2, JCOPY ;loop
ret
;-------------------------------------------------
JCPL:
;-------------------------------------------------
; Complement the destination.
; Simply change all bits.
;-------------------------------------------------
JNEG:
;-------------------------------------------------
; Negate the destination
; It is complement and add 1
; That is called twos complement.
setb C ;set c
JNEG1: mov A, @R0 ;destination
cpl A ;complement
addc A, #0 ;add 1
mov @R0, A ;save
inc R0 ;next
djnz R2, JNEG1 ;loop
ret
;-------------------------------------------------
JINCSC:
;-------------------------------------------------
; Increment the destination.
; SC: set carry, signed
; WC: with carry that comes in.
setb C ;set
;---------
Chapter 43 Math Functions 315
JINCWC:
;---------
mov A, @R0 ;destination
addc A, #0 ;add C to byte
mov @R0, A ;save
inc R0 ;next
djnz R2,JINCWC ;loop
ret
;-------------------------------------------------
JDECSC:
;-------------------------------------------------
; Decrement the destination
; SC: set carry
; WC: with carry that comes in.
setb C
;--------- ;WITH CARRY
JDECWC:
;---------
mov A, @R0 ;destination
subb A, #0 ;take away the carry
mov @R0, A ;save
inc R0 ;next
djnz R2,JDECWC ;loop
ret
;-------------------------------------------------
JINC10:
;-------------------------------------------------
; Increment the value by 10.
; This is a decimal increment
;-------------------------------------------------
JSHIFTL:
;-------------------------------------------------
316 Systems Design and the 8051 Durham
; Rotate
left carry by 1 bit at time.
; SHIFT
clears the C
; ROTATE
leaves C bit as it comes in.
; R2 = #
bits
;ROTATE C=0
clr C
;--------- ;ROTATE CARRY
JROTATEL:
;---------
mov A,@R0 ;point to HexS etc
rlc A
mov @R0,A ;update variable
inc R0 ;next bit
djnz R2,JROTATEL ;continue loop
ret
;-------------------------------------------------
JIFZERO:
;-------------------------------------------------
; Test if the value is zero.
; C=1, if zero
; C=0, in not zero
clr C
JZER1: mov A, @R0 ;get value
jnz JZER9 ;notZero
inc R0 ;next
djnz R2, JZER1 ;loop
setb C
JZER9: ret
;-------------------------------------------------
JIFLESS:
;-------------------------------------------------
; If @R0 < @R1, then C=1.
; Subtract but do not save results.
; R2 = # bytes
;subb BUT NOT SAVE
clr C
ret
;-------------------------------------------------
JSUBSC:
;-------------------------------------------------
; Subtract @R0 = @R0 - @R1.
; SC: set carry, Signed
; CC: clr carry, Unsigned
; R2 = # bytes
;SIGNED
setb C ;set borrow
sjmp JSUB1
;--------- ;UNSIGNED
JSUBCC:
;---------
clr C
JSUB1: mov A,@R0 ;point to dest
subb A,@R1 ;@R0 = @R0 - @R1
mov @R0,A
inc R1
inc R0 ;next bit
djnz R2,JSUB1 ;loop
ret
;-------------------------------------------------
JADDCC:
;-------------------------------------------------
; @R0 = @R0 + @R1
; R2 = # bytes
;add & C=0
clr C
ret
;-------------------------------------------------
JMULX16:
;-------------------------------------------------
mov R2,#16
mov R0,#HexA
ljmp JMULXR1
;-------------------------------------------------
JMULXR1:
;-------------------------------------------------
; Multiply @R0 by one byte in R1.
; R2 = number of bytes in R0
; R3:(@R0) = R1*(@R0)
;
mov R3, #0 ;clear carry byte
;LOOP
JMXR1: mov A, @R0 ;LSByte
mov B, R1 ;1 byte multiplier
mul AB ;1 byte multiply
;TERMINATE
ret
;+++++++++++++++++++++++++++++++++++++++++++++++++
JDIV32:
;-------------------------------------------------
; Standard arrangement for multiply.
; Do this or a similar procedure before calling
; the math manipulation process.
Chapter 43 Math Functions 319
;-------------------------------------------------
JDIV16:
;-------------------------------------------------
; Standard arrangement for multiply.
; Do this or a similar procedure before calling
; the math manipulation process.
;-------------------------------------------------
JDIVIDE:
;-------------------------------------------------
;--Entry: HexA, TmpA
;--Exit: GapA, FraA
; Divide routine for up to Size=4 bytes.
;
; Operator / Divisor = Quotient.Fraction + Remain
; HexA / TmpA = GapA . FraA + RemA
;
; R3 = ;counter for # units
; R2 = ;number of bytes
; R1 = ;source
; R0 = ;destination
;
; Divide and Fraction loop have the following.
; Loop times: R3= 8*SizeX; R3>0; R3 is decrement
; Results: Rem:Op<<=1; C=Rem/Divisor
; Rem -=Divisor
;ZERO VARIABLES
mov R0, #RemA ;remain
mov R2, #4 ;all
lcall JCLEAR ;Rem = 0
rl A
rl A
rl A
mov R3, A ;R3=8*Size =loop
;DIVIDE LOOP
JDIV1: lcall JDIV ;divide
mov R0, #GapA ;quotient
mov R2, Size
lcall JROTATEL ;Quo= Quo<<1 | C
djnz R3, JDIV1 ;loop
;CLEAR FRACTION
mov R0, #FraA ;fraction
mov R2, Size
lcall JCLEAR ;Fract = 0
;FRACTION LOOP
JFRAC: lcall JDIV ;divide
Mov R0, #FraA ;fraction
Mov R2, Size ;size
lcall JROTATEL ;Frac= Fract<< 1 | C
djnz R3, JFRAC ;loop
ret
;-------------------------------------------------
JDIV:
;-------------------------------------------------
; Rem:Op<<=1; C=Rem/Divisor; Rem -= Divisor
;DIVIDE
clr C
mov R0, #HexA ;operator
mov R2, Size ;# bytes
lcall JROTATEL ;C:Op = Op*2
Chapter 43 Math Functions 321
JDIV9: cpl C ;C = !C
ret
;-------------------------------------------------
JMUL32:
;-------------------------------------------------
; Standard arrangement for multiply.
; Do this or a similar procedure before calling
; the math manipulation process.
ljmp JMULTIPLY
;-------------------------------------------------
JMUL16:
;-------------------------------------------------
; Standard arrangement for multiply.
; Do this or a similar procedure before calling
; the math manipulation process.
ljmp JMULTIPLY
;-------------------------------------------------
JMULTIPLY:
;-------------------------------------------------
; Multiply multiple bytes. Variables are used
; as pointers to the values.
; @ArgG = @ArgH * @ArgT
; Gap = Hex * Tmp
;
;SizeT equ 33H ;same space as Tmp upper bytes
;ArgG equ 32H ;used in multiply
;ArgT equ 31H ;
;ArgH equ 30H ;same space as Tmp upper bytes
;GapH equ 3BH ;8 digit
;GapA equ 34H ;result
;TmpD equ 2FH ;4 byte
;TmpA equ 2CH ;math low byte
;HexD equ 2BH ;double word
;HexA equ 28H ;low byte of variable
;
; R6 = size, mul
; R5 = carry, mul
; R4 = mul
; R3 = loop control iteration
; R2 = loop control & size number of bytes
; R1 = @ source
; R0 = @ destination
;
; Move the location of the source and destination
; to the ArgS variables.
; Move the size of the Arguments to SizeS.
; The Arg and Size will be incremented as the
; process goes through each byte.
;
; Xcand= multiplicand, Xer= multiplier
;LOOP
JMUX1: mov R0, ArgH ;Xcand addr
mov A, @R0 ;Xcand data
Chapter 43 Math Functions 323
;NIBBLE MULTIPLY
JMUX2: mov A, R2 ;Xcand data
mov B, @R1 ;Xer data
inc R1 ;next byte
mul AB ;B:A= *R1++ * R2
;CARRY BY 1
JMUX3: add A, @R0 ;Xcand data
mov @R0, A ;save new Xcand
inc R0 ;C:*R0++ += *R0 + A
jnc JMUX9 ;C<>0, next loop
mov A, #1
djnz R3, JMUX3 ;next Xcand bit
;
inc R5 ;inc carry byte
324 Systems Design and the 8051 Durham
;TERMINATE
ret
;-------------------------------------------------
JSQROOT:
;-------------------------------------------------
; QuoS = square root of HexS
; Enter with a value.
; Rotate the 2 MSB into a new variable.
; Compare comparison with new.
; If comparison < new, then C=1.
; Then new is greater than nearest multiple of 2.
; So shift another bit into answer.
; Calculate new = new-compare-C = new-(compare+1)
; This removes last compare from re consideratio.
; Multiply comparison by 2.
; If Comparison < new then orl #4
; This sets bit equiv to nest multiple.
; Continue.
;
; SHL 2 bits into D If X<D, C=1, C->Q, D=D-X-C
; If X>D, C=0. C->Q
; SHL 1 bits in X If X>D, X=X orl #4
;
; HexA = Input 4 bytes
; TmpA = comparison 4 bytes
; RemA = remaining 4 bytes
; GapA = result 2 bytes
;
; R0, R1, R2, R3
;INITIALIZE
mov Size,#4 ;#bytes of source
;CLEAR VARIABLES
mov R0,#GapA ;result
mov A,Size ;# bytes
rr A ;only need 1/2
mov R2,A ;2 bytes
lcall JCLEAR ;clear
ret
⇐⇑⇒
SECTION IV – HARDWARE
⇐⇑⇒
44
Thought
The universal engineering unit = $
Dr. D
Parts are separated into categories. The Proto then uC group is the
basic components to make a working computer. All these will be
later used on a development board. This also includes cable for the
SPI download of programs
uC board only____________________
Projects ________________________
⇐⇑⇒
* V
IO/CK 1 24 VCC
I1 2 23 F9
I2 3 22 F8
I3 4 21 F7
I4 5 20 F6
I5 6 19 F5
I6 7 18 F4
I7 8 17 F3
I8 9 16 F2
I9 10 15 F1
I10 11 14 F0
Ground 12 13 I11
22V10 PLD
332 Systems Design and the 8051 Durham
* V
P1.0 1 T2 40 VCC
P1.1 2 T2 EX AD0 39 P0.0
P1.2 3 AD1 38 P0.1
P1.3 4 AD2 37 P0.2
P1.4 5 SS/ AD3 36 P0.3
P1.5 6 MOSI AD4 35 P0.4
P1.6 7 MISO AD5 34 P0.5
P1.7 8 SCK AD6 33 P0.6
Reset 9 AD7 32 P0.7
P3.0 10 RXD VPP 31 /EA
P3.1 11 TXD PROG/ 30 ALE
P3.2 12 INT0/ 29 /PSEN
P3.3 13 INT1/ A15 28 P2.7
P3.4 14 T0 A14 27 P2.6
P3.5 15 T1 A13 26 P2.5
P3.6 16 /WR A12 25 P2.4
P3.7 17 /RD A11 24 P2.3
Xtal2 18 A10 23 P2.2
Xtal1 19 A9 22 P2.1
Ground 20 A8 21 P2.0
* V
A1 1 14 VCC
/Y1 2 13 A6
A2 3 12 /Y6
/Y2 4 11 A5
A3 5 10 /Y5
/Y3 6 9 A4
Ground 7 8 /Y4
* V
C1+ 1 16 VCC
V+ 2 15 Ground
C1- 3 14 T1OUT
C2+ 4 13 R1 IN
C2- 5 12 R1OUT
V- 6 11 T1IN
T2OUT 7 10 T2IN
R2IN 8 9 R2OUT
Max C1 – C5
232 1 uF
232A 0.1 uF
RS 232 Interface
* V
T2IN 1 20 R2OUTC
T1IN 2 19 R2IN
R1OUT 3 18 T2OUT
R1IN 4 17 V-
T1OUT 5 16 C2-
GND 6 15 C2+
Vcc 7 14 V+
C1+ 8 13 C1-
GND 9 12 V-
CS- 10 11 C2+
RS 233 Interface
Chapter 44 Parts & Pin-outs 335
* V Pin Function
a 1 14 common 1 a
f 2 ⎯ a 13 b 13 b
common 3 f/ / b 12 nc 10 c
dp pre 4 ⎯ g 11 g 8 d
nc 5 e/ / c 10 c 7 e
nc 6 ⎯ d 9 dp post 2 f
e 7 8 d 11 g
4 dp pre
9 dp post
3 common
14 common
7 Segment display
* V
CH0 1 16 VCC
CH1 2 15 CCLK
COM 3 14 SCLK
/DOR 4 13 DI
EOC 5 12 DO
VREF- 6 11 /CS
VREF+ 7 10 /CONV
DGnd 8 9 VA+
LTC 1098 analog / digital converter
* V
REF+ 1 8 VCC
AN-IN 2 7 SCLK
REF- 3 6 DOUT
GND 4 5 /CS
TLC549 analog / digital converter
Chapter 44 Parts & Pin-outs 337
* V
A14 1 VPP ROM 28 VCC
A12 2 ROM A14 27 /WE
A7 3 26 A13
A6 4 25 A8
A5 5 24 A9
A4 6 23 A11
A3 7 22 /OE
A2 8 21 A10
A1 9 20 //CE
A0 10 19 DQ7
DQ0 11 18 DQ6
DQ1 12 17 DQ5
DQ2 13 16 DQ4
Ground 14 15 DQ3
* V
A15 1 28 VCC
A12 2 27 A14
A7 3 26 A13
A6 4 25 A8
A5 5 24 A9
A4 6 23 A11
A3 7 VPP 22 /OE
A2 8 21 A10
A1 9 20 /CE
A0 10 19 DQ7
DQ0 11 18 DQ6
DQ1 12 17 DQ5
DQ2 13 16 DQ4
Ground 14 15 DQ3
⇐⇑⇒
338 Systems Design and the 8051 Durham
Two connectors are used on the board. One is required for the
RS232 communications which will connect by cable to the PC serial
port. The other is required for in-system-programming (ISP) which
will connect by cable to the PC parallel port.
Note, connect a 1.5K resistor between the cable and the reset.
RJ45 Cables
⇐⇑⇒
45
DEVELOPMENT BOARD
Thought
A design – build contract
means you do it all.
Design _________________________
Options ________________________
HyperTerminal __________________
The program is run from the development board. Use the sample
test program MODTest shown as a simple software illustration. Run
the program through an assembler. Take the *.hex file results and
download to the board memory. This program is very simple, but
illustrative.
Schematic _______________________
PROCESSOR
1. 89S8252 (8051 core) w/ in-system programming, internal
program & data memory
2. Crystal 11.059 MHz
3. Reset can be from auto circuit, pushbutton, and ISP.
4. Package is 40 pin, board to fit electrical gang-box.
EXTERNAL MEMORY
5. Expansion memory socket in a common socket
a. 32K eeprom
b. 32K sram w/ socket for DIP or wide
c. Memory pin 1, 27, and OE from PLD
POWER
6. Wall-wart mini-jack power connector pin
7. LP2954 voltage regulator enlarge hole size
8. Add pins for 5V & Ground
9. Place filter capacitor on line.
ISP
10. Quad buffer on in-system-programming lines for port 1.
11. Enable buffer with uc reset complemented from PLD.
12. Connect in and out lines as required.
RESET
13. Place capacitor and resistor to auto reset on pin 9.
14. Place pushbutton for manual reset.
PORT 1
18. Connect IIC to pins 6 & 7, share with SPI
19. Connect 7-segment select lines to pins 2-4.
20. Connect SPI on pins 5-7.
PORT 3
21. Connect RS232 on pins 0&1
22. Connect handshake on pin 2 (INT0).
23. Connect infrared receive/ transmit module to P33 (Int1).
24. If Int1 is used separately, the infrared must be covered with
black tape.
25. Connect RS485 select to P34 (T0).
26. Connect LED & pushbutton to P35 (T1).
I/O LATCHES
27. All external I/O uses memory-mapped connections.
28. Display-Out Latch for 7-segment data.
a. Latch Enable from PLD.
b. Output Enable is connected to ground.
c. Take data to on-board 7-segment display through current
limiting resistors.
d. Take data out after resistor to expansion header.
29. Key-Out Latch for keypad column output.
a. Latch Enable from PLD. Enable when write to column.
b. Output Enable is connected to ground.
c. Use upper nibble for columns out to keypad.
d. Use other bits for digital out.
30. Key-In Latch for keypad row input.
a. Output Enable from PLD. Enable when read from row.
b. Latch Enable connected to 5 volts.
c. Use lower nibble for rows in from keypad..\
d. Connect pull-up resistors on keypad inputs.
e. Other bits are for digital input.
31. Address Latch to separate address from data on Port 0.
a. LE is connected to ALE.
b. OE is connected to ground.
DISPLAY CONTROL
Chapter 45 Development Board 345
LCD
33. Bypass auto-contrast circuit with a jumper to ground.
34. Add backlight connector adjacent to LCD header
35. LCD has 3 control lines, RW’, RS, En. Shared with 7-segment.
a. Take controls to LCD header.
b. Connect Enable to P1.2.
c. Connect Write enable to P1.1.
d. Connect data/instruction register select to P1.0.
A/D CONVERT
36. Use with serial peripheral interface.
a. Connect serial I/O to port 1 SPI bus using MISO, SCK
b. Connect /CS to P1.4, /SS.
37. Make reference voltage 0-5 volts for rail to rail operation.
38. Make header for A/D input with analog ground.
39. Connect analog ground to digital ground at 1 point via a jumper
that can be isolated.
INFRARED
40. Add infrared receiver / transmitter
41. Connect to P33 (Int1) pin
SERIAL
42. Use Max 233 since it does not require external caps.
a. Because of limited port space, only 1 handshake is used..
b. Connect Int0 as handshake control.
c. Header selects in or out line for connection to RJ45
43. Add Max 485 chip as option.
a. Connect control lines RE and DE together to P34 (T0).
b. Connect serial differential lines to header.
c. These will parallel the serial lines for the Max233.
346 Systems Design and the 8051 Durham
IIC
44. Connect IIC to Port 1.
a. SDA connect to P17.
b. SCL connect to P16
RJ45 CONNECTORS
45. Connect 3 in-system-programming lines plus common to ISP
connector.
46. Connect serial TX, RX, and handshake to serial connector.
a. Connect handshake to a jumper between out and in
handshake
b. Configurable for computer or modem
OFF-BOARD HEADERS
54. In-system-program port through 4-bit isolation latch
a. Connect in and out lines as required.
Chapter 45 Development Board 347
55. Seven-segment
a. Data from Display-Out latch
b. Seven-segment control lines from Port 1 through 7406.
56. LCD
a. Data from P0
b. Control from microprocessor.
c. Add backlight connector. It can have separate power source.
57. Address latch output connect for expansion MMIO
58. Keypad
a. Column from latch upper nibble.
b. Row to latch lower nibble with pull-up resistors.
59. Address latch
a. Output address for MMIO or expansion
b. Have pins including ALE, PSEN, MMIO RD, MMIO WR.
60. Analog input
a. Connect to ADC
b. Analog ground
61. RS485 needs only 2 differential data lines
62. IIC needs 2 lines.
63. Power pins for 5V & Ground
SELECT JUMPERS
64. External memory EA’ select 5V or Ground
65. Seven-segment onboard select ground or 7406 / MosFet
66. Memory Output Enable select ground or PLD
67. LCD contrast jumper to Ground
68. Handshake select for RS232
GENERAL
69. Be cautious that fan out is not a problem on port 0.
PORT CONNECTIONS
70. Port 1
a. 10 – SegA / RS
b. 11 – SegB / RW’
c. 12 – SegC / En
d. 13 –
e. 14 – /SS
f. 15 – SPI MOSI
348 Systems Design and the 8051 Durham
g. 16 – SPI MISO
h. 17 – SPI SCK
71. Port 3
a. 30 – serial RXD
b. 31 – serial TXD
c. 32 – Int1 serial handshake
d. 33 – Int0 infrared input
e. 34 – T0 RS485 select
f. 35 – pushbutton and LED
g. 36 – write’
h. 37 – read’
⇐⇑⇒
46
IN SYSTEM PROGRAMMING
Thought
What is the tradeoff between
hardware and software?
Both the Code and Data memory arrays can be programmed using
the serial SPI bus while RST is pulled to VCC. The serial interface
consists of pins SCK, MOSI (input) and MISO (output).
The Code and Data memory arrays have separate address spaces:
0000H to 1FFFH for Code memory and 000H to 7FFH for Data
memory.
Xtal2
Xtal1
Ground
The SCLK line shifts data into the device (MOSI) on a rising edge.
So SCLK must be made LO then HI to input to the device from the
controller.
The SCLK line shifts data out from the device (MISO) on a falling
edge. So SCLK must be made HI then LO to output from the device
to the controller.
Chapter 46 In-System Programming 353
Connections are needed on the personal computer for the three data
lines and a reset line. The only access with that many control wires
is the parallel port for the printer.
Note place a 1.5K resistor between the connector and the reset line.
Connectors _____________________
⇐⇑⇒
SECTION V – ARCHITECTURE
⇐⇑⇒
47
INSTRUCTION SET
Thought
Triad Principle:
Any item that can be uniquely identified,
can be further explained by three components
MOD
There are many ways data can be obtained. These are called
addressing modes. The machine has seven unique modes -
immediate, direct, register, indirect, relative, absolute, and bit.
358 Systems Design and the 8051 Durham
0 1 2 3 4 5 6 7
0 nop jbc jb jnb jc jnc jz jnz
bit,rel bit, rel bit, rel rel rel rel rel
I ajmp acall ajmp acall ajmp acall ajmp acall
(P0) (P0) (P 1) (P 1) (P2) (P2) (P3) (P3)
2 ljmp lcall ret reti orl anl xrl orl
addr16 addr16 [2C] [2C] dir, A dir, A dir, a C, bit
3 rr rrc rl rlc orl anl xrl jmp
A A A A dir, #data dir, #data dir, #data @A+DPTR
4 inc dec add addc orl anl xrl mov
A A A, #data A, #data A, #data A, #data A, #data A, #data
5 inc dec add addc orl anl xrl mov
dir dir A, dir A, dir A, dir A, dir A, dir dir, #data
6 inc dec add addc orl anl xrl mov
@R0 @R0 A, @R0 A, @R0 A, @R0 A, @R0 A, @R0 @R0,@dat
7 inc dec add addc orl anl xrl mov
@R1 @R1 A, @R1 A, @R1 A, @R1 A, @R1 A, @R1 @R1,#dat
8 inc dec add addc orl anl xrl mov
R0 R0 A,R0 A.R0 A,R0 A,R0 A,R0 R0, #data
9 inc dec add addc orl anl xrl mov
R1 R1 A, R1 A, R1 A, R1 A, R1 A, R1 R1,#data
A inc dec add addc orl anl xrl mov
R2 R2 A,R2 A,R2 A, R2 A,R2 A,R2 R2,#data
8 inc dec add addc orl anl xrl mov
R3 R3 A,R3 A,R3 A,R3 A,R3 A,R3 R3,#data
C inc dec add addc orl anl xrl mov
R4 R4 A,R4 A,R4 A, R4 A,R4 A,R4 R4,#data
D inc dec add addc orl anl xrl mov
R5 R5 A,R5 A,R5 A,R5 A,R5 A,R5 R5,#data
E inc dec add addc orl anl xrl mov
R6 R6 A,R6 A,R6 A,R6 A,R6 A,R6 R6,#data
F inc dec add addc orl anl xrl mov
R7 R7 A,R7 A,R7 A,R7 A,R7 A,R7 R7,#data
Chapter 47 Instruction Set 365
8 9 A B C D E F
0 sjmp mov orl anl push pop movx movx
REL DPTR,#d16 C, /bit C, /bit dir dir A,@DPTR @DPTR, A
1 ajmp acall ajmp acall ajmp acall ajmp acall
(P4) (P4) (P5) (P5) (P6) (P6) (P7) (P7)
2 anl mov mov cpl clr setb movx movx
C, bit bit, C C, bit bit bit bit A, @R0 @R0, A
3 movc A, movc A, inc cpl clr setb MOW movx
@A+PC @A+DPTR DPTR C C C A, @RI @RI, A
4 div subb mul cjne A, swap da clr cpl
AB A, #data AB #data, rel A A A A
5 mov subb cjne xch djnz mov mov
dir, dir A, dir A, dir, rel A, dir dir, rel A, dir dir, A
6 mov subb mov cjne xch xchd mov mov
dir,@R0 A, @R0 @R0, dir @R0, A, @R0 A, @R0 A, @R0 @R0, A
#data, rel
7 mov subb mov cjne xch xchd mov mov
dir,@R1 A, @R1 @R1, dir @R1, A, @R1 A, @R1 A, @R1 @R1, A
#data, rel
8 mov subb mov cjne xch djnz mov mov
dir, R0 A, R0 R0, dir R0, #data, A, R0 R0, rel A, R0 R0, A
rel
9 mov subb mov cjne xch djnz mov mov
dir, R1 A, R1 R1, dir R1, #data, A, R1 RI, rel A, R1 R1, A
rel
A mov subb mov cjne xch D jnz mov mov
dir, R2 A. R2 R2 dir R2, #data, A, R2 R2, rel A, R2 R2, A
rel
B mov subb mov cjne xch djnz mov mov
dir, R3 A, R3 R3, dir R3, #data, A, R3 R3, rel A. R3 R3, A
rel
C mov subb mov cjne xch djnz mov mov
dir, R4 A. R4 R4, dir R4, #data, A, R4 R4, rel A, R4 R4, A
rel
D mov subb mov cjne xch djnz mov mov
dir, R5 A, R5 R5, dir R5, #data, A, R5 R5, rel A, R5 R5, A
rel
E mov subb mov cjne xch djnz mov mov
dir, R6 A, R6 R6, dir R6, #data, A. R6 R6, rel A, R6 R6, A
rel
F mov subb mov cjne xch djnz mov mov
dir, R7 A, R7 R7, dir R7 #data, A, R7 R7, rel A, R7 R7, A
rel
⇐⇑⇒
48
MEMORY ORGANIZATION
Thought
Experience is great to have.
I just do not like getting it.
MOD
The Motorola scheme uses the Princeton approach, while the Intel
philosophy developed around the Harvard technique. This applies
both to the personal computer systems as well as the microcontroller
devices.
Code memory is accessed based on the chip line /EA. If the line is
low, control goes to external memory. If the line is high, initial
control goes to internal memory. The next line of code after the top
of internal memory is external memory. This transition is regardless
of /EA setting. The next address will be in sequence. In other words,
the low external memory is inaccessible.
FFFF FFFF
56K Bytes
External
Program Memory
368 Systems Design and the 8051 Durham
Instructions that access code memory use the movc mnemonic. This
also activates the /PSEN line.
Internal External
FF SFR FFFF
Direct
80 Addressing
7F Internal RAM
Direct & Indirect 64K Bytes
00 Addressing
0000
Data Memory
Internal External
Expansion FF FFFF
Memory
FF SFR Indirect only
Direct 80
80 Addressing 64K Bytes
7F Internal RAM
Direct & Indirect EEPROM 7FF
00 Addressing movx
Addressing 000 0000
The basic processor has 128 bytes of internal data that is available.
The entire area may be used as general-purpose data. In addition,
370 Systems Design and the 8051 Durham
the lower part can be used as registers. Another group of bytes is bit
addressable.
The basic instruction that accesses this area is mov. It does not
influence any external pins or lines. Numerous other instructions
can also be used, depending on the addressing mode.
⇐⇑⇒
49
Thought
What is so special
about function registers?
First time user
The registers that will be addressed in this section are the ports as
well as the control and mode for status flags, power control, timers,
and serial.
376 Systems Design and the 8051 Durham
Ports __________________________
Four ports are connected to external pins. As such, they are the
input and output connections to the processor. All ports can be used
for general-purpose input and output. In addition, ports 0, 2, and 3
have special applications. On some machines, even port 1 has
additional functions. The four ports are similar, but the hardware for
each is different because of the functions.
To make the port pins perform as an input, first place a 1 on each bit
that is to be read. This will pull the line high so that external
switches may be connected. Then the data that is read from the port
address is the status of the external switches.
Port 0 __________________________
The port has very weak internal pull-up resistors. When used as an
output, the port functions like the other ports. However, it is limited
in the driving current. When the port is used as an input, it must
have external pull-up or pull-down resistors attached. Connect a 2.2
KΩ resistorto 5 volts or to ground as required.
Chapter 49 Special Function Registers 377
Port 1 __________________________
After the SPI exchange, the port pins can revert to standard input /
output. However, the port pins should not be used for several
instruction cycles after the in system programming, or the machine
may lock up.
Port 2 __________________________
Port 3 __________________________
CY AC F0 RS1 RS0 OV — P
SMOD Double baud rate bit. If Timer 1 is used to generate baud rate and SMOD =
1, the baud rate is doubled when the Serial port is used in modes 1, 2, or 3.
Serial port is used in modes 1, 2, or 3.
— Not implemented, reserved for future use.
— Not implemented, reserved for future use.
— Not implemented, reserved for future use.
GF1 General purpose flag bit.
GF0 General purpose flag bit.
PD Power Down bit. Setting this bit activates Power Down operation in select
processors.
IDL Idle Mode bit. Setting this bit activates Idle Mode operation in select
processors. If 1s are written to PD and IDL at the same time, PD takes
precedence.
380 Systems Design and the 8051 Durham
Interrupts ______________________
In addition, for external interrupts, pins INT0 and INT1 (P3.2 and
P3.3) must be set to 1, and depending on whether the interrupt is to
be level or transition activated, bits IT0 or IT1 in the TCON register
may need to be set to 1. ITx = 0 is used for level activated, while
ITx = 1 makes the interrupt transition activated.
Both the interrupt enable and the interrupt priority registers are bit
addressable. These can be changed with setb, clr, anl, orl, and xrl
instructions.
Two tables are given for selecting the mode. The last table has
TMOD values that can be used to set up Timer 0. It is assumed that
only one timer is used at a time. If Timers 0 and 1 must run
simultaneously in any mode, the value in TMOD for Timer 0 must
be ORed with the value required for Timer 1.
GATE When TRx (in TCON) is set and GATE = 1, TIMER/COUNTERx runs
only while the INTx pin is high (hardware control). When GATE = 0,
TIMER/COUNTERx will run only while TRx = 1 (software control).
C/T Timer or Counter selector. Cleared for Timer operation (input from
internal system clock). Set for Counter operation(input from Tx input
pin).
M1 Mode selector bit.
M0 Mode selector bit.
384 Systems Design and the 8051 Durham
M1 M0 Mode Operation
0 0 0 13-bit Timer
0 1 1 sixteen bit Timer/Counter
1 0 2 eight bit Auto-Reload Timer/Counter
1 1 3 Split Timer Mode: (Timer 0) TL0 is an eight bit
Timer/Counter controlled by the standard Timer 0
control bits, TH0 is an eight bit Timer and is
controlled by Timer 1 control bits.
1 1 3 (Timer 1) Timer/Counter 1 stopped.
Serial __________________________
0 NA Multiprocessor
1 70H Environment
2 B0H (SM2 = 1)
3 F0H
⇐⇑⇒
50
SFR EXTENDED
Thought
Be strong, be courageous,
Be not afraid.
General Joshua, ~1500 BC
Timer/counter 2 _________________
The SCK pin is the clock output in the master mode but is the clock
input in the slave mode. Writing to the SPI data register of the
master CPU starts the SPI clock generator, and the data written
shifts out of the MOSI pin and into the MOSI pin of the slave CPU.
After shifting one byte, the SPI clock generator stops, setting the
end of transmission flag (SPIF). If both the SPI interrupt enable bit
(SPIE) and the serial port interrupt enable bit (ES) are set, an
interrupt is requested.
There are four combinations of SCK phase and polarity with respect
to serial data, which are determined by control bits CPHA and
CPOL.
SPIE SPCR. 7 SPI Interrupt Enable. This bit, in conjunction with the ES bit
in the IE register, = 1 enable SPI interrupts. SPIE = 0 disables
SPI interrupts.
SPE SPCR. 6 SPI Enable. SPI = 1 enables the SPI channel and connects
SS, MOSI, P1.7. SPI = 0 disables the SPI channel.
DORD SPCR. 5 Data Order. DORD = 1 selects LSB first data transmission.
DORD = 0 selects MSB first data transmission
MSTR SPCR. 4 Master/Slave Select. MSTR = 1 selects Master SPI mode.
MSTR = 0 selects slave SPI mode
CPOL SPCR. 3 Clock Polarity. When CPOL = 1, SCK is high when idle.
When CPOL =0, SCK of the master device is low when not
transmitting.
CPHA SPCR. 2 Clock phase. The CPHA bit together with the CPOL bit
controls the clock and data relatinship between master and
slave.
SPR0 SPCR. 1 SPI clock rate select. These 2 bits control the SCK rate of the
SPR1 SPCR. 0 device configured as amster. They have no effect on the
slave. The SCK frequency is the oscillator frequency divided
by the values.
SPR1 SPR0 Divisor
0 0 4
0 1 16
1 0 64
1 1 128
SPIF SPSR. 7 SPI Interrupt Flag. When a serial transfer is complete, the
SPIF bit is set and an interrupt is generated if SPIE = 1 and
ES = 1. The SPIF bit is cleared by reading the SPI status
register with SPIF and WCOL bits set, and then accessing the
SPI data register
WCOL SPSR. 6 Write collision flag. The bit is set if the SPI data register is
written during a data transfer. During transfer, the result of
reading the SPDR register may be incorrect, and writing to it
has no effect. The WCOL bit and the SPIF bit are cleared by
reading the SPI status register with SPIF and WCOL set, and
then accessing the SPI data register.
394 Systems Design and the 8051 Durham
;-------------------------------------------------
;Program: EEPROM.ASM
;Initial: July 28, 2004
;By: Dr. Marcus O. Durham, PhD, PE
; Tulsa, OK, USA
; [email protected]
; www.ThewayCorp.com
;Copyright (c) 2004. All rights reserved
; Original adapted from Atmel.
;
;Purpose:
; A set of routines are provided to write and
; read from the on board EEPROM.
;
;Processor: 8031 family
;PROM: 8k (2000H) onboard
;Crystal: 11.059 MHz
;Assembler: Intel ASM51
;#################################################
; ASSIGNMENTS
;#################################################
;CONSTANTS
;-------------------------------------------------
; ;WMCON REGISTER
Spcr data 0d5h ;SPI control register
;#################################################
; PROGRAM
;#################################################
org 00h
396 Systems Design and the 8051 Durham
;-------------------------------------------------
org 0080h ;Address past reserve
INITIAL:
MAIN:
;-------------------------------------------------
lcall WMEEPRD ;read eeprom
;-------------------------------------------------
WMEEPRD:
;-------------------------------------------------
; WMCON is used to access internal EEPROM.
; WMCON is not bit addressable, so Boolean
; functions are necessary to control bits.
; EEPROM read
;-------------------------------------------------
WMEEPWRD:
;-------------------------------------------------
; EEPROM write example, utilizing fixed delay
; for write cycle. Delay is worst case (10 ms).
; Write is followed by verify (read & compare)
; Code for delay is not shown.
; Code to handle verification failure not shown.
;-------------------------------------------------
WMEEPWRB:
;-------------------------------------------------
; EEPROM write example, utilizing RDY/BSY
; to determine the end of the write cycle.
; Write is followed by verify (read and compare)
; Needs timeout to prevent write error from
; causing an infinite loop.
;-------------------------------------------------
WMEEPWRP:
;-------------------------------------------------
; EEPROM write example, utilizing data polling
; to determine the end of; the write cycle.
; After data is loaded, the code loops on read
; until data is returned true.
; Write verification is implicit in this method.
; Needs timeout to prevent write error from
; causing an infinite loop.
398 Systems Design and the 8051 Durham
⇐⇑⇒
SECTION VI – COMMUNICATION
⇐⇑⇒
51
ASCII
Thought
Seldom does one problem produce a failure.
It takes at least two problems to cause a catastrophe.
MOD
What is it _______________________
32 20 (space) 48 30 0 64 40 @
33 21 ! 49 31 1 65 41 A
34 22 " 50 32 2 66 42 B
35 23 # 51 33 3 67 43 C
36 24 $ 52 34 4 68 44 D
37 25 % 53 35 5 69 45 E
38 26 & 54 36 6 70 46 F
39 27 ' 55 37 7 71 47 G
40 28 ( 56 38 8 72 48 H
41 29 ) 57 39 9 73 49 I
42 2A * 58 3A : 74 4A J
43 2B + 59 3B ; 75 4B K
44 2C , 60 3C < 76 4C L
45 2D - 61 3D = 77 4D M
46 2E . 62 3E > 78 4E N
47 2F / 63 3F ? 79 4F O
80 50 P 96 60 ` 112 70 p
81 51 Q 97 61 a 113 71 q
82 52 R 98 62 b 114 72 r
83 53 S 99 63 c 115 73 s
84 54 T 100 64 d 116 74 t
85 55 U 101 65 e 117 75 u
86 56 V 102 66 f 118 76 v
87 57 W 103 67 g 119 77 w
88 58 X 104 68 h 120 78 x
89 59 Y 105 69 i 121 79 y
90 5A Z 106 6A j 122 7A z
91 5B [ 107 6B k 123 7B {
92 5C \ 108 6C l 124 7C |
93 5D ] 109 6D m 125 7D }
94 5E ^ 110 6E n 126 7E ~
95 5F _ 111 6F o 127 7F
⇐⇑⇒
52
RS 232
Thought
God does not throw dice.
Dr. Albert Einstein
Connections _____________________
25 to 3 jumper ]
25-pin 3-pin 3-pin
Funct DB25P DB25S DB9S
TX 2 2 3
RX 3 3 2
4]
5]
6]
8]
Gnd 7 7 5
Chapter 52 RS 232 405
Schematic _______________________
COMPUTER TERMINAL
1 GROUND GROUND 1
2 TRANSMIT DATA TRANSMIT DATA 2
3 RECEIVE DATA RECEIVE DATA 3
4 REQUEST TO SEND REQUEST TO SEND 4
5 CLEAR TO SEND CLEAR TO SEND 5
8 CARRIER DETECT CARRIER DETECT 8
6 DATA SET READY DATA SET READY 6
22 RING INDICATOR RING INDICATOR 22
20 DATA TERMINAL READY DATA TERMINAL READY 20
7 SIGNAL GROUND SIGNAL GROUND 7
1 1
2 TRANSMIT DATA TRANSMIT DATA 2
3 RECEIVE DATA RECEIVE DATA 3
4 REQUEST TO SEND REQUEST TO SEND 4
5 5
8 8
6 DATA SET READY DATA SET READY 6
22 22
20 20
7 SIGNAL GROUND SIGNAL GROUND 7
⇐⇑⇒
53
NETWORK CONNECTION
Thought
To err is human.
To forgive is not a computer function.
Popular quip
Network ________________________
The diagrams show the color-coding and pin arrangements for these
designs. A design designation can be used with any connector that
has that number of pins or more. The common connector
designation is based on the maximum number of pins.
Plug designation
The pins are numbered when looking at a plug with the contacts
facing up. Pin number 1 is on the left. The corresponding pin 1 is
observed in the jack, when the contacts are on the top. The strip
designation is the standard termination strip for networks.
| | | | | | | |
RJ45 1 2 3 4 5 6 7 8
RJ12 1 2 3 4 5 6
RJ11 1 2 3 4
The USOC standards start with Pair 1 on the middle two pins. Pair 2
is on the next two pins outward. Pair 3 is on the next two pins
outward. Finally, Pair 4 is on the outermost two pins.
The TIA standards also start with Pair 1 on the middle two pins,
4&5. For TIA568A, Pair 2 is on the next two pins outward, 3 & 6,
and Pair 3 is on the first two pins, 1 & 2. For TIA568B, Pair 3 is on
the next two pins outward and Pair 2 is on the first two pins. Finally,
Pair 4 is on the last two pins, 7 & 8.
Chapter 53 Network Connection 409
Only two pairs are used for computer networking. Therefore, the
other two pairs are available for other digital service, such as digital
telephone.
PAIR AUDIO
Function Strip Jack Speaker Plug
White/blue Surround R + 1 Red low Red Green
Blue/white Surround R - 2 Red low Black
White/orange Surround L + 5 White low Red White
Orange/white Surround L - 6 White low Black
White/green Stereo R + 3 Red top Red Red
Green/white Stereo R - 4 Red top Black
White/brown Stereo L + 7 White top Red Black
Brown/white Stereo L - 8 White top Black
54
Thought
What you believe
is what happens.
MOD
The speed is quiet fast. Typical propagation delays are less that 15
ns and as low as 5 ns - faster than standard TTL 7400 series logic.
A Enable
W
Enable = A & !W
This is actually the equation for a latch enable when A is the address
and W is the write not line.
The file begins with header information. The only required field is
the filename. The device type must be specified. Then the file lists
assignments for the input pins. Next comes the specification for the
input/output cell pins. Finally, the equations are listed. Comments or
descriptions can be placed anywhere within the program.
A pin 2
W pin 3
EQUATIONS
Enable.com = A & !W
Data
MmWr
@R-
GatedLatch = (MmWr & D)#(!MmWr & GL)#(D & GL)
@R+
SP := logic equation
AC := logic equation
Registers ________________________
Enable.COM = A & !W
Q.D = D
Q will take the value of D following the rising edge of the clock on
pin 1. Multiple registers can be configured to form counters. Each
intermediate state will be an output pin.
Result.OE = B & C
Limitations ______________________
One of the limitations of the simple PLD such as the 22V10 is the
limit on internal logic. Every term that is used must be either an
input or an output. There are no internal states. As a result,
intermediate states use an output pin and preclude its use for other
connections. This limitation simply results from the device being a
simple array that has connections ‘burned’.
DESCRIPTION
The description is optional. The title block
information must be enclosed within single
quotation marks.
The device must be specified.
end_DESC;
PEEL22CV10
418 Systems Design and the 8051 Durham
"Pins
"Registered clock or input: 1
"Input: 2,3,4,5,6,7,8,9,10,11, 13
"Input or output logic macro cell (OLMC):
" 14,15,16,17,18,19,20,21,22,23
"
"-------
"Symbols are used for programming functions
" Quote = comments not printed
" ' = comments for header to be printed'
" ! = not
" & = AND
" # = OR
" $ = exclusive-or
" = is equation for combination logic
" ; = last character in an equation
"-------
"Application
"Memory can be changed from EPROM to SRAM
"by changing the chip & /OE jumper.
"PLD / PEEL program selects MemP1 and MemP27.
"-------
"Address assignments.
"Because of the Don't Cares, the effective
"memory-mapped address can be 8xxn.
"-------
"Memory switching latch was for old BIOS
"Kept for record purposes, original file is lost.
"CE = WRFF & ucA7 & ucD0 # !WRFF&CE
"OE = PSEN&RD # RD&!CE
"---------------
"PIN ASSIGNMENTS
"INPUTS
A00 pin 1
A01 pin 2
A02 pin 3
A14 pin 4
A15 pin 5
AD00 pin 6
Reset pin 7
" pin 8
PSEN pin 9
RDn pin 10
WRn pin 11
" pin 13
420 Systems Design and the 8051 Durham
DEFINE
"Define variables do not have feedback.
MmAd = A15
EQUATIONS
"Equations define logic functions
"Register variables have .D extension for D FF.
"Combinational variables have .COM extension.
IspOEn.com = !Reset;
TEST_VECTORS
"Test vectors are used to verify the logic works.
"This is a partial truth table.
"The first line specifies input output variables.
"Next line are input output values.
"C is clock transition.
"0 is an input low, 1 is an input high
"L is output low, H is output high.
"X is don't care
The assembled file (*.map) contains the pin node connections and
all the product terms.
The JEDEC file (*.jed) is the information that is sent to burn the
programmable logic device. This is a common language among
many vendors.
⇐⇑⇒
55
Thought
Educating process:
Encourage – instruction – example.
Dr. Jerry Falwell
Background ____________________
tD = L / R
Chapter 55 Circuit Time & Phase Shift 423
tD = R * C
f = 1 / 2π√(L * C)
Digital circuits have either an on or off state. The state will change
based on the input. If the input branches have different time delays,
then the digital state will not change at precisely the time expected.
Delay ___________________________
Wr’
Wr’ (stretched)
The resistor value must be large enough to keep Wr’ from sinking
too much current. A value in excess of 2 k Ohms is generally
424 Systems Design and the 8051 Durham
The resistor value should correspond to the exact timing needed. For
29 ns, the value would be 2.9 k Ohms.
tD = R * C = 2900 * 10 e-12 = 29 ns
Clocks are simply signals that cycle between low and high values.
State variables change state only at the clock edge. State changes are
level independent. The edge may be a rising edge on the transition
from low to high. Alternately it can be a trailing or falling edge on
the transition from high to low.
tL tH
tPERIOD
Interaction _____________________
Consider the timing for addressing. The processor asserts the ALE
(address latch enable) line high. This is usually connected to a
74573 latch enable. Then the processors asserts the address on port
0. After adequate set-up time, the processor asserts the ALE low.
This causes the latch to trap the information that was on port 0.
Next the input control line is asserted low. This is the PSEN’ or
RD’. Then the data is brought in on port 0. For writing, the data is
first placed on port 0, then the WR’ is asserted low.
Any chips controlled by these lines, must respond within the time
frame that the line is asserted. Otherwise, the data will not transfer
between the chip and the processor.
⇐⇑⇒
426 Systems Design and the 8051 Durham
⇐⇑⇒
56
Thought
I change my life,
when I change my mind.
Jim Stovall
Each team creates code that looks exactly like all the other. In
addition, variables are commonly defined so each team can access
them.
;
; 8051 has external memory on prom
; 8951 has 4K (07ffH) internal flash eprom
; 898252 has 8K flash & 2K eeprom
;
; To program 8051, burn an external prom/eeprom.
; To program low memory of 8951, burn flash
; To program 898252, program using SPI to port 1.
; P15 = MOSI
; P16 = MISO
; P17 = SCLK
; Ground = common
; Use program AEC_ISP.exe to download from PC
;
; When the uP is reset, it looks at EA'.
; If EA'=0, then external eprom is read.
;
; IF EA'=1, then internal eprom is read.
; Internal eprom is executed until it hits end.
; Then external eprom is used, even if EA'=1.
;
; EA' is pin 31.
; To begin program from prom, strap EA' to 0.
; To use the internal flash, strap EA' to 1.
;
;-----------------------------
;
; The 8951 has 4K (0FFFh) internal flash prom.
; Make the last internal executable line be 0FFFh
; The next instruction will be 1000h on external
; prom/sram.
; So, org the external program to 1000H.
; Initially make program organize to hi memory.
; org 1000H ;external
;
; If it is moved to low memory (onboard flash),
; the address must be known so the hi memory can
; call the routine.
; For example in low memory
; org 0250H ;Next inst @ 0250H
;SCRNDATA:mov ;low mem routine
;
; The high memory PROM/SRAM overlays the same
; space. It is just not available to the uC.
Chapter 56 Extreme Programming Harmonization 433
;#################################################
;
; ASSIGNMENTS
;
;#################################################
;
; Assignments include
; 1. constants for symbols and sizes
; 2. constants for ext mmio addresses
; 3. variables assigned to internal RAM locations
;+++++++++++++++++++++++++++++++++++++++++++++++++
;CONSTANTS
;-----------------------------
;SYMBOLS
Scrl equ 42d ;scroll key,"*",2AH
Entr equ 35d ;enter key,"#",23H
None equ 0FFH ;blank key
;-----------------------------
;EXTERNAL ADDRESS
FilAdH equ 00 ;address file base for DPH
434 Systems Design and the 8051 Durham
;+++++++++++++++++++++++++++++++++++++++++++++++++
;STACK
;-----------------------------
;
; The stack is moved up high to prevent it from
; overwriting data. Stack counts up from the next
; location past the stack pointer base.
;
; The default stack location is 07H. It will over
; write the registers.
;
; Two bytes are used by each interrupt and each
; subroutine call. So enough stack space must be
; reserved for nested loops.
;
; ;STACK RESERVED
; equ 5FH ;Move stack to 60H & above
;
;+++++++++++++++++++++++++++++++++++++++++++++++++
;USER VARIABLES
;-----------------------------
;
; All the RAM locations I used are shown below.
; This is so the user will not overwrite them.
;
; Place any user variables within this range.
;
;-----------------------------
;USER DEFINED VARIABLES
;place user variable here
; equ 5Fh ;
;and everything in between
;+++++++++++++++++++++++++++++++++++++++++++++++++
;DEFINED VARIABLES
;-----------------------------
;
; Defined variables are used by many routines.
; These are fixed locations that should not be
; changed since the order is critical to SqROOT.
;
; Note that the math variables ArgX, RemX, FraX
; locations are shared with TmpX and GapX
; Math procedures are seldom done. When they are,
; the process is completed before other functions
; are attempted. Therefore, there is no conflict.
;-----------------------------
; ;BITS LOCATION
; equ 27H ;last byte reserved for bit
; equ 20H ;first byte for bit usage
;
;-----------------------------
;SCREENS
ScnFil equ 1FH ;File where data is stored
ScnMem equ 1EH ;bytes of memory required
ScnGet equ 1DH ;cursor loc present
ScnCur equ 1CH ;cursor loc desired & temp
ScnDis equ 1BH ;bytes of display space req
ScnTyp equ 1AH ;type data, if #, it is dp
;-----------------------------
;BANK3
QikB equ 19H ;Interrupt HEX value, msb
QikA equ 18H ;Interrupt HEX value, lsb
;-----------------------------
;KEYS
KeyCol equ 17H ;present column number
KeyBit equ 16H ;byte moves a bit w/ column
KeyRow equ 15H ;row number pushed
KeyMul equ 14H ;multiple key count
Chapter 56 Extreme Programming Harmonization 437
;-----------------------------
;BANK2
;R1 equ 11H ;
;R0 equ 10H ;
;-----------------------------
;CHARACTERS, HOLD, COUNT
CharP equ 0FH ;undebounced previous input
CharL equ 0EH ;character to LCD & Serial
MenuL equ 0DH ;loop @MENUS
LatCr equ 0CH ;control latch bits status
ScnDph equ 0BH ;hold DPH
ScnDpl equ 0AH ;hold DPL
;-----------------------------
;BANK1
;R1 equ 09H ;SRAM address, interrupts
;R0 equ 08H ;SRAM address, background
;-----------------------------
;BANK 0, USE W/ MATH & LOOP
LoopC equ 07H ;loop counter
;+++++++++++++++++++++++++++++++++++++++++++++++++
;BITS ASSIGNMENTS
;-----------------------------
;
;AT RAM byte 20H
FgC bit 01H ;temporary for C, etx
FgKeyH bit 00H ;flag key held down
438 Systems Design and the 8051 Durham
;+++++++++++++++++++++++++++++++++++++++++++++++++
;SPECIAL FUNCTION REGISTERS
;-----------------------------
;
; SFR are listed for information. With limited
; assemblers, remove the ; since the address must
; be defined.
;
; ;SFR DEFINED
;B equ 0F0H ;second math register
;Acc equ 0E0H ;accumulator
;PSW equ 0D0H ;processor status word
;IP equ 0B8H ;interrupt priority
;P3 equ 0B0H ;port 3
;IE equ 0A8H ;interrupt enable
;P2 equ 0A0H ;port 2
;SBUF equ 99H ;serial buffer
;SCON equ 98H ;serial control
;P1 equ 90H ;port 1
;TH1 equ 8DH ;timer hi byte 1
;TH0 equ 8CH ;timer hi byte 0
;TL1 equ 8BH ;timer lo byte 1
;TL0 equ 8AH ;timer lo byte 0
;TMOD equ 89H ;timer mode
;TCON equ 88H ;timer control
PCON equ 87H ;power control reg
;DPH equ 83H ;data pointer hi
;DPL equ 82H ;data pointer low
;SP equ 81H ;stack pointer
;P0 equ 80H ;port 0
;-----------------------------
;bit IN SFR
Acc7 equ 0E7H ;Accumulator bit 7
Acc6 equ 0E6H ;accum bit 6
BankH equ 0D4H ;PSW register bank high bit
BankL equ 0D3H ;PSW register bank low bit
Over equ 0D2H ;PSW bit 2, overflow on add
;P equ 0D0H ;parity, PSW
;TI equ 99H ;transmit is complete
;RI equ 98H ;receive is complete
;TR1 equ 8EH ;timer 1 start
;TF0 equ 8DH ;timer 0 overflow
Chapter 56 Extreme Programming Harmonization 439
;-----------------------------
;PORT USE
P33 equ 0B3H ;Port33 Hi=PC Busy,uP no xm
;Not always used in prog
;to use, setb P33 for input
P35 equ 0B5H ;Port35 Hi=uP BUSY,stop ser
;xmit to uP in download mod
;#################################################
;
; PROGRAM
;
;#################################################
org 00H
START:
;-----------------------------
; When processor is reset, program control comes
; here. Jump to the first executable address
; after all interrupts reserved locations.
ljmp INITIAL
;*************************************************
;
; INTERRUPTS
;
;*************************************************
;
; Interrupt set-up is discussed in a later
; section. It is associated with timer/counters.
;
;-----------------------------
440 Systems Design and the 8051 Durham
;INTERRUPT-External 0
;-----------------------------
org 03H
reti
;-----------------------------
;INTERRUPT-Timer 0
;-----------------------------
; The procedure provides direction when timer
; completes count.
org 0BH
ljmp TIMECAL ;interrupt processor
;-----------------------------
;INTERRUPT-External 1
;-----------------------------
org 13H
reti
;-----------------------------
;INTERRUPT-Timer 1
;-----------------------------
; Timer 1 is used for serial. So this procedure
; will never be executed.
org 1BH
;-----------------------------
;INTERRUPT-Serial
;-----------------------------
; This is not used. The bits are polled in
; various other routines.
org 23H
;-----------------------------
;COPYRIGHT
;-----------------------------
; Ownership of program is stored in memory.
org 0033H ;Address past vectors
Chapter 56 Extreme Programming Harmonization 441
;*************************************************
;
; INITIAL & MAIN
;
;*************************************************
org 0080h ;Addres past reserve
; org 2000h ;Address if external
;-----------------------------
INITIAL:
;-----------------------------
; Setup the initial conditions.
;-----------------------------
end
⇐⇑⇒
57
DOCUMENTATION
Thought
The job is not finished,
until the paperwork is done.
Popular quip
Report _________________________
what the project is about. The length should be less than 250
words.
10. A Time sheet should breakout the time invested in each phase of
the project. As a minimum this will be planning, software,
hardware, trouble-shooting, and report preparation.
The first and most obvious practice is to draw a block for each chip.
Label the chip number and its function (e.g. uP, ROM, RAM, etc.)
inside the block. Labeling the chip's function is especially important
when using unusual chips. However, there is one exception to the
block labeling; discrete gate diagrams are discussed below.
Every pin of each chip should be labeled with its function on the
inside of the block and its pin number on the outside of the block.
Some groups of pins have a similar function such as address-bus
pins. These can be labeled as a group instead of drawing a pin-for-
pin representation. Make sure that the pin numbers listed on the
outside of the block correspond appropriately to the pin descriptions
on the inside of the block. For example, A0 corresponds to pin 39.
Power supply connections for the gate need not be specified unless
they are different from the standard. In most cases, power is applied
to the upper right corner pin and ground is applied to the lower left
corner pin. Consider a 14-pin chip. The upper right pin is number 14
and has +5 V while the lower left pin is number 7 and has ground.
Lines of similar function, such as address lines and data lines, need
not be drawn separately. It is common practice to use a single bus
line as long as the line is wider than normal. Draw a slash through
the bus line with the number of lines on the bus. If several, but not
all, lines branch off from the bus, label the branches and make a
new bus line if necessary.
⇐⇑⇒
END
Thought
The end or top of one phase
is simply the beginning or bottom of the next.
Valedictorian speech by K. D. Durham
⇐⇑⇒
AUTHOR