Ez-Micro Manual hc11 But Useful Small
Ez-Micro Manual hc11 But Useful Small
Made Easy
Using the MC68HC11
Raj Shah
President
Advanced Microcomputer Systems, Inc.
Pompano Beach, Florida
Educational Division
Acknowledgments
ACKNOWLEDGMENTS
“Microprocessor Design Made easy Using the MC68HC11” was designed and developed
through the talents and energies of many hard working and dedicated individuals.
The concept of using EZ-MICRO Tutor Board and EZ-MICRO Manager software along with
this workbook in the schools has been well accepted by several community colleges as well as
universities.
ISBN 0-9642962-4-1
Third Edition March, 2000
Fourth Edition January, 2002
EZ-COURSEWARE
Table of Contents
7DEOHRI&RQWHQWV
Lesson 1 Introduction to Microprocessors
Lesson 2 MC68HC11 Architecture and Addressing Modes
Lesson 3 Programming the MC68HC11
Lesson 4 Using the EZ-MICRO Tutor Software
Lesson 5 Software Interface to EZ-MICRO CPU-11
Lesson 6 Introduction to Programming
Lesson 7 Introduction to C Programming
Lesson 8 HC11 Technical Information
Lesson 9 Interfacing Input/Output and Timer Devices
Lesson 10 Serial Input/Output
Lesson 11 Analog to Digital and Digital to Analog Conversion
Lesson 12 Assembler Manual
Lesson 13 Monitor Command
Lesson 14 6811 Commands by Subject
Appendix: A) References
B) Specfications For Liquid Crystal Display Module
C) LCD Driver
D) MC68HC711E9 Technical Summary
EZ-COURSEWARE
Table of Contents
EZ-COURSEWARE
Introduction
EZ-COURSEWARE 1-1
Introduction
Most of us already use products with microcontrollers embedded in them without even knowing
it. Microcontrollers touch almost every facet of daily life and provide sophisticated features to
consumer products at low cost. The following is a short list of some common products that use
microcontroller computers.
Audio equipment. Most CD players have electronic control buttons, digital displays, and
automatic track selection and sequencing — all run by a microcontroller.
Automobiles. Virtually every car in production today uses a microcontroller to control the
delivery of fuel and adjust the spark timing for the engine. Microcontrollers can also be found in
automatic transmissions, anti-lock brakes, and dashboard gauges.
HVAC controllers. You probably know them better as thermostats, the wall devices that
regulate the temperature of our homes and workplace. Unlike the bi-metal devices of old, today’s
smart heating and air conditioning controllers have a microcontroller for a brain.
Microwave ovens. Many microwave ovens can be programmed for various cooking times and
power levels. Some even have sensors that automatically sense the food’s temperature and
change the program accordingly. A microcontroller controls these and other functions.
Security systems. If it weren’t for the microcontroller, which is able to detect motion and verify
passwords, personal and building security would still be stuck in the world of locks and
deadbolts.
All microprocessors and microcontrollers are digital devices, in that they use numbers to direct
and control their actions — as opposed to analog devices, which use quantities like weights and
1-2 EZ-COURSEWARE
Introduction
measures for their data input. For example, a VCR has a microcontroller for its brain, whereas a
toaster usually has an analog bi-metal sensor (its “brain”) that senses the amount of moisture in
the bread and (hopefully) pops up the toast before it burns.
The first digital computer was “invented” when early humans realized that they could count
sheep or bushels of corn using fingers (digits). Since that time, inventors have constantly sought
better, faster, and cheaper ways to count and tally.
The earliest known computing instrument is the abacus, a simple adding machine composed of
beads strung on parallel wires in a rectangular frame, that’s used simply as a memory aid by a
person making mental calculations. In contrast, adding machines, electronic calculators, and
computers make physical calculations without the need for human reasoning. Blaise Pascal is
widely credited with building the first "digital calculating machine" in 1642 as a way to help his
father, who was a tax collector. His machine could add up numbers entered by means of dials. In
1671, Gottfried Wilhelm von Leibniz improved on the design by introducing a special "stepped
gear" mechanism, which let the adding machine do multiplication, too. However, the prototypes
built by Leibniz and Pascal weren’t widely used but remained curiosities until more than a
century later, when in 1820, Thomas of Colmar (Charles Xavier Thomas) developed the first
commercially successful mechanical calculator that could add, subtract, multiply, and divide.
At about the same time (1812), Charles Babbage, a professor of mathematics at Cambridge
University, England, advanced the concept of a “difference engine:” an automatic calculating
machine that many consider to be the forerunner of today’s electronic computer. What Babbage
realized was that that many long computations, especially those needed to prepare mathematical
tables, consisted of routine operations that were regularly repeated; from this he surmised that it
ought to be possible to do these operations automatically. By 1822 he had built a small working
model for demonstration. With financial help from the British government, in 1823 Babbage
started construction of a full-scale, steam-driven difference engine but lost interest in the project
before completing it — partly because the machining techniques of his era weren’t precise
enough to create so complex a device.
Not for another century (1941) was serious attention again devoted to developing a calculating
machine — this time, for generating mathematical tables needed by the World War II armies for
determining the trajectory of ballistics. By now, state-of-the-art electronics had advanced to the
point where mechanical devices weren’t even a consideration. The first electronic calculator was
the ENIAC (for Electrical Numerical Integrator And Calculator), which used 18,000 vacuum
tubes, occupied 1,800 square feet of floor space, consumed 180 kW of power (enough energy to
power a city of 30,000), and ran hot enough to supply all the heat needed to warm the seven-
story building it was housed in. The vacuum tubes were soon replaced with transistors (1955),
which were supplanted in turn by the integrated circuit in 1964.
EZ-COURSEWARE 1-3
Introduction
different courses of action depending on the specific inputs it’s been given, especially input from
previous calculations. For example, a computer used in a payroll department will “look” at how
many income tax deductions a particular employee has chosen, then look at the employee’s gross
salary, and then access the right look-up table based on both factors to decide how much tax to
subtract from that person’s paycheck. Similarly, a computerized cash register in a supermarket
can “remember” to add sales tax at the end of your bill for the paper towels and laundry soap in
your grocery cart, but not for your tax-free onions and chicken wings. This is what separates a
calculator from a computer: the ability to choose a course of action dependent on the outcome of
a previous calculation. Some call it “machine reasoning.” It has since come to be known as
programming.
At first machine reasoning wasn’t all that swift—mostly because the electronics of that time
wasn’t all that advanced. Where today’s Pentium processors sport more than 3 million
transistors, the semiconductor makers of twenty years ago were hard pressed to fit a couple
thousand transistors on a silicon chip.
The first microprocessor chip was Intel’s 4004, a 4-bit processor that contained 2300 transistors
and ran at 100 kilohertz (100 kHz). One hertz (Hz) is the time it takes for an electrical signal to
swing from positive to negative and back again. For example, the power outlet that you plug
your TV and VCR into changes polarity 60 times a second, or 60 Hz. A kilohertz is 1000 Hz. In
the computer world, the higher the hertz rating, the faster things get done. Today’s
microprocessors run at 66 megahertz (66 MHz) and faster.
The 4004 was invented as an engineer’s lark that actually turned into a product looking for an
application — blue sky stuff. Fortunately, it did find a home — in more than a few Sears hand-
held calculators. And for good reason. Unlike an adding machine, the 4004 didn’t know how to
add or subtract; it was simply a logic chip. Instead, it had something better — it had reasoning
plus it had memory. Essentially, it had all the answers to any math calculation stored in an area
on the microprocessor chip called read-only memory (ROM). Hence, the calculator knew the
answer to your math question before you asked. All it had to do was look it up in one of its many
tables.
When people first started counting, they used the obvious — their ten fingers (including
thumbs). When our caveman ran out of fingers, he made a mark on the cave wall, or whatever,
and started counting on his fingers again. This led to our present 10-base decimal system.
Whenever a number is larger than ten, it assumes a new position in the tally. For example, 91
means there are nine sets of ten plus one. A 10-base counting system isn’t the only one possible,
1-4 EZ-COURSEWARE
Introduction
though. The Mayan Indians of Central America developed a numerical system based on the
number 20. Obviously they included toes as well as fingers.
The computer lacks fingers and toes, but true to its electrical nature it recognizes two values: on
and off. If the signal is on, it represents a one (1); if it’s off, it represents a zero (0). This method
is called binary counting. Each digit in the binary system is a power of two, which means the
progression is 1, 2, 4, 8, 16, 32, 64...and so forth. In binary, the number 91 is written as 1011011
(64 + 16 + 8 + 2 + 1). A binary digit is called a bit. If a binary number is 4-bits in length, it’s
called a nibble; 8-bits is a byte. Generally, computer power is expressed in kilobytes. One
kilobyte (which is actually 1024 bytes) is written as 1K (note that the “K” is capitalized). String
1,000 K together and you have a megabyte, or 1MB.
Simple Microcontroller
The 8080 could address 64K of memory (the 4004 could manage only 4K) and was an instant
success with aspiring computer companies like Atari. Within a year (1976) Intel introduced the
8085, which was basically the 8080 with built-in peripheral logic. (We’ll explain peripheral logic
in Lesson 2.) By now the technology had advanced to the point where it was possible to place
tens of thousands of transistors on a silicon chip, so a lot of space became available for what
used to be outboard functions, such as counters and timers. It wasn’t long before other silicon
foundries jumped on the CPU bandwagon, Zilog with its Z80 (a faster version of the 8080, and
undoubtedly the first CPU clone) and MOS Technologies with its 6502. Motorola entered the
fray in 1975 with the 8-bit 6800 microprocessor.
By 1978 the personal computer movement was in full stride. The 8080-based Tandy TRS-80
had appeared in 1977, as did the 6502-based Apple II, and the 6502-based Commodore PET
made its debut in 1979. By 1980 the market was flooded with dozens of 8080- and Z80-based
EZ-COURSEWARE 1-5
Introduction
machines, most of them from small companies with few resources and even smaller production
capabilities. It wasn’t until the advent of Intel’s 8088 in late 1979 that big industry took notice of
this burgeoning market.
The 8088 is essentially the same chip as the 8086, in that its internal data path is 16-bits wide.
The CPU can process two bytes of information at the same time, thereby increasing throughput
and performance. What Intel did with the 8088 was retain the 16-bit CPU core, but reduce the
width of the external bus down to 8-bits. Unfortunately, the 8088 was considerably slower than
the 8086 because it had to access the 8-bit bus twice before it could process data: once to get the
8-bits near the bottom of the bus and again to input the upper 8-bits. Both the 8086 and 8088 had
20 address lines, which gave them a memory capacity of 1MB — 16 times more than the 64K
offered by the 8080, 6800, and 6502.
About the same time, Motorola not-so-quietly introduced its first 16-bit microprocessor: the
68000. Unlike Intel’s 8086/8088, the 68000 had 24 address lines that provided access to 16MB
of memory — an amount of memory so humongous as to seem mindboggling at the time. Seeing
the potential, Apple immediately scooped up the new CPU for use in its new Macintosh
computer. Zilog put up a gallant, but unsuccessful, battle to stay in the 16-bit race by introducing
the Z8000, an 8086 compatible.
Keeping a tight hold on the reins, Intel immediately began bolstering its line of 16-bit CPUs.
First was the 80186, which was an 8086 with several common support functions built right in:
clock generator, system controller, interrupt controller, DMA (Direct Memory Access)
controller, and timer/counter. However, the 80186 wasn’t used as a mainstream CPU for desktop
computers, instead finding a short-lived niche in single-board processors for industry.
Next was the 80286, which made its debut in IBM’s Personal Computer AT (the AT stands for
Advanced Technology) in 1984. The 286, as it’s commonly called, paved the way for the
advanced Intel-compatible CPUs of today by expanding the number of memory address lines
from 20 to 24, resulting in 16MB of memory space — equal to that of Motorola’s 68000. But by
this time there was a large base of programs written for the 20-bit-wide address space of the
8086 and 8088. To advance the technology without abandoning existing software, the 286
introduced a new mode of operation called protected mode. Basically, any program written to the
old 8086 standard would run on the new 286 using the standard 1MB of memory provided by the
1-6 EZ-COURSEWARE
Introduction
8086 and 8088, while providing a path to the upper 15MB of memory without conflict. Despite
heroic attempts (EMS expanded memory is one), though, DOS-based programs still couldn’t
break through the 1MB barrier without dragging down the speed of the system to a crawl — or
worse, crashing the system. It wasn’t until the release of Microsoft’s Windows (a powerful,
graphics-based overlay on the DOS operating system) that software programs were able to take
full advantage of the full 16MB.
By 1985 the field had narrowed to two dominant suppliers of microprocessors: Intel and
Motorola. AMD, a prominent silicon foundry, joined this elite circle as a second source for both
giants (an infusion of cash and exchange of technology that later led AMD to successfully
develop its own line of CPUs). Hitachi, too, took a stab at second-sourcing Motorola products,
but it didn’t last long (mostly Hitachi acquired the technology for use in its custom products,
which included a long list of consumer microcontrollers for use in everything from automobiles
to VCRs).
Over the next few years, Intel released several versions of the 386 microprocessor, most of
which differed only in speed. In 1988 Intel introduced the 386SX, which was the 386 equivalent
of the 8088. Built around a 32-bit core, the 386SX used multiplexing to reduce the data bus to
16-bits. Like the 8088, it took two passes at the input data before the instruction command could
be executed. While the performance of the 386SX was significantly lower than the 386, so was
its price. It was, finally, a 32-bit system that John Q. Public could afford. Another version of the
386, the 386SL, came in 1990. Basically, the 386SL is identical to the 386SX, but it also
includes power-management circuitry that optimizes the device for use in portable computers —
a first for Intel and the industry.
Meanwhile, Motorola was busy grooming its 32-bit microprocessor, the 68020, which came
fashionably late to the 32-bit party in the summer of 1985. Like the 386, the 68020 could directly
address 4GB of memory. But Motorola upstaged Intel by incorporating a built-in memory cache
of 256 bytes, a small amount of extremely fast memory that contains the last-used instructions
for quick access. A good analogy is your kitchen cupboard. Let’s say that you just used the bottle
of soy sauce and put it on the counter where you’re working within easy reach — this is a cache.
Now if the bottle isn’t within easy reach, you go the cupboard and start searching for it, which
takes more time. This is the same as searching through the motherboard’s random-access
memory (RAM). If it turns out that you are out of soy sauce, then you have to hop in the car and
go to the supermarket. This is the same as going to the hard disk for information. Before the
EZ-COURSEWARE 1-7
Introduction
development of the 68020, only big mainframe computers had cache capacity — desktops
didn’t.
Shortly after the announcement of the 68020 came the 68030, which had an additional 256-byte
cache for data — for a total of 512 bytes (0.5K). While small by today’s standards, it was the
first time caching was introduced into the world of desktop computing as a speed enhancement.
For Motorola to put the cache on the chip itself as a primary cache, as opposed to secondary
cache (which is placed on the motherboard) was unprecedented and a notable landmark. In fact,
it took Intel four years to catch up to the new technology.
So it took no time at all for Intel to switch to testing its 486 chips for CPU performance first, and
follow up with a math coprocessor check. Those chips that passed the first phase but flunked the
math were labeled 486SX, and went into lower-priced, conventional desktops without math
processors. Those chips that passed their math tests went into a higher-priced model, now called
the 486DX. As yields improved, and demand for the lower-priced 486SX increased, the 486SX
selection process was winnowed down to testing the CPU only, with a subsequent blowing of the
fuse that fed power to the math coprocessor (just in case the math coprocessor was functional,
but flawed).
Another important feature of the 486 line was the introduction of 3.3-volt technology —
something that Motorola couldn’t match until two years later. Up to 1990 microprocessor logic
was based on a 5-volt power supply. However, the amount of heat a semiconductor generates is a
function of speed multiplied by voltage. By 1990, the speed of computer chips (both
microprocessors and external logic chips) hit a heat barrier — if they went any faster, they’d
simply burn up. Reducing the voltage reduced the heat build-up and let the chips run faster. By
the year 2000, it’s expected computer chips will run at 500 MHz using 0.9-volt power sources.
What was Motorola doing all this time? It was busy working on the 68060, a third generation
68000 chip that introduced the concept of superscalar pipelining, a technique again borrowed
from mainframe technology, which permits multiple instructions to run at the same time. This
chip saw the light of day in early 1994. Motorola was also busy developing a line of
microcontroller chips, like the 68HC11, which we’ll talk about at length starting with Lesson
Two.
1-8 EZ-COURSEWARE
Introduction
EZ-COURSEWARE 1-9
Introduction
and 8K for data. The Pentium also sports a superscalar pipeline. While the fastest Pentium sold
today runs at 100 MHz, there’s a 150-MHz version lurking in the wings, just waiting for its
debut.
At about the same time, Motorola conceded that after more than a decade of development, its
68000 architecture had run out of steam. Instead of continuing as a solo act, though, Motorola
decided to hook up with IBM and Apple in a three-way consortium to meet the enormous
demands of the new 64-bit market. The result was the PowerPC, a 64-bit superscalar CPU that
can effectively execute up to three instructions at the same time, compared to the Pentium’s two
instructions. Like the Pentium, the PowerPC can address up to 4GB of memory, and has a built-
in math coprocessor. A pleasant surprise is 32K of cache memory, double that of the Pentium.
The PowerPC is the first desktop microprocessor to implement RISC (Reduced Instruction Set
Computing), a type of instruction code first used by IBM in its high-end workstations. With
RISC, most instructions execute in only one clock cycle (one clock cycle is equal to one hertz),
and instructions can even be completed out of order. By comparison, all Intel processors,
including the Pentium, use CISC (Complex Instruction Set Computing) instructions. While CISC
instructions are longer and can do in one statement what it takes RISC 100 instructions to
accomplish, RISC runs a lot faster. The drawback is that RISC processors require special coding,
which means the enormous base of Intel software can’t run on the PowerPC without translation,
and the time it takes to translate the code slows the PowerPC to a crawl — literally. Performance
is about the same as an old 386 system. This potentially-perilous battle between the Pentium and
the PowerPC chips is reminiscent of the Betamax-VHS videotape tug-of-war, which left
bloodied losers on all sides (especially the consumers who bet on the Beta). Hopefully, Apple
and IBM working together will command enough clout that this market won’t be ignored, but
will inspire ample software written specifically for the PowerPC chip as it is for the Intel chips
of the present.
1-10 EZ-COURSEWARE
Introduction
Lesson 1 Questions
1) What is a microprocessor?
3) Name three or more household appliances that contain microcontrollers, and explain the
microcontroller’s function in each product.
8) Can you think of other common examples (besides the ones given in this chapter) of machine
reasoning/computer logic?
11) How many bits are in a byte? How many bytes are in a kilobyte?
13) What is the difference between 8-bit, 16-bit, and 32-bit microprocessors?
14) How does multiplexing work, and what are the advantages of using multiplexing?
15) What advantages do computers gain from scalar and superscalar architecture?
17) Why are computer manufacturers eager to lower the voltage of the power supplies in their
microprocessors?
EZ-COURSEWARE 1-11
Introduction
1-12 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
EZ-COURSEWARE 2-1
MC68HC11 architecture and addressing modes
Because many colleges and trade schools now require at least one microcomputer course that
includes hands-on laboratory work programming and using microcontrollers, EZ-Courseware
includes a microcontroller development system based on Motorola’s very popular — and very
powerful — 68HC11 microcontroller chip.
This lesson contains details of the 68HC11’s internal subsystems and functions. While the
information in this lesson is much more detailed than would usually be required for normal use
of the microcontroller, a user who is familiar with the detailed operation of the part is more
likely to find a solution to an unexpected system problem. Often a trick based on software or
MCU resources can be used rather than adding expensive external circuitry. This is particularly
true of the 68HC11 family of MCUs, which includes many built-in hardware features like timers
and I/O port translators.
68HC11 Overview
The 68HC11 is a family of 8-bit microcontrollers fabricated using High-Density Complementary
Metal-Oxide Semiconductor (HCMOS) technology. HCMOS provides smaller size and higher
speeds than standard CMOS, yet retains CMOS’s high noise immunity and low power
consumption. In addition, the technology is a fully static design which allows for operations
from 3 MHz down to dc that further reduces power usage, making it ideal for use in battery-
operated equipment. Several of the 68HC11 MCUs have a low-voltage counterpart, using the
68L11 designation, that can operate over a voltage range of 3.0 to 5.5 volts.
All members of the 68HC11 family are software compatible. They differ only in their hardware
features, mostly in the size and type of the built-in memory and the input/output functions. Table
2-1 lists the different versions of the 68HC11 and the unique features of each one.
2-2 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
The alphanumeric code for this family of MCUs is shown in Figure 2-1. When a feature applies
to all family members, the general coding sequence of MC68HC11 is used, although this is
frequently shortened to just 68HC11. When talking about a specific part, the last two characters
define the part’s features and the amount of built-in memory. For example, A0 tells us that the
device has 22 I/O lines with 256 bytes of Random Access Memory (RAM); an A1 designation
adds 512 bytes of Electrically Erasable Programmable Read-Only Memory (EEPROM) to the
chip.
EZ-COURSEWARE 2-3
MC68HC11 architecture and addressing modes
2-4 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
The main 16-bit, free-running timer has three input-capture lines, five output-compare lines, and
a real-time interrupt function. An 8-bit pulse accumulator can count external events or measure
external time periods. A watchdog circuit protects against software failures by automatically
resetting the MCU in case the clock is lost or runs too slow. And there are 40 I/O pins that link
you to the real-time outside world.
Don’t let the above terms frighten you. They simply describe the power of the 68HC11 in a
nutshell. In the following sections of this lesson, the building blocks of the 68HC11 will reveal
themselves as we examine each in detail.
EZ-COURSEWARE 2-5
MC68HC11 architecture and addressing modes
Registers
Central to the CPU’s operation are internal registers — a special type of imbedded memory that
can manipulate operation instructions and temporarily store data. The CPU registers are an
integral part of the CPU and are not accessed in the same way as the other registers in the
68HC11. Most of the time these registers are accessible only through opcodes. The 68HC11
CPU contains sevens registers, which are shown in Figure 2-3. The function of each of the CPU
registers is discussed in the following sections.
ACCUMULATOR A ACCUMULATOR B
ACCUMULATOR D
INDEX REGISTER X
INDEX REGISTER Y
STACK POINTER
PROGRAM COUNTER
Accumulators (A and B)
Any general-purpose register that holds a data number is called an accumulator. The 68HC11
CPU has two 8-bit accumulator registers, labeled A and B. The data number in an accumulator
may be the result of an instruction — for example, the sum or two numbers — or used as a
staging area to hold pending opcodes.
While most operations can use accumulator A or B interchangeably, there are some operations
that use only accumulator A or accumulator B. They include:
2-6 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
4. The add, subtract, and compare instructions involving both accumulators A and B
(ABA, SBA. and CBA) only operate in one direction; therefore, it is important to
plan ahead so the correct operand ends up in the correct accumulator.
Although the 68HC11 is an 8-bit device, there are several instructions that permit 16-bit
operations. These instructions use both accumulators A and B as a single 16-bit register known
as accumulator D. As you will see in Lesson 3, a 16-bit accumulator saves programming steps
when binary values greater than 8-bits are being manipulated. Because accumulator D is a
combination of two already-defined registers, it is not counted as a separate register.
The two 16-bit index registers, X and Y, are used for the indexed addressing mode (explained in
Section Two below). These registers contain the memory addresses of data to be used for the
next operation or operations. The 68HC11 family is unique in that it has two index registers; its
predecessors had only one. The second index register is especially useful for moves and in cases
where operands from two separate tables are involved in a calculation — like choosing from
column A and column B in a Chinese menu. In the earlier 6800 CPUs, the programmer had to
store the index to some temporary location so the second index value could be loaded into the
index register, which is like having column A and column B on separate menus on separate
tables, and you running between the two tables to place an order. Obviously, two index registers
are faster than one.
The 16-bit stack pointer register controls the operation of the stack. The number in the stack
pointer is a memory address of where the stack begins. Normally, the stack pointer register is
initialized by one of the very first instructions in an application program. Each time a new byte is
added to the stack, which is called a push operation, the stack pointer number is automatically
reduced by one, and each time a byte of data is retrieved from the stack, called a pop, the stack
pointer is automatically incremented by one. Stacks are usually last-in-first-out (LIFO)
structures, which means the last element pushed onto the stack is the first one popped from it.
EZ-COURSEWARE 2-7
MC68HC11 architecture and addressing modes
The five status bits, also called status flags, reflect the results of arithmetic or Boolean logic
operation. The stop bit is used to enable or disable the stop instruction. Some programmers
consider the stop bit dangerous because it stalls the oscillator, which can lead to a system crash if
you are not careful.
The interrupt masks are used to disable all or selected CPU and MCU interrupts. Like the
instruction register, most of the 68HC11’s interrupts are invisible to the user. In the 68HC11,
interrupts are signaled by flags. Once during each machine cycle the interrupt flags are checked
to see if any are set. A set flag indicates an event has occurred that needs immediate attention. If
no flags are set, the CPU takes no action and proceeds to the next instruction. If a flag is set, the
CPU may act upon it immediately using built-in firmware or notify the software of the situation
via the condition code register. A detailed analysis of 68HC11 interrupts is given in Section Four
of this lesson.
Memory
As important as the CPU is to a MCU, it would not be a microcontroller without on-chip
memory. Onboard memory is what separates a microprocessor, like Intel’s Pentium chip, from a
microcontroller: microcontrollers have built-in memory, and microprocessors don’t. Computer
memory falls into four major categories:
2-8 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
1. Read/write memory, which allows the CPU to both write numbers into storage and
read them back later.
2. Read-only memory, which holds hold numbers in storage that cannot be altered —
the numbers are permanent.
3. Volatile memory, which loses the information stored in its memory banks when
electrical power is removed.
4. Nonvolatile memory, which uses a storage technology that does not require
electrical power to retain information.
The type of memory that is appropriate for any particular application depends on the application
and where you are in the design cycle of the product. The 68HC11 supports four different types
of memory:
The size and type of memory included in any particular 68HC11 chip varies. For example, the
68HC11A8 has 256 bytes of RAM, whereas other members of the 68HC11 family have RAM
that ranges in size from 192 bytes to 1K. Some support ROM and EEPROM, others don’t. Refer
to Table 2-1 for details.
RAM
Random access memory is included in all 68HC11 MCUs. Unlike the other 68HC11 memory
options, RAM is the only memory that is fast enough for real-time read/write operations.
Generally, RAM is volatile memory because it needs periodic refreshing to keep the data alive.
While still volatile — in other words, if you loose power, you loose everything in RAM —
68HC11 RAM memory is static. Which means if the clock stalls your data isn’t lost. As soon as
the clock starts up again, the program picks up where it left off. The RAM memory in desktop
computers is dynamic memory, which looses its data when the clock stops.
As mentioned, the size of the RAM varies according to 68HC11 device type. The more RAM
you have, the more items you can juggle at the same time — but the more the MCU will cost. So
there is a tradeoff here, and finding the right size RAM for your application may take some
serious forethought on how compactly the program code can be written, or how you can trim the
end-product’s features to meet the target price.
EZ-COURSEWARE 2-9
MC68HC11 architecture and addressing modes
ROM
The primary purpose of the read-only memory is to hold the user’s application program, which
ideally holds all coding so that the only external input comes from an I/O port device, and not
the user. While not as fast as RAM, ROM is cheap, which means you can afford to buy a lot of
it. A 68HC11AK2 can support up to 32K of ROM, with the 68HC11A8 sporting 8K of ROM.
Unlike RAM, once a software routine is programmed into a 68HC11 ROM, it is forever carved
in stone. There is nothing you can do to change it. Your program codes are placed into the
MCU’s ROM at the time the MCU is fabricated using masks that produce a memory matrix
pattern that clones your program on the chip as it comes off the assembly line. While the cost of
making the mask is high initially, if thousands of ICs with the same code are manufactured, the
cost of the masks is inconsequential. A typical application for a masked ROM is a high-volume
product containing a MCU, like those used in microwave ovens, cassette players, and other
consumer products.
EPROM
When only a few devices are required for low-volume products or lab development, the cost of a
masked ROM is prohibitive. A less expensive and more flexible alternative is to substitute the
ROM with an EPROM. Virtually all versions of the 68HC11 have an EPROM equivalent. The
cost of the MCU is slightly higher, but you save the expense of making a ROM mask.
EPROM-based MCUs are more flexible because it’s easier to make changes in the design. For
example, let’s say an unexpected bug occurs in your original software model six months after the
product has been shipping. If the MCU is ROM-based, this means you have to go through the
expense of creating a new ROM mask. With EPROM MCUs, all you have to do is make changes
in your software and start programming the new devices with the fixed code. Better yet, it is
possible that the defective products already shipped can be fixed in the field by reprogramming
the old MCUs, if you choose the right EPROM part.
The EPROM works on the principle of a charged capacitor. Essentially, a capacitor is used to
turn a transistor on or off, depending on whether the capacitor is charged or not. If the transistor
is turned on, it represent a binary one; turned off, it represents a zero. Once charged, the
capacitor will retain its charge for many years. The thousands of capacitors inside the EPROM
are properly charged using a PROM programming device. (You will learn how to use one of
these programming machines later in this course.)
Discharging the capacitors erases the EPROM’s memory. This is done by shining an ultraviolet
(UV) light on the top of the chip, which causes the charge to leak off the capacitors. Erasing the
EPROM requires a special, intense UV light source of a certain color, and the process generally
takes 15 minutes and longer. This is done on purpose to prevent the EPROM from accidentally
being erased by exposure to ambient room light or sunlight. Once erased, the EPROM can be
reprogrammed. This lets you fix a bug in existing products, or permits you to use the MCU for
another application.
For it to work, though, the EPROM has to be erasable, which means the MCU has to come in a
ceramic package with a quartz window built into its top. This packaging is more expensive than
2-10 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
plastic packages, which are not erasable. In applications where it is desirable to program the
memory during assembly and where erasing is unnecessary, you can save money by buying an
EPROM MCU in a plastic package.
Unfortunately, like sunburns, constant exposure to intense UV light takes its toll. Most EPROMs
can only be erased and programmed about 100 times before they wear out and fail. Another
disadvantage of EPROM is it must be removed from the circuit for erasing and programming.
This means the MCU has to be socketed to allow removal. Sockets are costly and less reliable
than soldering.
EEPROM
Electrically erasable programmable read-only memory gives you the best of both worlds —
easily erasable data with in-circuit programming. EEPROMs are ideal for use in prototype
devices and during the development (R&D) stage of a product because the memory can be
changed over and over again with little effort.
The storage mechanism in the EEPROM is the same as for the EPROM: an electrically-charged
capacitor. The difference between the two is that the EEPROM has an electrical erasing circuit
built into it; it does not need a UV window. The MCU controls the erasing hardware through
software. Moreover, the erasing procedure takes but a few milliseconds instead of minutes.
Better yet, the typical lifetime of an EEPROM is many thousands of cycles.
Despite the ability to erase and write numbers electrically, though, EEPROM memory is not
read/write. The write time is much too long for real-time read/write, which needs nanosecond
response times. Like the EPROM, it is nonvolatile read-only memory.
Flash Memory
While it is not a 68HC11 option, you’ve probably heard of flash memory, the newest type of
nonvolatile user-programmable memory. The reason for bringing this up is because some
members of Motorola’s 68HC16 16-bit family of microcontrollers have on-chip flash EPROM.
And it is conceivable that flash memory may appear in a future version of a 68HC11 MCU
because the technology can pack a lot of memory in a very little space.
Moreover, not all of your designs will be limited solely to the memory on the MCU. There will
be plenty of times when you need to add outboard memory. In many circuits, flash EPROM can
replace UV-erasable EPROM and EEPROM for nonvolatile storage of programs and data —
something to keep in mind, considering the flexibility and low price of flash memory.
“Flash” describes the ability to erase an entire array of memory at once, or “in a flash.” Well,
almost in a flash. Both RAM and EEPROM are faster. Because the flash EPROM is electrically
erasable, it can be erased and programmed in-circuit, eliminating the need to have a socket.
Again, the flash memory’s storage technology is based on that of a charged capacitor driving a
transistor. Like UV-erasable memory, flash memory must be erased before it can be
programmed. On-the-fly overwrite, like RAM and EEPROM supports, is not permitted. With
some flash EPROMs, you erase the entire device at once. Others divide the memory into several
blocks, each of which is individually erasable.
EZ-COURSEWARE 2-11
MC68HC11 architecture and addressing modes
Unfortunately, the flash EPROM has an erase speed of about 1 second, far too slow for real-time
read/write performance. Their life span is about 10,000 cycles, the same as an EEPROM. And
they are more expensive than UV-erasable EPROMs, but less expensive than EEPROM. In other
words, flash EPROM fills the price/performance gap between cheap UV-erasable EPROM and
expensive EEPROM. See the comparison chart in Table 2-2 for more details.
CONFIG Register
The CONFIG register is an unusual control register used to enable or disable ROM, EEPROM,
and the EEPROM security feature of the 68HC11. Unlike ordinary control registers, CONFIG is
an EEPROM register that retains its contents after all power is removed from the chip (e.g.,
when shipped from the Motorola factory). However, the contents of this register can be altered to
meet the demands of your the end-user customer, making it a powerful tool for custom designs.
You will hear more about this register as you proceed through this lesson.
2-12 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
Unlike the CPU, though, these registers cannot be accessed via opcodes. Instead, they are located
in the 68HC11’s memory — be it RAM, ROM, EEPROM, or any combination of the three —
along with the software application data. Because these registers reside in the main memory
section of the MCU, they are located at protected addresses within the 64K address range of the
CPU — reserved memory locations that are off limits to anything but opcodes and instructions.
Accidentally writing application data in one of these addresses will crash the system faster than
you can say “oops.”
In the 68HC11 family of MCUs, memory address locations between hexadecimal 0000 through
003F are reserved for the microcontroller’s I/O registers (see Table 2-3 for a copy of the 68HC11
memory map). This method of having I/O registers as easily addressable as data memory
locations is called memory mapped I/O.
EZ-COURSEWARE 2-13
MC68HC11 architecture and addressing modes
2-14 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
EZ-COURSEWARE 2-15
MC68HC11 architecture and addressing modes
Addressing Modes
The 68HC11 has six addressing modes which can be used to reference and access memory:
1. Extended
2. Direct
3. Immediate
4. Inherent
5. Indexed
6. Relative
All MCU instructions consist of two parts — an opcode followed by an effective address. The
effective address is where the data is located. How many steps the instructions have to go
through to address and access the 68HC11’s registers impacts significantly on the speed of the
application, and the complexity of the programming code.
The following provides an overview of each of the six addressing mode. Complete programming
details on these addressing modes will be taken up in later lessons.
Extended
The extended address mode is the most robust of the six. As mentioned above, the 68HC11 uses
16-bit addresses. Unlike other addressing modes, the full 16-bit address of the targeted memory
area is contained in the extended addressing instruction code, which is why it is often referred to
as the absolute addressing mode. The minimum extended address mode instruction code consists
of three bytes: at least one opcode byte and the two address bytes.
Extended addressing has the advantage that it is less sensitive to address locations or hardware.
The instruction works the same at any location in memory. Moreover, the data number can also
be anywhere in the memory. The hardware does not care about either, because everything about
extended addressing is explicit.
Direct
The direct address mode takes advantage of the MCU reserved memory area between
hexadecimal memory addresses 0000 and 00FF. (Remember the first reserved register address
does not begin until 1000). This area contains 256 bytes of RAM common to all 68HC11 MCUs
(except the 68HC11D0 and 68HC11D3, which are limited to 192 bytes). This area is reserved
exclusively for temporary data storage.
Because the first address byte of this memory space is always 00 (00FF being the highest
memory location), addressing overhead can be reduced from two bytes to one byte. In fact, that
is what direct addressing does. In the direct addressing mode, the high-order byte is assumed to
be 00, so only the lower byte (00 through FF) has to be included in the instruction. This reduces
the instruction from three bytes to two bytes, one for the opcode and one for the least-significant
byte (LSB) address, which takes less time to execute. Moreover, it is fast RAM memory, which
speeds things up even more.
2-16 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
Immediate
In the immediate addressing mode, an address is not needed. The opcode itself seeks out the
register specified by the instruction, and immediately inserts the two or more bytes of data
following the opcode into the specified register. While an immediate addressing instruction is
three or more bytes in length, its operation is very fast because no additional clock ticks are
needed to locate the data in memory and then load it into the register. Everything, opcode and
data, is built into the immediate addressing instruction.
Inherent
Some opcode instructions do not need either an address or data byte. These opcodes are simply
an instruction that causes an operation to take place. A perfect example is the ABA instruction,
which tells the CPU to add the contents of the B accumulator to the contents of the A
accumulator, then put the sum into the A accumulator. This mode of operation in called inherent
addressing.
Indexed
The index addressing mode uses the X and Y index registers. These registers contain the
memory address of data to be used for the next operation or operations. Indexed addressed
instructions contain an opcode and an offset byte. The instruction forms the effective address by
adding the offset byte to the number in the index register. This method has the advantage that the
offset byte is only one byte, whereas the number contained in the index register is two bytes,
which means you can point to an absolute address using only two bytes of code instead of the
three bytes needed by the extended addressing mode.
Relative
Like indexed addressing, relative addressing uses an offset byte to locate data in memory. This
time, though, the relative addressing mode is used only for branch instructions. With but a
couple exceptions, relative addressed instructions require two bytes of code: an opcode and the
relative offset byte. The offset byte can be any value between -128 and +127 bytes. If the branch
condition is true, the offset value is added to the contents of the program counter to form the new
effective branch address. There will be more on branch programming in Lesson 6.
EZ-COURSEWARE 2-17
MC68HC11 architecture and addressing modes
Like the CPU, the I/O ports are controlled by internal registers. Figure 2-5 shows the registers
and control bits connected with parallel input/output operations. These registers and control bits
are used to specify the direction of data flow at each bidirectional port pin, as well as to let other
on-chip subsystems share use of the I/O pins.
2-18 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
Port A
Port A is a general-purpose I/O port that shares its 8 pins with the main timer system and the
pulse accumulator system. The PORTA register, at hexadecimal address 0000, controls the
digital input and output functions of pins PA0 through PA7 (the actual pin number depends on
which package you choose; see Figure 2-6 for an example). Pins PA0, PA1, and PA2 are input
only. Pins PA3 through PA6 are output only. Pin PA7 is bidirectional and its direction is
determined by the data direction bit (DDRA5) in the PACTL register.
While the PORTA register may be read at any time. writing to the PORTA register controls the
corresponding output pins only if they are not controlled by the timer. Details on port A’s timing
features are given in Section Four of this lesson.
Ports B and C
Port B is a general-purpose, 8-bit output-only port, whereas port C is a general-purpose 8-bit
bidirectional port. Ports B and C are used for both data I/O and address I/O, depending on the
operating mode of the 68HC11. When the MCU is in the single-chip mode, these 18 pins are
used for general-purpose input, output, and handshaking. When the MCU is in the expanded
mode, these pins are used for a multiplexed address/data bus.
The mode select pins, MODA and MODB, are used by the 68HC11 to select the operating mode
during reset. After reset, the MCU no longer requires input on these pins to keep the device in
the selected mode, and they may be used for their alternate function of load instruction register
(LIR) indicator and the standby power (VSTBY) source to keep the MCU’s RAM alive when main
power is not present, respectively. These pins are available to you in your EZ-COURSEWARE
microcontroller development system.
EZ-COURSEWARE 2-19
MC68HC11 architecture and addressing modes
There are two handshaking pins associated with these ports when in the single-chip mode,
named STRA and STRB. The STRA pin is an edge-detecting input that causes port C data to be
latched into a special internal latch register (PORTCL) located at hexadecimal address 0005. The
active edge for STRA is software selectable, making it easy to interface this pin with a wide
variety of peripheral devices and timing schemes. The STRB pin is an output strobe associated
with the handshake I/O functions of ports B and C to indicate valid data is available on the port
B output lines.
Controlling this show is the active-high latch enable AS signal and R/W signal. Address
information is allowed into the external latch when AS is high, and the stable address
information is latched when AS is low. The E-clock (see Section Four below) is used to
synchronize external devices to drive data into the CPU during the second half of the read bus
cycle. The R/W signal indicates the direction of the data: high for read, low for write.
Port D
Port D is a 6-pin bidirectional port that can be configured as either general-purpose I/O lines or
as an interface to the 68HC11’s internal serial communications subsystem. Officially known as
the serial peripheral interface (SPI), this serial interface is primarily used to communicate with
serial peripheral devices, like a telephone modem or liquid-crystal display (LCD).
Unlike the parallel port communications methods of the B and C ports, which can send or
receive an 8-bit byte in a single E-clock tick, only a single bit can be sent at once through the
serial port — making serial I/O communications about twelve times slower than parallel I/O
communications when you count the control bits needed to keep things in sync.
2-20 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
The SCI can operate over a wide range of baud rates. Essentially, the baud rate is equal to the
number of bits per second (bps) you can push data through the two wires that make up a serial
connection. The baud rates range from 75 bps up to 131, 072 bps. The 68HC11 supports both
synchronous and asynchronous serial communications.
For asynchronous communications, pin PD0/RxD is used to receive serial data and pin PD1/TxD
is used to transmit serial data. In asynchronous communications, the synchronizing signals are
embedded into the data stream, making it the slowest form of I/O communications.
The other four lines of port D can be configured for synchronous serial communications.
Basically, the two protocols differ in that synchronous handshaking signals are sent over two
separate pins and the data over another two, rather than embedded in the serial data stream as in
the asynchronous mode. While synchronous communications is faster than asynchronous, it
requires more hardware. Virtually all telephone modems are two-wire asynchronous, whereas
many factory sensors are four-wire synchronous for faster MCU response.
Port E
Port E is an 8-bit input port used for general-purpose digital inputs and/or analog voltage signals.
This port supports the following inputs:
These inputs are designed so that the digital input buffers are disabled at all times except for part
of a cycle during an actual digital read of port E. Because of this circuitry, the analog and digital
functions do not normally interfere with each other, although turning on the digital buffer during
an analog sample may cause small disturbances on the input line that could lead to measurement
errors. However, it is easy enough to write software that avoids the two from happening at the
same time.
In the analog voltage mode, the selected Port E pins interface with the built-in analog-to-digital
(A/D) converter. An A/D converter creates a binary number that is proportional to an unknown
input voltage, and is normally used to read signals from analog sensors, like temperature and
pressure gauges.
When using the E port for digital input, the digital input data can be found in the PORTE register
located at hexadecimal memory location 000A. When using the E port for analog voltage input,
the A/D control register (ADCTL), at hexadecimal memory location 0030, selects which pins are
to be used for digital logic and which are allocated for analog voltage input. Refer to Section
Five in this lesson for details on the A/D converter.
EZ-COURSEWARE 2-21
MC68HC11 architecture and addressing modes
Figure 2-7 is a block diagram of the main timer system. It will be helpful to refer to this figure as
we go through the following discussion. Since the architecture of the main timer is primarily a
software-driven system, several application examples are included. Don’t be confused if the
software examples are sketchy at this point. They will be discussed in detail later in this course.
2-22 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
Main Timer
All the MCU’s timing signals are derived from its E-clock, which is driven by a crystal-
controlled oscillator. Typically, the oscillator runs at 8 MHz, which is reduced to 2 MHz using
internal dividers. This produces a fundamental E-clock timing period of 500 nanoseconds (ns).
The number of clock cycles required to do an operation is based on this timing. For example, an
instruction that takes four clock cycles requires 4 x 500ns, or 2 us to complete. A few of the
EZ-COURSEWARE 2-23
MC68HC11 architecture and addressing modes
68HC11 MCUs run as fast as 3 MHz, using a 12-MHz crystal, which produces a fundamental E-
clock timing period of 333 ns.
The E-clock’s frequency, and subsequent timing period, can be further reduced using an on-chip
prescaler (upper left in Figure 2-7). The prescaler can divide the E-clock frequency in
increments of 1, 4, 8, and 16. The prescaler is software programmable via two registers.
However, the prescaler’s rate can only be set once, and this must be done within the first 64
clock cycles after reset. After that, the rate remains fixed until the next reset. In many
microcontroller development systems, you do not have access to the bus within the first 64 clock
cycles. The prescaler default setting is one.
The prescaler feeds a 16-bit free-running counter. The counter’s registers are set to zero on reset.
The counter, which is the central element in the main system timer, is then incremented each
time it receives a clock signal from the prescaler. Physical time is represented by the number in
the counter’s 16-bit register. This number is available to several circuits in the MCU, including
the input-capture and output-compare functions.
Input Capture
The input-capture (IC) function is typically used to record the time at which an external event
occurred by latching the contents of the counter number in one of the three IC registers. This
number can be used to measure the period and/or pulse width of an input signal. Or it can be
used in conjunction with an output compare function to establish a delay time between an input
and output action.
Output Compare
The output-compare (OC) function is also a fundamental element of the timer architecture.
Generally, output compare is used to program an action to occur at a specific time. For each of
the five output-compare functions, there is a separate 16-bit compare register and a dedicated 16-
bit comparator. The value in the compare register is compared to the value of the free-running
counter on every bus cycle. When two values match, an output is generated, which sets an
output-compare status flag and initiates the automatic actions for that output-compare function.
You can use this to do anything from sounding a beeper to cycling a chemical batch process.
Another use of output compare is to generate a specific time delay. For example, to produce a
10-millisecond delay to time programming of an EEPROM byte. When used with the input-
capture function, the process can be looped to produce a string of pulses of specific frequency
and duty cycle.
Timer Overflow
As previously stated, the free-running timer counter starts at zero and is incremented by one with
each prescaler pulse. When the count reaches hexadecimal FFFF, the counter rolls over to zero
and starts over again. This is called a timer overflow, and when it occurs a timer overflow flag is
set. This flag can be used to measure periods that are greater than the range of the timer counter
can hold. This is similar to the way we use an hour to represent 60 minutes. It can also be used to
generate a hardware interrupt. This flag can be reset by writing to the TOF bit of the free-running
2-24 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
counter’s TFLG2 register. If overflow indicators are not important to a particular application,
just tell the software to ignore them.
The clock input to the COP system is tapped off the free-running counter chain. The time-out
period is set by the CR1 and CR2 bits in the configuration options (OPTION) register. While it is
a powerful tool, you must use COP carefully. If you are designing a product where it is
imperative that the cycle is not interrupted, like a chemical batch process, it is not wise to use
COP. The results could be disastrous. In this scenario, use the time-out features of the output-
compare function to sound an alarm instead of an automatic COP system reset. The COP system
is enabled or disabled using the NOCOP bit in the CONFIG register.
Interrupts
Also linked to the main timer are the 68HC11’s real-time interrupts. If you write programs that
must respond quickly to events that may occur unpredictably, you should know how to use
interrupts.
Most software programs are sequential. That is, they execute a series of instructions, one after
the other, in a predefined order. For example, an automatic dishwasher would wash, rinse, and
dry in that order. Simple enough. But what if the user wanted to open the door to add a coffee
cup to the menagerie of plates, pots, and pans halfway through the cycle? In other words,
interrupt the process.
Using interrupts, a microcontroller can quickly detect and respond to events like the following:
1. A sensor generates a warning, such as fluid level is too high or too low.
2. A power failure has occurred.
3. A timer times out, announcing a subsequent operation is pending.
4. A counter overflows, indicating that a defined number of events have
occurred.
5. Data arrives at an I/O port for processing.
6. A user requests action to be taken by pressing a key.
Interrupt-driven programs are fast and efficient. They enable a MCU to respond to an event that
may occur at any time and return to whatever it was doing before the interrupt occurred — or
take another course of action.
EZ-COURSEWARE 2-25
MC68HC11 architecture and addressing modes
In the 68HC11 (and most MCUs), interrupts are signaled by register flags. Once during each
machine cycle, the 68HC11 checks all the registers to see if an interrupt flag is set. A flag
indicates an event has occurred that requires immediate attention. The 68HC11 has two types of
interrupts: external interrupts that stop the program because of an input signal, and those that
output a signal from the MCU to an external device to halt its operation.
Interrupt Vectors
External interrupts are received on the IRQ and XIRQ pins. In addition to IRQ and XIRQ, five
other pins on the 68HC11 can also be used to generate external interrupt requests: PC0/IC3,
PA1/IC2, PC2/IC1, PA7/OC1, and AS/STRA. These pins are associated with the timer and I/O
handshakes. Internal interrupts are generated from the serial interface unit (SCI), pulse
accumulator, timer unit, a software interrupt instruction, an illegal opcode, COP watchdog, and a
clock monitor.
Each interrupt is associated with a vector address. Without getting too complicated at this point,
these vectors point to a memory address that initiates a routine to clear the interrupt and go back
to the main program where it left off. Each interrupt has a priority, with highest priority given to
the most important interrupt request. While priority of interrupts may be of little concern in
many applications, I would sure like to know ahead of time when a boiler is getting ready to
explode. This scenario definitely takes priority over a burned-out light bulb. Table 2-5 lists the
interrupt vectors for the 68HC11A8 from highest to lowest priority.
2-26 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
EZ-COURSEWARE 2-27
MC68HC11 architecture and addressing modes
Before you think interrupts are forever carved in stone, think again. You can write your own
interrupt service routines. The vector jump table in RAM allows the user to write different
routines using the PSEL bits of the HPRIO register, each having its own starting address. The
first byte in the vector jump table must always be a JMP (jump) instruction whose opcode is 7E.,
but more about that later. Just know that you have complete control over the 68HC11’s
interrupts, except for the reset codes.
Resets
Resets are also tied to the main clock. One of the things about the 68HC11 is that the reset
structure in the 68HC11 is quite different from other MCUs. The 68HC11’s reset system can
generate a reset output if reset-causing conditions are detected by internal hardware or firmware,
as evidenced by the optional COP watchdog timer described above.
Once the reset condition is recognized, internal register and control bits are forced to an initial
state. The functions and registers involved are:
So you have to be careful that a reset does not clear your external operation in the middle of a
cycle because of a software glitch. I can’t stress enough what the consequences of a 68HC11
reset would do in the middle of a chemical batch process.
Thankfully, most 68HC11 reset interrupts are maskable. That is, you can prevent them from
happening by simply setting a bit in a register. Better yet, you can prevent them from happening
by paying close attention to interrupts and writing tight code that doesn’t bomb. Which is why I
recommend EEPROM versions of the 68HC11, or versions without built-in memory for the first
go around, as is the case with the 68HC11D0 used in the EZ-Courseware microcontroller
development system. MCUs with EEPROM or outboard memory are more expensive, agreeably,
but more flexible. Moreover, the code is easily translated into ROM or EPROM after all the bugs
are worked out.
In addition to the sources already described, a MCU reset can be forced by pulling the RESET
pin low. The outcome is the same an internal reset.
2-28 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
Special Resets
There are two additional reset conditions that place the 68HC11 into special modes of operation.
They are special-test and special-bootstrap. These modes, along with the Single-Chip and
Expanded modes discussed in Section Three above, are set via the MODA and MODB bits of the
CONFIG register.
Generally, these bits are not available to the end user because of their specialized functions. For
example, the test mode overrides several automatic protection mechanism, which leads to risks
when working in this mode of operation. However, they are quite helpful when developing new
products. Which is why the EZ-Courseware microcontroller development system evaluation
board has jumpers for putting the 68HC11 into both of these special operating modes.
The designers of the 68HC11 anticipated that, during product development, there would be times
when it would be necessary to jump directly into the EEPROM after reset. The special bootstrap
mode does just that. Once booted, the EEPROM software can locate itself at address 0000 and
proceed to do what software programs do, like clearing registers of existing data, writing new
data into them and doing a clean reboot. Too many users make the mistake of assuming all
registers and I/O pins are still in their reset state when a new program loads. This is a way to
level the playing field, and branch out to the real working part or the software. Sometimes it can
be used for real-world applications, but it is not recommended.
EZ-COURSEWARE 2-29
MC68HC11 architecture and addressing modes
2-30 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
When the software program begins a conversion, the SAR register is loaded with the binary
number 1000000 — a value that produces an internal A/D comparison voltage which is halfway
between the A/D’s high and low reference voltages. The converter then samples the unknown
input voltage, which it latches into a sample-and-hold circuit. If the unknown voltage is higher
than the A/D voltage, the binary number is incremented to 1100000, which raises the comparison
voltage to a higher value, and another comparison is made. If the unknown voltage is lower than
the A/D voltage, the binary number is decremented to 0100000, which lowers the comparison
voltage, and a comparison is made.
Notice that the comparison process begins with the most-significant bit (MSB) and continues to
the least-significant bit (LSB). If the unknown voltage is higher than the comparison voltage, the
bit retains its 1 value; if the unknown voltage is lower, the bit is returned to 0. The process is
repeated eight times, once for each of the A/D bits, to arrive at a binary value that is equal to the
unknown voltage. In a 5-volt reference framework, each LSB binary value is equal to about 20
millivolts; consequently a binary code of 01110111 would equal 2.34 volts.
A/D Accuracy
For the conversion process to be repeatable and accurate, the input voltage must fall within the
same range as the A/D’s high and low reference voltages. Typically +5 volts and 0 volts are
used, which means the external sensor should have a full-range output of +5 volts.
EZ-COURSEWARE 2-31
MC68HC11 architecture and addressing modes
2-32 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
EZ-COURSEWARE 2-33
MC68HC11 architecture and addressing modes
2-34 EZ-COURSEWARE
MC68HC11 architecture and addressing modes
Lesson 2 Questions
SECTION ONE
2) What does CPU stand for, and what is its purpose in a microcontroller?
3) What is an opcode?
7) What does ROM stand for? How is it programmed and when is it used?
9) What are the two main differences between EPROM and EEPROM?
10) In what type of designs should you use select EPROM over EEPROM?
SECTION TWO
9) Do all addressing modes need a data byte to work? If not, which ones?
EZ-COURSEWARE 2-35
MC68HC11 architecture and addressing modes
SECTION THREE
1) How many I/O ports does the 68HC11 have, and how are they labeled?
3) What is the difference between an input line, output line, and a bidirectional line?
5) Which port has only six pins, and why is this significant? In other words, what else does this
port do that requires less than eight pins?
6) Describe the difference between single-chip mode and extended mode operation.
7) How many data lines are needed for synchronous serial communications? How many for
asynchronous?
8) What is a baud?
10) Port E has an A/D control register. What is it called and where is it located?
SECTION FOUR
2) When would you use the input-capture (IC) and output-compare (OC) the functions?
4) How does the timer overflow work, and what can you use it for?
6) How do you keep the COP watchdog timer from timing out?
7) What is an interrupt?
10) What effect does a hardware reset have on the stack if the reset occurs while a program is
running?
2-36 EZ-COURSEWARE
Programming the MC68HC11
EZ-COURSEWARE 3-1
Programming the MC68HC11
Now that you understand what the 68HC11 is capable of doing, it is time to show you how to
make the MCU work; e.g., how to program the 68HC11. In this lesson, you will learn how to
write programming code, convert it into an application program, and load the application
program into the EZ-Courseware microcontroller development system.
Instruction Sets
Like all processors, the 68HC11’s software operations are done using an instruction set, a
defined number of opcodes that control the CPU and MCU registers. The 68HC11 comes from a
long line of Motorola microprocessors beginning with the MC6800. The 68HC11 can run all the
6800 and 6801 instructions, plus 91 additional instructions.
Instruction Operation
Generally, several machine cycles are needed to complete the operation of an instruction as the
CPU proceeds through its various states. A complete instruction operation happens in two
distinct phases: the fetch phase and the execute phase.
During the fetch phase, a copy of the instruction is moved from its memory location into the
CPU registers. Usually the control unit will fetch the instructions from the memory in the
physical order of the memory registers--one after another. This method reduces the software
overhead because the only addressing operation necessary to find the next memory location is to
increment the program counter. If the control unit has to fetch the instruction from scattered
memory locations, it takes more machine cycles and more time.
During the execute phase, the fetched instruction is run. Once the process is started, the control
unit will automatically continue to fetch and execute instructions until something stops it--
typically an interrupt or reset. In most MCU applications, programs run in loops, like a dog
chasing its tail, so that they continuously control the devices connected to them.
Instruction Groups
An instruction set is divided into functional groups of instructions. That way, it is easier to find
your way around when writing a program. For example, if you need an arithmetic function,
simply look in that group and find the instruction that is applicable to your program. Basically,
there are five major groups, divided accordingly:
1. Arithmetic operations.
2. Logical operations.
3. Load and store operations.
4. Testing and branching.
5. Input and output.
Prebytes
While all 6800 instructions will run on the 68HC11, many of the 68HC11 instructions will not
run on the 6800, 6801, 6802, and 68701 processors. That is because these microprocessors do
not have a Y index register, like the 68HC11 does. When the Y index register opcodes are
included in the instruction set, the number of opcodes exceeds 256--more than can fit into an 8-
bit number. Consequently, some 68HC11 instructions have double-byte opcodes.
3-2 EZ-COURSEWARE
Programming the MC68HC11
To make the 68HC11 instruction set backward compatible with previous Motorola 6800
processors, the 68HC11 uses a prebyte. The prebyte precedes the normal single opcode byte, and
is coded in such a way that if the processor does not recognize it, the system won’t crash.
Instead, an error flag is set. Prebyte instructions are also used to allow the CPU to perform 16-bit
arithmetic operations.
However, the use of a prebyte requires a double-fetch operation, which takes more clock cycles.
The result is a performance hit when using the Y index register. Which is why you should use
the X index register for all 8-bit opcode operations whenever possible.
The following is a short description of each of these groups, and the opcodes that fall within their
realm. Many of these groups have subgroups, and some instructions appear in more than one
group. For example, the transfer accumulator A to Condition Code Register (TAP) appears in the
CCR group and in the load and store group. Examples of the 68HC11 instruction use will follow
later in this lesson.
EZ-COURSEWARE 3-3
Programming the MC68HC11
Arithmetic Operations
This group of instructions includes add, subtract, compare, increment, and decrement. Both 8-bit
and 16-bit arithmetic operations are supported, as are 2’s-compliment (signed) and binary
(unsigned) operations. While test instructions are included, they are seldom used because most
arithmetic operations automatically update the condition code register (CCR) bits.
3-4 EZ-COURSEWARE
Programming the MC68HC11
EZ-COURSEWARE 3-5
Programming the MC68HC11
Logical Operations
This instruction group contains the handful of extremely powerful opcodes that set the
microprocessor apart from a simple calculator: logic operations. This group of instructions
performs the Boolean logical operations AND, Inclusive OR, exclusive OR, and 1’s
complement.
3-6 EZ-COURSEWARE
Programming the MC68HC11
EZ-COURSEWARE 3-7
Programming the MC68HC11
3-8 EZ-COURSEWARE
Programming the MC68HC11
Branching
These instructions allow the CPU to make decisions based on the condition code register bits. If
you look carefully, you will see that for every branch condition there is a branch for the opposite
condition. All branch instructions are 2-byte instructions, with the first byte being the opcode
and the second byte being the address offset in 2’s complement format.
Function Opcode REL DIR EXT INDX INDY INH
Branch if Carry Clear BCC X
Branch if Carry Set BCS X
Branch if Equal Zero BEQ X
Branch if Greater Than or Equal BGE X
Branch if Greater Than BGT X
Branch if Higher BHI X
Branch if Higher or Same BHS X
(same as BCC)
Branch if Less than or Equal BLE X
Branch if Lower (same as BCS) BLO X
Branch if Lower or Same BLS X
Branch if Less Than BLT X
Branch if Minus BMI X
Branch if Not Equal BNE X
Branch if Plus BPL X
Branch if Bit(s) Clear in Memory Byte BRCLR X X X
Branch Never BRN X X X X
Branch if Bit(s) Set in Memory Byte BRSET
Branch if Overflow Clear BVC X
Branch if Overflow Set BVS X
Table 3-9. Branch instructions
Jumps
The jump instruction allows control to be passed to any address in the 64K memory map.
EZ-COURSEWARE 3-9
Programming the MC68HC11
Interrupt Handling
While most programs run in a loop so that the software continuously services the devices
connected to the MCU, there are times when it is better for the MCU to wait for an external
interrupt to occur. This allows the MCU to be in a standby mode to conserve power until it is
needed, as would be the case when the MCU is used as an intelligent alarm. Three opcodes are
associated with this feature.
Miscellaneous
This group contains three instructions which do not fit into any other defined group, but are
useful in some situations. They are NOP, STOP, and TEST.
NOP does what it sounds like — absolutely nothing. It simply wastes two clock cycles, and is
used to add a small delay into the program while it waits for an external peripheral to catch up.
For precise delays, NOP can be combined with the BRN branch command to produce a three-
cycle NOP.
STOP causes all MCU clocks to freeze, which reduces power consumption to virtually nothing.
The TEST instruction is used only during factory testing, and is treated as an illegal opcode in
normal operating modes. When used with the Test Mode, though, it can be used to help program
the CONFIG register.
An advantage of machine language programs is the programs are very compact and small.
Because they are small in size, you don’t need as much RAM to run them, which saves you
money. Machine language programs also runs faster than programs that are written using other
programming methods, like interpreted and compiled language programming.
3-10 EZ-COURSEWARE
Programming the MC68HC11
Each operation begins with a memory address. Sometimes the address by itself is enough, which
is the case when initializing the reserved memory space for use in the direct addressing mode,
but mostly the address points to a memory location.
The next item is the hexadecimal data byte of the opcode instruction, like a fetch data instruction
(LDAA). The data byte contains the binary code needed to execute the opcode in the selected
addressing mode. For example, the data byte needed to execute the LDA instruction in the direct
addressing mode is 96. When working in the immediate addressing mode, the LDA data byte is
86.
Most instructions, like LDA, need more than one clock cycle to complete. For every clock cycle,
the address has to be changed (usually in increments of one). Many times a different data byte is
used for each cycle. Which is why machine language is so demanding. There is no room for
error. One mistake in either an address or opcode byte, and the program crashes.
EZ-COURSEWARE 3-11
Programming the MC68HC11
No longer do you have to calculate the memory address or enter the data byte. An assembler
program does that for you. All you need is an opcode and an operand (when applicable). The
assembler then deciphers the opcode, assigns the addresses, sets the proper data bytes, and
moves the associated data values into the right registers or memory locations.
Being a programming language rather than a machine code, assembly language programming
has the added advantage of easily creating branching and looping subroutines. After writing a
few machine language programs, you will notice that certain patterns are repeated over and
again. The only thing that changes are the addresses. Basically, an assembly language subroutine
is a block of code that is a complete program in itself. When embedded in a program, the
subroutine can be called into action using a single line of assembly code. The assembler makes
sure the addresses are in order and do not conflict.
Another advantage of assembly language programming is that the program is portable between
MCUs. Because the command is not MCU specific, a program written for the 68HC11 can be
used with other Motorola microprocessors and microcontrollers using a cross-assembler.
The assembler program then reads the source code and translates the 68HC11 mnemonics into
memory addresses and data bytes, which are further reduced to binary numbers. These binary
numbers are stored in an object module; the contents of this module is called the object code.
The last step is to create an executable load module, such as a disk file, that can be read by a
loader program to put the binary numbers into the MCU’s memory. The load module, or
application program, is generally created using a linker program which adds the loader program
to the object code and puts both into a single, executable file. You now have an application
program, just like a machine language program, but this time created in easier-to-use assembly
language.
At this point, the object code is no longer needed, and can be discarded. The source code,
however, should be saved in case you make changes to the program. A new object module has to
be created and linked each time you make changes to the source code.
3-12 EZ-COURSEWARE
Programming the MC68HC11
Label Field
The first field is an optional label that is used like a bookmark. The main use for a label is to
identify the beginning of a subroutine. The label is programmer defined — that is, you decide
what the label’s name should be. Generally, it is something that is related to the code it points to.
For example, if you have a timer routine that you use many times in a program, it would be wise
to label the starting line of the subroutine TIMER1 to distinguish it from other timer subroutines
you may have. The label must start with an alphabetic character (A - Z) and must not include
spaces. If the line does not require a label, a space or tab has to be inserted in its place as a place
holder because the assembler has to find something — albeit a transparent character — to
sequence its operation.
Opcode Field
After the label is the opcode field. Sometimes referred to the operation field, the opcode field
contains the 68HC11 opcode. This is the only line entry that is mandatory; without an opcode,
the assembler ignores the program line.
Operand Field
Third in line is the operand. Generally, the operand is an argument needed to qualify the
operation of the opcode. This field is also used to hold data that is staged for insertion into a
register, or to point to an address. When the opcode indicates the operand is data or an address,
there are four ways to identify the type of the number:
Note that if no symbol is used, the number is assumed to be in decimal format. Be careful,
though, because some assemblers assume no symbol to be hexadecimal numbers.
Comment Field
The fourth and last field is simply reserved for your comments. Generally, it is used to jog your
memory when working through a lengthy program. For example, a comment like “timer1
EZ-COURSEWARE 3-13
Programming the MC68HC11
started” and “temp too high interrupt” helps a lot when reading through a long list of opcodes
and subroutines. Like the label field, this field is optional.
Additional Comments
Sometimes it is helpful to insert comments into the source code that are not related to a specific
opcode or label. For example, “The following section is a 30-second clock” or “This code
executes only when a power failure occurs.” To insert references like this, start the line with an
asterisk (*). When the assembler comes across a line beginning with an asterisk, it simply skips
over it, so there is no performance hit incurred by adding these comments to the source code.
3-14 EZ-COURSEWARE
Programming the MC68HC11
As you can see, each field has its own column. This makes it easier to read the program, and is
easily accomplished using the keyboard <Tab> key. The first column, the label field, is required.
If you do not have a label, it must be replaced with a tab or space. This is a must, as is an opcode
in the second field. The operand field is dependent on the needs of the opcode. Notice that in two
instances the opcode (ORG) is an assembler directive. This will be discussed later. Comments,
while optional, should be clear and succinct.
EZ-COURSEWARE 3-15
Programming the MC68HC11
Lesson 3 Questions
1) What is the difference between an instruction set and an instruction group?
4) Why are the 68HC11’s arithmetic instructions divided into two groups?
7) Describe the difference between maching language programming and assembly language
programming.
9) What is the significance of having to know the number of machine cycles needed to complete
an instruction when working in machine language?
12) Describe the three steps needed to create an application load module.
13) List the four assembly language code fields, and describe their functions.
3-16 EZ-COURSEWARE
EZ-Micro Tutor Software
EZ-COURSEWARE 4-1
EZ-Micro Tutor Software
System Requirements
In order to run the EZ-MICRO Manager software, the following equipment is required:
Software Installation
To install the EZ-MICRO Manager software onto your hard drive, insert the CD that was
provided with the EZ-MICRO TUTOR™ microprocessor board.
If your computer is setup to run automatically setup from the CD-ROM, follow the instructions
on the screen and installation software will install EZ MICOR software on your hard drive.
If your computer is not setup to run automatic setup from the CD-ROM, using Windows
Explorer go to CD-ROM and double click SETUP.EXE file. Then follow the instruction on the
screen.
Before starting the EZ-MICRO Manager software, press the master reset button (S1) on the EZ-
MICRO TUTOR™ microprocessor board. This will ensure that the software will communicate
properly with the hardware.
After the installation is complete, click Start menu on bottom left hand corner of your Window
Desktop, goto Programs, select EZ-COURSWARE and select EZ Micro.
All of the commands that are issued to the EZ-MICRO TUTOR™ microprocessor board are
selected from the various pull down menus located across the top of the EZ-MICRO Manager
presentation screen (Figure 4.1). Therefore, it is not necessary to memorize numerous commands
in order to communicate to the CPU using this program.
4-2 EZ-COURSEWARE
EZ-Micro Tutor Software
Several files (including several sample assembly language routines) are included on the EZ-
MICRO CD. At AMS, we are always adding new features in the software and more
documentation.
Please visit our web site www.advancedmsinc.com/update/ and download free updates.
The EZ-MICRO Manager presentation screen is divided into the following functions.
T The "Title Bar", located at the top of the screen, displays the the title of this software and
version number.
T The "Action Bar", located just below the Title Bar, contains the various pull down menus
where the commands that are issued to the EZ-MICRO TUTOR™ microprocessor board can be
selected.
Notice that in all three cases a menu will be pulled down. To access an adjacent menu, simply
press the right or left arrow keys on the keyboard or point at the menu heading with the mouse.
EZ-COURSEWARE 4-3
EZ-Micro Tutor Software
A menu bar is located within the pull down menu and is used to select one of the commands in
the menu. The menu bar can be moved up or down by pressing the up or down arrow keys on the
keyboard. Once the menu bar is positioned on the desired command, press the ENTER key to
select that command. If you are using a mouse, point at the command and click the left mouse
button to select the command. Listed to the right of each command in the pull down menus are
"hot keys" which allow you to select a command (in the current pulled down menu) by simply
pressing its hot key on the keyboard.
T The "Registers" display window is located in the upper right corner of the EZ-MICRO
Manager presentation screen. This window is used to display the current 68HC11
microprocessor register contents. These registers are: the Program Counter (P), Y-index (Y), X-
index (X), A-accumulator (A), B-accumulator (B), Condition Code (C) and Stack Pointer (S).
Modify Registers
68HC11 microprocessor have several registers namely, program counter (P), Y-index (Y), X-
index (X), A-accumulator (A), B-accumulator (B), Condition Code (C) and Stack Pointer (S)
register. To modify any of these registes, double click Register value in the register window.
When you double click P, the following dialog box will appear displaying the current Program
counter contents. Enter the desired value and Press OK.
T The "Watch Variables" display window is located below the Registers display window. This
window is used to monitor the contents of several memory locations at once while
running/debugging the assembled code.
T The "Breakpoints" display window is located below the Watch Variables display window.
This window is used to display the current user breakpoints that have been entered into the
breakpoint address table.
T The "Main Display" window is the large area located in the left half of the EZ-MICRO
Manager presentation screen. This window is used to display the EZ-MICRO TUTOR™
memory contents, disassembled memory listing, trace of program execution and a graphical plot
of user memory.
4-4 EZ-COURSEWARE
EZ-Micro Tutor Software
Assemble File
The "Assemble File" command in the FILE menu is used to assemble a Motorola 68HC11
assembly language source file into a Motorola S-Record hex file. The assembled S-Record file
can be later downloaded to the EZ-MICRO TUTOR™ microprocessor board and executed.
Select the Assemble File command from the FILE menu. Select the file "LCD.asm". and press
Open. This operation will create two files LCD.S19 and LCD.LST
When viewed by the user, S-Records are essentially character strings made of several fields
which identify the record type, record length, memory address, code/data and checksum. Each
byte of binary data is encoded as a 2-character hexadecimal number. The first character
represents the high order 4 bits, and the second the low order 4 bits of the byte.
The five fields which comprise an S-Record are shown in the following figure:
EZ-COURSEWARE 4-5
EZ-Micro Tutor Software
Printable
Field Contents
Characters
Type 2 S-Record type — S0, S1, etc.
Record The count of the character pairs in the record,
2
Length excluding the type and record length.
The 2-, 3-, or 4-byte address at which the data field
Address 4,6, or 8
is to be loaded into memory.
From 0 to n bytes of executable code, memory
Code/Data 0-2n
loadable data or descriptive information.
The least significant byte of the one's complement
of the sum of values represented by the pairs of
Checksum 2
characters making up the record length, address,
and code/data fields.
Eight types of S-Records have been defined to accommodate the needs of encoding,
transportation and decoding functions. However, the BUFFALO monitor program that is used by
the EZ-MICRO TUTOR™ supports only the S1 and S9 record types. Therefore, all records that
are downloaded to the EZ-MICRO TUTOR™ must be S1 type until the S9 record terminates the
data transfer.
4-6 EZ-COURSEWARE
EZ-Micro Tutor Software
Type Description
S0 The header record for each block of S-Records. The code/data field may
contain any descriptive information identifying the following block of S-
Records. The address field is normally zeros.
S1 A record containing code/data and the 2-byte address at which the
code/data is to reside.
S2-S8 Not applicable to the EZ-MICRO TUTOR™.
S9 A termination record for a block of S1 records. The address field may
optionally contain the 2-byte address of the instruction to which control
is to be passed. If not specified, the first entry point specification
encountered in the object module input will be used. There is no
code/data field.
S00600004844521B
S1130000285F245F2212226A000424290008237C2A
S11300100002000800082629001853812341001813
S113002041E900084E42234300182342000824A952
S107003000144ED492
S9030000FC
The above module consists of an S0 header record, four S1 code/data records and an S9
termination record.
EZ-COURSEWARE 4-7
EZ-Micro Tutor Software
The third, fourth and fifth lines of the S-Record example are also of type S1.
Finally, the last line is the S9 termination record and is described below.
4-8 EZ-COURSEWARE
EZ-Micro Tutor Software
Load S-Record
The "Load S-Record" command in the FILE menu is used to download an assembled Motorola
S-Record hex file into user memory located on the EZ-MICRO TUTOR™ microprocessor
board.
Select the S-Record file "LCD.s19" and Press Open. You will see the following dialog box
asking to enter Starting Position. This is the address from where the program will start.
LCD.ASM does start at 2000. Press OK.
Edit Source
The "Edit Source" command in the FILE menu is used to edit an existing assembly language
source file (or any ASCII file).
EZ-COURSEWARE 4-9
EZ-Micro Tutor Software
4-10 EZ-COURSEWARE
EZ-Micro Tutor Software
Create Source
The "Create Source" command in the FILE menu is used to create a new assembly language
source file.
Configure Port
The "Configure Port" command in the FILE menu is used to configure the COM port (or serial
port) of the host computer or terminal for communicating with the EZ-MICRO TUTOR™
microprocessor board.
When the EZ-MICRO TUTOR™ is first powered-on, its serial port will be configured to 9600
baud, no parity, eight bit word length and one stop bit. The options that you select for the host
serial port must match these settings (9600,N,8,1) exactly or you will not be able to
communicate with the EZ-MICRO TUTOR™. Note: When the EZ-MICRO Manager software is
started (in the "normal" mode) for the first time, the Configure Port dialog box will automatically
be displayed so that you can select the COM port that you will be using to communicate to the
EZ-MICRO TUTOR™ microprocessor board.
When the "Configure Port" command is selected from the SYSTEM menu, a dialog box will
appear allowing you to select the port address, baud rate, parity, word length and stop bit
parameters. The options that are selected in the Configure Port dialog box will be saved to the
EZ-MICRO Manager's configuration file (ezmicro.cfg) when you exit the program normally.
That is, by selecting Exit from the FILE menu. Once the serial port options have been selected,
the Configure Port dialog box will not be displayed again when the EZ-MICRO Manager
software is re-started.
It is possible to change the serial port parameters of the EZ-MICRO TUTOR™'s serial interface
by configuring the serial port register ($002B). If changes are made to the serial port of the EZ-
MICRO TUTOR™, then you will need to select the identical parameters for the host computer's
serial port. Note: If a reset occurs on the EZ-MICRO TUTOR™, the serial interface (of the EZ-
MICRO TUTOR™) will return to its default value (9600,N,8,1).
Exit
EZ-COURSEWARE 4-11
EZ-Micro Tutor Software
In order to "exit" the EZ-MICRO Manager software normally, select this command. After
selecting this command, you will return to the DOS prompt.
Note: If you are evaluating the EZ-MICRO TUTOR™microprocessor board and you are running
the EZ-MICRO Manager software in the "normal" mode, then any changes that have been made
to the host serial port (ie. baud rate, parity, word length and stop bits) using the Configure Port
option will be saved to the configuration file (ezmicro.cfg). These serial port parameters will be
used again the next time the program is started.
Go
The "Go" command in the RUN menu allows the user to initiate user program execution (free
run in real time). The user may optionally specify a starting address where execution is to begin.
Otherwise, execution begins at the current program counter (or P-register) address. Program
execution continues until a breakpoint is encountered or until the EZ-MICRO TUTOR™ master
reset button (S1) is pressed. If a valid breakpoint is not reached by the executed program, then
you will need to press the master reset button in order to stop program execution.
Note: The contents of the Registers and Watch Variables windows are only updated after
program execution has stopped. Pressing the EZ-MICRO TUTOR™ master reset button will
remove the breakpoints that have been entered into the breakpoint address table.
Example: If you are evaluating the EZ-MICRO TUTOR™ microprocessor board then you will
want to first assemble the source file "LCD.asm" by selecting the Assemble Source command
from the FILE menu. After the source file has been assembled, select Load S-Record from the
FILE menu and select the assembled S-Record file "LCD.s19" to be downloaded to the EZ-
MICRO TUTOR™ microprocessor board.
Next, select Go from the RUN menu and enter "2000" as the address of the first instruction to be
executed. This will begin the execution of the program that we have downloaded to the EZ-
MICRO TUTOR™. LCD.ASM program will display a test Pattern 01234567 on first line of
LCD and "ABCDEFG" test pattern on the second line.
To stop the program execution, press the master reset button (S1) on the EZ-MICRO TUTOR™
microprocessor board. The EZ-MICRO Manager software will sense that a reset has occurred
and will automatically exit from the Go command
To demonstrate the ability of the EZ-MICRO TUTOR™ to stop program execution at a
breakpointed address, select the Set Breakpoint command from the DEBUG menu and enter the
breakpoint address "2068". This address corresponds to an instruction (in the program that was
downloaded to the EZ-MICRO TUTOR™ that .wrties test pattern on first LCD line. Select Go
once more from the RUN menu and enter "2000" as the address of the first instruction to be
4-12 EZ-COURSEWARE
EZ-Micro Tutor Software
executed. Notice that the software will display the first line and then MICRO Manager software
will sense that a breakpoint has been encountered and program execution will be stopped.
Call
The "Call" command in the RUN menu allows the user to execute a user program subroutine.
Execution starts at the current program counter (or P-register) address, unless a starting address
is specified. Program execution continues until a breakpoint is encountered or until the EZ-
MICRO TUTOR™ master reset button (S1) is pressed. If a valid breakpoint is not reached by
the executed program, then you will need to press the master reset button in order to stop
program execution.
Note: The contents of the Registers and Watch Variables windows are only updated after
program execution has stopped. Pressing the EZ-MICRO TUTOR™ master reset button will
remove the breakpoints that have been entered into the breakpoint address table.
Proceed
The "Proceed" command in the RUN menu is used to proceed or continue program execution
without having to remove assigned breakpoints. This command is used to bypass assigned
breakpoints in a program executed by the GO command. The program will continue to "proceed"
to the next assigned breakpoint. If a valid breakpoint is not reached by the executed program,
then you will need to press the master reset button in order to stop program execution.
Note: The contents of the Registers and Watch Variables windows are only updated after
program execution has stopped. Pressing the EZ-MICRO TUTOR™ master reset button will
remove the breakpoints that have been entered into the breakpoint address table.
The EZ-MICRO Manager software will sense when the next valid breakpoint is reached and will
automatically exit from the Proceed command
Step ( F8 - Hotkey )
The "Step" command in the RUN menu is used to execute each instruction one at a time. Note:
Jumper location H8 on the EZ-MICRO TUTOR™microprocessor board must have a jumper
strap inserted for this command to function properly. Execution starts at the current program
counter (or P-register) address. Each instruction that is executed will be displayed in the Main
Display window. To execute the next instruction, simply press the PgDn key on the keyboard (or
point at the down arrow button with the mouse and click the left mouse button). The register
contents in the Registers display window and the Watch Variables will be updated after each
instruction that is executed.
EZ-COURSEWARE 4-13
EZ-Micro Tutor Software
Pressing the master reset button on the EZ-MICRO TUTOR™ will "clear" the current
breakpoints that have been set. However, any source code that has been downloaded into user
memory will not be affected by this hardware reset.
Add Variable
The "Add Variable" command in the DEBUG menu is used to add watch variable addresses into
the watch variable's address table. A watch variable is simply a memory location on the EZ-
MICRO TUTOR™ microprocessor board that you wish to monitor the contents of.
The EZ-MICRO Manager software allows the user to enter up to thirty addresses (or memory
locations) into the watch variable's address table. The Save Watches command (in the FILE
menu) can be used to save this list of addresses so that they can be quickly re-loaded when the
EZ-MICRO Manager software is re-started. This saves the user from having to re-enter the list
each time the EZ-MICRO Manager software is run.
Remove Variable
The "Remove Variable" command in the DEBUG menu is used to remove the address of a
specific watch variable from the watch variable's address table. When prompted, enter the hex
address of the watch variable that you want to remove. Note: This command will be "grayed out"
when there are no watch variables currently defined in the watch variable's address table:
Set Breakpoint
The "Set Breakpoint" command in the DEBUG menu is used to place an address into the
breakpoint address table. When prompted, enter the hexadecimal address of where the
breakpoint is to be inserted. A maximum of four breakpoints may be set and will be displayed in
the Breakpoints window. If four breakpoints have already been set, the message "Breakpoint
table is FULL" will appear when a fifth breakpoint is entered.
Whenever the Go, Call or Proceed commands are selected (from the RUN menu), then
"breakpoints" are inserted into the user code at the address specified in the breakpoint address
table. During user program execution, the program will stop execution immediately preceding
the execution of any instruction's address that is in the breakpoint address table.
4-14 EZ-COURSEWARE
EZ-Micro Tutor Software
Breakpoints are implemented by placing a software interrupt (SWI) at each address specified in
the breakpoint address table. The SWI service routine saves and displays the internal machine
state, then restores the original opcodes at the breakpoint location before returning control back
to the EZ-MICRO Manager program.
Note: SWI opcodes cannot be executed or breakpointed in user code because the BUFFALO
monitor program uses the SWI vector. Only RAM locations can be breakpointed. Branch on self
instructions cannot be breakpointed.
Remove Breakpoint
The "Remove Breakpoint" command in the DEBUG menu is used to remove one of the
breakpoints that have been set in the breakpoint address table. When prompted, enter the address
of the breakpoint that is to be removed from this list.
Line Assemble
The "Line Assemble" command in the DEBUG menu is a single line assembler/disassembler that
can be used to input code directly into user RAM. Note: This command will be "grayed out"
when running the EZ-MICRO Manager software in the demo mode.
When the Line Assemble command is selected, you will be prompted to enter the starting
address to begin the "in-line" assembly. Next, you will be prompted to enter a source line. Each
source line is converted into the proper machine language code and is stored in memory
overwriting previous data on a line-by-line basis at the time of entry.
All valid opcodes are converted to assembly language mnemonics. All invalid opcodes will be
displayed as an error message. If an error does occur, then the same address location is re-opened
and the source line can be re-entered.
Note: Pressing the ENTER key (without entering anything) will leave the current instruction
unchanged and advance to the next valid instruction.
All numerical values are assumed to be hexadecimal. Therefore, no base designators (such as $,
%, etc.) are allowed. Operands must be separated by one or more spaces. Any characters after a
valid mnemonic are ignored. Addressing modes are designated as follows:
EZ-COURSEWARE 4-15
EZ-Micro Tutor Software
c.) Direct and extended addressing is specified by the length of the address operand (1
or 2 digits specifies direct, 3 or 4 digits specifies extended).
d.) Relative offsets for branch instructions are computed by the assembler. Therefore,
the valid operand for any branch instruction is the branch-if-true address, not the
relative offset.
Memory Dump
The "Memory Dump" command in the MEMORY menu is used to display the hexadecimal
contents of user memory (located on the EZ-MICRO TUTOR™ microprocessor board) to the
screen.
For example, select the Memory Dump command from the MEMORY menu and you will be
prompted to enter the starting memory location to begin the hexadecimal memory dump. Enter
the hex address "1000" for this example and press the ENTER key (or click the left mouse
button) to accept this hex number. Note: The starting address that is specified may be either
RAM or ROM address space (0000h-FFFFh).
Note: The memory addresses will appear as "XX00" only during the demo mode. This is done
since there are only 256-bytes of memory (0000h-00FFh) available when running the EZ-
MICRO Manager in the demo mode.
4-16 EZ-COURSEWARE
EZ-Micro Tutor Software
Use the PgUp and PgDn keys to view the previous or next page of the hexadecimal memory
dump (or point at the up and down arrow buttons with the mouse and click the left mouse
button).
Disassemble
The "Disassemble" command in the MEMORY menu is used to display a disassembled listing of
the program code to the screen. Note: This command will be "grayed out" when running the EZ-
MICRO Manager software in the demo mode.
When the Disassemble command is selected, you will be prompted to enter the address of the
first line of code (or instruction) to be disassembled.
Block Fill
The "Block Fill" command in the MEMORY menu allows the user to repeat a specific pattern
throughout a determined user memory range. To demonstrate this feature, select the Block Fill
command from the MEMORY menu and the following dialog box will be displayed.
Enter "2000" for the starting address location, enter "203F" for the ending address location and
enter "AA" for the pattern. Press the OK button to accept the parameters you have just entered.
To view the changes that have been made to the memory locations (2000h-203Fh), select the
Memory Dump command from the MEMORY menu and enter "2000" as the starting hex
address to begin the memory dump.
Block Move
The "Block Move" command in the MEMORY menu allows the user to copy or move a "block"
of memory to a new memory location. To demonstrate this feature, select the Block Move
command from the MEMORY menu and the following dialog box will be displayed.
EZ-COURSEWARE 4-17
EZ-Micro Tutor Software
Enter "1010" for the starting address location and enter "103F" for the ending address location of
the block of memory to move. Enter "1050" for the destination hex address to receive the block
(48-bytes) of memory. Press the OK button to accept the parameters you have just entered.
To verify that the block of memory (2000h-203Fh) was copied to 2050h, select the Memory
Dump command from the MEMORY menu and enter "2000" as the starting hex address to begin
the memory dump.
The HELP Menu
The HELPin HELP menu provide trhe help on the software
About EZ-MICRO
Selecting this command will display the current version of the EZ-MICRO Manager software
that is currently running.
4-18 EZ-COURSEWARE
EZ-Micro Tutor Software
Section Two:
Features
EZ-COURSEWARE 4-19
EZ-Micro Tutor Software
Specifications
The following table lists the specifications of the EZ-MICRO TUTOR™microprocessor board.
CHARACTERISTIC SPECIFICATION
CPU MC68HC11E0
Terminal I/O Port RS-232C compatible
Temperature:
Operating +25 Degrees C
Storage -40 to +85 Degrees C
Relative Humidity 0 to 90% (non-condensing)
Dimensions: Width 7 Inch
Length 6 Inch
General Description
The EZ-MICRO TUTOR™microprocessor board provides an easy way of learning the
MC68HC11E0 Motorola microprocessor. The MC68HC11E0 is a high-performance micro
controller unit (CPU) that is based on the MC68HC11E9 design. The MC68HC11E0 chip offers
high speed, low power consumption and multiplexed buses capable of running up to 3 Mhz.
The MC68HC11E0 is also an excellent economical alternative device for applications that
require the HC11 CPU but where fewer peripheral functions and less memory are required. Refer
to the Motorola MC68HC11 CPU data sheet (see appendix) for additional device information.
Hardware Preparation
Unpacking Instructions
If the package is damaged upon receipt, request that the carrier's representative be present during
the unpacking and inspection of the EZ-MICRO TUTOR™microprocessor board. The following
materials should be included in the EZ-MICRO TUTOR™microprocessor “evaluation” package:
T EZ-MICRO TUTOR™ Microprocessor Board.
T 9 Volt AC Power supply.
T RS-232 Serial Cable (with 9 pin “DB” connectors).
T EZ-MICRO Manager Software CD-ROM
4-20 EZ-COURSEWARE
EZ-Micro Tutor Software
Hardware Preparation
This portion of the manual describes the inspection and initial jumper selection for the
EZ-MICRO TUTOR™ microprocessor board which is shown in the following figure (Fig. 4.27).
EZ-COURSEWARE 4-21
EZ-Micro Tutor Software
The EZ-MICRO TUTOR™microprocessor board has a built-in "power-on" reset logic that will
reset the CPU at initial power-up of the device, however, there is also an external user reset
button provided at switch location SW1( Labeled 2 in Figure 4-27).
Depending on the user's application, you may need to insert or remove jumper straps in order to
configure the operation of the EZ-MICRO TUTOR™microprocessor board. The following
sections describe each jumper position and its function. These jumper locations are shown in
Figure 4.27.
4-22 EZ-COURSEWARE
EZ-Micro Tutor Software
may vary. For instance, the definition for V.10 has a dead area from +0.3v to -0.3v. Many
receivers designed for RS-232 are sensitive to differentials of 1v or less.
This can cause problems when using pin powered widgets - line drivers, converters, modems
etc. These type of units need enough voltage & current to power them self's up. Typical URART
(the RS-232 I/O chip) allows up to 50ma per output pin — so if the device needs 70ma to run we
will need to use at least 2 pins for power. Some devices are very efficient and only require one
pin (some times the Transmit or DTR pin) to be high — in the "SPACE" state while idle.
The following FIG 1 shows standard 25 pin RS232 connector and pin description. All AMS
products uses 9 pin RS232 interface shown in FIG 4.28.
RS-232 Interface
RS-232 (EIA Std) applicable to the 25 pin interconnection of Data Terminal Equipment (DTE)
and Data Communications Equipment (DCE) using serial binary data.
EZ-COURSEWARE 4-23
EZ-Micro Tutor Software
Signal Description:
CTS Clear To Send [DCE --> DTE]
DCD Data Carrier Detected (Tone from a modem) [DCE --> DTE]
DCE Data Communications Equipment eg. Modem
DSR Data Set Ready [DCE --> DTE]
DSRS Data Signal Rate Selector [DCE --> DTE] (Not commonly used)
DTE Data Terminal Equipment eg. computer, printer
DTR Data Terminal Ready [DTE --> DCE]
FG Frame Ground (screen or chassis)
NC No Connection
RCk Receiver (external) Clock input
RI Ring Indicator (ringing tone detected)
RTS Ready To Send [DTE --> DCE]
RxD Received Data [DCE --> DTE]
SG Signal Ground
SCTS Secondary Clear To Send [DCE --> DTE]
SDCD Secondary Data Carrier Detected (Tone from a modem) [DCE --> DTE]
SRTS Secondary Ready To Send [DTE --> DCE]
SRxD Secondary Received Data [DCE --> DTE]
STxD Secondary Transmitted Data [DTE --> DTE]
TxD Transmitted Data [DTE --> DTE]
4-24 EZ-COURSEWARE
EZ-Micro Tutor Software
requests for the transfer of information between a DTE and a DCE. Data cannot be transferred
unless the appropriate flow control line are first asserted.
The interface can send data either way( DTE to DCE, or, DCE to DTE) independently at the
same time. This is called FULL DUPLEX operation. Some systems may utilize software codes
so that information may only be transmitted in one direction at a time ( HALF DUPLEX), and
requires software codes to switch from one direction to another (i.e., from a transmit to receive
state).
Request To Send (RTS) This signal line is asserted by the computer (DTE) to inform the
modem (DCE) that it wants to transmit data. If the modem decides this is okay, it will assert the
CTS line. Typically, once the computer asserts RTS, it will wait for the modem to assert CTS.
When CTS is asserted by the modem, the computer will begin to transmit data.
Clear To Send (CTS) Asserted by the modem after receiving a RTS signal, indicating that the
computer can now transmit.
Data Terminal Ready (DTR) This signal line is asserted by the computer, and informs the
modem that the computer is ready to receive data.
Data Set Ready (DSR) This signal line is asserted by the modem in response to a DTR signal
from the computer. The computer will monitor the state of this line after asserting DTR to detect
if the modem is turned on.
Receive Signal Line Detect (RSLD) This control line is asserted by the modem, informing the
computer that it has established a physical connection to another modem. It is sometimes known
as Carrier Detect (CD). It would be pointless a computer transmitting information to a modem
if this signal line was not asserted. If the physical connection is broken, this signal line will
change state.
Transmit Data (TD) is the line where the data is transmitted, a bit at a time.
Receive Data (RD) is the line where data is received, a bit at a time. A lot of signals work in
pairs. Some signals are generated by the DTE, and some signals are generated by the DCE. If
you were measuring the signals on a computer which was NOT connected to a modem, you
could only expect to see those signals that the DTE can generate.
The following table lists some of the signal pairs and the device responsible for generating them.
EZ-COURSEWARE 4-25
EZ-Micro Tutor Software
DTE DCE
TD RD
RTS CTS
DTR DSR
Table 4.8 Signal Pairs
Data is transmitted and received on pins 2 and 3 respectively. Data Set Ready (DSR) is an
indication from the Data Set (i.e., the modem or DSU/CSU) that it is on. Similarly, DTR
indicates to the Data Set that the DTE is on. Data Carrier Detect (DCD) indicates that a good
carrier is being received from the remote modem.
Pins 4 RTS (Request To Send - from the transmitting computer) and 5 CTS (Clear To Send -
from the Data set) are used to control. In most Asynchronous situations, RTS and CTS are
constantly on throughout the communication session. However where the DTE is connected to a
multi-point line, RTS is used to turn carrier on the modem on and off. On a multi-point line, it's
imperative that only one station is transmitting at a time (because they share the return phone
pair). When a station wants to transmit, it raises RTS. The modem turns on carrier, typically
waits a few milliseconds for carrier to stabilize, and then raises CTS. The DTE transmits when it
sees CTS up. When the station has finished its transmission, it drops RTS and the modem drops
CTS and carrier together.
4-26 EZ-COURSEWARE
EZ-Micro Tutor Software
Clock signals (pins 15, 17, & 24) are only used for synchronous communications. The modem or
DSU extracts the clock from the data stream and provides a steady clock signal to the DTE. Note
that the transmit and receive clock signals do not have to be the same, or even at the same baud
rate.
Note: Transmit and receive leads (2 or 3) can be reversed depending on the use of the equipment
- DCE Data Communications Equipment or a DCE Data Terminal Equipment.
RS-232 Specifications
SPECIFICATIONS RS232
Mode of Operation Single Ended
Total Number of Drivers and Receivers on One 1 DRIVER
Line 1 RECVR
Maximum Cable Length 50 FT.
Maximum Data Rate 20kb/s
Maximum Driver Output Voltage +/-25V
Driver Output Signal Level
Loaded +/-5V to +/-15V
(Loaded Min.)
Driver Output Signal Level
Unloaded +/-25V
(Unloaded Max)
Driver Load Impedance (Ohms) 3k to 7k
Max. Driver Current in High Z State Power On N/A
Max. Driver Current in High Z State Power Off +/-6mA @ +/-2v
Slew Rate (Max.) 30V/uS
Receiver Input Voltage Range +/-15V
Receiver Input Sensitivity +/-3V
Receiver Input Resistance (Ohms) 3k to 7k
EZ-COURSEWARE 4-27
EZ-Micro Tutor Software
Input Port
The fundamental technique for interfacing I/O devices to a microprocessor is to interconnect the
devices to the processor’s address, data and control buses. The processor uses the buses to send
and receive data from memory and peripheral devices. The input port allows the microprocessor
to read in an 8-bit binary number which will be set to a ‘1’ or a ‘0’ by the toggle switches on the
EZ-MICOR TUTOR™ board. There are two types of input ports on EZ-MICOR TUTOR™
board. The micorcontroller 68HC11E0 has built-in Input/output ports such as Port A and
external input port using 74LS373 ( U9). The 74LS373 transparent latch is used to isolate the 8-
bit input value from the data bus in order to prevent bus contention. Port A is connected to 4X4
Matrix Keypad and 74LS373 (U9) is connected input swithc SW2. The input port must be
memory-mapped into the address space. The 8-bit input value should be enabled onto the data
bus only on a CPU read operation from the memory address range designated for the input port.
This is explained in deatil in Chapter 9.
Output Port
There are two types of output ports on EZ-MICOR TUTOR™ board. The micorcontroller
68HC11E0 has built-in Input/output ports such as Port A and external output port using
74LS374( U6 and U8). The 74LS374 transparent latch is used to isolate the 8-bit output value
from the data bus in order to prevent bus contention. Port A is connected to 4X4 Matrix Keypad
and 74LS374 (U6) is connected to Digital to Analog converter U14 and 74LS374 ( U8) output
latch is connected to LEDs. The output port allows the microprocessor to write out an 8-bit
binary number which will be latched by the 74LS374 D-type flip-flops. The output port must be
memory-mapped into the address space. The 8-bit output value should be grabbed from the data
bus only on a CPU write operation from the memory address range designated for the output
port. This is explained in deatil in Chapter 9.
In the EZ-MICRO TUTOR™ system, a GAL22V10 is used to implement the control logic
needed to activate the input and output ports and all other peripherals at the appropriate times.
The GAL22V10 will decode the address and control signals presented on the buses to determine
4-28 EZ-COURSEWARE
EZ-Micro Tutor Software
when the peripheral should be selected. The Boolean equations are written in PALASM and
compiled into a JEDEC file for programming the PAL chip.
At the simplest level, PALASM allows the user to enter Boolean equations that describe an
output signal as a sum-of-products function of the input signals. PALASM also includes the
higher level “if-then” type statements that can be used in implementing state machines.
Complete information on PALASM’s state machine language can be found in AMD’s
PALASM User’s Manual. (http://www.amd.com)
A PALASM design file is a simple text file with the extension “pds”. The pds file for EZ-
MICRO TUTOR™ is included below. PALASM’s Boolean operators are:
/ NOT logical operator
* AND logical operator
+ OR logical operator
= Output equation operator
; Comment delimiter
The Pin statements allow you to specify the names and attributes of the pins used in your design.
Each pin that you use in your design must be declared with pin statement. The pds file for the
EZ-MICRO TUTOR™ Gal is shown below. [attach actual file for this PAL]
TITLE 68HC11 Eval Board.. U5 8-24-2000
PATTERN REV 1.5
REVISION 1.5
CHIP U5 PAL22V10
CLK A10 A11 A12 A13 A14 RW E NC1 NC2 NC3 GND
A15 DOUT DING DAC_O RAMW DINOC LCD_RW LCD_E RAM ROM OE VCC GLOBAL
EQUATIONS
/OE = E * RW
/RAM = /A15 * /A14 * E
/ROM = A15 * E
/RAMW = E * /RW
DING = /A15 * A14 * /A13 * /A12 * /A11 * /A10 * RW * E
DINOC = /DING
/DOUT = /A15 * A14 * /A13 * /A12 * /A11 * A10 * /RW * E
LCD_RW = /A15 * A14 * /A13 * /A12 * A11 * RW
LCD_E = /A15 * A14 * /A13 * /A12 * A11 * E
/DAC_O = /A15 * A14 * /A13 * A12 * /A11 * /A10 * /RW * E
EZ-COURSEWARE 4-29
EZ-Micro Tutor Software
DAC
Most transducers and sensors produce signals that are continuous or analog in nature. For
example, sensors that are used to measure force, velocity, acceleration, temperature, volume,
weight and proximity typically produce analog voltages or currents. In addition, an electronic
system designer may need to produce an analog output signal, such as in a speech synthesis
system. Data conversions systems, namely analog-to-digital (A to D) and digital-to-analog (D to
A) converters, allow designers to interface digital microprocessors to an analog world.
In the EZ-MICRO TUTOR™ system, the operational amplifier U15 converts the unipolar
current output from the DAC into a single-ended voltage output. The reference current in the
DAC is set by R22. In the EZ-MICRO TUTOR™ system, the reference current is set to 5V /
4.7K = -1.06 mA. The transconductance gain of the op amp is set by R25 and is -(2.7K)(-1.06).
The DAC is configured to operate with a voltage range of 0-5 volts corresponding to the eight-
bit values of 0x00-0xFF. Actually, the analog output range of the DAC will be from 0 to
5*(255/256) V.
Vout=(5V/R22)*R25
ADC
The analog-to-digital converter is on-board the HC11E9.The A/D converter is a successive
approximation converter; the successive approximation A/D is the most popular type of
converter. In this A/D, each digital bit starting from the most significant bit (MSB) is in analog
form compared to the analog input voltage. If the analog voltage of this bit is less than the
incoming analog voltage, this bit value is retained for the digital output and added to the
previous one. Otherwise, it is discarded. The conversion ends when the least significant bits
(LSB) have been compared.
The A/D system is an 8-channel, 8-bit, multiplexed input converter. The converter does not
require an external sample and hold circuit because the circuit uses an all-capacitive charge
redistribution technique to convert analog signals to digital values. A/D converter timing can be
synchronized to the system E clock or to an internal resistor capacitor (RC) oscillator.
The A/D converter system consists of four functional blocks: multiplexer, analog converter,
digital control, and result storage. We will discuss each block.
Multiplexer – The multiplexer selects one of 16 inputs for conversion. Input selection is
controlled by the value of bits CD-CA in the ADCTL register. The eight port E pins are fixed
direction analog inputs to the multiplexer, and additional internal analog signal lines are routed
4-30 EZ-COURSEWARE
EZ-Micro Tutor Software
to it. Port E pins can also be used as digital inputs. Digital reads of port E are not recommended
during the sample portion of the A/D conversion cycle.
Analog converter – Conversion of an analog input selected by the multiplexer occurs in this
block. It contains a digital-to-analog (DAC) array, a comparator and a successive approximation
register (SAR). Each conversion is a sequence of eight comparison operation, beginning with the
most significant bit (MSB). Each comparison determines the value of a bit in the successive
approximation register.
The DAC array performs two functions. It acts as a sample and hold circuit during the entire
conversion sequence, and provides comparison voltage to the comparator during each successive
comparison. The result of each successive comparison is stored in the SAR. When a conversion
sequence is complete, the contents of the SAR are transferred to the appropriate result register.
Digital control – All A/D converter operations are controlled by bits in register ADCTL. In
addition to selecting the analog input to be converted, ADCTL bits indicate conversion status,
and control whether single or continuous conversions are performed. Finally, the ADCTL bits
determine whether conversions are performed on single or multiple channels.
Result registers – Four 8-bit registers ADR[4:1] store conversion results. Each of these registers
can be accessed by the processor in the CPU. The conversion complete flag (CCF) indicates
when valid data is present in the result registers.
A/D converter clocks – The CSEL bit in the OPTION register select whether the A/D converter
uses the system E clock or an internal RC oscillator for synchronization. When E-clock
frequency is below 750 kHz, charge leakage in the capacitor array can cause errors, and the
internal oscillator should be used. When the RC clock is used, additional errors can occur
because the comparator is sensitive to the additional system clock noise.
An input voltage equal to VRL converts to $00 and an input voltage equal to VRH converts to $FF
(full scale), with no overflow indication.
Make sure that your input signal to the ADC is always within the 0-5V range.
LCD
The LCD module is an off-the-shelf display module based on Hitachi’s HD44780U Dot Matrix
Liquid Crystal Display Controller/Driver. (http://www.hitachi.com) The LCD module displays
alphanumeric characters from a character generator ROM and drives a dot-matrix liquid crystal
display. Each character is formed within a 5 x 8 dot matrix. The display is 16 characters wide
and two lines deep.
The LCD module can interface directly to the microprocessor bus. The enable logic comes from
the address decode logic inside the GAL22V10.
EZ-COURSEWARE 4-31
EZ-Micro Tutor Software
Only the instruction register (IR) and the data register (DR) can be controlled by the
microprocessor. There are four categories of instruction:
1. designate LCD functions, such as display format, data length, etc.
2. set internal RAM addresses within the LCD module
3. perform data transfer with internal RAM in the LCD module
4. perform other miscellaneous functions
Normally, instructions that perform data transfer with internal RAM in the LCD module are used
the most. However, auto-increment of LCD RAM addresses after each data write can lighten the
program load of the MPU. Since the display instruction can perform concurrently with display
data write, the user can minimize system development time with maximum programming
efficiency.
Control instructions
Clear display $01
Return home $02
Entry mode set $06
Display on/off
Cursor shift
Function set
Instruction Description
Clear display
Clear display writes space code (20h)
For the 2-line display, the cursor automatically moves from the first to the second line after the
40th digit of the first line has been written. Thus, since there are only 16 characters in the first
line, the address must be again set after the 16th character is completed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
2 line 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F
C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF
4-32 EZ-COURSEWARE
EZ-Micro Tutor Software
Keypad
The EZ-MICRO TUTOR™ hardware supports a 4x4 keypad. The keypad has four rows
connected to the lower 4 bits of Port A and four columns connected to the upper 4 bits of Port A.
The rows are always outputs; the columns are always inputs. All 16 keys on the keypad are
normally open. The four columns are inputs to the processor and are pulled up to +5V through
4.7K resistors on the EZ-MICRO TUTOR™ board. The upper 4 bits of Port A will be read as
‘1’s when no key is pressed.
The microprocessor scans the 4x4 keypad in order to detect key presses by the user. Here’s how
the algorithm works. The processor drives ROW1 low while leaving the other three row lines
high. Next the processor reads the upper nibble of Port A. A low detected on any one of the four
lines indicates that a column key has been pressed. This procedure is repeated for each of the
four rows.
Note that the EZ-MICRO TUTOR™ monitor uses PA3 to support the Trace function in the
debugger. The low level keypad routines also use PA3 as one of the row output lines. For this
reason, the user may not Trace or Single Step through the keypad scanning routine.
Installation Instructions
The EZ-MICRO TUTOR™microprocessor board has been designed for table top operation. An
optional RS-232C compatible host computer can be used for downloading assembled code to the
EZ-MICRO TUTOR™microprocessor board via the I/O port connector J1. Note: Do not use a
"NULL modem" cable when connecting the EZ-MICRO TUTOR™microprocessor board to the
host computer. This may damage one or both of the serial ports.
EZ-COURSEWARE 4-33
EZ-Micro Tutor Software
If your application requires a DB-25 male pin configuration, then an optional DB-9 to DB-25
converter may be used and is shown in the following figure.
4-34 EZ-COURSEWARE
EZ-Micro Tutor Software
EZ-COURSEWARE 4-35
EZ-Micro Tutor Software
Lesson 4 Questions
SECTION ONE
2) What should you always do before starting the EZ-MICRO Manager software ?
5) How can someone get additional information concerning a particular command in one of the
pull down menus ?
6) How does the EZ-MICRO Manager software communicate to the EZ-MICRO TUTOR™
board ?
7) What is the default baud rate of the serial port interface on the EZ-MICRO TUTOR™
board ?
8) How can someone modify the contents of the EZ-MICRO TUTOR™ registers when using
the EZ-MICRO Manager software ?
9) What steps must be taken in order to download a program to the EZ-MICRO TUTOR™
board?
10) What type of hex file is produced by the EZ-MICRO Manager assembler ?
11) How does someone begin execution of a program that is downloaded to the EZ-MICRO
TUTOR™ board ?
4-36 EZ-COURSEWARE
EZ-Micro Tutor Software
SECTION TWO
2) What is the DB-9 connector used for on the EZ-MICRO TUTOR™ board ?
3) What is the purpose of the 60 pin connector (J5) on the EZ-MICRO TUTOR™ board ?
4) What mode of operation is being used on the EZ-MICRO TUTOR™ board and how do you
know ?
5) Should you use a NULL modem serial cable to connect the EZ-MICRO TUTOR™ board to
the host terminal or computer ?
6) The RS232-C standard specifies a 9 pin male connector for the DTE.
TRUE or FALSE
7) In RS232, the signal Carrier Detect (CD) indicates the modem is turned on and has received a
signal from another modem.
TRUE or FALSE
8) In RS232, when a DTE asserts the signal Request to Send (RTS), the DCE should respond
with Data Terminal Ready (DTR).
TRUE or FALSE
9) In RS232, valid voltages are within the range +25 volts to -25 volts.
TRUE or FALSE
10) A null modem cable allows two DTE devices to connect together using RS232.
TRUE or FALSE
EZ-COURSEWARE 4-37
EZ-Micro Tutor Software
4-38 EZ-COURSEWARE
Interface to the EZ-MICRO CPU-11
EZ-COURSEWARE 5-1
Interface to the EZ-MICRO CPU-11
It is not expected that an in depth understanding of these procedures will be achieved at this
time, but that an appreciation of the overall process will be attained.
Procedure
1. Boot up the PC. Run EZ MICRO MANAGER software.
2. The EZ-MICRO Manager program allows you to accomplish several tasks. It allows the
serial communication between the EZ-MICRO TUTOR™ microprocessor board and the PC.
It also allows you to assemble 68HC11 assembly code, download the assembled code to
EZ-MICRO TUTOR™ microprocessor board and execute/debug the code.
3. To provide power to the EZ-MICRO TUTOR™ microprocessor board, connect the 9 volt
AC wall transformer that is provided into a 110 Volt AC source and connect the 9 Volt plug
into the EZ-MICRO TUTOR™ power jack connector J6.
4. Connect one end of the serial cable that is provided to the COM port (or serial port) of the
PC. Connect the other end of the cable to the serial port (9 pin male “DB” connector) of the
EZ-MICRO TUTOR™ microprocessor board.
5-2 EZ-COURSEWARE
Interface to the EZ-MICRO CPU-11
6. In order to create the assembly source code file “XXXLAB1.ASM” for this example
procedure, you must select the Create Source command from the FILE menu and enter the
name of the file that you wish to create.
Note: Replace XXX by your initials. The EZ-MICRO Manager editor can be used to create
source code files that are compatible with the assembler. Enter the following source code:
ORG $2000
ARRAY RMB 10
ORG $2120
LDAB #0 * for i=0 to 9
LOOP1 LDX #ARRAY * form array { i}
ABX
STAB 0,X * array {i} = i
INCB * next i
CMPB #10 * LAST i?
BNE LOOP1 * if not, do again
LOOP2 JMP LOOP2 * wait here forever
After you have finished entering the above assembly language source code, save the file
and exit the editor.
EZ-COURSEWARE 5-3
Interface to the EZ-MICRO CPU-11
7. The next step is to assemble your source code using the EZ-MICRO Manager software. To
do this, select Assemble File from the FILE menu and select the name of the assembly
language source code file that you just created namely, XXXLAB1.ASM. Two new files
will be created by the assembler:
To view the assembled program listing, use the EZ-MICRO Manager editor (by selecting the
Edit Source command from the FILE menu) to view the file XXXLAB1.LST.
Look at the listing file to make sure that there are no assembler errors. Any errors
encountered by the assembler are probably due to typographical errors. Correct any errors in
the XXXLAB1.ASM file and re-assemble until there are no errors.
9. Examine the program in memory by using the Memory Dump command selected from the
MEMORY menu. Enter 2000 as the starting memory address to be dispalyed.
The bytes from $2120 to $212F are the machine code program that has been downloaded to
the EZ-MICRO TUTOR™ microprocessor board. The ARRAY memory space is from
$2000 to $2009 Note: It is possible that the first two lines may be other values. Do not be
concerned at this time. To excute the program, select the GO command in the RUN menu,
and enter 2120 as the address to begin program execution.
5-4 EZ-COURSEWARE
Interface to the EZ-MICRO CPU-11
The EZ-MICRO TUTOR™ will execute the program and then continuously loop on the last
instruction "LOOP2 JMP LOOP2" until the RESET button is pressed on the EZ-MICRO
TUTOR™ microprocessor board. After pressing the RESET button, examine the memory by
using the MEMORY menu and selecting the Memory Dump command. Enter 2100 as the
starting memory address.
The display will look as follows :
Note how the bytes in the ARRAY memory space ($2000 to $2009) have been initialized to
values 00 through 09.
10. Modify the ARRAY memory locations ($2000 to $2009) so that they contain FF again. To
do this, use the Block Fill command in the MEMORY menu. After selecting the Block Fill
command, enter 2000 as the starting memory address, enter 2009 as the ending memory
address and enter FF for the pattern.
11. The program could be executed again, however aside from the fact that the memory locations
change, the program flow is not very clear.The EZ-MICRO Manager offers several
commands that can aid in following program flow.These commands work together to support
tracing program flow, monitoring register and memory contents, and setting up breakpoints.
The details of these commands are contained in Lesson 4. The following exercise will use the
Register Modify and Trace commands to step through the program one instruction at a time.
The Register Modify command can be used to display and modify the contents of the A, B,
X, Y, C (condition code), S (stack pointer), and P (program counter) registers. Registers are
memory locations that are closely bound to the core microprocessor. Registers have a variety
of special functions that regular memory locations do not share.The registers that are used by
this program are B, X, C, and P.
The B register is a general purpose 8 bit wide register that is used to hold the variable that
controls the loop count, index into the ARRAY and the data that is stored in the ARRAY.
The X register is a 16 bit register that is used to address or point to, the array element that
will be initialized.
EZ-COURSEWARE 5-5
Interface to the EZ-MICRO CPU-11
The C register,often called the flag register, has bits that are set or reset depending on various
conditions that result from program execution, For this example the Z (zero) flag is used (bit
2 in the C register). The Z flag is set to 1 (true) when the execution of certain instructions
results in zero, otherwise it is reset to 0 (false).
Consider the effects of the "CMPB #10" instruction.This instruction compares the contents of
the B register to the value 10. If they are equal, the Z flag is set. If not , the Z flag is reset.
This flag setting is used in the following instruction "BNE LOOP1" to determine if the loop
should be executed again or if it has finished.
The P register contains the address of the next instruction that will be fetched. In order to
start tracing the program execution from the entry point at $2120, the P register must be
initialized to this value. Modify the contents of the P register as follows: Pull down the
DEBUG menu and select Modify Register. A dialog box will appear showing the current
register contents.
Change the value of P (or Program Counter) to 2120. Press the OK button to accept this
change to the register.
Once the P register is initialized, the Step ( F8) command can be used . Select the Step
command from the RUN menu.
The following text shows the result of steppiing the program flow through the first loop.
The assembly listing on left hand side is what you will see in the window on left labled
Program Monitor. The Register values on right hand side are the values you will see in
Registers window on upper right hand corner.Note: It is helpful to follow the program
execution with the program listing provided at the end of this chapter.
Stepping through the program one instruction at a time is a powerful way to analyze the
program flow. However , it can be noted that stepping a code section that loops many times
could become very tedious. The EZ-MICRO Manager offers another command called Set
5-6 EZ-COURSEWARE
Interface to the EZ-MICRO CPU-11
Breakpoint which allows the program to run until it reaches to the instruction where the
breakpoint has been established. At that point, the EZ-MICRO Manager monitor program
takes over and allows the memory, register and trace commands to be excuted. If there is
time left in the lab feel free to experiment with the Set Breakpoint command that is described
in Lesson 4 in this courseware workbook.
EZ-COURSEWARE 5-7
Interface to the EZ-MICRO CPU-11
Laboratory Report
The lab report for this lab will invole writing a short (1 to 4 paragraphs) description for EACH of
the major components that is contained in your EZ-MICRO TUTOR™ package .The primary
thrust of these summaries is to identify the type of information and capabilities contained in each
component. Becoming familiar with the package contents will make it easier to find infomation
as it is needed while working with the EZ-MICRO TUTOR™. It is NOT expected that all of the
documentation enclosed with the EZ-MICRO TUTOR™ will be memorized, but rather that it
should be familiar and quickly accessed to derive necessary information.
5-8 EZ-COURSEWARE
Interface to the EZ-MICRO CPU-11
EZ-COURSEWARE 5-9
Interface to the EZ-MICRO CPU-11
Lesson 5 Questions
1) What tasks does the EZ-MICRO Manager software allow you to accomplish ?
4) Why is it a good idea to generate a list file when assembling the source code ?
6) How can someone examine the program in memory that has been downloaded to the
EZ-MICRO TUTOR™ board ?
5-10 EZ-COURSEWARE
Interface to the EZ-MICRO CPU-11
EZ-COURSEWARE 5-11
Interface to the EZ-MICRO CPU-11
5-12 EZ-COURSEWARE
Introduction to Programming
Introduction to Programming
EZ-COURSEWARE 6-1
Introduction to Programming
You have probably been exposed to computer programming in a high level language. In this
Lesson we will provide at starting point for programming at the assembly code level. Computer
programs are generally written in symbolic languages, rather than in binary or hex notation. The
same is even true of assembly language programming. In Lesson Three we introduced the set of
mnemonics that exist for the 'HC11 instruction set. Now we will use this instruction set to build
basic programming structures such as tables, lists, loops and subroutines.
The essential difference between all the assembly, or low level, languages and a high level
language is the relationship between all the source code instructions and the machine code. An
instruction written in an assembly code will be assembled in a one-for-one translation into the
machine code. This is not true for a high level language where each statement will probably
result in many instructions in machine code.
The main advantage of the compiler that you use to compile your Basic or C is that the source
program statements actually look like English and can be read easily. For example, one
statement in a high level language can solve a complete problem. It can define a number of
alternative results dependent upon any calculable conditions, whereas an instruction in an
assembly language could define only one stage in the arithmetic operation or one simple
conditional branch.
As a simple example of what is possible with a high level language, a typical statement is shown
below in a pseudo-code format:
To generate its equivalent in a low level language would be more complex and would require a
routine of several program statements. One equivalent routine implemented in 'HC11 assembly
language is shown below.
Through the use of examples, in this Lesson we will provide an introduction to assembly
language programming. The techniques described and developed within this Lesson will be used
in the Laboratories that accompany each of the remaining Lessons in the EZ-Micro course. The
major ideas to be discussed include look-up tables, lists, loops, and subroutines.
6-2 EZ-COURSEWARE
Introduction to Programming
Addressing Modes
The most used instruction is probably LDA, which puts a byte into the accumulator. We will use
this instruction to explain some addressing modes and to show how to read your Motorola
reference materials. The instruction LDA has two types, LDAA and LDAB referring to the A
and B accumulators, each being one byte registers. We will mostly use the A register.
1) The instruction LDAA #$3B means "put the binary equivalent of the hex number 3B
into accumulator A". We said binary equivalent because all numbers are reduced to binary when
they end up inside any kind or RAM. We could write the instruction as LDAA #59 and get the
same result because 59 decimal equals 3B hex, and they both equal 00111011 binary. The
assembler will know when it sees the $ sign to read hex and if there is no $ sign it will read
decimal. It is often helpful to write the instruction directly in binary, LDAA #%00111011,
because this lets you see which bits are high and low. These might be output pins connected to
switches.
The key element in this instruction is the # sign. This indicates immediate mode and lets the
assembler know that you want the number 3Bhex put into A and not the number-in-the-address
3Bhex as in the next example.
2) LDAA $49 means "copy the byte(number) which is in address 49hex of memory into
the accumulator A". This is Direct Mode and only memory addresses from O through FFhex
(255) are used.
3) The most general form is LDAA $23B7 which will copy a byte from any address in
the 68HC11 memory space (from O thorough FFFFH) into the accumulator. This is extended
mode.
4) The instruction LDAA $4, X says "read the address in X, add 4 to it to get the address
X+4, and then copy the byte in X+4 into the accumulator". Of course we must have an
instruction somewhere before in the program which places an address into X (X holds a 2 byte
address so this instruction can also work throughout the entire 64K memory area.
Note that we do not know what is in A now because we do not know what number is in address
1022H.
Lets resolve this problem as follows.
EZ-COURSEWARE 6-3
Introduction to Programming
A now contains the number 23H. -We do not move numbers directly into or out of memory. We
always move by way of the accumulator. Accumulator B was used above just to show it is
equivalent to A. We could have used only A.
5) Index Y is used in the same way as Index X. The assembly language code will be
identical. There is a slight difference in how the processor creates the same result. We discuss
that now.
First, for practice, look in your references and find the Opcodes for LDAA. In the IMM mode it
shows the code as 86 ii. That means the machine language bytes for this instruction are 86H
followed by iiH, where ii is the single byte number you placed in the instruction. For example in
LDAA #S3A the instruction LDAA # is machine code 86H, and ii is replaced by 3AH. That
makes a total of two bytes for the instruction (see the Byte and Cycle columns next to the
Opcode column). When this instruction ends up in your system memory it will take two
consecutive bytes, the first will hold 86H and the second will hold 3AH.
Now look in your reference and find the Opcode for LDAA $0, Y. It is 18H+A6H, and the
operand ff is $0 in this example. This is a three byte instruction as opposed to LDAA $0, X
which is a two byte instruction. Also notice the Index Y LDAA instruction requires five cycles
whereas the Index X LDAA requires only four cycles. With a 4MHz crystal each cycle is 1
microsecond. These two-byte Opcodes appear first in the 68HC11. The older Motorola 6800
microcontroller, which uses the same one byte machine codes as the 68HC11, has only one byte
instructions.
There are two more addressing modes: Inherent (INH), and Relative (REL).
Inherent is the simplest mode. Inherent mode instructions have nc Operands. For example, DEX
is an instruction which reduces the value of the X register by one. If X holds the value 4567H
and you give the instruction DEX the new value in X will be 4566H. DEX is a one byte
instruction. However the equivalent instruction for register Y, DEY, is a two byte instruction.
Relative addressing refers to the branch instructions. It means you can jump back 128 bytes of
code or forward 127 bytes of code relative to your present position. For example, the instruction
BRA 100 means jump forward 100(decimal) bytes of code and continue from there. Here is
where an assembler does some work for you. The instruction would normally be given as BRA
LABEL1 where LABEL1 is a label placed later (but not too much later or you will get an error
message, or worse yet not get one) in your code. The assembler will determine how many bytes
of code from your present position to LABEL1 and replace LABEL1 in the instruction BRA
LABEL1 with the correct number. Otherwise you have to get out your Programming Guide and
start counting bytes. By the way, LABEL1 is just a name we made up; it has no special meaning
to the 68HC11 or the assembler.
6-4 EZ-COURSEWARE
Introduction to Programming
Programming Examples
Now that you understand how to use the reference materials we can go -ahead and give examples
without explaining every detail about each instruction. Also when you see the list file created by
the assembler you will know how to interpret the hex bytes (Opcodes and Operands) given in the
left columns.
The above program will turn on the 4 led's, but in a rather crude way. It follows that we did not
need to send zeros to all of the port pins, four pins would do. In fact by changing all the bits in
these registers we may upset some othe part of the system which uses these pins. We need some
way to change only those pins of interest while not affecting the others.
Let's try again, this time changing only pins 2, 3, 4, and 5 of port D We use "masks" and logic
instructions.
EZ-COURSEWARE 6-5
Introduction to Programming
Notice that the instructions ANDA can use extended addressing so the full addresses of
LEDOUT can be used in the instructions.
ORG $2000
;Setup Register DDRD
LDX #$0000
BSET DDRD,X %11111111
;
BCLR PORTD, X %11110000
END
The BSET and BCLR instructions will meet many of your needs in manipulating the I/O pins of
the controller.
Remember the reset location of the Control Registers is starting at 1000H but the EZ-MICRO-11
moves these registers to start at 0000H. DDRD is at 1009H after reset. We then move it to
0009H. Therefore we say DDRD EQU $09 and set X=$0000 so that when we use indexed
addressing the address X+DDRD = 0009H.
The JUMP instruction place the address we want the program to jump to in the PC. The JUMP
instruction can be executed in one of two modes: extended or indexed. It can jump anywhere in
memory.
JMP Label5 ;jump to execute the instruction at Label5
.
.
.
Label5 LDX #$1000 ;any instruction codes in memory
6-6 EZ-COURSEWARE
Introduction to Programming
BRANCH instructions differ from JUMP instructions in that they do not supply a direct address.
The address to be jumped to (branched to) is always relative to the current address in the
program counter. The addresses must be within 128 bytes from the current PC.
Mostly, branch instructions use the condition codes to decide whether to branch. Condition
codes are states of the bits (N,Z,V,C) in the Condition Code Register (CCR). Some branch
instruction do not use the condition codes at all. For example, BRA (branch always), BRN
(branch
never).
ORG $2000
BRA MAIN ;branch to where MAIN located at 2050H
ORG $2050
MAIN BRA MAIN ;program does nothing, loops forever
END
JMP will always work, so why not use JMP instead of BRA? JMP takes up one extra byte of
program memory (see your Opcodes table).
BEQ (Branch if equal) tests the state of the Z bit in the CCR and causes a branch if Z is set.
Check CMP (two forms CMPA and CMPB) in your 68HCll Reference Manual. Look where it
says "Operation (ACCX)-(M)". That means it will subtract 41H (in this example) from the
value in A and inspect the resulting number; A does not change. The only action this instruction
takes is to set some CCR bits for use by later instructions. In this example we are interested in
the z-bit because that is the only bit which the BEQ instruction looks at.
LDX #$0000
EZ-COURSEWARE 6-7
Introduction to Programming
Using Subroutines
When we write a program, we often find that we are repeating the same sequence of instructions
in several different parts of the program. These sequences of instructions must be used at
different places in the program. Without the subroutines, we would be forced to repeat these
sequences of instructions in the source code, and the machine instructions generated by the
assembler would be repeated in memory creating a larger program, plus much extra typing.
Fortunately, we have the ability to define subroutines and to use the instructions that support
them.
;MAIN PROGRAM
;Demonstrate subroutine
;The program calls the delay subroutine to delay some machine cycles
;your program lines, and then a jump to sub
.
.
.
JSR DELAY ;jump to subroutine
;SUBROUTINE DELAY, subs usually put after the main program
DELAY
PSHX ;save content of IX register on stack
LDX #FFFF ;place FFFFh into IX
L1: DEX ;decrement IX ~
BNE L1 ;loop back and decrement until IX = 0000
PULX ;restore IX register from stack
RTS ;return from subroutine
END ;end of assembly
There may have been a value in the X register which we need when we return to the main
program. So we push original value X on the stack and save it until the end of the subroutine and
then pop (pul) it off the stack just before returning. It is good programming practice to make sure
all registers which are used in the sub are restored this way to their original values upon
returning from the sub.
6-8 EZ-COURSEWARE
Introduction to Programming
The assembler equates the address of the first data byte (41H) with t label TABLE. The fourth
data byte is 44H and it is 3 data bytes after t first data byte 41H. That is why we put LDAB #$3
to get to the four byte.
Software Interrupt
When you run test programs with the debugger you can insert S instructions (inherent mode) in
the program at points of interest. T debugger will stop your program at that point and return to
the comput display screen with the current register values. You can also che memory data with
the M XXXX command. To continue with the program ju use the C command. This way you can
see what is going on with CCR bit the accumulator etc., or your program variables. A little
practice wi this technique is worth thousands of words.
Here are some miscellaneous instructions and programming steps you wi find useful.
Clear Instruction
CLRA ;clear Accumulator A
CLR $5000 ;clear memory byte at 5000Hex
EZ-COURSEWARE 6-9
Introduction to Programming
Addition Instructions
LDAA #$50 ;put 50hex into A-accumulator
STAA $200 ;store 50Hex at the address of 200Hex
LDAA #$6
ADDA $200 ;Add 50hex with 6Hex (A now contains 56Hex)
LDAB #$2 ;place 2Hex in Accumulator B
ABA ;add A and B then put the result in A
;A-register now has 58Hex
ABA Instruction
LDAA #$FF ;A = FF
LDAB #$6 ;B = 6
ABA ;A+B-,A , add A and B
;result A = 05H, with carry flag set
;so the result is 105H
;total is more than FFFFH so the carry flag was set. total ls 18EA6H
NEGATE Instruction
The NEGATE Instruction will perfor,m a 2s complement negation of a number by subtracting
it from 00.
LDAA #%00000101 ;place 5Hex in A-register
NEGA ;A = 11111011
Multiplication Instruction
Multiply A x B -> D
LDAA #$FE
LDAB #$FD
MUL ;result is FB06hex (A = FB, B = 06)
AND instruction
LDAA #%00111001
ANDA #%00001111
;after ANDA instruction A =%00001001
6-10 EZ-COURSEWARE
Introduction to Programming
Look-up Tables
Look-up tables can provide the embedded systems designer the capability to generate or translate
data that cannot be calculated due to timing constraints.
Microprocessors are especially well suited to keep track of and access tables and lists.
In Lesson Three, the 2-byte index register was introduced. In the indexed addressing mode, the
contents of the index register are used to compute an indexed address. The indexed addressing
mode is best illustrated by example. Suppose the index register contains $1000.
In the instruction
LDAA $05,X
the X part tells the assembler that this is the indexed addressing mode. Executing the instruction,
the 'HC11 adds the offset (5 in this example) to the contents of the index register ($1000 in this
example) and the sum is the address of the data which is loaded into accumulator A.
There are instructions that directly affect the index register. Refer to Lesson Three where we saw
that the instruction STX is similar to STA; the contents of the index register is stored in two
consecutive memory locations. Two other instructions that affect the index register are INX,
which will increment the index register and DEX, which will decrement the index register.
In a look-up table two equivalent sets of values are stored side by side so that any value can be
retrieved easily. A temperature conversion chart is a familiar example of a look-up table. To look
up the equivalent temperature in degrees C for a temperature given in degrees F, we could use
the table shown in Figure 6.1 below. The advantage of using this table is that we avoid
multiplication by a fraction. The disadvantage of using this table that we cannot lookup the
equivalent temperature in degrees C for 20.5 degrees F.
deg F deg C
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Figure 6.1 Lookup Table for Temperature Conversion
EZ-COURSEWARE 6-11
Introduction to Programming
There are many uses of tables in computing. For example, a computer can perform the square
root operation in a number of ways. One way is to store a table of all the possible values of
square roots and look up the answer for a given number. Depending on factors such as length of
the calculation and the sized of the table, the programmer will have to choose between
performing the required calculation and using a look-up table.
Now, as another example, we will use indexed addressing in the 'HC11 to retrieve the square of a
number by retrieving the value from a look-up table. Refer to Figure 6.2, which shows the table
is squares stored in data memory beginning at address $1000.
LDX #$1000
LDAA $2,X
STAA SQUARE
The index register has been loaded to point at the base of the table. The address pointed to by the
LDA A instruction is computed by adding the offset ($02) to the contents of the index register
($1000) which $1002. The contents of the location $1002 is $04 which is the squared value that
we are after.
Lists
We can think of a list as a one-dimensional table or an array. The text editor in the EZ-Micro
Manager software works with a list of ASCII characters. There are many ways to manipulate this
list. We may want to move it to another location, search through it for specific items, or delete
items.
First, consider a simple example. Suppose we want to create a list of all zeros starting with
location $1000 and ending with location $101F. Your software could use the CLR instruction to
clear each individual memory location between and including these addresses. However, the
resulting program would not make very efficient use of program memory.
Alternatively, we would like to make a loop that uses just one CLR instruction and steps through
the list clearing each location sequentially. As we did with tables, we will use the indexed
addressing mode.
6-12 EZ-COURSEWARE
Introduction to Programming
Loops
Counting loops
In a counting loop we go through the loop a definite number of times. We define a loop counter
as a device used to keep track of the number of times through a loop. The loop counter can be a
register or a memory location; the only requirement is that we must be able to load, increment,
and decrement the loop counter.
Consider an example where we want to go through a loop 5 times. First of all, we can either
count up or count down. If we start at 0 and count up, we want the 'HC11 to execute the loop for
values of the counter equal to 0, 1, 2, 3, and 4.
Our software must exit the loop after the loop hits 5 but before executing the loop for the sixth
time.
If we start at 5 and count down, we want the 'HC11 to execute the loop for values equal to 5, 4,
3, 2, and 1. Our software must exit the loop after the loop counter hits 0 but before executing the
loop for the sixth time.
In general, because the 'HC11 can automatically check the Z bit, it is more efficient to count
down. In order for our software to detect when the loop counter hits a non-zero number (like 5)
we must use the compare instruction. The code segment below shows an implementation of a
counter that decrements from 5 to 0. The instructions inside the loop execute exactly 5 times.
LDAA #5
COUNT DEC A
:
{instructions inside the loop}
:
BNE COUNT
Timing Loops
Counting is a good way to create a programmable delay in your software. The 'HC11E0 in the
EZ-Micro Tuotr architecture is running at 1 MHz and yet our application may be required to
blink a light once every 5 seconds. Alternatively, our software may need to time a 5 millisecond
delay in a communications application.
In any given microprocessor each instruction in each addressing mode takes a precise and
deterministic amount of time to execute. This means that we can calculate how long it takes to
make a certain number of passes through a loop. By looking at each instruction's information
sheet, we can identify the "execution time", a value given in terms of cycles. The cycle time of
the 'HC11 on-board the EZ-Micro Tutor Board running from an 8 MHz crystal is 500 ns. The
LDAA instruction requires 4 cycles to execute in the immediate addressing mode. This means
that it takes 2 usecs for LDAA #5 to execute on the EZ-Micro Tutor system. Take note of Table
6.2 below, where the execution times of a few common looping instructions are provided.
EZ-COURSEWARE 6-13
Introduction to Programming
Now let's revisit our code segment that executes a loop five times. This time we will modify the
code segment such that there are only two NOP instructions inside the loop. The NOP instruction
is typically used to provide additional delay.
LDA #5
COUNT DEC A
NOP
NOP
BNE COUNT
The initialization of the loop only occurs once. The LDA instruction requires 1 usec. The time
for 5 passes through the interactive part of the loop can be computed as 5 passes x 5 usec/pass =
25 usec. So the total time required for one execution of the loop is 26 usecs.
The largest loop counter that we can create with a single byte of memory or a single byte register
is 256. However if we now use a 16-bit register as a loop counter we can count up to (or down
from) 65,535. For a loop that requires 10 cycles per iteration, the total time required for one
execution of the loop is now 327,675 usec plus 1 usec to initialize the loop. Notice that as the
time required for all the iterations grows large the time required to initialize the loop becomes
less and less significant.
The index register is a 16-bit register that is very well-suited for a loop counter.
The instructions LDX, INX and DEX make it easy. For example, consider the following code
segment that creates a delay of a little less than 0.3 seconds.
6-14 EZ-COURSEWARE
Introduction to Programming
Nesting our 0.3 second loop inside a counting loop of 5 will provide us with a delay of about 1.5
seconds. The short segment of assembly code shown below demonstrates one way in which this
nested delay can be implemented.
LDA #5
OUTER_LOOP DECA
LDX #65,535
COUNT DEX
BNE COUNT
BNE OUTER_LOOP
Subroutines
Depending on how much experience you've had with higher level languages, you may have
already been introduced to subroutines and functions. Any routine that can be used over and over
again is a good candidate for a subroutine. Take for example the multi-second delay that we just
developed in the last section. Suppose we name that code segment DELAY1. Then as part of a
much larger program we could just branch to the routine DELAY1.
Of course, there's one problem with this programming technique. After the delay routine finishes
execution, what code will the microprocessor execute next? What we would like to do is to
return back to the main program and continue executing that code beginning at the instruction
immediately following our branch instruction. Sounds like what we need is some kind of a
bookmark in our main program to keep track of where we should return to.
As we learned in Lesson Two, practical programs frequently need to save values and addresses
generated by an operation for use later in the program. A stack is a means of temporarily storing
return addresses or data when the CPU is executing a routine. The stack may be located
anywhere in the 64K address space of the 'HC11 and may be any size up to the amount of
memory available in the system. The 16-bit register called the stack pointer controls the
operation of the stack.
The Program Counter (PC) is a 2-byte register that holds the address of the next location whose
contents are to be fetched. Obviously this is an important pointer that we don't want to loose
track of.
Now we see that the bookmark that we spoke of earlier is implemented by pushing the program
counter onto the stack. This operation frees the program counter for subroutine use. After the
microprocessor finishes execution of the subroutine, it pops the old program counter contents
from the stack and resumes executing the main program.
When we transfer control from the main program to the subroutine we are calling the subroutine.
In the 'HC11 there are two instructions for calling a subroutine — BSR and JSR. Both of these
instructions automatically cause the microprocessor to push the current program counter onto the
stack before executing the first instruction of the subroutine.
EZ-COURSEWARE 6-15
Introduction to Programming
When we transfer control back to the main program from the subroutine we are returning from
the subroutine. In the 'HC11 the RTS instruction is used for returning from a subroutine. This
instruction automatically causes the microprocessor to pop the program counter from the top of
the stack and continue from there.
One additional note — the program counter is a 16-bit register. The stack is 8-bits wide by
definition because it resides in memory. For this reason, during a subroutine call, two bytes
representing the program counter are pushed onto the stack. First PCL is pushed followed by
PCH. Also recall that the stack grows from high memory towards low memory. This means that
if the stack pointer contents were $001F and the program was pushed onto the stack then PCL
would be in address $001F and PCH would be in $001E. Of course, the program counter is
popped off the top of the stack in reverse order. First PCH is popped followed by PCL.
Let's look at one example in detail. Suppose it is necessary to convert a binary number into its
ASCII equivalent at a number of different places within a program. This could be accomplished
by making multiple copies of the conversion routine and placing them at the required points
within the program. The resulting program may be difficult to maintain and requires additional
program memory. For this reason, we decide to create a subroutine. The binary number must
somehow be transferred to the subroutine for conversion. Similarly the subroutine must
somehow transfer the ASCII character back to the main program.
Passing parameters
Subroutines like the DELAY routine do not require that any data be passed into it. By the same
reasoning, the DELAY routine does not return any data either. However, usually, we want a
subroutine to operate on variable data that is supplied to it by the main program, like the ASCII
conversion example. Giving data to a subroutine and getting data from a subroutine is called
passing parameters.
One way of passing parameters is through memory locations. Memory locations are defined by
the main program and used by the subroutine. One advantage of this scheme is that in general
there will be a lot of available memory for passing parameters. One drawback with this scheme
is that it is not portable. If I try to call your subroutine with my main program I may not have the
memory locations available that you are expecting to be free. Using the ASCII conversion
example, this method is demonstrated in the following code segment.
ORG $2000
MEM_XFER RMB 1
ORG $3000
MAIN LDX #$0020
TXS * initialize stack ptr
LDAB BYT2CONV * load ACC B with byte to convert
STAB MEM_XFER * load data memory
JSR BN2ASC * jump to subroutine
LDAB MEM_XFER * retrieve ASCII character
: * continue with main code
:
6-16 EZ-COURSEWARE
Introduction to Programming
* Subroutine BIN2ASC
* Pulls byte from stack and converts to ASCII character '0' - '9'
* Sets msbit if out of range
BN2ASC LDAB MEM_XFER * load byte from memory into ACCB
CMPB #0 * check for out of range
BMI B2AERR
CMPB #10
BGE B2AERR
BRA B2A
B2AERR BCLR
BSET #$80
B2A ORAB #$30
STAB MEM_XFER * put the ASCII character in memory
RTS
Another way of passing parameters is through an accumulator. This scheme has the advantage of
portability. We can save the value that the main program had in the accumulator by pushing that
value onto the stack before making the subroutine call. Later the main program can restore the
original value to the accumulator by popping that value off the top of the stack. Again using the
ASCII conversion example, this method is demonstrated below.
ORG $2000
MAIN LDX #$0020
TXS * initialize stack ptr
LDAB BYT2CONV * load ACC B with byte to convert
JSR BN2ASC * jump to subroutine
: * ASCII character in ACC B
: * continue with main code
:
* Subroutine BIN2ASC
* Pulls byte from stack and converts to ASCII character '0' - '9'
* Sets msbit if out of range
BN2ASC CMPB #0 * check for out of range
BMI B2AERR
CMPB #10
BGE B2AERR
BRA B2A
B2AERR BCLR
BSET #$80
B2A ORAB #$30
RTS
A third, and perhaps more powerful, method involves storing the parameter on the stack prior to
making the subroutine call. This method is commonly used in high level language compilers
since it is a flexible scheme that produces portable code. Consider the following code segment of
our ASCII conversion example.
EZ-COURSEWARE 6-17
Introduction to Programming
ORG $1000
ORG $1000
MAIN LDX #$0020
TXS * initialize stack ptr
LDAB BYT2CONV * load ACC B with byte to convert
PSHB * push it onto the stack
JSR BN2ASC * jump to subroutine
PULB * put ASCII character in ACC B
: * continue with main code
:
* Subroutine BIN2ASC
* Pulls byte from stack and converts to ASCII character '0' - '9'
* Sets msbit if out of range
BN2ASC TSX * copy stack pointer into X
LDAB 2,X * point to the byte to convert
* and load in ACCB
CMPB #0 * check for out of range
BMI B2AERR
CMPB #10
BGE B2AERR
BRA B2A
B2AERR BCLR
BSET #$80
B2A ORAB #$30
STAB 2,X * put the ASCII char on the stack
RTS
The stack is empty prior to setting up the subroutine call; that is, the stack pointer points to
$001F ready to push a byte onto the stack. When the byte to convert is pushed onto the stack, the
byte is stored at $001F and the stack pointer is updated to point to $001E, ready for the next
push. When the subroutine is called, the return address (contents of the program counter which
point to the next instruction to be executed after the JSR) is pushed onto the stack, one byte at a
time, and the stack pointer is updated to point at $001C.
At this time, the byte for conversion is stored at (stack pointer + 3). A careful review of the TSX
instruction reveals that the address loaded into the X register actually equals the contents of the
stack pointer + 1. That is why the constant offset used in the indexed addressing mode is a '2' and
not a '3'. Similarly, the TXS instruction loads the contents of the X register - 1 into the stack
pointer.
In this example, only a single byte was passed as a parameter. It is not difficult to extend this
concept to include a long list of parameters.
A fourth way of passing parameters is by passing a pointer. This may be particularly useful if we
have a lot of parameters to pass. Suppose we have a list of numbers for which we want to
6-18 EZ-COURSEWARE
Introduction to Programming
compute the sum. Instead of passing the numbers themselves to the subroutine, we can pass a
pointer that tells where the numbers are. The code segment below is an example of how a
program might pass a set of parameters via a pointer. The list of numbers to be summed is 16
entries long; no check is made for overflowing a value of 255.
* Subroutine SUM
* This subroutine computes the sum of a list of numbers
* The starting address of the list is passed in the index
* register. The length-1 is passed in ACCB.
* The subroutine returns the mean value in ACCA
=========
INIT LDA A #2 * initialize stack pointer
STA there
* enable interrupts
RTS * return to main program
EZ-COURSEWARE 6-19
Introduction to Programming
about returning from the subroutine was that the microprocessor restores control to the main
program at the point where the subroutine was called.
Now we will consider another special section of code called an Interrupt Service Routine, which
is a kind of special-purpose subroutine. Whenever an interrupt occurs that needs to be handled
by the microprocessor, the microprocessor services the interrupt by transferring control to a
program called an interrupt service routine. You will write the ISR especially for the situation
that caused the interrupt. After servicing the interrupt, the microprocessor restores control to the
main program at the point where the subroutine was called.
Interrupts
We saw that when the microprocessor makes a call to a subroutine, the internal hardware
automatically saves the program counter contents. Un subroutine calls only the program counter
contents are the microprocessor's responsibility. If we want to save additional registers then it is
up to us to push these onto the stack.
When an interrupt occurs, however, we get more help from the microprocessor. When the
microprocessor receives an interrupt (except RESET) it pushes the contents of all the registers
except for the stack pointer onto the stack. These registers include the program counter (2 bytes),
the index register (2 bytes), ACCA (1 byte), ACCB (1 byte), and the status register (1 byte). This
means that the stack pointer contents will always be 7 less right after an interrupt. This process is
called saving the program context.
The instruction RTI is similar to the RTS instruction in that its purpose is to put things back the
way they were before the interrupt. It restores the program context by popping registers from the
stack. Control is transferred back to the point in the program where it was interrupt because the
program counter contents are restored. The I bit in the status register is automatically restored
because we are returning the pre-interrupt status register from the stack.
What operations does our software have to perform in the interrupt service routine?
The answer to this question depends of course on the source of the interrupt. However, we can
still make generalizations about what must be accomplished inside your ISR.
The first thing your ISR will have to do is pro-actively control whether or not you want to be
interrupted from servicing this interrupt. In the EZ-Micro TUTOR Laboratories, we do not want
to support nested interrupts. For this reason, we want to make sure that interrupts are disabled
while we are in the interrupt service routine. This is the default case for the 'HC11
microprocessor. Also, we must make sure that when we leave the ISR that the correct interrupts
are enabled. Again, the 'HC11 microprocessor takes care of this for us by default.
The second thing your ISR will have to do is to push any data onto the stack that you want to
protect. Later, when your ISR is complete and you are ready to return from this interrupt, you
can pop these data back off the stack to their original locations.
Next your ISR will perform the "meat" of the work. If the source of the interrupt was that serial
data was received, then your software will go and read the serial data. We will see many more
practical applications of interrupts in the later Lessons and Laboratories.
6-20 EZ-COURSEWARE
Introduction to Programming
The final thing that we must do before our ISR passes control back to the main program is clear
the source of the interrupt. Under many conditions, the normal program flow will be sufficient to
clear the source of the interrupt. For example, vectoring to the ISR and then reading data may be
enough to clear the source of a serial port interrupt. However, this may not always be the case.
We must make sure that we clear the source of the interrupt. Otherwise, when we return control
back to the main program there will be an interrupt pending; it will be the same interrupt that we
just service. You can see that the result will be an infinite loop and we will loose control of our
program.
Interrupt vectors
Where should our interrupt service routines reside in program memory? The highest locations in
the 'HC11 memory are assigned to the interrupt vectors. There are two vectors for each interrupt;
one for the low and one for the high-order byte of the address of its service routine. Figure 6.3
shows the assignment of the interrupt vectors for the 'HC11.
$FFD6,D7 SCI
$FFD8,D9 SPI
$FFDA,DB Pulse Accumulator Edge
$FFDC,DD Pulse Accumulator Overflow
$FFDE,DF Timer
$FFE0,E1 Timer Input4/Output5
$FFE2,E3 Timer Output Compare 4
$FFE4,E5 Timer Output Compare 3
$FFE6,E7 Timer Output Compare 2
$FFE8,E9 Timer Output Compare 1
$FFEA,EB Timer Input Capture 3
$FFEC,ED Timer Input Capture 2
$FFEE,EF Timer Input Capture 1
$FFF0,F1 Real-Time interrupt
$FFF2,F3 IRQ* pin
$FFF4,F5 XIRQ* pin
$FFF6,F7 Software Interrupt
$FFF8,F9 Illegal Opcode
$FFFA,FB COP failure
$FFFC,FD Clock Monitor Fail
$FFFE,FF RESET
Figure 6.3 Interrupt Vectors
EZ-COURSEWARE 6-21
Introduction to Programming
The location of the interrupt vectors is part of the hardware of the microprocessor, but the
contents of the interrupt vectors are determined by the system designer. In the EZ-Micro Tutor
architecture, there are "dummy" addresses in each user interrupt vector. This gives you a handle
on the interrupt vector so that your interrupt service routine can still be pointed to. You can
either place your routine at the dummy address or point to another location in memory by using a
jump instruction.
Figure 6.4 below shows you where the dummy addresses are for some interrupts used in the EZ-
Micro Tutor Laboratories so your interrupt service routines can be pointed to.
6-22 EZ-COURSEWARE
Introduction to Programming
ORG $0900
num1 RMB 1
num2 RMB 1
sum RMB 1
ORG $1000
LDAA num1
ADD num2
STAA sum
However, you must carefully consider what happens after the microprocessor executes the final
STAA instruction. Unless you control what happens next, the program counter will be pointing
to the "next instruction". The trouble is that there is no "next instruction". In the Labs for the EZ-
Micro Tutor Board you will terminate your program with an infinite loop. Simply add the
following lines to the end of your code.
TERM_LOOP NOP
NOP
BRA TERM_LOOP
Also, consider an example where you are writing software for a microprocessor based system
that is interrupt-driven. Most of the time your software is simply waiting for an interrupt to
occur. For this application you may want to incorporate a WAI instruction (Wait for Interrupt)
into your code.
EZ-COURSEWARE 6-23
Introduction to Programming
Questions
Laboratory
The exercises in this Laboratory are designed to tie together all of the programming techniques
that were introduced in this Lesson. The simple programs that you write in this Laboratory will
become the basis for the more complex programs that you will write in future Laboratories. For
this reason, it is important that you understand the concepts discussed on this Lesson.
Indexed addressing will be used extensively in all of the remaining EZ-Micro Tutor Labs.
Counting loops and time delay loops will be used in the routines that support the keypad and
display.
As our programs become more complicated, we will naturally want to construct our code so that
it is more understandable and readable. We will use subroutines throughout. Finally, because we
don't want the microprocessor to be constantly polling status flags, our software will be
interrupt-driven in the remaining Laboratories.
Laboratory 6_1
Write a program that uses a look-up table to compute the square of a given number. The number
will be in the range from 0 to 10. While developing your program, use the following guidelines.
1. Choose $3000 as the origin of your program code segment.
2. Choose $2000 as the origin of your look-up table.
3. Assume that the number to be squared is in Accumulator B. Use LDAB #3 as the
default.
Assemble your program and make sure that there were no errors. Download your program to the
EZ-Micro Tutor Board. Execute your code and verify proper operation. Using the single-step
feature of the EZ-Micro Manager software, step through your code from the beginning. Pay
close attention to the X register and observe how indexed addressing works.
Laboratory 6_2
Write a program that creates a delay of approximately 1 second and then increments the contents
of Accumulator A and delays again. This delay-then-increment process should continue
indefinitely. While developing your program, use the following guidelines.
1. Choose $2000 as the origin of your program code segment.
2. Create a nested loop; use index register X as the inner loop counter and ACCB as the
outer.
Assemble your program and make sure that there were no errors. Download your program to the
EZ-Micro Tutor Board. Execute your code and verify proper operation. As a rough check, halt
execution of your program after 10 seconds. You should see a value of $0A in Accumulator A.
6-24 EZ-COURSEWARE
Introduction to Programming
Laboratory 6_3
Convert the program from Lab 6_1 into a subroutine. Write a main program that calls the look-
up routine four successive times in order to get the square of four different numbers. Your
program should terminate at that point. Use the following guidelines as you develop your
program.
1. Choose $3000 as the origin of your program code segment.
2. Choose $2000 as the origin of your look-up table.
3. Find the squares of 4, 1, 8, and 3.
Assemble your program and make sure that there were no errors. Download your program to the
EZ-Micro Tutor Board. Execute your code and verify proper operation. Using the single-step
feature of the EZ-Micro Manager software, step through your code from the beginning. Pay
close attention to the stack as program control passes from the main program to the look-up
subroutine and back to the main program again.
EZ-COURSEWARE 6-25
Introduction to Programming
6-26 EZ-COURSEWARE
Introduction to C Programming
Introduction to C Programming
EZ-COURSEWARE 7-1
Introduction to C Programming
History of C
"C was originally developed by Dennis Ritchie of the Bell Laboratories in 1972. The language
was named "C" because it was the successor to a language named "B" (no lasting fame,
however). C was developed as a high level language that could be used to rewrite the UNIX
operating system. Today, most of the UNIX operating system and most of the programs that run
under UNIX are written in C."
— C Programming Language
Earl L. Adams 1992
Benefits of C
C has an extensive library for mathematical computations, character analysis, input and output
functions, hadware structure, and graphics. While some functions are used more that others, they
are all offered and are able to be used by the best programmers. Why write a code to find square
roots or alter strings, when there are "header" files that can be used to call these special
functions. C is also a relatively easy language to learn, so that you can also write some programs
for your everyday life. Yes, there are more advance programs, but it is easy enough to learn to
write simple programs.
C Compiler
Basicly, a compiler takes as input a file containing "Source Code", or a set of (semi) human
readable commands, and translates it into machine code. The translation is the output of the
compiler. As far as running the code, that is done by the OS, at least the invokeing of the
machine code. Technicaly, the computer (hardware and all) "runs" the code.
Keywords
There are 32 words defined as keywords in C. These have predefined uses and cannot be used for
any other purpose in a C program. They are used by the compiler as an aid to compiling the
program. They are always written in lower case. A complete list follows;
7-2 EZ-COURSEWARE
Introduction to C Programming
In addition to this list of keywords, your compiler may define a few more. If it does, they will be
listed in the documentation that came with your compiler. Each of the above keywords will be
defined, illustrated, and used in this tutorial.
Integer
There are two type of Intergers namely, Whole numbers (which can be positive or negative) and
Unsigned integers. In both of these types there can be long or short integers.
int is the keyword used to define integers in C Programming. The following C statement is being
used to declare integer variable called weight and the value of this variable is 16.
int weight;
weight = 16;
Floating Point
The floating point numbers can be postive or negative and they are fractional numbers such as
3.14 or -2.5.
float is the keyword used to define Floating Point numbers. The following C statement is used to
define float variable pi and the value of this variable is 3.14
float pi;
pi = 3.14;
Double
Double numbers also can be positive or negative and they are exponential numbers such as
3.14E5.double is the keyword used to define Double numbers. The following C statement is used
to define pi with more accuracy than 2 digit decimal number defined in above example.
double pi;
pi = 314E+5;
Character
As the name implies these are the ASCII charactres such as X ,Y,Z etc. A char is the keyword
being used to define Character. The following C statement is used to define key which as value
of X
char key;
key = 'X'; Must use Single quotes to define Single character.
EZ-COURSEWARE 7-3
Introduction to C Programming
main()
{
int weight;
float pi;
char key;
double pi;
7-4 EZ-COURSEWARE
Introduction to C Programming
Operators:
There are two types of Operators, Arithmetic operator and the Relational Operators.
Arithmetic Operators
The symbols of the arithmetic operators are:
Operation Operator
Multiply *
Divide /
Addition +
Subtraction -
Increment ++
Decrement --
Modulus %
Operation Operator
equal to ===
not equal !=
less than <
less than or equal to <=
greater than >
greater than or equal to >=
EZ-COURSEWARE 7-5
Introduction to C Programming
Arrays
Arrays are used to define multiple variables of the same data type. For example the values of
stock prices for the different Dow 30 companies. If you do not use arrays and define as Floating
point values of different stock prices the C statement will look like this
If you have to keep track of stock prices all 7,500+ publicly traded companies the program can
become cumbersome.
float stock[30];
stock[0] = 100.5;
stock[1] = 5.75;
stock[2] = 39.5;
................
................ and so on
In the above example, stock prices of each company is represented by stock[0], stock[1], and so
on. Notice that indexing starts at 0 (zero) and not 1. Arrays, like other variables in C, must be
declared before they can be used.
Individual value in Array is called an element and the square brackets [ ] are being used as part
of the syntex.
In the above example of stock prices we can refer one of the element of the array as stock[i].
The value of I can be from 0 to 30.
7-6 EZ-COURSEWARE
Introduction to C Programming
Structures
A structure is a group of data types. These data type can be same data type or it can be different.
In the above example of stock prices, we can define one structure nyse ( New York Stock
Exachnge) that consists of different companies, for example DOW 30, FORTUNE 500 and
DOTCOM 50. The structur will be defined as follows,
struct nyse {
float dow30
float fortune500
float dotcom50
}
Print Formatting :
The following characters, placed after the \ character in a printf() statement, have the following
effect.
EZ-COURSEWARE 7-7
Introduction to C Programming
Pointers
Pointer are very widley used in C langaage. It is little bit difficult to understand at first, but once
you understand the concept it will make programming very easy and very structure. In previous
example when we define variable either interger, float or character, the compiler assigns memory
address for each variable. For example when we defined pi as float variable, the compiler assigns
a specific memory location. For simplicity let us assume this location is 1000.The value of pi (
3.14) is stored in this memory location.
1000 3.14
float_pointer=&pi
The above statement assigns the memory address of pi to float_pointer. The memory address of
this pointer will be something different than 1000. Again for simplicity let us assume that it is
2000. So the loation 2000 does not hold the value of pi but it holds the memory address where
the value of pi is stored. In our example it will be 1000.
2000 1000
1000 3.14
Initially it does not explains what are the advanteges of using the pointers. But once you
understand all the uses of pointers in C, especially using pointers defining arrays and strings.
As mentioned before to go into more detail on this subject is beyond the scope of this book. We
have given several references at the end of book and also we have included some freeware
tutorial on the CD. Please refer any of these references for more detail explanation.
7-8 EZ-COURSEWARE
Introduction to C Programming
Functions
One of the main advantage of C langauage is that it offers the concept of modular and structured
way of programming. Function is used to carry out different tasks. If you are familiar with
assembly language programming where it was called subroutine.
All C programs has atleast one function and that is main and it is called as follows.
void main( )
There are two types of function. One type of function where no data is being passed between
caller and functions itself. The other one where data is being passed.
The syntax is to include void before the name of the function if there are no data or parameters
are being passed and opening and closing brackets ( ) after the name of the function. In the case
where the data or parameters are bening passed you use following syntax.
return A+B;
This is the most simple function but it explains the concept. A and B are the parameters being
passed to function and function return the answer.
Another example of the function is where you are printing something on the termianl. For
example,
Loops
You can implement Loops in C programming three different ways.
1. for loop
2. while
3. Do…. While
EZ-COURSEWARE 7-9
Introduction to C Programming
100.5
5.75
39.5
……………….
……………… and so on
While
while (x < y)
{
x++;
printf("%d\n",x);
}
do
{
x++;
printf("%d\n",x);
}
while ( x < y )
7-10 EZ-COURSEWARE
Introduction to C Programming
Making Decisions
C programming language provides two ways to make decisions. One where you can use if
statemant and the second choice is where you can use switch and case statement.
If Statements
The if statement allows two different opeartions to occur depending upon the circumstances. Fo
example
switch() case:
If there are more than two circumstances switch case must be used. This makes easier to follow
the program.
#include <stdio.h>
main()
{
int operation, A, B, C;
printf("enter any two numbers ");
scanf("%d %d", &A, &B );
printf("enter operation to be performed\n");
printf("1=add\n");
printf("2=subtract\n");
printf("3=multiply\n");
printf("4=divide\n");
scanf("%d", &opearation );
switch( opearation ) {
case 1: C = A + B; break;
case 2: C = A - B; break;
case 3: C = A * B; break;
case 4: C = A /B; break;
default: printf("Invalid selection\n");
}
printf("%d Result %d is %d\n", C );
The break at the end of each case statement indicates it is the end of that particular operation and
go to the statement after right brace.You must remember that you can not use expression or
ranges for the case, it must be either interger or character constants.
The following operations are explained with one statement or their calling syntax. Again for
detail info pl. refer to any of the sources listed at the end of book or some on the CD.
EZ-COURSEWARE 7-11
Introduction to C Programming
KEYBOARD INPUT
scanf("%d", &number);
FILE INPUT/OUTPUT
in_file = fopen( "myfile.dat", "r" );
DATA CONVERSION
The following functions convert between data types.
atof() converts an ascii character array to a float
atoi() converts an ascii character array to an integer
itoa() converts an integer to a character array
UNION
This is a special data type which looks similar to a structure, but is very different. The
declaration is,
union mixed {
char letter;
float radian;
int number;
};
union mixed all;
POINTERS TO FUNCTIONS
int (*func_pointer)();
SYSTEM CALLS
Calls may be made to the Operating System to execute standard OPsys calls, eg,
#include <process.h>
main() /* SYS.C */
{
char *command = "dir";
system( "cls" );
system( command );
}
7-12 EZ-COURSEWARE
HC11 Technical Information
Instruction set
The instruction set table lists all the valid op codes and the details of the corresponding
instruction. It is a principal aid to machine language and assembly language programmers. The
instruction set table lists the instructions in alphabetic order by name. Unfortunately, this means
that you must know the name of an instruction before you cab find it in the table. However, the
names of most instructions strongly imply the operation performed, so a little creative guessing
will help you find the desired instruction quickly.
register a = 8 bit
register b = 8 bit
register d = 16 bit (a = MSB, b = LSB)
register x = 16 bit
register y = 16 bit
cc notes:
- not changed
x updated according to data
0 set to 0
1 set to 1
3 c|=(msn>9)
4 Most significant bit of b*
5 Set when interrupt occurs* If previously set,
a Non-Maskable interrupt is required to exit the wait state*
8-2 EZ-COURSEWARE
HC11 Technical Information
bhs 24 3 2 -- - - -- - - -- - - -- - - -- - - bra(hs) - - - - - -
bita 85 2 2 95 3 2 a5 4 2 18a5 4 2 b5 4 3 -- - - a&m - - x x 0 -
bitb c5 2 2 d5 3 2 e5 4 2 18e5 4 2 f5 4 3 -- - - b&m - - x x 0 -
ble 2f 3 2 -- - - -- - - -- - - -- - - -- - - bra(le) - - - - - -
blo 25 3 2 -- - - -- - - -- - - -- - - -- - - bra(lo) - - - - - -
bls 23 3 2 -- - - -- - - -- - - -- - - -- - - bra(ls) - - - - - -
blt 2d 3 2 -- - - -- - - -- - - -- - - -- - - bra(lt) - - - - - -
bmi 2b 3 2 -- - - -- - - -- - - -- - - -- - - bra(mi) - - - - - -
bne 26 3 2 -- - - -- - - -- - - -- - - -- - - bra(ne) - - - - - -
bpl 2a 3 2 -- - - -- - - -- - - -- - - -- - - bra(pl) - - - - - -
bra 20 3 2 -- - - -- - - -- - - -- - - -- - - bra - - - - - -
brclr -- - - 13 6 4 1f 7 4 181f 7 4 -- - - -- - - bra(!(m&im)) - - x x 0 -
brn 21 3 2 -- - - -- - - -- - - -- - - -- - - bra( 0) - - - - - -
brset -- - - 12 6 4 1e 7 3 181e 7 3 -- - - -- - - bra(!(/m&im)) - - x x 0 -
bset -- - - 14 6 3 1c 7 3 181c 7 3 -- - - -- - - m|=im - - x x 0 -
bsr 8d 5 2 -- - - -- - - -- - - -- - - -- - - bsr - - - - - -
bvc 28 3 2 -- - - -- - - -- - - -- - - -- - - bra(vc) - - - - - -
bvs 29 3 2 -- - - -- - - -- - - -- - - -- - - bra(vs) - - - - - -
cba -- - - -- - - -- - - -- - - -- - - 11 1 1 a-b - - x x x x
clc -- - - -- - - -- - - -- - - -- - - 0c 1 1 c=0 - - - - - 0
cli -- - - -- - - -- - - -- - - -- - - 0e 1 1 i=0 - 0 - - - -
clr -- - - -- - - 6f 5 2 186f 5 2 7f 5 3 -- - - m=0 - - x x 0 0
clra -- - - -- - - -- - - -- - - -- - - 4f 1 1 a=0 - - x x 0 0
clrb -- - - -- - - -- - - -- - - -- - - 5f 1 1 b=0 - - x x 0 0
clv -- - - -- - - -- - - -- - - -- - - 0a 1 1 v=0 - - - - 0 -
cmpa 81 2 2 91 3 2 a1 4 2 18a1 4 2 b1 4 3 -- - - a-m - - x x x x
cmpb c1 2 2 d1 3 2 e1 4 2 18e1 4 2 f1 4 3 -- - - b-m - - x x x x
com -- - - -- - - 63 6 2 1863 6 2 73 6 3 -- - - m=~m - - x x 0 1
coma -- - - -- - - -- - - -- - - -- - - 43 1 1 a=~a - - x x 0 1
comb -- - - -- - - -- - - -- - - -- - - 53 1 1 b=~b - - x x 0 1
cpd 1a83 5 4 1a93 6 3 1ab3 7 4 cdb3 7 4 1aa3 7 3 -- - - d-m - - x x x x
cpx 8c 3 3 9c 4 2 ac 5 2 18ac 5 2 bc 5 3 -- - - x-m - - x x x x
cpy 188c 3 3 189c 4 2 18ac 5 2 1aac 5 2 18bc 5 3 -- - - x-m - - x x x x
daa -- - - -- - - -- - - -- - - -- - - 19 2 1 a=da(a) - - x x x 3
dec -- - - -- - - 6a 6 2 6a 6 2 7a 6 3 -- - - m-=1 - - x x x -
deca -- - - -- - - -- - - -- - - -- - - 4a 1 1 a-=1 - - x x x -
decb -- - - -- - - -- - - -- - - -- - - 5a 1 1 b-=1 - - x x x -
des -- - - -- - - -- - - -- - - -- - - 34 1 1 s-=1 - - - - - -
dex -- - - -- - - -- - - -- - - -- - - 09 1 1 x-=1 - - - x - -
eim -- - - 75 6 3 65 7 3 1865 7 3 -- - - -- - - m^=im - - x x 0 -
eora 88 2 2 98 3 2 a8 4 2 18a8 4 2 b8 4 3 -- - - a^=m - - x x 0 -
eorb c8 2 2 d8 3 2 e8 4 2 18e8 4 2 f8 4 3 -- - - b^=m - - x x 0 -
inc -- - - -- - - 6c 6 2 186c 6 2 7c 6 3 -- - - m+=1 - - x x x -
inca -- - - -- - - -- - - -- - - -- - - 4c 1 1 a+=1 - - x x x -
incb -- - - -- - - -- - - -- - - -- - - 5c 1 1 b+=1 - - x x x -
ins -- - - -- - - -- - - -- - - -- - - 31 1 1 s+=1 - - - - - -
inx -- - - -- - - -- - - -- - - -- - - 08 1 1 x+=1 - - - x - -
jmp -- - - -- - - 6e 3 2 186e 3 2 7e 3 3 -- - - jmp - - - - - -
jsr -- - - 9d 5 2 ad 5 2 18ad 5 2 bd 6 3 -- - - jsr - - - - - -
ldaa 86 2 2 96 3 2 a6 4 2 18a6 4 2 b6 4 3 -- - - a=m - - x x 0 -
ldab c6 2 2 d6 3 2 e6 4 2 18e6 4 2 f6 4 3 -- - - b=m - - x x 0 -
ldd cc 3 3 dc 4 2 ec 5 2 18ec 5 2 fc 5 3 -- - - d=m - - x x 0 -
lds 8e 3 3 9e 4 2 ae 5 2 18ae 5 2 be 5 3 -- - - s=m - - x x 0 -
ldx ce 3 3 de 4 2 ee 5 2 18ee 5 2 fe 5 3 -- - - x=m - - x x 0 -
lsr -- - - -- - - 64 6 2 1864 6 2 74 6 3 -- - - (u)m>>=1 - - x x x x
lsra -- - - -- - - -- - - -- - - -- - - 44 1 1 (u)a>>=1 - - x x x x
lsrb -- - - -- - - -- - - -- - - -- - - 54 1 1 (u)b>>=1 - - x x x x
lsrd -- - - -- - - -- - - -- - - -- - - 04 1 1 (u)d>>=1 - - x x x x
mul -- - - -- - - -- - - -- - - -- - - 3d 7 1 d=a*b - - - - - 4
EZ-COURSEWARE 8-3
HC11 Technical Information
8-4 EZ-COURSEWARE
HC11 Technical Information
CPU Registers
7 A 0 7 B 0
15 D 0
15 X 0
15 Y 0
15 SP 0
15 PC 0
S X H I N Z V C
The MC68HC11 has two 8-bit accumulators (A and B), one 16-bit accumulator (D) formed by A
and B; where A is the MSB and B is the LSB. The microcontroller also has two 16-bit index
registers, namely X and Y. A 16-bit stackpointer (SP) and a 16 bit programcounter (PC). The
condition-code-register, or flag-register, has 8 flags:
I/O Registers
The following quick-reference table shows all control registers and bits. The addresses are those
resulting from a hardware reset. The registers are generally grouped according to the device they
are associated with. Some registers are input/output registers while other perform only control
functions. Reference appropriate text material before using these registers.
EZ-COURSEWARE 8-5
HC11 Technical Information
w = write
r = read
1000 porta
1001 reserved
1002 pioc
w 1******* staf: strobe a flag, set at active edge of stra
pin/inactive
w *1****** stai: hardware interrupt request when STAF=1
w **1***** cwom: port c open-drain
w ***1**** hnds: handshake/simple strobe mode
w ****1*** oin: output/input handshake select
w *****1** pls: STRB pulse/level active
w ******1* ega: rising/falling edge select for STRA
w *******1 invb: STRB active high/low
1003 portc
1004 portb
1005 portcl
1006 reserved
1007 ddrc: data direction register for port c (1=output)
1008 portd (b0**b5)
rw 1******* mode0 or boot: strb
rw 1******* mode1 or test: r/w
rw *1****** mode0 or boot: stra
rw *1****** mode1 or test: as
rw **1***** pd5/ss*
rw ***1**** pd4/sck
rw ****1*** pd3/mosi
rw *****1** pd2/miso
rw ******1* pd1/txd
rw *******1 pd0/rxd
1009 ddrd: data direction register for port d (1=output)
(b0**b5)
100A porte: port e data register
100B cforc: timer compare force register
w 1******* foc1
w *1****** foc2
w **1***** foc3
w ***1**** foc4
w ****1*** foc5
w 11111111 force compare(s)
w *****xxx reserved
100C oc1m: set bits to enable oc1 to control corresponding
pin(s) of port a
w 1******* oc1m7
w *1****** oc1m6
w **1***** oc1m5
w ***1**** oc1m4
8-6 EZ-COURSEWARE
HC11 Technical Information
w ****1*** oc1m3
w *****xxx reserved
w 11111111 force compare(s)
100D oc1d: if oc1mx is set, data in oc1dx is output to port a
bit-x
on successful oc1 compares
w 1******* oc1d7
w *1****** oc1d6
w **1***** oc1d5
w ***1**** oc1d4
w ****1*** oc1d3
w *****xxx reserved
w 11111111 force compare(s)
100E tcnt: timer counter register
1010 tic1: timer input capture register
1012 tic2: timer input capture register
1014 tic3: timer input capture register
1016 toc1: timer output compare register
1018 toc2: timer output compare register
101A toc3: timer output compare register
101C toc4: timer output compare register
101E toc5: timer output compare register
1020 tctl1: timer control register 1
w 1******* om2
w *1****** ol2
w **1***** om3
w ***1**** ol3
w ****1*** om4
w *****1** ol4
w ******1* om5
w *******1 ol5
for all pairs:
w 00****** timer disconnected from output pin logic
w 01****** ocx output line: toggle
w 10****** ocx output line: 0
w 11****** ocx output line: 1
1021 tctl2: timer control register 2
w xx****** reserved
w **1***** edg1b
w ***1**** edg1a
w ****1*** edg2b
w *****1** edg2a
w ******1* edg3b
w *******1 edg3a
for all pairs:
w **00**** capture: disabled
w **01**** capture: on rising edge only
w **10**** capture: on falling edge only
EZ-COURSEWARE 8-7
HC11 Technical Information
w ****xx** reserved
w ******00 rtr1,rtr0: interrupt rate divide by 2^13
w ******01 rtr1,rtr0: interrupt rate divide by 2^14
w ******10 rtr1,rtr0: interrupt rate divide by 2^15
w ******11 rtr1,rtr0: interrupt rate divide by 2^16
1027 pacnt: pulse accumulator count register
1028 spcr: spi control register
w 1******* spie: spi interrupt enable
w *1****** spe: spi system enable
w **1***** dwom: port d: open-drain/normal
w ***1**** mstr: master/slave mode
w ****1*** cpol: clock polarity
w *****1** cpha: clock phase
w ******00 spr1,spr0: spi e-clock divided by 2
w ******01 spr1,spr0: spi e-clock divided by 4
w ******10 spr1,spr0: spi e-clock divided by 8
w ******11 spr1,spr0: spi e-clock divided by 16
1029 spsr: spi status register
r 1******* spif: spi interrupt request
r *1****** wcol: write collision status flag
r ***1**** modf: spi mode error interrupt status flag
r **x*xxxx reserved
102A spdr: spi data register
102B baud: sci baud rate control register
w 1******* tclr: clear baud counter chain (test only)
w *x****** reserved
w **00**** scp1,scp0: serial prescaler select: divide e-
clock by 1
w **01**** scp1,scp0: serial prescaler select: divide e-
clock by 2
w **10**** scp1,scp0: serial prescaler select: divide e-
clock by 4
w **11**** scp1,scp0: serial prescaler select: divide e-
clock by 13
w ****1*** rckb: sci baud rate clock test (test only)
w *****000 scr2,scr1,scr0: prescaler output divide by 1
w *****001 scr2,scr1,scr0: prescaler output divide by 2
w *****010 scr2,scr1,scr0: prescaler output divide by 4
w *****011 scr2,scr1,scr0: prescaler output divide by 8
w *****100 scr2,scr1,scr0: prescaler output divide by 16
w *****101 scr2,scr1,scr0: prescaler output divide by 32
w *****110 scr2,scr1,scr0: prescaler output divide by 64
w *****111 scr2,scr1,scr0: prescaler output divide by 128
102C sccr1: sci control register 1
w 1******* r8: receive bit 8
w *1****** t8: transmit bit 8
w ***1**** m: ninth data bit
EZ-COURSEWARE 8-9
HC11 Technical Information
1036 reserved
1037 reserved
1038 reserved
1039 option: system configuration options
w 1******* adpu: a->d system powered up/down
w *1****** csel: a->d and ee use an internal-r-c/system-e
clock
w **1***** irqe: irq configured for falling edges/low
level
w ***1**** dly: enable/disable oscillator start-up delay
(from stop)
w ****1*** cme: slow or stopped clocks cause
reset/disabled
w *****x** reserved
w ******00 cr1,cr0: e/2^15 divided by 1
w ******01 cr1,cr0: e/2^15 divided by 4
w ******10 cr1,cr0: e/2^15 divided by 16
w ******11 cr1,cr0: e/2^15 divided by 64
103A coprst: arm/reset cop timer circuitry, write $55 and $aa to
reset cop watchdog timer
103B pprog: eeprom programming register
w 1******* odd: program odd rows in half of eeprom
(test only)
w *1****** even: program even rows in half of eeprom
(test only)
w **x***** reserved
w ***1**** byte: erase only one byte/row or all of eeprom
w ****1*** row: erase only one 16 byte row/all 512 bytes
of eeprom
w *****1** erase: erase/normal read of program mode
w ******1* eelat: eeprom busses configured for program or
erase/read
w *******1 eepgm: program or erase power switched on/off
to program eeprom:
* set eelat
* write data to desired address
* set eepgm for the required
programming time
to erase eeprom:
* select row = 1/0
* select byte = 1/0
* set erase and eelat = 1
* write to an eeprom address to be
erased
* set eepgm for the required erase time
period
103C hprio: highest priority interrupt and misc*
w 1******* rboot: boot rom enabled/not in map (normal)
EZ-COURSEWARE 8-11
HC11 Technical Information
8-12 EZ-COURSEWARE
HC11 Technical Information
note: The bits of this register are implemented with eeprom cells programming and erasure
follow normal eeprom procedures. The erased state of this location is $0f. A new value
programmed into this register is not readable until after a subsequent reset sequence.
Interrupt vectors
In this list you can find the many interrupt vectors of the HC11. The interrupts are ranked from a
low to high priority.
cc register mask
/ local mask
/ /
FFC0 ? ????? reserved
FFC2 ? ????? reserved
FFC4 ? ????? reserved
FFC6 ? ????? reserved
FFC8 ? ????? reserved
FFCA ? ????? reserved
FFCC ? ????? reserved
FFCE ? ????? reserved
cc register mask
/ local mask
/ /
FFD0 ? ????? reserved
FFD2 ? ????? reserved
FFD4 ? ????? reserved
FFD6 i div* sci serial system
masks:
rie for SCI receive data register full
rie for SCI receiver overrun
ilie for SCI idle line detect
tie for SCI transmit data register empty
tcie for SCI transmit complete
FFD8 i psie SPI serial transfer complete
FFDA i paii pulse accumulator input edge
FFDC i paovi pulse accumulator overflow
FFDE i toi timer overflow
cc register mask
/ local mask
/ /
FFE0 i oc5i timer output compare 5
FFE2 i oc4i timer output compare 4
ffe4 i oc3i timer output compare 3
FFE6 i oc2i timer output compare 2
EZ-COURSEWARE 8-13
HC11 Technical Information
cc register mask
/ local mask
/ /
FFF0 i rtii real time interrupt
FFF2 i div* irq (external pin or parallel i/o)
masks:
none for external pin
stai for parallel i/o handshake
FFF4 x none xirq pin (pseudo non-maskable interrupt)
FFF6 - none swi
FFF8 - none illegal opcode trap
FFFA - nocop cop timeout
FFFC - cme cop clock monitor timeout
FFFE - none reset
Instruction set
The instruction set table lists all the valid op codes and the details of the corresponding
instruction. It is a principal aid to machine language and assembly language programmers.
The instruction set table lists the instructions in alphabetic order by name. Unfortunately, this
means that you must know the name of an instruction before you cab find it in the table.
However, the names of most instructions strongly imply the operation performed, so a little
creative guessing will help you find the desired instruction quickly.
register a = 8 bit
register b = 8 bit
register d = 16 bit (a = MSB, b = LSB)
register x = 16 bit
register y = 16 bit
cc notes:
- not changed
x updated according to data
0 set to 0
1 set to 1
3 c|=(msn>9)
4 Most significant bit of b.
5 Set when interrupt occurs. If previously set,
a Non-Maskable interrupt is required to exit the wait state.
addressing modes flags
instruct. immed direct ind,x ind,y extend inherent explanation h i n z v c
----------------------------------------------------------------------------------------------
aba -- - - -- - - -- - - -- - - -- - - 1b 1 1 a+=b x - x x x x
abx -- - - -- - - -- - - -- - - -- - - 3a 1 1 x+=(uc)b - - - - - -
8-14 EZ-COURSEWARE
HC11 Technical Information
EZ-COURSEWARE 8-15
HC11 Technical Information
8-16 EZ-COURSEWARE
Interfacing Input/Output and Timer Devices
EZ-COURSEWARE 9-1
Interfacing Input/Output and Timer Devices
This Lesson describes parallel I/O operations and the main timer system in the 'HC11. These
subsystems were introduced to the student in Lesson Two where we discussed the 'HC11E0
architecture. In that Lesson, we learned that there are two general-purpose I/O ports built into the
MCU. Also, the main 16-bittimer has three input capture lines, five output-compare lines, and a
real-time interrupt function. Overall, there are 32 I/O pins that link your software to the real-time
outside world.
Small package size and low pin count are important for low-cost applications. However, each
I/O function will potentially add more pins to the package. Let's make a wish-list of I/O
functions that we may want to have on our microcontroller or microprocessor and keep a running
tally of pin count.
If we add power and ground, the crystal oscillator, and reset, then it is easy to see that we can
quickly get into packages that contain more than 60 pins or more. These packages are expensive
to manufacture and the large footprint takes up expensive real estate on your PC board. We need
some means of minimizing pin count.
One of the ways that microcontrollers can maximize the functionality of the I/O pins is to
implement shared functions for each of the ports. This is the case for all of the 32 input/output
pins on the 'HC08D0. Port A is shared with the timer and input/output capture functions. Port B
and port C are shared with the expanded mode of operation by multiplexing the external address
and data bus. Port D is shared with two serial ports and two control lines needed for expanded
mode.
In the following sections of this Lesson and later in Lesson Eight, each of these I/O subsystems
will be discussed in detail. By discussing each of the four ports in a separate section in this
Lesson, we will cover general-purpose I/O, the timer subsystem, the single-chip mode of
operation, and the expanded mode of operation in this Lesson. The two serial ports will be
discussed in Lesson Ten.
Port A
The I/O for the timer subsystem is multiplexed with general-purpose I/O on port A. Pins PA0,
PA1, and PA2 can be used for general-purpose input or as input edge-detect pins. Port A reads
are completely independent of timer input-capture functions. Pins PA3 - PA6 can be used for
general purpose output or as output-compare pins. When one of these pins is being used for an
9-2 EZ-COURSEWARE
Interfacing Input/Output and Timer Devices
The two registers associated with port A are shown below in Figure 1 and Figure 2. In the
PACTL register we are concerned with bit 7 (DDRA7) and bit 6 (PAEN). We will discuss the
functionality of the remaining five bits later in this section. The PORTA register is the data
register for port A.
7 6 5 4 3 2 1 0
DDRA7 PAEN PAMOD PEDGE 0 0 RTR1 RTR0 PACTL
$0026
Figure 9.1 Port A control register
7 6 5 4 3 2 1 0
D7 D6 D5 D4 D3 D2 D1 D0 PORTA
$0000
Figure 9.2 Port A data register
The three tables below summarize the programming options for controlling the functionality of
port A. Table 9.1 describes the three input pins, Table 9.2 describes the four output pins, and
Table 9.3 describes the one input-output pin.
EZ-COURSEWARE 9-3
Interfacing Input/Output and Timer Devices
Having discussed the programmable modes of operation for port A, we must now go into more
detail about the main timer. The main timer is at the heart of the pulse accumulator subsystem
and the output compare subsystem.
Main Timer
The main timer system is based on a free-running 16-bit timer with a four-stage programmable
prescaler. Three independent input-capture functions can be used to automatically latch the time
when a selected transition is detected at the corresponding timer input pin. Five output-compare
functions are included to automatically generate output signals for timing software delays. Also a
programmable periodic interrupt is available off the main timing chain. The user can select one
of four rates for the interrupt.
The timer subsytem is controlled by a set of registers which contain the appropriate control bits.
Each of these registers will be identified and described in the following paragraphs.
7 6 5 4 3 2 1 0 TCNT
D15 D14 D13 D12 D11 D10 D9 D8 $000E
D7 D6 D5 D4 D3 D2 D1 D0 $000F
Figure 9.3 Timer counter register
A programmable prescaler allows the user to select one of four clocking rates to drive the 16-bit
main timer counter. The fastest rate causes the main timer to clock at the E-clock rate, which
results in a timer resolution of 500ns and a timer range of 32.77 ms between overflows (for
E=2MHz). The slowest rate cause the main timer to clock at an E divided by 16 rate, which
results in a timer resolution of 8 usec and a timer range of 524.3 ms between overflows (for E=2
MHz). You can see that this choice allows the programmer to make the classic trade-off between
range and resolution.
The following register and paragraphs explain the prescaler select bits. There are two bits to
consider, PR1 and PR0, in the TMSK2 register. Note that the other bits in this register are not
related to the timer prescaler.
7 6 5 4 3 2 1 0 TMSK2
TOI RTII PAOVI PAII 0 0 PR1 PR0 $0024
Figure 9.4 Timer Mask 2 Register
These two bits select the prescale rate for the main 16-bit free-running timer. Table 9.4
summarizes the programming options for controlling the prescaler. Note that in normal modes,
this prescale factor cannot be changed "on the fly". The prescaler can only be changed once in
the first 64 bus cycles after reset.
9-4 EZ-COURSEWARE
Interfacing Input/Output and Timer Devices
The clock source for the RTI function is a free running clock that cannot be stopped or
interrupted. For this reason, the time between successive RTI time-outs will be a constant; the
time will not depend on any software latencies.
Warning. The most common problem that the user encounters with the RTI system is that they
forget to clear the RTIF (the interrupt flag) after it is recognized. Note that if the flag is not
cleared by a specific software write to the TFLG2 register, it will already be pending the next
time it is checked. This sequence results in an infinite loop.
The following registers and paragraphs explain the RTI control bits and the registers in which
they can be found. There are four bits to consider. There are two bits available to program the
RTI rate, one bit to enable the interrupt, and one bit to provide a flag indicating that the RTI has
occurred.
7 6 5 4 3 2 1 0 TMSK2
TOI RTII PAOVI PAII 0 0 PRI PRQ $0024
7 6 5 4 3 2 1 0 TFLG2
TOF RTIF PAOVF PAIF 0 0 0 0 $0025
7 6 5 4 3 2 1 0 PACTL
DDRA7 PAEN PAMOD PEDGE 0 0 RTR1 RTR0 $0026
Figure 9.5 Real-time Interrupt Registers
First, consider the two bits that determine the rate at which interrupts will be requested by the
RTI system. These bits are RTR1 and RTR0 from the PACTL register. Table 9.5 summarizes the
programming options for controlling the prescaler.
EZ-COURSEWARE 9-5
Interfacing Input/Output and Timer Devices
Next, consider real-time interrupt enable bit, RTII, from the TMSK2 register. This bit allows the
user to configure the RTI system for polled or interrupt-driven operation but does not affect the
setting or clearing of the RTIF flag. When RTII is zero, interrupts are inhibited, and the RTI
system is operating in a polled mode.
Finally, consider the real-time interrupt flag, RTIF, from the TFLG2 register. This status bit is
automatically set to one at the end of every RTI period. The user can clear this bit by writing to
the TFLG2 register with a '1' in the corresponding flag bit location (bit 6 in this case). Remember
the warning that was given above regarding clearing the RTIF.
Input capture
Each input-capture function includes a 16-bit latch, input edge-detection logic, and interrupt
generation logic. Each 16-bit latch captures the current value of the free-running counter when a
selected edge is detected at the corresponding timer input pin. The software can select the edge
polarity that will be recognized by programming appropriate control bits. The user can configure
each of the three input-capture pins independently of the other two. The EDGxB and EDGxA
pair of bits determine which edge(s) the input capture functions will be sensitive to. The three bit
pairs are packed into the TCTL2 register as shown in Figure 9.6.
7 6 5 4 3 2 1 0 TCTL2
0 0 EDG1B EDG1A EDG2B EDG2A EDG3B EDG3A $0021
Figure 9.6 Timer Control Register 2
These bit pairs are encoded as shown in Table 9.6 for controlling the input capture configuration.
The input-capture latches can be read by software as pairs of 8-bit registers. As long as double-
byte read instructions such as load D (LDD) is used to read input-capture values, the
programmer is assured that the two bytes belong with each other. The three pairs of 8-bit
registers are shown in Figure 9.7.
9-6 EZ-COURSEWARE
Interfacing Input/Output and Timer Devices
7 6 5 4 3 2 1 0 T1C1
D15 D14 D13 D12 D11 D10 D9 D8 $0010
7 6 5 4 3 2 1 0
D7 D6 D5 D4 D3 D2 D1 D0 $0011
7 6 5 4 3 2 1 0 T1C2
D15 D14 D13 D12 D11 D10 D9 D8 $0012
7 6 5 4 3 2 1 0
D7 D6 D5 D4 D3 D2 D1 D0 $0013
7 6 5 4 3 2 1 0 T1C3
D15 D14 D13 D12 D11 D10 D9 D8 $0014
7 6 5 4 3 2 1 0
D7 D6 D5 D4 D3 D2 D1 D0 $0015
Output compares
Each of the five output-compare functions has a 16-bit compare register and a dedicated 16-bit
comparator. When a match is detected between the free-running timer value and the 16-bit
compare register, a status flag is set and an interrupt can be generated.
Output pins for the five output-compare functions can be used as general-purpose output pins or
as timer outputs that are directly controlled by the timer system.
The 16-bit output-compare register for each output-compare function can be read or written by
software as a pair of 8-bit registers. There are five pairs of 8-bit registers as shown in Figure 9.8.
EZ-COURSEWARE 9-7
Interfacing Input/Output and Timer Devices
7 6 5 4 3 2 1 0 TOC1
D15 D14 D13 D12 D11 D10 D9 D8 $0016
7 6 5 4 3 2 1 0
D7 D6 D5 D4 D3 D2 D1 D0 $0017
7 6 5 4 3 2 1 0 TOC2
D15 D14 D13 D12 D11 D10 D9 D8 $0018
7 6 5 4 3 2 1 0
D7 D6 D5 D4 D3 D2 D1 D0 $0019
7 6 5 4 3 2 1 0 TOC3
D15 D14 D13 D12 D11 D10 D9 D8 $001A
7 6 5 4 3 2 1 0
D7 D6 D5 D4 D3 D2 D1 D0 $001B
7 6 5 4 3 2 1 0 TOC4
D15 D14 D13 D12 D11 D10 D9 D8 $001C
7 6 5 4 3 2 1 0
D7 D6 D5 D4 D3 D2 D1 D0 $001D
7 6 5 4 3 2 1 0 TOC5
D15 D14 D13 D12 D11 D10 D9 D8 $001E
7 6 5 4 3 2 1 0
D7 D6 D5 D4 D3 D2 D1 D0 $001F
Figure 9.8 Output Compare Registers
The software has further control over the operation of the five outputs. The following two
registers contain the output-compare status flags and the local interrupt enable bits for the
output-compare functions. There are five interrupt enable bits and five output control flags that
are found in two registers as shown in Figure 9.9 and Figure 9.10 below.
7 6 5 4 3 2 1 0 TMSK1
OC1I OC2I OC3I OC4I OC5I IC1I IC2I IC3I $0022
Figure 9.9 Output-Compare Interrupt Enables
7 6 5 4 3 2 1 0 TFLG1
OC1F OC2F OC3F OC4F OC5F IC1F IC2F IC3F $0023
Figure 9.10 Output-Compare Flags
The OCxF status bit is automatically set to one each time the corresponding output-compare
register matches the free-running timer. This status bit is by writing to the FLG1 register with a
'1' in the corresponding data bit position. The OCxI control bit allows the user to configure each
output-compare function for polled or interrupt-driven operation. When the OCxI bit is '0', the
9-8 EZ-COURSEWARE
Interfacing Input/Output and Timer Devices
If the OCxI control bit has been programmed to a '1' and a hardware interrupt request is
generated, then the programmer must clear the OCxF bit by writing to the TFLG1 register before
leaving the interrupt service routine.
Pulse Accumulator
The pulse accumulator is based on an 8-bit counter and can be configured to operate as a simple
event counter or for gated time accumulation. Control bits allow the user to configure and
control the pulse accumulator sub-system. Two maskable interrupts are associated with the
system, each having its own controls and interrupt vector.
The pulse accumulator system is based on an 8-bit up-counter that can be read or written at any
time. The pulse accumulator enable (PAEN) control bit enables/disables this 8-bit counter. The
pulse accumulator mode (PAMOD) bit controls the mode of operation. In the event counting
mode, the 8-bit counter is incremented by one at each active edge of the PAI pin. In the gated
time accumulation mode, the 8-bit counter is clocked by the E clock divided by 64. This clock is
gated by the PAI pin.
The input buffer on the PAI pin is always connected from the pin to the pulse accumulator and
port A read logic, but the output buffer is enabled or disabled by the data direction control bit
(DDRA7) in the pulse accumulator control (PACTL) register.
The following register and paragraphs describe the pulse accumulator related bits in the PACTL
register.
7 6 5 4 3 2 1 0 PCNTL
DDRA7 PAEN PAMOD PEDGE 0 0 RTR1 RTR0 $0026
Figure 9.11 Pulse Accumulator Control Register
The 8-bit pulse accumulator counter, PACNT, is not affected by reset and can be read or written
at any time. When the count in the PACNT register overflows from 255 to 0 an interrupt will be
generated.
7 6 5 4 3 2 1 0 PACNT
D7 D6 D5 D4 D3 D2 D1 D0 $0027
Figure 9.12 Pulse Accumulator Count Register
This mode changes the pulse accumulator into a timer. The 8-bit PACNT register is incremented
every 64th E-clock cycle as long as the PAI pin is active.
A common use of the gated time accumulation mode is to measure the duration of single pulses.
We can set the counter to zero before the pulse starts, and the resulting pulse time is directly read
when the pulse is finished.
It is easy to measure times that are in the range of the 8-bit timer. However, it is also possible to
measure times longer than the range of the 8-bit counter.
This completes our discussion of port A. We have identified the control and status registers that
are associated with each of the main timer subsystems. We should now be able to configure the
eight port A bits for general-purpose input/output. Alternatively we should be able to program
the port A bits for gated time accumulation, if required.
Port B
The eight port B pins are fixed-direction output pins. However the functionality of these pins in
shared between general-purpose outputs and high-order address outputs. There is no data
direction register or special control register associated with port B. In single-chip mode, port B
can be used for eight general-purpose output ports. In expanded mode, the MCU core takes
control of port B and utilizes the eight bits for the higher order address outputs.
7 6 5 4 3 2 1 0 PORTB
D7 D6 D5 D4 D3 D2 D1 D0 $0004
Figure 9.13 Port B Data Register
Port C
Port C is also a complex port on the 'HC11E0 because it can act as general-purpose bidirectional
I/O or as a time-multiplexed address/data bus port. It will be easier to explain port C operation if
we break down the functionality into single-chip and expanded mode operation.
Single-Chip mode
In this mode, port C is a general-purpose, 8-bit, bidirectional I/O port. The selection of whether
each pin is an input or an output is independently controlled by a corresponding bit in the data
direction register. For port C this is DDRC.
7 6 5 4 3 2 1 0 PORTC
D7 D6 D5 D4 D3 D2 D1 D0 $0003
Figure 9.14 Port C Data Register
7 6 5 4 3 2 1 0 DDRC
DDRC7 DDRC6 DDRC5 DDRC4 DDRC3 DDRC2 DDRC1 DDRC0 $0007
Figure 9.15 Port C Data Direction Register
9-10 EZ-COURSEWARE
Interfacing Input/Output and Timer Devices
It is possible to program the outputs of port C for wired-OR operation. The CWOM (think
wired-OR mode) control bit in the PIOC register (see below) allows the programmer to disable
the P-channel driver of the complementary pair output buffer. The N-channel driver is not
affected by CWOM. For this reason, if the user programs the CWOM bit to a logic '1' then all of
the port C pins become open-drain outputs. Note that the CWOM bit effects all eight bits of port
C. Port C can only be configured for wired-OR operation when the 'HC11 is in the single-chip
mode of operation.
7 6 5 4 3 2 1 0 PIOC
0 0 CWOM 0 0 0 0 0 $0003
Figure 9.16 Parallel I/O Control Register
We will return to this topic of single-chip mode and expanded-mode later in this Lesson. At that
time we will review the configuration of the EZ-Micro Tutor™ system architecture and
determine several schemes that will allows to expand the hardware in order to support future
Laboratories. But for now we must conclude our discussions of the four I/O ports.
Port D
Port D is the fourth parallel I/O port on the 'HC11. Port D supports 6 general-purpose,
bidirectional I/O pins that can be independently configured either as inputs or outputs. This port
shares its functionality between being general-purpose I/O and supporting two separate serial
interface subsystems. The two serial interface subsystems are called the serial communications
interface (SCI) and the serial peripheral interface (SPI).
When port D is configured for general-purpose I/O, the selection of whether each of the pins is
an input or an output can be independently controlled by programming the corresponding bit in
the data direction register. A '1' programmed into a particular data direction register makes the
corresponding pin an output. Alternatively, a '0' programmed into a particular data direction
register makes the corresponding pin an input. All I/O pins are inputs at power-on reset.
7 6 5 4 3 2 1 0 PORTD
0 0 D5 D4 D3 D2 D1 D0 $0008
Figure 9.17 Port C Data Direction Register
EZ-COURSEWARE 9-11
Interfacing Input/Output and Timer Devices
7 6 5 4 3 2 1 0 DDRD
0 0 DDRD5 DDRD4 DDRD3 DDRD2 DDRD1 DDRD0 $0009
Figure 9.18 Port D Data Direction Register
When the SCI receiver is enabled, the PD0/RxD pin becomes an input dedicated to the RxD
function. Likewise, when the SCI transmitter is enabled, the PD1/TxD pin becomes an input
dedicated to the TxD function. We will have more to say about the SCI subsystem in Lesson
Eight.
The SPI subsytem is a 4-wire system. Three of the pins are dedicated to the SPI functions when
the SPI system is enabled. They are PD2/MISO, PD3/MOSI, and PD4/SCK. The fourth pin,
PD5/SS* can be used as a general-purpose output by setting the corresponding DDRD5 bit as
long as the SPI is configured for the master mode of operation. We will have more to say about
the SPI subsystem in Lesson Eight.
The remaining two pins (bit 6 and bit 7) in port D are PD6/AS and PD7/RW*. Both of these pins
are control lines used in the expanded operating mode.
We have now completed our review of the four I/O ports on the 'HC11D0. During this review,
we discovered that each of the I/O ports shares its pins with more than one function. We also
saw that the function of the port B pins and the port C pins depends on the operating mode of the
'HC11. The next step in our discussion on how to interface parallel I/O to the 'HC11E0 is
understanding these operating modes.
In the next paragraphs we will discuss in more detail what is meant by single chip and expanded
mode.
Expanded Mode
9-12 EZ-COURSEWARE
Interfacing Input/Output and Timer Devices
This mode of operation allows external memory and peripheral devices to be accessed by an
external address and data bus. Now it is interesting to note that this is a time-multiplexed
address/data bus. In order to save I/O pins, the low-order eight bits of the address are
multiplexed with the data on the port C pins. In this manner only 18 pins are needed to support a
16-bit address bus, an 8-bit data bus and two control lines.
How are the data and lower address lines multiplexed? An external transparent latch such as the
74LS373 separates the two sets of 8 lines. This transparent latch is clocked by the address strobe
signal (AS). In expanded mode, the R/W* line functions as the read/write bus control signal.
EZ-COURSEWARE 9-13
Interfacing Input/Output and Timer Devices
9-14 EZ-COURSEWARE
Interfacing Input/Output and Timer Devices
Laboratory 9.1
Keypad
This Laboratory will interface device to the EZ-Micro Tutor™ Board. The input device will be a
4X4 keypad and the output device will be PC Monitor.
This algorithm is called "scanning" the keypad and kepad connections are called 4X4 matrix.
The general-purpose I/O lines from port A are used to scan the keypad. The four input pins
(PA0, PA1, PA2, PA3) are connected to the rows. The four output pins (PA4, PA5, PA6, P7) are
connected to the columns. Our software can scan the keypad by writing and reading to and from
port A.
Procedure
This Laboratory will involve writing a program which will input any key from the keypad and
displaying on PC monitor.
2) Load your program to begin execution from external RAM beginning at address 2000h.
Use the "ORG $2000" assembler directive to accomplish this task.
EZ-COURSEWARE 9-15
Interfacing Input/Output and Timer Devices
As you press any key on the keyapd, PC monitor display will display the key that was pressed.
Pree ESC to get out of this program
If the test described above did not work properly, step through the following procedure:
1) Make sure power is applied to the EZ-Micro Tutor™ Board. The power indicator LED
(D3) should be on.
2) Make sure all connections between the Keypad/Display Lab Board and the EZ-Micro
Tutor™ Board are correct and making a good connection.
3) Make sure that the KEYPAD.ASM file is properly assembled and the KEYPAD.S19
file has been properly created.
4) Make sure that the KEYPAD.S19 file is downloaded properly to The EZ-Micro
Tutor™ Board. Download again if necessary.
Laboratory 9.2
LCD Display
The EZ Micro Tutor comes with 2 lines 16 characters LCD display. The LCD display is
connected as I/O device to Micorcontroller. The I/O decoding is done through 22V10 GAL( U5).
And address line A0.
There are three control lines that control the LCD display. These control lines are LCD_E,
LCD_RW, and LCD_RSS. The first two control lines LCD_E and LCD_RW are controlled
through U5 (GAL) and LCD_RSS is connected to Address line A0.
The IO addresses LCD display occupies are $4800(HEX) and $4801(HEX). The address $4800
is the control.
The following assembly program LCD.ASM is used to test LCD display. It writes number 0 on
1st line and character A on 2nd line.
LCD.ASM
*************************************************************************
* This Program (LCD.ASM) tests LCD Display *
* on EZ-MICRO TUTOR Board From Advanced Micorcomputer Systems Inc. *
* The updated software can be downloaded from our website *
* www.advancedmsinc.com *
* copyright 2000 by Advanced Micorcomputer Systems Inc. *
*************************************************************************
9-16 EZ-COURSEWARE
Interfacing Input/Output and Timer Devices
* Equates
CONTROL EQU $4800 *RS low
DATA EQU $4C00 *RS high
* External references
BUFALO EQU $e000 *start of BUFFALO monitor
OUTPUT EQU $e3c2 *BUFFALO subroutine for OUTPUTing a character in A
ORG $2000
MAIN
LDAA #$3C *Function set: data length=8, lines=2,
dots=5x10
STAA CONTROL
JSR DLY10MS
* Delay subroutine
DLY10MS EQU * delay 10ms at E = 2MHz
PSHX
LDX #$0D06
DLYLP DEX
BNE DLYLP
PULX
RTS
EZ-COURSEWARE 9-17
Interfacing Input/Output and Timer Devices
Laboratory 9.3
Digital Input and Digital output
The EZ-Mico Tutor board has one external Digital input Port 74LS373 ( U9). The four input
lines are connected to Dip switch SW2. These individual switches simulate sensor switch or any
other kind of ON-OFF switch.The other four input lines are connected to J4 connector.
The IO address of this Input port is $4000 Hex. The board has one external Digital output port
74LS374 U9. The four input lines are connected to four LEDS D1through D4.The other four
output lines are connected to J4 connector. The IO address of the LED output port is $4400.
The following assembly program reads input port ( DIP switch) and turn on resepective LED.
DIN.ASM
*************************************************************************
* This Program (DIN.ASM) tests Input port on EZ-MICRO TUTOR Board *
* From Advanced Micorcomputer Systems Inc. *
* The updated software can be downloaded from our website *
* *
* www.advancedmsinc.com *
* *
* copyright 2000 by Advanced Micorcomputer Systems Inc. *
* *
*************************************************************************
ORG $2000
MAIN
9-18 EZ-COURSEWARE
Interfacing Input/Output and Timer Devices
Laboratory 9.4
Measuring period of input signal using TCAP and concept of
interrupts
This Laboratory is designed to provide experience with two major concepts: measuring the
period of an input signal using the input capture time, and interrupts.
The input capture timer supports accurate timing of the period and/or duty cycle of input signals.
As we learned in this Lesson, the 'HC11E0 can be configured for up to 3 input capture channels
at a time. Since each channel functions independently, it is only necessary to study and
understand the operation of one channel in order to understand them all.
All of the timer related functions of the 'HC11E0 microcontroller (input capture, output compare,
pulse accumulator, and watchdog timer) are based on a 16-bit free-running counter. This counter
simply increments once for each E clock (2 MHz on the EZ-Micro Tutor™ Board with the 8
MHz system clock) from $0000 to $FFFF.
The input capture function is composed of a 16-bit register that can be loaded with the current
counter value when an input signal active edge occurs. We learned in this Lesson that the input
capture function is controlled by configuration registers that can be programmed to specify such
parameters as the polarity of the active edge, status flags, and interrupt processing.
It is to our benefit to free the processor from the burden of polling flags to identify when an input
capture has occurred. If a polling scheme were used, the processor would have little time to
perform any other tasks that may be necessary for the system to function. Furthermore, the
polling scheme may introduce unwanted latency because we may not "see" that the flag has been
set immediately. Combining the timer input capture process with an interrupt control scheme
will free the processor to perform other tasks during the time between the active edges of the
input signal that triggers the input capture.
Interrupts are conceptually quite simple. Every time the phone rings, an interrupt occurs.
Whatever is being done is temporarily suspended, the phone is answered and the call processed,
then the suspended task is picked up from where it was left off. In fact this is quite analogous to
processing an interrupt with the 'HC11E0 microcontroller. In order to set up an interrupt process,
the following steps must be performed.
1) Create the Interrupt Service Routine (ISR) software that will execute when the
interrupt is processed. Typically this involves reading or writing to the I/O system that
generates the interrupt signal. As we were warned in the Lesson, the interrupt flag
must be cleared during the processing of the ISR. This is to prevent the occurrence of
false interrupts due to a single stimulus. The process of clearing the interrupt flag is
dependent on the I/O system that is generating the interrupt. The ISR will normally
terminate with a Return From Interrupt (RTI) instruction to return back to the
interrupted process.
EZ-COURSEWARE 9-19
Interfacing Input/Output and Timer Devices
2) Install the address that points to the ISR in the vector location that is associated with
the system that will generate the interrupt signal. Each source of interrupt has a unique
pair of addresses that are used to direct the interrupt process to the entry point for the
ISR.
9-20 EZ-COURSEWARE
Serial Input/Output
Serial Input/Output
EZ-COURSEWARE 10-1
Serial Input/Output
Transferring data between systems can be accomplished in a number of different ways. So far,
the input/output operations that we discussed in Lesson Seven have dealt with parallel I/O,
meaning the simultaneous transmission of a group of bits (a byte in our case). In this chapter
we'll introduce serial I/O, meaning the transmission of bits one at a time.
A serial input port is a single wire over which serial data is input to the microcontroller from a
peripheral device. A serial output port is a wire over which serial data is output from the
microcontroller to a peripheral device. The major advantage of serial I/O is that it uses fewer
wires than parallel I/O. Remember from Lesson Seven that increased pin count can have a direct
impact on package cost as well as PC board cost. The major draw back of serial I/O is that is
slower than parallel I/O. To send one ASCII character serially, we need to transmit a byte of data
1 bit at a time instead of all at once.
The most apparent application of serial I/O is in transmitting coded characters, such as ASCII.
For this reason we will be discussing mostly serial transmission of ASCII characters in this
Lesson.
One way we can transmit serial ASCII characters is asynchronously, meaning that indefinite
periods of time may lapse between transmission of characters. There is no shared serial clock
between the two devices. Each character must be unique and recognizable by itself.
Alternatively, we can transmit serial ASCII characters synchronously by taking the same amount
of time to transmit each character with no time lapses in between characters. Synchronous
transmissions require that a common external clock exist between the two devices that are
communicating. Typically one of the devices functions as the master, providing the serial clock
as an additional input to the slave device.
In this Lesson we will consider both asynchronous serial I/O and synchronous serial I/O. The
HC11E0 supports both of these serial transmission schemes by multiplexing these functions on
port D. When the serial communications interface (SCI) is enabled, the PD0/RxD pin becomes
an input and the PD1/TxD pin becomes an output. These two wires comprise the asynchronous
serial port. When the serial peripheral interface (SPI) system is enabled, the PD2/MISO,
PD3/MOSI, PD4/SCK, and PD5/SS* pins become dedicated to SPI functions. These four wires
comprise the synchronous serial port.
10-2 EZ-COURSEWARE
Serial Input/Output
7 6 5 4 3 2 1 0
A 0 1 0 0 0 0 0 1
The transitions from '0' to '1' and from '1' to '0' seem easy to detect but how can the asynchronous
receiver detect that there are five sequential zeros present in the middle of the data stream?
Bits transmitted in an asynchronous serial stream have to be defined in terms of bit times. We
can choose from among a number of standard bit times for a particular application. The bit time
depends directly on the number of bits per second, called the baud rate; the bit time is the
reciprocal of the baud rate. Some common available baud rates and their corresponding bit times
are shown in Table 10.1.
110 9.09 ms
150 6.67 ms
300 3.33 ms
600 1.67 ms
1200 0.83 ms
2400 0.417 ms
4800 0.208 ms
9600 0.104 ms
12000 0.083 ms
19200 0.052 ms
Table 10.1 Common Baud Rates and Bit Times
In order to define the beginning and end of an ASCII character, the data bits are framed with one
start bit at the beginning of the character and one or more stop bits at the end of the character.
When no characters are being transmitted, the data line is high, called a mark. The start bit is a
'0', called a space. The stop bit or bits are a '1' and the line stays high if no further characters are
transmitted.
The number of characters transmitted per second is called the character rate. To calculate the
character rate from the baud rate, we need to know how many bits are in a character. A character
with 1 stop bit contains 10 bits and a character with 2 stop bits contains 11 bits. You may have
seen options for character formats on the setup screen of your modem application software for
example.
EZ-COURSEWARE 10-3
Serial Input/Output
Inside the 'HC11E0 there are registers for initializing and configuring the asynchronous serial
communications interface (SCI). The fundamental clock running in the SCI module is the 16x
receiver baud rate clock. This fast clock allows the SCI receiver hardware to oversample the
incoming bitstream by a factor of 16. This 16x clock is derived from the crystal frequency and
the baud rate, in turn, is derived from the 16x clock.
SCI registers
The user can program the SCI configuration by five registers: BAUD, SCCR1, SCCR2, SCSR,
and SCDR. Each of these registers is discussed in detail in the following sections.
The baud rate control register (BAUD) is used to select the baud rate. Normally this register is
written once during initialization to set the SCI baud rate. The baud rate is derived from the E
clock and both the receiver and transmitter use the same baud rate.
7 6 5 4 3 2 1 0 BAUD
TCLR 0 SCP1 SCP0 RCKB SCR2 SCR1 SCR0 $002B
Figure 10.1 BAUD Register
Two bits in the BAUD register select a prescale factor for the baud generator: SCP1 and SCP0.
Table 10.2 shows the highest baud rates that result for the four prescaler values at the EZ-Micro
crystal frequency of 4 MHz.
In addition to programming the SCPx bits, the three SCRx bits select a binary submultiple of the
highest baud rate. The result of these two subdividers working in series is the 16x receiver baud
rate clock. Table 10.3 shows the SCI baud rates that result for various settings of the SCRx bits
and the 4800 baud rate from Table 10.2.
10-4 EZ-COURSEWARE
Serial Input/Output
The serial transmission can be configured for either 8-bit or 9-bit data characters. The 9-bit data
format is most commonly used for an extra stop bit. The SCCR1 register contains the control bits
related to programming the data format.
7 6 5 4 3 2 1 0 SCCR1
R8 T8 0 M WAKE 0 0 0 $002C
Figure 10.2 SCI Control Register 1
The M bit controls the character length for both the transmitter and receiver at the same time.
Programming a '0' into this bit selects one start bit, eight data bits, and one stop bit.
Programming a '1' into this bit selects one start bit, nine data bits, and one stop bit. In the
Laboratories associated with the EZ-MICRO TUTOR™ Boards, we will always be operating the
SCI in the eight data bit mode, which is the default coming out of reset. For this reason, we will
not offer a detailed discussion regarding the 9-bit data format. For more information about this
mode, the interested reader should refer to the M68HC11 Reference Manual.
The main control register for the SCI subsystem is SCCR2; this register is shown in Figure 10.3
below. All eight bits in this register are important control bits and we need to understand the
operation of each one.
7 6 5 4 3 2 1 0 SCCR2
TIE TCIE RIE ILIE TE RE RWU SBK $002D
Figure 10.3 SCI Control Register 2
The reset state of the SBK bit (Send Break) is '0', which enables normal transmitter operation.
Programming this bit to '1' enables the transmitter to send synchronous break characters. A break
character holds the transmit line at logic zero.
Similarly, the reset state of the RWU (Rx Wake Up) bit is '0', which enables normal receiver
operation. Programming this bit to '1' causes the receiver to go to sleep until the start of the next
message. Your software can set the RWU bit after deciding that a particular SCI message is of
no interest. The receiver wake up logic automatically recognizes when the message of no interest
is complete and clears the RWU bit to wake up the receiver.
The RE bit is the receiver enable bit. When a '1' is programmed into this bit the SCI receiver is
enabled; when a '0' is programmed into this bit the SCI receiver is disabled.
The TE bit is the transmitter enable bit. When a '1' is programmed into this bit the SCI
transmitter is enabled; when a '0' is programmed into this bit the SCI receiver is disabled. Note
that the transmitter cannot be turned off in the middle of a character. The transmitter keeps
control of the TxD pin until any character in progress is finished.
ILIE represents the Idle-Line Interrupt enable bit. Programming this bit to a '1' allows the
hardware to generate an SCI interrupt request when IDLE is set to one. Programming this bit to a
EZ-COURSEWARE 10-5
Serial Input/Output
'0' disables IDLE interrupts. Software will have to poll the IDLE flag. We will discuss the IDLE
flag in the next section when we consider the SCI status register.
The RIE bit controls Receive Interrupt Enables. When this bit is a '0' rx interrupts are disabled.
When this bit is a '1' an SCI interrupt is requested when either RDRF or OR is set to one. These
status bits are two of the flags contained in the SCI status register.
TCIE is the Transmit Complete Interrupt Enable bit. Similar to the bits above, programming this
bit to a '0' will disable the TC interrupt. Programming this bit to a '1' will enable the TC interrupt
and the hardware will request an SCI interrupt whenever TC is set to one. When we discuss the
SCI status register you will see the TC flag.
The TIE bit is the transmit interrupt enable bit. When a '1' is programmed into this bit, TDRE
interrupts are enabled; when a '0' is programmed into this bit, TDRE interrupts are disabled. The
TDRE is the normal indication from the SCI hardware that a new character may now be written
to the SCDR.
Having discussed the main control register, we will now discuss the status register. The seven
bits associated with the SCI subsystem are located in the SCSR, which is shown in Figure 10.4
below.
7 6 5 4 3 2 1 0 SCCR2
TDRE TC RDRF IDLE OR NF FE 0 $002E
Figure 10.4 SCI Status Register
The function of these seven bits can be grouped into two categories. Some of these bits generate
hardware interrupt requests; others indicate errors in the reception of a character. All of the status
bits are automatically set by the corresponding conditions having been met in the SCI logic. It is
important to note that once set, these bits remain set until software completes a clearing
sequence. For example, to clear the TDRE flag, software must read the SCSR while the TDRE
bit is set, and then write to the TDR. This process does not involve any additional instructions
because these are exactly the normal steps in response to the TDRE anyway.
The Framing Error bit (FE) will be set by the SCI subsystem hardware when a framing error was
detected for the character in the SCDR. The definition of a framing error is when the stop bit is
not detected in the last bit time.
NF is the Noise Flag bit. This bit will be set to a '1' when the data recovery logic inside the SCI
hardware detected noise during reception of the character in the SCDR. Noise is indicated during
the data bit times if the three samples taken near the middle of the bit time do not unanimously
agree. Like many systems, we will ignore the NF bit and rely on the fact that the data recovery
logic has already made a good first-order attempt to correct the problem.
When the Idle_line Detect bit (IDLE) is set to a '1', the TxD line has become idle. The idle
condition is defined as at least a full character time of logic one on the Rxd line. For our case, a
character time is 10 bit times (M=0).
10-6 EZ-COURSEWARE
Serial Input/Output
The Receive Data Register Full bit (RDRF) will be set to '1' as the normal indication that a
character has been received by the SCI. Specifically, a character has been received and has
transferred from the receive shift register to the parallel SCDR where the software can read it.
Note that the NF and FE status bits will provide additional information about the newly received
character in the SCDR. Furthermore, the OR flag would indicate that another character was
serially received and was ready to be transferred from the shift register to the parallel SCDR, but
the previously received character was not read yet.
TC is the Transmit Complete bit. When this bit is set to a '1' the transmitter has completed
sending and has reached an idle state. The TDRE bit indicates that the last character has
transferred from the SCDR to the transmit shift register. The TC bit indicates that the last bit has
been shifted out.
The Transmit Data Register Empty bit (TDRE) will be set to '1' as an indication that a new
character may now be written to the SCDR. In normal transmit operation, this bit will be
checked by your software to see if the SCDR can accept new data from you. The SCI is double-
buffered. This means that the TDR holds the second character in line while the transmit serial
shift register sends out the next character.
The SCI Data Register (SCDR) shown in Figure 10.5 below is actually two separate registers.
When the SCDR is read, the read-only RDR is accessed; when the SCDR is written, the write-
only TDR is accessed. This register location ($002F) may be referred to by any of the
mnemonics SCDR, TDR or RDR.
SCDR
7 6 5 4 3 2 1 0 $002F
R7 R6 R5 R4 R3 R2 R1 R0 RDR (read)
T7 T6 T5 T4 T3 T2 T1 T0 TDR (write)
Figure 10.5 SCI Data Register
We stated in the section above that the SCI receiver is double buffered. This means that the
receiver can be processing up to two characters at any given time. One of the characters is stored
in the readable parallel receive data buffer (RDR) and the other is in the process of shifting into
the receiver serial shift register. Without double-buffering the transmitting device on the other
end would be required to insert delays between transmitted characters to avoid a receiver
overrun. Note that an overrun can still occur in a double-buffered SCI receiver if a serial
character is received and is ready to transfer into the parallel RDR before the previously received
character is read out.
EZ-COURSEWARE 10-7
Serial Input/Output
Reviewing the previous two paragraphs, we see that programming a value of $2C into the
SCCR2 will configure the SCI for what we will call our normal mode of operation on the EZ-
MICRO TUTOR™ Board.
Status Register
Out of the seven status bits associated with the SCI in the SCSR2 register, we will only be
concerned with two of these bits in normal operation. The TDRE bit will be set by the SCI
hardware to indicate that a new character may now be written to the SCDR. When the TDRE bit
is set, an interrupt will not be generated; out software will poll this bit. The RDRF bit will be set
to indicate that a character has been received and has transferred from the receive shift register to
the parallel SCDR where software can read it. When the RDRF is set, an interrupt request will be
generated by the hardware. We will have to write an interrupt service routine to handle this serial
interrupt.
10-8 EZ-COURSEWARE
Serial Input/Output
SPI Transfer
As we will see later, there are two control bits that can be programmed to select one of four SPI
transfer formats. Figure 10.6 is a timing diagram of one particular case. (CPHA = '1' and CPOL =
'0').
SPI Registers
Inside the 'HC11E0 there are registers for initializing and configuring the serial peripheral
interface (SPI). The user can program the SPI configuration by three registers: SPCR, SPSR and
SPDR. Each of these registers is discussed in detail in the following sections. Also because the
port D data direction control register influence SPI activities, it will be discussed briefly. A
detailed discussion about the port D pins can be found in Lesson Seven.
The main control register for the SPI system is the SPI Control Register (SPCR). Your software
can read or write this register at any time. This register is shown in Figure 10.7 below.
7 6 5 4 3 2 1 0 SPCR
SPIE SPE DWOM MSTR CPOL CPHA SPR1 SPR0 $0028
Figure 10.7 SPI Control Register
EZ-COURSEWARE 10-9
Serial Input/Output
The two bits, SPR0 and SPR1, control the bit rate for transfers when the SPI is operating as a
master. Note that when the SPI is operating as a slave, the serial clock is an input form the
master. In this mode, SPR0 and SPR1 have no control. Figure 10.8 shows the bit rates that can
be programmed by SPR0 and SPR1. The SPI clock rate is derived from a programmable divider
off E clock.
The CPHA bit controls the selection of one of two, fundamentally different transfer formats.
The CPOL bit controls clock polarity. When we program a '1' into this bit, active low clocks are
selected and SCK will idle in the low state. When we program a '0' into this bit, active high
clocks are selected and SCK will idle in the high state.
MSTR is the Master/Slave Mode Select bit. Programming a '1' into this bit will configure the SPI
as master; programming a '0' into this bit will configure the SPI as slave.
Programming the SPE bit to a '1' will enable the SPI system. Programming the SPE bit to a '0'
will disable the SPI system.
Finally, the SPIE bit is the SPI Interrupt Enable control bit. If this bit contains a '1' then an SPI
interrupt will be requested at the end of a SPI transfer. If this bit contains a '0' then and interrupt
will not be requested. The software can poll the SPIF flag in order to detect the end of a SPI
transfer.
The read-only SPI Status Register (SPSR) contains status flags indicating the completion of a
SPI transfer and the occurrence of certain SPI errors. These flags are set automatically by the SPI
subsystem hardware. Refer to Figure 10.9 for the location of status bits within the register.
7 6 5 4 3 2 1 0 SPSR
SPIF WCOL 0 MODF 0 0 0 0 $0029
Figure 10.9 SPI Status Register
The error flags, WCOL and MODF, are automatically set if the hardware detects an error
condition during the SPI transmission. Write collision errors and mode faults are beyond the
scope of this Lesson. For more information about these faults, the interested reader should refer
to the M68HC11 Reference Manual.
10-10 EZ-COURSEWARE
Serial Input/Output
The SPI Transfer Complete Flag (SPIF) is automatically set to a '1' at the end of a SPI transfer.
Generally speaking, SPIF is set at the end of the eighth SCK cycle. Depending on the particular
mode of operation and whether the device is acting as master or slave, will determine the exact
time that SPIF will be set.
The port D Data Direction Register (DDRD) was discussed in Lesson Seven. The description of
the DDRD in this section is only intended to cover material related to the SPI system. Refer to
Figure 10.10 below as each bit is described in detail.
7 6 5 4 3 2 1 0 DDRD
0 0 DDRD5 DDRD4 DDRD3 DDRD2 DDRD1 DDRD0 $0009
SS* SCK MOSI MISO TxD RxD
Figure 10.10 Port D Data Direction Register
When the SPI system is enabled as a slave (SPE=1; MSTR=0), the PD5/SS* pin is the slave
select input. Conversely when the SPI system is enabled as a master (SPE=1; MSTR=1), the
function of the PD5/SS* pin now depends on the value in DDRD5. When a '0' is programmed in
DDRD5, the SS* pin is used as an input to detect mode-fault errors. As we indicated earlier,
mode-fault errors are beyond the scope of this Lesson. When a '1' is programmed in DDRD5, the
PD5/SS* pin now acts a general-purpose output that is not affected by the SPI system. Many
times in typical applications, the PD5/SS* pin is connected to the SS* input pin of a slave
device.
DDRD4 is the Data Direction Control for bit 4 of port D. It shares functionality with SCK. When
the SPI system is enabled as a slave, the PD4/SCK pin acts as the SPI serial clock input. When
the SPI system is enabled as a master, the DDRD4 bit must be set to '1' to enable the SCK
output.
The Data Direction Control bit DDRD3 must be set to '1' to enable the master serial data output
when the SPI system is enabled as a master. When the SPI system is enabled as a slave, the
PD3/MOSI pin acts as the slave serial data input, regardless of the state of DDRD3.
The final bit in the port D Data Direction Control Register is DDRD2. This bit must be set to '1'
to enable the slave serial data output when the SPI system is enabled as a slave. When the SPI
system is enabled as a master, the PD2/MISO pin acts as the master serial data input, regardless
of the state of DDRD2.
SPCR
EZ-COURSEWARE 10-11
Serial Input/Output
Configuring one device as slave master will require that set the MSTR bit in the SPI control
register. In addition to setting this bit, we will select CPOL = '0' and CPHA = '1'. The selection
of the SPI bit rate is arbitrary as long as the SPI master and SPI slave are configured to operate at
the same rate. For the EZ-Micro Laboratories in this Lesson, we will select a divide by 4
configuration. Furthermore, we will enable SPI interrupts by setting the SPIE bit. Based on this
discussion, we should program a value of $D5 into the control register on the master and a value
of $C5 into the control register on the slave side.
SPSR
When our software reads the SPI status register, we will only be concerned with the SPIF bit, a
flag indicating the completion of an SPI transfer.
DDRD
The SPI master will be driving SCK and SS* as outputs. For this reason, we will program $38
into DDRD (address $0009) on the master device. Conversely, the SPI slave will be receiving
SCK and SS* as inputs. For this reason, we will program $04 into DDRD on the slave device.
SPDR
We can read and write to the SPI data register at address $002A. This register is double-buffered
in and single-buffered out.
10-12 EZ-COURSEWARE
Serial Input/Output
Questions
Laboratory 10.1
Procedure
This Laboratory involves interfacing two EZ-MICRO TUTOR™ Main Boards using the built-in
SCI ports. The hardware interconnections between the two EZ-MICRO TUTOR™ Main Boards
are detailed below in Figure 10.11. You will be implementing a three-wire bidirectional interface
scheme. The required signals are TxD, RxD and Ground. Note that the TxD signal from one
system connects to the RxD signal from the other.
No handshaking of any kind is implemented for simplicity purposes. Additional lines for
handshake support to address overrun errors may be typically implemented in some applications.
For example, in an RS-232 interface between your computer and your external modem, two
handshake signals are defined — RTS* (Request to Send) and CTS* (Clear to Send). These lines
are used to determine when characters can be transferred without overrun problems. Other
schemes may use additional signal.
In this experiment, the receiver will be capable of accepting characters without an overrun error.
This is a realistic assumption because our software will be dedicated to servicing the serial port.
Similar to Laboratory 9_1, you will be using the Keypad/Display Lab Board. System 'A' will
send a character ('%') to system 'B' which will interpret this character as a "request for data"
(RFD) code. When system 'B' receives this code, it will transmit the number "123" to system 'A'
which will then display that number on the LED displays using the display driver routine from
Laboratory 9_2.
A good scheme for testing the operation of the system is to use your PC to emulate each of the
systems for the other one before connecting them together for final system integration. Thus, the
PC could emulate the master module and send the request character (type the '%' character) and
could display the number "123" to test the slave module. The PC could emulate the slave module
and monitor the output of the master module to look for the request character (%), then respond
with the typed number "123". This scheme allows testing of one module at a time to ease the
integration process.
EZ-COURSEWARE 10-13
Serial Input/Output
Because the sequence of operations is critical to the successful interfacing of the two EZ-Micro
Boards, the pseudo-code for system 'A' and system 'B' processors is provided at the end of this
Laboratory.
Laboratory Report
The laboratory report for this experiment will involve planning a handshaking scheme for your
serial interface. This handshaking scheme can involve software/hardware or software only
schemes. Your handshaking scheme does not need to be implemented for this report.
The report should consist of an introduction, description of the proposed handshaking scheme
and documentation of the proposed changes to the existing system. The documentation could
consist of schematic diagrams of the interface connections, detailed pseudo code or assembly
language listings of the handshake routines, along with timing diagrams to indicate the sequence
of the handshake process.
Laboratory 10.2
Procedure
This Laboratory involves interfacing two EZ-Micro Main Boards using the built-in SPI ports.
The hardware interconnections between the two EZ-Micro Main Boards are detailed below in
Figure 10.12. You will be implementing a four-wire bidirectional interface scheme. The required
signals are MISO, MOSI, SS* and Ground. In the figure below, system 'A' is the SPI master and
system 'B' is the SPI slave. Note that MOSI signal from one system connects to the MISO signal
from the other. Furthermore, note that the SPI master is using PD5/SS* as a general-purpose
output, whereas the SPI slave is using PD5/SS* and the slave select input.
Again, similar to Laboratory 9_1, you will be using the Keypad/Display Lab Board. The master
will send a character ('%') to the slave which will interpret this character as a "request for data"
(RFD) code. When the slave receives this code, it will write the number "1" to the SPI data
10-14 EZ-COURSEWARE
Serial Input/Output
register and wait. Note that the slave has no means of telling the host that the data is ready. After
a delay, the master will send another character ('%') to the slave. The slave data will be
automatically returned to the master, which will then display that number on the LED displays
using the display driver routine from Laboratory 9_2.
Because the sequence of operations is critical to the successful interfacing of the two EZ-Micro
Boards, the pseudo-code for the master and slave processors is provided at the end of this
Laboratory.
Laboratory Report
This laboratory report will involve planning a handshaking scheme for the SPI interface. As it
currently stands, our interface is rather one-sided. The master can assert SS* at any time and
transfer data to the slave. At that time, the slave has the opportunity to transfer data to the
master. However, our interface does not provide the slave device with a means of telling the
master that it has data ready to send. Your new handshaking scheme can involve both hardware
and software. This scheme does not have to be implemented for this report. You only have to
describe your idea.
The report should consist of an introduction, description of the proposed scheme, and
documentation of the proposed changes to the existing system. The documentation could consist
of schematic diagrams of the interface connections, detailed pseudo code or assembly language
listings of the handshake routine, and timing diagrams to indicate the sequence of the handshake
process.
EZ-COURSEWARE 10-15
Serial Input/Output
10-16 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
EZ-COURSEWARE 11-1
Analog to Digital and Digital to Analog Conversion
As engineers, we must make tradeoffs between cost and performance. How fast should we
sample the input signal? How many bits of resolution do we need? What types of errors can our
system tolerate? These are the types of questions that the material presented in this Lesson will
help to answer.
D/A Conversion
Many systems accept a digital word as an input signal and translate it or convert it to an analog
voltage or current. These systems are called digital-to-analog converters. The resolution of the
D/A converter defines the smallest change of output voltage as a fraction of full scale. For the
case of an 8-bit D/A converter (like the one on the EZ-Micro A/D-D/A Lab Board), the output
can increase in steps of 19.53 mV up to a maximum of 256 steps. Each step is called a quantum.
The conversion time allows us to calculate the speed of conversion of a D/A converter and
thereby obtain the maximum conversion frequency or the maximum number of conversions that
can be carried out per second. The conversion time is the time required for the output to reach
the desired value within the specified error. It is dependent on the components used and the
worst case is when all the bits change simultaneously from 0 to 1.
The last important characteristic of a D/A converter is its accuracy. It is defined as the difference
between the output signal obtained and the calculated theoretical value. The accuracy is usually
expressed as a percentage of full-scale or as a fraction of the quantum and rarely in absolute
units of mV or uV. The accuracy quoted by manufacturers is usually +/- 1/2 quantum. All bits
are involved in the definition of the accuracy but their effect varies according to their weight. To
understand this, consider that the MSB controls a corresponding voltage equal to one half the full
scale voltage.
Types of DACs
The D/A conversion process is quite straightforward and is easier to understand than the A/D
conversion. In fact, many of the A/D conversion techniques incorporate a DAC as an essential
step. The examples which follow will generally make use of a 4-bit digital word. This is only a
matter of convenience; the concepts can readily be extended to 8-bits and beyond.
Weighted Resistor
A weighted resistor network is one method of achieving the digital-to-analog conversion. Such a
circuit is given in Figure 11.1, where VA is the analog voltage output and RL is selected to be
much larger than 8R. The weighting of the resistor ladder is that of binary coded decimal (8, 4, 2,
1), with the most significant bit (MSB) resistance being one-eighth that of the LSB.
11-2 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
Each of the digital inputs will have a voltage corresponding to a '1' or a '0' in whatever logic line
is being converted. The output voltage, VA, can be determined for the weighted resistor ladder
and the general expression can be reduced to
where Vm is the voltage condition of the MSB, Vnm is that of the next most significant bit, Vnl
is that of the next least significant bit, and Vl is that of the LSB. Compute the values for various
binary inputs with V1 = 3.0 V or 0.0 V. Does the output behave as you expected?
The accuracy and stability of the DAC in Figure 11.1 depend primarily on the absolute accuracy
of the resistors how the resistors track with each other over temperature. The weighted resistor
ladder suffers in implementation from the fact that a wide range of resistor values is needed. For
example, for a 10-bit DAC the largest resistance is 51.2 Mohm if the smallest is 10 kohm. The
ladder-type converter described in the following avoids these difficulties.
Binary Ladder-type
The binary ladder network largely overcomes the problems of the weighted resistor network. The
binary ladder D/A circuit is shown in Figure 11.2. Only two resistor values are needed. We
observe from the figure that at any of the ladder nodes the resistance is 2R looking to the left or
the right or toward the switch.
EZ-COURSEWARE 11-3
Analog to Digital and Digital to Analog Conversion
For example, to the left of node 0 there is 2R to ground; to the left of node 1 there is a parallel
combination of two 2R resistors to ground in series with R, for a total resistance of 2R, and so
forth. Therefore, if any switch, take for example N-2, is connected to VR, the resistance seen by
VR is 2R + R -= 3R and the voltage at node N-2 is (VR/3R)R = VR/3.
Input Codes
Frequently used input codes for D/A converters are sign-magnitude, offset-binary and two's-
complement bipolar codes. These codes are graphically described in Figure 11.3 for an 8-bit
example. Sign magnitude is especially useful for outputs that are in the vicinity of zero. The
most significant bit represents the sign, '0' means positive. The remaining seven bits represent
the magnitude in the range from 0 to 127. Offset binary is the easiest to implement in the
converter hardware. However, there is a major bit transition in going from just below zero up to
zero. Note that one level below zero is represented as 01111111 and zero is represented as
00000000; seven bits have to flip. Two's complement is more computer compatible. This code
consists of a binary number for the positive magnitudes and the two's complement of each
positive code for the negative magnitudes.
11-4 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
In your software that you develop in the Labs, use offset-binary input code when you write to the
DAC08032 on the EZ-Micro A/D-D/A Lab Board. With the reference voltage set to 6.0 V, the
relationship between digital input code out observed output voltage is given by:
GLJLWDOFRGH
9RXW 9
Note that offset binary is readily converted to two's-complement by simply complementing the
MSB.
A/D Conversion
Analog to digital conversion is the process of transforming a continuous signal into a discrete
time representation. This process has been describe as the process of converting real world
signals to a form that used in the electrical world of digital systems. Extensive theoretical and
mathematical studies have been performed analyzed the A/D process as well as the D/A process.
The introduction provided in this section will try to identify the key concepts involved with
analog-to-digital conversion.
EZ-COURSEWARE 11-5
Analog to Digital and Digital to Analog Conversion
Consider the continuous time analog function f(t) shown in Figure 11.4. The amplitude of this
signal varies between 0 and 1 over the period shown from t0 to tp. To determine the amplitude of
this signal at time ts, it could be approximated by the representation "0.5" which would be
reasonably close. On the other hand, it may be more accurate to say "0.53" or even
"0.5268345500284384". In fact, the absolute value of f(t) at time ts might go on forever!
Deciding how many places of accurateness are necessary to represent f(t) at ts is the process of
discrete representation. Analog-to-digital conversion is the process of determining a number that
closely approximates an input signal at a particular point in time.
All A/D converters implement the operations of sampling, quantizing, and encoding in order to
relate analog input to digital values. One conversion is performed during each sample period T.
Quantization of a sampled analog waveform involves the assignment of a finite number of
amplitude levels that increases to some full-scale (FS) value such as 5 volts. The quantizing
interval q shown in Figure 11.5(a) represents the least significant bit (LSB) resolution. Its value
is determined by both the full-scale amplitude value and by the total number of level provided by
an n-bit converter, which is 2^n. If we assume that the A/D converter is based on uniform
quantization, the quantization error e is a sawtooth function range in value up to +\- 1/2 LSB as
shown in Figure 11.5(b).
11-6 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
An 8 bit converter is used on the EZ-Micro A/D-D/A Lab Board. Such a converter will represent
a signal as one of 2^8 or 256 steps. If the Vrh to Vrl reference voltage is 5 volts, each discrete
step will represent about 19.53 mV. The quantization error will be in the range of +/- 1/2 LSB, or
about +/- 10 mV. In comparison, 12-bit converter would have a step size of about 1.22 mV.
EZ-COURSEWARE 11-7
Analog to Digital and Digital to Analog Conversion
Aliasing
If the signal is not sampled at a sufficient rate, the signal energy that is contained in the higher
frequencies will be "aliased" to a lower frequency. This aliasing distortion will be investigated in
one of the Laboratory experiments at the end of this Lesson.
Aliasing is illustrated in the time domain by Figure 11.6, which demonstrates the unique
mapping of an analog input sample to its sampled-data representation, as shown by the dots.
However, the sampled-data representation does not have a unique reverse mapping, as
demonstrated by the dashed line aliased waveform.
Antialiasing filters
In most cases, it is desirable to minimize the sampling rate of a discrete-time system for
processing analog systems. This is because the amount of digital signal processing as well as the
memory requirements are proportional to the number of samples to be processed. In most
applications a prefilter, called an anti-aliasing filter, is used. Consider an example from speech
processing. Speech signals may have significant frequency content throughout the range from 4
Hz to 20 kHz. However, intelligible speech can be processed even if we only consider the low
frequency band up to about 3.5 kHz. For this reason, speech processing systems may include a
lowpass anti-aliasing filter with a cutoff frequency of about 3.5 kHz on the front end.
On the EZ-Micro A/D-D/A Lab Board there is a lowpass anti-aliasing filter on the front end.
Refer to the schematic diagram of the A/D-D/A Lab Board. The anti-aliasing filter is a 2nd order
lowpass Butterworth filter that is comprised of the op amp designated as U12-C and the
associated passive components surrounding it. Note that an analog input applied to the test point
designated as T3 will go through the front-end filter but the same input applied instead to the test
point designated as T4 will not go through the filter.
All A/D converters employ one or more comparators. The integrator type A/D converter is used
extensively because it represents an excellent compromise of conversion rate, accuracy, and cost.
The essential block diagram of the dual slope integrator system is given in Figure 11.7. At the
start, the control logic closes switch AS1 and opens switch AS2. Thus Vin is applied to the
integrator. At the same time, the clock is enabled and begins to add pulses to the counter. These
processes continue until the counter has been filled. the next clock pulse reloads the counter to
zero and transmits an overflow pulse to the control logic. This causes switch AS1 to be opened
and AS2 to be closed, thus applying -Vref, which is a known voltage, to the integrator. Whatever
value of voltage was stored on the integrator, Vin/RC, will be "removed" linearly with time by -
Vref/RC. The comparator, which serves as a zero crossing detector, signals when the removal of
voltage from the capacitor is complete. This disables the clock. The key is that the number of
counts in the counter is proportional to the unknown voltage. Get it?
EZ-COURSEWARE 11-9
Analog to Digital and Digital to Analog Conversion
The successive-approximation type of A/D converter offers an enhanced rate of conversion with
high accuracy. The functional block diagram of a successive approximation A/D converter, as
shown in Figure 11.8, is deceptively simple. The important feature is the special control logic.
The functionality of this logic is illustrated by the waveform in the lower portion of the figure.
The control logic sequentially determines whether the input is (a) outside the range of the D/A
converter, (b) greater than the D/A output for a '1' in the MSB, ... and so forth until (c) greater
than the D/A output for a '1' in LSB. There is a significant amount of digital logic required in the
implementation of the successive-approximation type of A/D converter. Note that N fixed time
periods are needed to deliver an N-bit output providing a constant conversion time. Conversion
accuracy depends upon the stability of the reference voltage and the error budget includes a term
representing the +/- ½ LSB quantization error as discussed in the previous section.
11-10 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
The voltage-comparison tracking converter is especially useful for parallel conversion systems
that employ one A/D converter per channel. In operation its conversion time is variable, and it
tracks the input signal at a rate of 2^(-n) per count of the n-bit counter. For example, an 8-bit
converter with an integral 1 MHz clock will track an input signal up to a 2^(-8) x 1 MHz or 4
kHz conversion rate, with 256 counts per conversion.
The ADC that is used on the EZ-Micro A-D/D-A Lab Board is the ADC0804 from National
Semiconductor. This converter is an 8-bit successive approximation analog-to-digital converter.
Its conversion time is specified as 100 usec with the on-chip clock generator running at 640 kHz,
which is how the clock is configured on the Lab Board. Analog voltages in the range from 0V to
5v will be converted to 8-bit binary representations in the range from $00 to $FF.
The ADC0804 supports a parallel interface that has been designed by the manufacturer to be
easy to interface with the host microprocessor. The access time for the parallel read operation is
specified to be 135 ns. Other ADCs may interface with the microprocessor via a serial interface.
For example, some converters support the SPI interface.
EZ-COURSEWARE 11-11
Analog to Digital and Digital to Analog Conversion
11-12 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
Multiplexer
The multiplexer selects one of 16 inputs for conversion. Input selection is controlled by the value
of bits CD:CA in the ADCTL register. The eight port E pins are fixed-direction analog inputs to
the multiplexer, and additional internal analog signal lines are routed to it. Port E pins also can
be used as digital inputs. Digital reads of port E pins are not recommended during the sample
portion of an A/D conversion cycle, when the gate signal to the N-channel input gate is on.
Because no P-channel devices are directly connected to either input pins or reference voltage
pins, voltages above V DD do not cause a latchup problem, although current should be limited
according to maximum ratings.
Analog Converter
Conversion of an analog input selected by the multiplexer occurs in this block. It contains a
digital-to-analog capacitor (DAC) array, a comparator, and a successive approximation register
(SAR). Each conversion is a sequence of eight comparison operations, beginning with the most
significant bit (MSB). Each comparison determines the value of a bit in the successive
approximation register. The DAC array performs two functions. It acts as a sample and hold
circuit during the entire conversion sequence and provides comparison voltage to the comparator
during each successive comparison. The result of each successive comparison is stored in the
SAR. When a conversion sequence is complete, the contents of the SAR are transferred to the
appropriate result register. A charge pump provides switching voltage to the gates of analog
switches in the multiplexer. Charge pump output must stabilize between 7 and 8 volts within up
to 100 µs before the converter can be used. The charge pump is enabled by the ADPU bit in the
OPTION register.
Digital Control
All A/D converter operations are controlled by bits in register ADCTL. In addition to selecting
the analog input to be converted, ADCTL bits indicate conversion status and control whether
single or continuous conversions are performed. Finally, the ADCTL bits determine whether
conversions are performed on single or multiple channels.
Result Registers
Four 8-bit registers ADR[4:1] store conversion results. Each of these registers can be accessed
by the processor in the CPU. The conversion complete flag (CCF) indicates when valid data is
present in the result registers. The result registers are written during a portion of the system clock
cycle when reads do not occur, so there is no conflict.
EZ-COURSEWARE 11-13
Analog to Digital and Digital to Analog Conversion
Conversion Sequence
A/D converter operations are performed in sequences of four conversions each. A conversion
sequence can repeat continuously or stop after one iteration. The conversion complete flag
(CCF) is set after the fourth conversion in a sequence to show the availability of data in the result
registers. Figure 11.11 shows the timing of a typical sequence. Synchronization is referenced to
the system E clock.
Address: $1039
Bit 7 6 5 4 3 2 1 Bit 0
Read:
ADPU CSEL IRQE(1) DLY(1) CME CR1(1) CR0(1)
Write:
Reset: 0 0 0 1 0 0 0 0
1. Can be written only once in first 64 cycles out of reset in normal modes or at any time in special modes
= Unimplemented
11-14 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
Conversion Process
The A/D conversion sequence begins one E-clock cycle after a write to the A/D control/status
register, ADCTL. The bits in ADCTL select the channel and the mode of conversion. An input
voltage equal to V RL converts to $00 and an input voltage equal to V RH converts to $FF (full
scale), with no overflow indication. For ratiometric conversions of this type, the source of each
analog input should use V RH as the supply voltage and be referenced to V RL .
Channel Assignments
The multiplexer allows the A/D converter to select one of 16 analog signals. Eight of these
channels correspond to port E input lines to the MCU, four of the channels are internal reference
points or test functions, and four channels are reserved. Refer to Table 11.2
EZ-COURSEWARE 11-15
Analog to Digital and Digital to Analog Conversion
1 AN0 ADR1
2 AN1 ADR2
3 AN2 ADR3
4 AN3 ADR4
5 AN4 ADR1
6 AN5 ADR2
7 AN6 ADR3
8 AN7 ADR4
9 - 12 Reserved —
13 V RH (1)
ADR1
14 V RL (1) ADR2
15 (V RH )/2 (1) ADR3
16 Reserved (1) ADR4
1. Used for factory testing
Single-Channel Operation
The two types of single-channel operation are:
1. When SCAN = 0, the single selected channel is converted four consecutive times. The
first result is stored in A/D result register 1 (ADR1), and the fourth result is stored in
ADR4. After the fourth conversion is complete, all conversion activity is halted until a
new conversion command is written to the ADCTL register.
2. When SCAN = 1, conversions continue to be performed on the selected channel with the
fifth conversion being stored in register ADR1 (overwriting the first conversion result),
the sixth conversion overwriting ADR2, and so on.
Multiple-Channel Operation
The two types of multiple-channel operation are:
1 When SCAN = 0, a selected group of four channels is converted one time each. The first
result is stored in A/D result register 1 (ADR1), and the fourth result is stored in ADR4.
After the fourth conversion is complete, all conversion activity is halted until a new
conversion command is written to the ADCTL register.
11-16 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
conversion result for the first channel in the group), the sixth conversion overwriting
ADR2, and so on.
Address: $1030
Bit 7 6 5 4 3 2 1 Bit 0
Read: CCF
SCAN MULT CD CC CB CA
Write:
1. Can be written only once in first 64 cycles out of reset in normal modes or at any time in special modes
= Unimplemented
EZ-COURSEWARE 11-17
Analog to Digital and Digital to Analog Conversion
When this control bit is clear, the four requested conversions are performed once
to fill the four result registers. When this control bit is set, conversions are
performed continuously with the result registers updated as data becomes
available.
MULT — Multiple Channel/Single Channel Control Bit
When this bit is clear, the A/D converter system is configured to perform four
consecutive conversions on the single channel specified by the four channel
select bits CD:CA (bits [3:0] of the ADCTL register). When this bit is set, the A/D
system is configured to perform a conversion on each of four channels where
each result register corresponds to one channel.
Address: $1030
Bit 7 6 5 4 3 2 1 Bit 0
Read: CCF
SCAN MULT CD CC CB CA
Write:
= Unimplemented
11-18 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
Channel Select
Control Bits Result in ADRx if
Channel Signal
MULT = 1
CD:CC:CB:CA
0000 AN0 ADR1
0001 AN1 ADR2
0010 AN2 ADR3
0011 AN3 ADR4
0100 AN4 ADR1
0101 AN5 ADR2
0110 AN6 ADR3
0111 AN7 ADR4
10XX Reserved —
1100 V RH (1) ADR1
1101 V RL (1)
ADR2
1110 (V RH )/2 (1) ADR3
1111 Reserved (1) ADR4
Analog-to-1. Used for factory testing D
igital (A/D) Converter
Table 2. A/D Converter Channel Selection
EZ-COURSEWARE 11-19
Analog to Digital and Digital to Analog Conversion
Write:
Write:
Write:
Write:
= Unimplemented
11-20 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
Laboratory 11.1
Digital to Analog output
The Micro Tutor Board has Digital to Analog chip and Current to Voltage coveter Op-AMP
circuit. DAC is connected to Output Latch 74LS373 and it has IO address of $5000 Hex.
The following Assembly language Program outputs Hex number from 00 to FF and it starts all
over again. This will give Sawtooth output at Pin 6 of U15 or pin 17 of J4. Switch jumper H5
from 1-2 to 2-3. The sawtooth output will be in reverse direction.
DAC.ASM
*************************************************************************
* This Program (DAC.ASM) tests Digital to Analog circuit *
* on EZ-MICRO TUTOR Board From Advanced Micorcomputer Systems Inc. *
* The updated software can be downloaded from our website *
* *
* www.advancedmsinc.com *
* *
* copyright 2000 by Advanced Micorcomputer Systems Inc. *
* *
*************************************************************************
* DAC test
* output a ramp function
ORG $2000
MAIN
LDAA #$00
LOOP INCA *increment ramp value
STAA DAC
JMP LOOP
* Delay subroutine
DLY10MS EQU * delay 10ms at E = 2MHz
PSHX
LDX #$0D06
DLYLP DEX
BNE DLYLP
PULX
RTS
EZ-COURSEWARE 11-21
Analog to Digital and Digital to Analog Conversion
A2D.ASM
*************************************************************************
* This Program (A2D.ASM) tests Analog to Digital circuit *
* on EZ-MICRO TUTOR Board From Advanced Micorcomputer Systems Inc. *
* The updated software can be downloaded from our website *
* www.advancedmsinc.com *
* copyright 2000 by Advanced Micorcomputer Systems Inc. *
* *
*************************************************************************
* Analog to Digital Converter Test
* Equates
* Registers
ADCTL EQU $30
ADR1 EQU $31
ADR2 EQU $32
ADR3 EQU $33
ADR4 EQU $34
* RAM
* External References
BUFALO EQU $E000
OUTPUT EQU $E3D8
*
****************************
* Define variables. *
****************************
ORG $2000
MAIN
JSR INIT_AD *initialize A/D converter hardware
JSR INIT_LCD *initialize LCD module
LDAA #$02
STAA CONTROL *LCD return home
JSR DLY10MS
11-22 EZ-COURSEWARE
Analog to Digital and Digital to Analog Conversion
JSR OUTPUT
JMP TOP
* Delay subroutine
DLY10MS EQU * delay 10ms at E = 2MHz
PSHX
LDX #$0D06
DLYLP DEX
BNE DLYLP
PULX
RTS
* Convert binary to ascii subroutine
* Binary value to convert is passed in ACCA
* BCD value returned in ACCA:ACCB
* example: ACCA=$14
* ACCA=$31 ACCB=$34
CONVERT PSHA
ANDA #$0F
ADDA #$30
TAB
PULA
LSRA
LSRA
LSRA
LSRA
ADDA #$30
RTS
EZ-COURSEWARE 11-23
Analog to Digital and Digital to Analog Conversion
11-24 EZ-COURSEWARE
Assembler Manual
Assembler Manual
EZ-COURSEWARE 12-1
Assembler Manual
Introduction
This is the user's reference manual for the IBM-PC hosted Motorola 8 bit cross assemblers. It
details the features and capabilities of the cross assemblers, assembler syntax and directives,
options, and listings. It is intended as a detailed reference and an introduction for those
unfamiliar with Motorola assembler syntax and usage.
Assemblers are programs that process assembly language source program statements and
translate them into executable machine language object files. A programmer writes his source
program using any text editor or word processor that can produce an ASCII text output. With
some word processors this is known as "non document" mode. Non document mode produces a
file without the non-printable embedded control characters that are used in document formating.
(Caution: assembling a file that has been formatted with embedded control characters may
produce assembler errors. The solution is to convert the source file to ASCII text.) Once the
source code is written, the source file is assembled by processing the file via the assembler.
Cross assemblers (such as the Motorola Assemblers) allow source programs written and edited
on one computer (the host) to generate executable code for another computer (the target). The
executable object file can then be downloaded and run on the target system. In this case the host
is an IBM-PC or compatible and the target system is based on a Motorola 68HC11
microprocessor.
Assembly Language
The symbolic language used to code source programs to be processed by the Assembler is called
assembly language. The language is a collection of mnemonic symbols representing: operations
(i.e., machine instruction mnemonics or directives to the assembler), symbolic names, operators,
and special symbols. The assembly language provides mnemonic operation codes for all
machine instructions in the instruction set. The instructions are defined and explained in the
Programming Reference Manuals for the specific devices, available from Motorola. The
assembly language also contains mnemonic directives which specify auxiliary actions to be
performed by the Assembler. These directives are not always translated into machine language.
Operating Environment
These assemblers will run on any IBM-PC, XT, AT, PS-2, or true compatible. The assemblers
may be run off of a floppy disk drive or they may be copied onto a hard drive for execution.
DOS 2.0 or later is required.
Assembler Processing
The Macro Assembler is a two-pass assembler. During the first pass, the source program is read
to develop the symbol table. During the second pass, the object file is created (assembled) with
reference to the table developed in pass one. It is during the second pass that the source program
listing is also produced. Each source statement is processed completely before the next source
statement is read. As each statement is processed, the Assembler examines the label, operation
code, and operand fields. The operation code table is scanned for a match with a known opcode.
12-2 EZ-COURSEWARE
Assembler Manual
During the processing of a standard operation code mnemonic, the standard machine code is
inserted into the object file. If an Assembler directive is being processed, the proper action is
taken.
Any errors that are detected by the Assembler are displayed before the actual line containing the
error is printed. If no source listing is being produced, error messages are still displayed to
indicate that the assembly process did not proceed normally.
Label Field
The label field occurs as the first field of a source statement. The label field can take one of the
following forms:
1. An asterisk (*) as the first character in the label field indicates that the rest of the source
statement is a comment. Comments are ignored by the Assembler, and are printed on the source
listing only for the programmer's information.
2. A whitespace character (blank or tab) as the first character indicates that the label field is
empty. The line has no label and is not a comment. 3. A symbol character as the first character
indicates that the line has a label. Symbol characters are the upper or lower case letters a- z,
digits 0-9, and the special characters, period (.), dollar sign ($), and underscore (_). Symbols
consist of one to 15 characters, the first of which must be alphabetic or the special characters
period (.) or underscore (_). All characters are significant and upper and lower case letters are
distinct. A symbol may occur only once in the label field. If a symbol does occur more than
once in a label field, then each reference to that symbol will be flagged with an error.
With the exception of some directives, a label is assigned the value of the program counter of the
first byte of the instruction or data being assembled. The value assigned to the label is absolute.
Labels may optionally be ended with a colon (:). If the colon is used it is not part of the label but
merely acts to set the label off from the rest of the source line. Thus the following code
fragments are equivalent:
EZ-COURSEWARE 12-3
Assembler Manual
here: deca
bne here
here deca
bne here
A label may appear on a line by itself. The assembler interprets this as set the value of the label
equal to the current value of the program counter. The symbol table has room for at least 2000
symbols of length 8 characters or less. Additional characters up to 15 are permissible at the
expense of decreasing the maximum number of symbols possible in the table.
Operation Field
The operation field occurs after the label field, and must be preceded by at least one whitespace
character. The operation field must contain a legal opcode mneumonic or an assembler directive.
Upper case characters in this field are converted to lower case before being checked as a legal
mneumonic. Thus 'nop', 'NOP', and 'NoP' are recognized as the same mneumonic. Entries in the
operation field may be one of two types:
Opcode. These correspond directly to the machine instructions. The operation code includes any
register name associated with the instruction. These register names must not be separated from
the opcode with any whitespace characters. Thus 'clra' means clear accumulator A, but 'clr a'
means clear memory location identified by the label 'a'.
Directive. These are special operation codes known to the Assembler which control the assembly
process rather than being translated into machine instructions.
Operand Field
The operand field's interpretation is dependent on the contents of the operation field. The
operand field, if required, must follow the operation field, and must be preceded by at least one
whitespace character. The operand field may contain a symbol, an expression, or a combination
of symbols and expressions separated by commas. The operand field of machine instructions is
used to specify the addressing mode of the instruction, as well as the operand of the instruction.
The following tables summarize the operand field formats for the various processor families.
(NOTE: in these tables parenthesis "()" signify optional elements and angle brackets "<>" denote
an expression is inserted. These syntax elements are present only for clarification of the format
and are not inserted as part of the actual source program. All other characters are significant and
must be used when required.)
12-4 EZ-COURSEWARE
Assembler Manual
The bit manipulation instruction operands are separated by spaces in this case since the HC11
allows bit manipulation instructions on indexed addresses. Thus a ',X' or ',Y' may be added to the
final two formats above to form the indexed effective address calculation.
Details of the M68HC11 addressing modes may be found in Appendix B.The operand fields of
assembler directives are described in Chapter 4.
Expressions
An expression is a combination of symbols, constants, algebraic operators, and parentheses. The
expression is used to specify a value which is to be used as an operand.
Expressions may consist of symbols, constants, or the character '*' (denoting the current value of
the program counter) joined together by one of the operators: + - * / % & | ^ .
Operators
The operators are the same as in c:
+ add
- subtract
* multiply
/ divide
% remainder after division
& bitwise and
| bitwise or
^ bitwise exclusive or
Expressions are evaluated left to right and there is no provision for parenthesized expressions.
Arithmetic is carried out in signed two- complement integer precision (that's 16 bits on the IBM
PC).
EZ-COURSEWARE 12-5
Assembler Manual
Symbols
Each symbol is associated with a 16-bit integer value which is used in place of the symbol
during the expression evaluation. The asterisk (*) used in an expression as a symbol represents
the current value of the location counter (the first byte of a multi-byte instruction).
Constants
Constants represent quantities of data that do not vary in value during the execution of a
program. Constants may be presented to the assembler in one of five formats: decimal,
hexadecimal, binary, or octal, or ASCII. The programmer indicates the number format to the
assembler with the following prefixes:
$ HEX or trailing H
% BINARY or trailing B
@ OCTAL or trailing Q
' ASCII
Unprefixed constants are interpreted as decimal. The assembler converts all constants to binary
machine code and are displayed in the assembly listing as hex.
A decimal constant consists of a string of numeric digits. The value of a decimal constant must
fall in the range 0-65535, inclusive. The following example shows both valid and invalid
decimal constants:
A hexadecimal constant consists of a maximum of four characters from the set of digits (0-9) and
the upper case alphabetic letters (A-F), and is preceded by a dollar sign ($). Hexadecimal
constants must be in the range $0000 to $FFFF. The following example shows both valid and
invalid hexadecimal constants:
12-6 EZ-COURSEWARE
Assembler Manual
A binary constant consists of a maximum of 16 ones or zeros preceded by a percent sign (%).
The following example shows both valid and invalid binary constants:
An octal constant consists of a maximum of six numeric digits, excluding the digits 8 and 9,
preceded by a commercial at-sign (@). Octal constants must be in the ranges @0 to @177777.
The following example shows both valid and invalid octal constan ts:
A single ASCII character can be used as a constant in expressions. ASCII constants are preceded
by a single quote ('). Any character, including the single quote, can be used as a character
constant. The following example shows both valid and inval id character constants:
For the invalid case above the assembler will not indicate an error.Rather it will assemble the
first character and ignore the remainder.
Comment Field
The last field of an Assembler source statement is the comment field. This field is optional and is
only printed on the source listing for documentation purposes. The comment field is separated
from the operand field (or from the operation field if no operand is required) by at least one
whitespace character. The comment field can contain any printable ASCII characters.
Comments may also begin with a semicolon. When a semicolon is used the comment may begin
in any column.
Assembler Output
The Assembler output includes an optional listing of the source program and an object file which
is in the Motorola S Record format. Details of the S Record format may be found in Appendix
E.The Assembler will normally suppress the printing of the source listing. This condition, as
well as others, can be overridden via options supplied on the command line that invoked the
Assembler.
EZ-COURSEWARE 12-7
Assembler Manual
Each line of the listing contains a reference line number, the address and bytes assembled, and
the original source input line. If an input line causes more than 6 bytes to be output (e.g. a long
FCC directive), additional bytes (up to 64) are listed on succeeding lines with no address
preceding them.
The assembly listing may optionally contain a symbol table or a cross reference table of all
symbols appearing in the program. These are always printed at the end of the assembly listing if
either the symbol table or cross reference table options (Paragraph 4.8) are in effect. The symbol
table contains the name of each symbol, along with its defined value. The cross reference table
additionally contains the assembler-maintained source line number of every reference to every
symbol. The format of the cross reference table is shown in Appendix D.
Error Messages
Error diagnostic messages are placed in the listing file just before
the line containing the error. The format of the error line is:
Errors in pass one cause cancellation of pass two. Warning do not cause cancellation of pass two
but are indications of a possible problem. Error messages are meant to be self-explanatory. If
more than one file is being assembled, the file name precedes the error:
File_name,Line_number: Description of error
Some errors are classed as fatal and cause an immediate termination of the assembly. Generally
this happens when a temporary file cannot be created or is lost during assembly.
Assembler Directives
The Assembler directives are instructions to the Assembler, rather than instructions to be directly
translated into object code. This chapter describes the directives that are recognized by the
Assemblers. Detailed descriptions of each directive are arranged alphabetically. The notations
used in this chapter are: ( ) Parentheses denote an optional element.
< > The element names are printed in lower case and contained in angle brackets. All elements
outside of the angle brackets '<>' must be specified as-is. For example, the syntactical element
(<number>,) requires the comma to be specified if the optional element <number> is selected.
The following elements are used in the subsequent descriptions:
12-8 EZ-COURSEWARE
Assembler Manual
In the following descriptions of the various directives, the syntax, or format, of the directive is
given first. This will be followed with the directive's description.
The EQU directive assigns the value of the expression in the operand field to the label. The EQU
directive assigns a value other than the program counter to the label. The label cannot be
redefined anywhere else in the program. The expression cannot contain any forward references
or undefined symbols. Equates with forward references are flagged with Phasing Errors.
The FCB directive may have one or more operands separated by commas. The value of each
operand is truncated to eight bits, and is stored in a single byte of the object program. Multiple
operands are stored in successive bytes. The operand may be a numeric constant, a character
constant, a symbol, or an expression. If multiple operands are present, one or more of them can
be null (two adjacent commas), in which case a single byte of zero will be assigned for that
EZ-COURSEWARE 12-9
Assembler Manual
operand. An error will occur if the upper eight bits of the evaluated operands' values are not all
ones or all zeros.
The FCC directive is used to store ASCII strings into consecutive bytes of memory. The byte
storage begins at the current program counter. The label is assigned to the first byte in the string.
Any of the printable ASCII characters can be contained in the string. The string is specified
between two identical delimiters which can be any printable ASCII character. The first non-
blank character after the FCC directive is used as the delimiter.
Example:
The FDB directive may have one or more operands separated by commas. The 16-bit value
corresponding to each operand is stored into two consecutive bytes of the object program. The
storage begins at the current program counter. The label is assigned to the first 16-bit value.
Multiple operands are stored in successive bytes. The operand may be a numeric constant, a
character constant, a symbol, or an expression. If multiple operands are present, one or more of
them can be null (two adjacent commas), in which case two bytes of zeros will be assigned for
that operand.
The FILL directive causes the assembler to initialize an area of memory with a constant value.
The first expression signifies the one byte value to be placed in the memory and the second
expression indicates the total number of successive bytes to be initialized. The first expression
must evaluate to the range 0-255. Expressions cannot contain forward references or undefined
symbols.
12-10 EZ-COURSEWARE
Assembler Manual
The ORG directive changes the program counter to the value specified by the expression in the
operand field. Subsequent statements are assembled into memory locations starting with the new
program counter value. If no ORG directive is encountered in a source program, the program
counter is initialized to zero. Expressions cannot contain forward references or undefined
symbols.
The PAGE directive causes the Assembler to advance the paper to the top of the next page. If no
source listing is being produced, the PAGE directive will have no effect. The directive is not
printed on the source listing.
The RMB directive causes the location counter to be advanced by the value of the expression in
the operand field. This directive reserves a block of memory the length of which in bytes is equal
to the value of the expression. The block of memory reserved is not initialized to any given
value. The expression cannot contain any forward references or undefined symbols. This
directive is commonly used to reserve a scratchpad or table area for later use.
The ZMB directive causes the Assembler to allocate a block of bytes. Each byte is assigned the
initial value of zero. The number of bytes allocated is given by the expression in the operand
field. If the expression contains symbols that are either undefined or forward references, or if the
expression has a value of zero, an error will be generated.
APPENDIX A
Character Set
EZ-COURSEWARE 12-11
Assembler Manual
The character set recognized by the Assemblers is a subset of ASCII. The ASCII code is shown
in the following figure. The following characters are recognized by the Assembler:
1. The upper case letters A through Z and lower case letters a through z.
5. The special symbol characters: underscore (_), period (.),and dollar sign ($). Only the
underscore and period may be used as the first character of a symbol.
,X Indexed addressing
9. The character "*" to indicate comments. Comments may contain any printable characters from
the ASCII set.
10. The special symbol backslash "\" to indicate line continuation. When the assembler
encounters the line continuation character it fetches the next line and adds it to the end of the
first line. This continues until a line is seen which doesn't end with a backslash or until the
system maximum buffer size has been collected (typically greater or equal to 256).
12-12 EZ-COURSEWARE
Assembler Manual
APPENDIX B
Addressing Modes
Prebyte
The number of combinations of instructions and addressing modes for the 68HC11 is larger than
that possible to be encoded in an 8-bit word (256 combinations). To expand the opcode map,
certain opcodes ($18, $1A, and $CD) cause the processor to fetch the next address to find the
actual instruction. These opcodes are known as prebytes and are inserted automatically by the
assembler for those instructions that require it.l In general the instructions contained in the
alternate maps are those involving the Y register or addressing modes that involve the Y index
register. Thus the programmer make the tradeoff between the convenience of using the second
index register and the additional time and code space used by the prebyte.
EZ-COURSEWARE 12-13
Assembler Manual
Immediate Addressing
Immediate addressing refers to the use of one or more bytes of information that immediately
follow the operation code in memory. Immediate addressing is indicated by preceding the
operand field with the pound sign or number sign character (#). The expression following the #
will be assigned one byte of storage.
Relative Addressing
Relative addressing is used by branch instructions. Branches can only be executed within the
range -126 to +129 bytes relative to the first byte of the branch instruction. For this mode, the
programmer specifies the branch address expression and places it in the operand field. The actual
branch offset is calculated by the assembler and put into the second byte of the branch
instruction. The offset is the two's complement of the difference between the location of the byte
immediately following the branch instruction and the location of the destination of the branch.
Branches out of bounds are flagged as errors by the assembler.
Indexed Addressing
Indexed addressing is relative one of the index registers X or Y. The address is calculated at the
time of instruction execution by adding a one-byte displacement to the current contents of the X
register. The displacement immediately follows the operation code in memory. If the
displacement is zero, zero resides in the byte following the opcode. Since no sign extension is
performed on a one-byte displacement, the offset cannot be negative. Indexed addressing is
indicated by the characters ",X" following the expression in the operand field. The special case
of ",X", without a preceding expression, is treated as "0,X".
12-14 EZ-COURSEWARE
Assembler Manual
APPENDIX C
Directive Summary
A complete description of all directives appears in Chapter 3.
ASSEMBLY CONTROL
SYMBOL DEFINITION
EZ-COURSEWARE 12-15
Assembler Manual
APPENDIX D
Assembler Listing Format
The Assembler listing has the following format:
The LINE# is a 4 digit decimal number printed as a reference. This reference number is used in
the cross reference. The ADDR is the hex value of the address for the first byte of the object
code for this instruction.
The OBJECT CODE BYTES are the assembled object code of the source line in hex. If an
source line causes more than 6 bytes to be output (e.g. a long FCC directive), additional bytes
(up to 64) are listed on succeeding lines with no address preceding them.
The # CYCLES will only appear in the listing if the "c" option is in effect. It is enclosed in
brackets which helps distinguish it from the source listing. The SOURCE LINE is reprinted
exactly from the source program, including labels. The symbol table has the following format:
SYMBOL ADDR
The symbol is taken directly from the label field in the source program. The ADDR is the
hexadecimal address of the location referenced by the symbol.
The cross reference listing has the following format:
The SYMBOL and ADDR are the same as above. The * indicates the start of the line reference
numbers. The LOCs are the decimal line numbers of the assembler listing where the label occurs.
12-16 EZ-COURSEWARE
Monitor Commands
Monitor Commands
EZ-COURSEWARE 13-1
Monitor Commands
Loading programs
Executing programs
Viewing memory
Changing memory
Setting breakpoints
Single-Stepping through code.
To start using the Buffalo monitor directly (versus using higher-level tools that come with our
development board) we can send and receive data through the RS-232 port. The Buffalo Monitor
monitors this line and processes characters read from it. Follow the following steps to setup the
RS-232 port and access the Buffalo Monitor software.
1. Launch HyperTerminal from Windows (hypertrm.exe). This would typically be under the
Communications menu. If you don't have it installed, you may need to install it from your
Windows disk(s).
2. It will ask for a name for the new connection. Call it a name you'll remember as being a
direct RS-232 connection, such as "RS232Con". Note that the type of connection you'll
be setting up is not specific to the Buffalo monitor. It's simply an RS-232 connection.
3. In the "Connect To" window, choose "Direct to Comm 1" or whatever communication
port you're using.
4. For the communication options, choose 9600 baud, 8 data bits, no parity, 1 stop bit and
Hardware flow control.
5. As for advanced options, this can be hardware dependent. On my computer, I use the
FIFO buffers option, have the transmit buffer set to it's highest setting (16) and the
receive buffer not quite as high (14). This seems to work well.
6. Within the HyperTerminal window, hit <Enter>, and you should see a ">" prompt. Hit
<Enter> again and you should see a listing of Buffalo Monitor commands.
7. Choose "File -> Save As", and save your configuration so it's available next time.
13-2 EZ-COURSEWARE
Monitor Commands
EZ-COURSEWARE 13-3
Monitor Commands
The 68HC11 is the same microcontroller regardless of whether it has a Buffalo Monitor or not.
Therefore, for the Buffalo Monitor to work it must work within the design of this
microcontroller. For example, when a power-up reset occurs, the microcontroller will always
vector to the address defined for the Power-Up Reset interrupt. The Buffalo Monitor cannot
change this; it's how the 68HC11 is designed. For the Buffalo Monitor to take control of the
68HC11, it must either put code in this address location, or change this interrupt's vector address.
13-4 EZ-COURSEWARE
Monitor Commands
The first thing we need to figure out is how the Buffalo monitor uses the 68HC11 registers and
interrupt vectors to control the microcontroller. The Buffalo Montior is memory-mapped to
addresses E000 through FFC0 (all addresses in this write-up are in Hex). The Interrupt Vector
Table is mapped from FFC0 to FFFF, although FFC0 through FFD5 is reserved. By doing a
memory dump of this table:
EZ-COURSEWARE 13-5
Monitor Commands
All of the addresses are in the range from 0x01C4 to 0x01FD. Using the same memory dump
command to see this section of memory (plus a couple bytes beyond 0x00FD) using:
> md 1c4 1ff
Looking at this
output, we see that
the vector table
addresses jump to
an instruction 7E
(the
microcontroller
always executes
the byte at the
jump location so it
must be an
instruction). 7E is
a jump instruction,
so 7E E3 71 (the
bytes at the address 1C0) is a "Jump E371" instruction. The result of this is to perform a jump to
E371, not 01C4, the address in the vector table.
The reason this is done is because the Buffalo Monitor must control some of the interrupt
addresses (such as power-up) so it sets the addresses it needs to the appropriate code in the
Buffalo Monitor, and sends the rest to a section in RAM where we can edit the addresses to be
what we want. Because the Buffalo Montior is in ROM, we cannot change the desired Interrupt
Vector addresses directly.
If you try to modify the Interrupt Vector Table addresses, you won't be able to because the
device that contains the Buffalo Monitor and the Vector Table is in ROM. To set-up an ISR, you
need to change the address at the location the Vector Table specifies, accounting for the first
jump instruction. So, the memory from 00C4 to 00FF (00FD + 2 bytes for the jump address) is
used for the "RAM-based Vector table" and cannot be used in our code.
For example, the Real-Time Interrupt (RTI) jumps to 00EB, which then jumps to E371. You'll
notice that all these interrupts except for the power-up reset jump to E371. This is in the Buffalo
Monitor memory and is undoubtedly a "do nothing" routine that simply returns. If you want to
13-6 EZ-COURSEWARE
Monitor Commands
write your own interrupt handler for the RTI, you must put the address of your handler in place
of E371 in bytes 00EC and 00ED.
It's clear that the Buffalo Monitor makes some assumptions about how it can use the memory. To
make sure we don't "step on its toes" when running our programs we need to be aware of what
memory we can use, and what the Buffalo Monitor uses.
EZ-COURSEWARE 13-7
Monitor Commands
It's common for software to "break" in some manner that is hard to track down. One example is
when the software "hangs". When this happens, there's no feedback to give hints as to what the
software is doing.
One option is to sprinkle "printf's" (in our case, PutStrRs232) to give us some history, but this
changes the code and can cause the problem to go away or manifest itself differently. This is
precisely what happened when I was trying to debug such an error. Adding PutStrRs232's caused
the program to run, but without them, it just hung. Also, printf's can also be a slow process.
Instead, we can use the Buffalo Monitor to track program execution. A few key commands will
be needed. We need to be able to set a breakpoint, single step through code and observe
variables. We need to know the address of such things, so your compile option must have
generated a listing of some type (LST file) that gives this information. While debugging, you'll
be looking at this listing repeatedly to figure out where to set the next breakpoint, where you're at
in the execution, etc.
We launch the program using the "Go" command, with an address. This sets the program counter
to the address we specify and starts execution. To keep the program from continuing indefinitely,
we first must setup a breakpoint at a desired location. Find the desired location by looking at the
output LST file and finding the code that matches the C code where you want to break. Since
you don't know where the software is hanging, you may need to do this several times, putting
breakpoints in various placed, until you start to locate where the software is hanging.
Unfortunately, we don't have a way to intermix the C and assembly code, so this can be
cumbersome.
A breakpoint is set by typing "B <address>" at the Buffalo prompt. This sets a breakpoint at the
specified address. You can set up to 4 breakpoints. Once you've set 4 of them, you need to clear
some. All breakpoints can be cleared by typing "B -" at the prompt. Breakpoints use the
Software Interrupt (SWI instruction). Therefore, to use breakpoints our software cannot use any
SWIs.
Once we've "breakpointed" at the desired location, we can single step and watch what's
happening. This is done using the trace command "T". The trace command uses XIRQ and OC5
interrupts, so these must also be available. Note that the Buffalo monitor uses OC5 to generate
an XIRQ interrupt, so the output of OC5, Port A pin 3, must be tied to the XIRQ pin. This is
already done on the EVBU board.
By executing "T" repeatedly, you can single step through the code and see where the code is
going. However, the Main Timer is still running even when execution is stopped. Since the
68HC11 inhibits interrupts when one occurs, higher-priority interrupts shouldn't cause a
problem, but when you single step the interrupts are enabled for a short time.
Care must be taken when debugging software in this way.
13-8 EZ-COURSEWARE
6811 Commands by Subject
6811 Commands by Subject
EZ-COURSEWARE 14-1
6811 Commands by Subject
14-2 EZ-COURSEWARE
6811 Commands by Subject
Arithmetic Operations
Addressing Mode
[Cycles to complete]
Function Mnemonic REL IMM DIR EXT INDX INDY INH
Add Accumulators ABA - - - - - - 2
Add Accumulator B to X ABX - - - - - - 3
Add Accumulator B to Y ABY - - - - - - 4
Add with Carry to A ADCA - 2 3 4 4 5 -
Add with Carry to B ADCB - 2 3 4 4 5 -
Add Memory to A ADDA - 2 3 4 4 5 -
Add Memory to B ADDB - 2 3 4 4 5 -
Add Memory to D (16 Bit) ADDD - 4 5 6 6 7 -
Compare A to B CBA - - - - - - 2
Compare A to Memory CMPA - 2 3 4 4 5 -
Compare B to Memory CMPB - 2 3 4 4 5 -
Compare D to Memory (16 Bit) CPD - 5 6 7 7 7 -
Decimal Adjust A (for BCD) DAA - - - - - - 2
Decrement Memory Byte DEC - - - 6 6 7 -
Decrement Accumulator A DECA - - - - - - 2
Decrement Accumulator B DECB - - - - - - 2
Increment Memory Byte INC - - - 6 6 7 -
Increment Accumulator A INCA - - - - - - 2
Increment Accumulator B INCB - - - - - - 2
Twos Complement Memory Byte NEG - - - 6 6 7 -
Twos Complement Accumulator A NEGA - - - - - - 2
Twos Complement Accumulator B NEGB - - - - - - 2
Subtract with Carry from A SBCA - 2 3 4 4 5 -
Subtract with Carry from B SBCB - 2 3 4 4 5 -
Subtract Memory from A SUBA - 2 3 4 4 5 -
Subtract Memory from B SUBB - 2 3 4 4 5 -
Subtract Memory from D (16 Bit) SUBD - 4 5 6 6 7 -
Test for Zero or Minus TST - - - 6 6 7 -
Test for Zero or Minus A TSTA - - - - - - 2
Test for Zero or Minus B TSTB - - - - - - 2
Multiply (D = A x B) MUL - - - - - - 10
Fractional Divide [ X = (D/X) ;
FDIV - - - - - - 41
D = remainder ]
Integer Divide [ X = (D/X) ;
IDIV - - - - - - 41
D = remainder ]
EZ-COURSEWARE 14-3
6811 Commands by Subject
Logical Operations
Addressing Mode
[Cycles to complete]
Function Mnemonic REL IMM DIR EXT INDX INDY INH
AND A with Memory ANDA - 2 3 4 4 5 -
AND B with Memory ANDB - 2 3 4 4 5 -
Bits(s) Test A with Memory BITA - 2 3 4 4 5 -
Bits(s) Test B with Memory BITB - 2 3 4 4 5 -
Ones Complement Memory Byte COM - - - 6 6 7 -
Ones Complement A COMA - - - - - - 2
Ones Complement B COMB - - - - - - 2
OR A with Memory (Exclusive) EORA - 2 3 4 4 5 -
OR B with Memory (Exclusive) EORB - 2 3 4 4 5 -
OR A with Memory (Inclusive) ORAA - 2 3 4 4 5 -
OR B with Memory (Inclusive) ORAB - 2 3 4 4 5 -
14-4 EZ-COURSEWARE
6811 Commands by Subject
EZ-COURSEWARE 14-5
6811 Commands by Subject
14-6 EZ-COURSEWARE
6811 Commands by Subject
EZ-COURSEWARE 14-7
6811 Commands by Subject
14-8 EZ-COURSEWARE
6811 Commands by Subject
Interrupt Handling
Addressing Mode
[Cycles to complete]
Function Mnemonic REL IMM DIR EXT INDX INDY INH
Return from Interrupt RTI - - - - - - 12
Software Interrupt SWI - - - - - - 14
Wait for Interrupt WAI - - - - - - **
As mentioned in the M68HC11 E Series Technical Data Document, 12 cycles are used beginning with the
opcode fetch. A wait state is entered which remains in effect for an integer number of MPU E-Clock cycles
(n) until an interrupt is recognized. Finally, two additional cycles are used to fetch the appropriate interrupt
vector (14 + n total).
Miscellaneous Instructions
Addressing Mode
[Cycles to complete]
Function Mnemonic REL IMM DIR EXT INDX INDY INH
No Operation (2-cycle delay) NOP - - - - - - 2
Stop Clocks STOP - - - - - - 2
Test TEST - - - - - - **
**Infinity or until reset occurs.
EZ-COURSEWARE 14-9
6811 Commands by Subject
14-10 EZ-COURSEWARE
Appendix
A) References
B) Specfications For Liquid Crystal Display Module
C) LCD Driver
D) MC68HC711E9 Technical Summary
EZ-COURSEWARE A-1
Appendix
A) References
Using the MC8HC11 microcontroller: a guide to interfacing and programming the
M68HC11 microcontroller
Skroder, John C.
ISBN 0-13-120676-1
1997 by Prentice-Hall, Inc.
Simon & Schuster / A Viacom Company
Upper Saddle River, New Jersey 07458
________________________________
ISBN 0-02-330555-X
1997 by Macmillan Publishing Co, a division of Macmillan, Inc.
Macmillan Publishing Co.
866 Third Avenue, New York, NY 10022
________________________________
A-2 EZ-COURSEWARE
Appendix
Timing Characteristics
EZ-COURSEWARE A-3
Appendix
A-4 EZ-COURSEWARE
Appendix C
INSTRUCTION DESCRIPTION
Outline
To overcome the speed difference between the internal clock of KS0066U and the MPU clock, KS0066U
performs internal operations by storing control informations to IR or DR. The internal operation is determined
according to the signal from MPU, composed of read/write and data bus (Refer to Table 7).
Instructions can be divided largely into four groups:
1) KS0066U function set instructions (set display methods, set data length, etc.)
2) address set instructions to internal RAM
3) data transfer instructions with internal RAM
4) others
The address of the internal RAM is automatically increased or decreased by 1.
Contents
1) Clear Display
0 0 0 0 0 0 0 0 0 1
Clear all the display data by writing “20H” (space code) to all DDRAM address,
and set DDRAM address to “00H” into AC (address counter).
Return cursor to the original status, namely, bring the cursor to the left edge on the first line of the display.
Make the entry mode increment (I/D = “High”).
2) Return Home
0 0 0 0 0 0 0 0 1 -
* “- “: don’t care
Return Home is cursor return home instruction.
Set DDRAM address to “00H” into the address counter.
Return cursor to its original site and return display to its original status, if shifted.
Contents of DDRAM does not change.
KS0066U 16COM / 40SEG DRIVER & CONTROLLER FOR DOT MATRIX LCD
0 0 0 0 0 0 0 1 I/D SH
0 0 0 0 0 0 1 D C B
0 0 0 0 0 1 S/C R/L - -
Shifting of right/left cursor position or display without writing or reading of display data.
This instruction is used to correct or search display data.(Refer to Table 6)
During 2-line mode display, cursor moves to the 2nd line after the 40th digit of the 1st line.
Note that display shift is performed simultaneously in all the lines.
When displayed data is shifted repeatedly, each line is shifted individually.
When display shift is performed, the contents of the address counter are not changed.
6) Function Set
0 0 0 0 1 DL N F - -
1 0 D7 D6 D5 D4 D3 D2 D1 D0
1 1 D7 D6 D5 D4 D3 D2 D1 D0
39 µs
Entry Mode Assign cursor moving direction
0 0 0 0 0 0 0 1 I/D SH
Set and enable the shift of entire display.
39 µs
Set display(D), cursor(C),
Display ON/
0 0 0 0 0 0 1 D C B and blinking of cursor(B) on/off
OFF Control
control bit.
39 µs
Cursor or Set cursor moving and display
Display 0 0 0 0 0 1 S/C R/L - - shift control bit, and the direction,
Shift without changing of DDRAM data.
39 µs
Set CGRAM Set CGRAM address in address
0 0 0 1 AC5 AC4 AC3 AC2 AC1 AC0
Address counter.
43 µs
Write Data to Write data into internal RAM
1 0 D7 D6 D5 D4 D3 D2 D1 D0
RAM (DDRAM/CGRAM).
43 µs
Read Data Read data from internal RAM
1 1 D7 D6 D5 D4 D3 D2 D1 D0
from RAM (DDRAM/CGRAM).
RS
R/W
No
DB7 DATA Busy Busy Busy DATA
Instruction Busy Flag Check Busy Flag Check Busy Flag Check Instruction
RS
R/W
INITIALIZING BY INSTRUCTION
Power on
0 1-line mode
N
Function set 1 2-line mode
RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0
0 0 0 0 1 1 N F X X 0 display off
F
1 display on
0 display off
D
1 display on
Display ON/OFF Control
RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0
0 cursor off
0 0 0 0 0 0 1 D C B C
1 cursor on
0 blink off
Wait for more than 39 µs B
1 blink on
Display Clear
RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0
0 0 0 0 0 0 0 0 0 1
Power on
0 1-line mode
Function set N
1 2-line mode
RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0
0 0 0 0 1 0 X X X X
0 display off
0 0 0 0 1 0 X X X X F
1 display on
0 0 N F X X X X X X
Display Clear
RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0
0 0 0 0 0 0 X X X X
0 0 0 0 0 1 X X X X
Initialization end