USE IN LIFE SUPPORT DEVICES OR SYSTEMS MUST BE EXPRESSLY AUTHORIZED.
STMicroelectronics PRODUCTSARE NOT AUTHORIZED FOR USE AS CRITICAL COMPONENTS IN
LIFE SUPPORT DEVICES OR SYSTEMS WITHOUT THE EXPRESS WRITTEN APPROVAL OF
STMicroelectronics. As used herein:
1. Life support devices or systems are those
which (a) are intended for surgical implant into
the body, or (b) support or sustain life, and
whose failure to perform, when properlyused in
accordance with instructions for use provided
with the product, can be reasonably expected
to result in significant injury to the user.
1
2. A critical component is any component of a life
support device or system whose failure to
perform can reasonably be expected to cause
the failure of the life support device or system,
or to affect its safety or effectiveness.
This book is a technical guide for ST7 users and may be approached in differentways:
For students and anyone unfamiliar with microprocessors, but with some experience of logic
circuits; they should start by reading Chapters 1 through 3.
For trained engineers wanting to get specific knowledge about the ST7 and microcontroller
programming in C language; they may skip Chapters 1 through 3 and go straight to Chapter
4.
For designers already familiar with the ST7, needin g more details about C-language
programming and how to use the ST7 internal peripherals; the application descriptions in
Chapters 5 and 8 through 10 are of special interest for them.
1.2 ABOUT THE AUTHORS
Jean-Luc Gregoriades teaches automated systems and industrial computer science at the
ElectricalEngineering department of the University of Cergy-Pontoise, France.
Jean-Marc Delaplace is an electronics and software engineer at Gilson S.A., a laboratory automation instrument maker.
As a team, theyhave alreadywrittenbooks on the ST6 (published a t Dunod Editions)and the
ST9 (published by STMicroelectronics).
1.3 HOW IS THIS BOOK ORGANIZED?
This book contains the following chapters:
Chapter 1: Introduction.
Chapter 2: How does a typical microcontroller work internally and how to use it.
Chapter 3: Programming a microcontroller.
Chapter 4: Architecture of theST7 core.
Chapter 5: The peripherals.
Chapter 6: The STMicroelectronics programming tools.
Chapter 7:The Debugger and the PROMprogrammer througha pedagogic application using
a ST72251.
Chapter 8: The C language and the C c ompiler.
Chapter 9: Application of the ST72251: a carrier-current system for domestic remote control.
Chapter 10: Application of the ST72311: a sailing com puter.
12/317
1 - Introduction
Chapter 11: Conclusion.
Chapters 1, 2 and 3 are a refresher on the conceptof a microcontroller.Chapter 1 introduces
the concept, Chapter 2 addresses the hardware and C hapter 3 addresses the software aspects.
Chapters 4 through 7 describe the ST7 and its programming tools, taking only assembly language into account.
Chapter 8 discusses the C language and techniques forusing the C Compiler for the ST7 microcontroller, its strengths and also its limitations.
Chapters 9 and 10 describe application projects using the ST72251 and the ST72311 members of the ST7 family. They tell the story of the design of devices that, though they do work,
were not intended to be commercial products.
1.4 WHY A MICROCO NTROLLER?
The microcontroller is just another choice when one has to design an application, and it competes with other technologies, like wired logic, a microprocessor system, or a Programmable
Logic Device of which many types are available.
All these solutions tend to reduce the number of components, the area of printed circuit used,
the number of connections, while increasing the computing power and keeping the cost low.
13/317
1 - Introduction
Thefollowing table showsa comparison of these solutions.Each one isdiscussed below.
Solution typeAdvantagesDrawbacks
Wired logic
Programmable logic
Microprocessor
Microcontroller
Very high speed
Cheap
High speed
Able to handle complex digital signals
Powerful
Wide choice of models
Configurable in wide limits
Allows almost all popular programming
languages
Simple electronic circuits are possible
with few components
Allows the most popular programming
languages such as BASIC or C.
Only for simple circuits
Limited number processing
Programming languages are specific
and non-portable
May be expensive
Many components even for simple systems
Relatively expensive
Standard configurations rarely exactly
fit the application’s needs implying the
use of over-sized models
Special configurations available, but
only for large quantities.
Wired logic uses commercially available logic functions and sometimes linear chips. Though it
is simple, it is neither practical nor economical to consider this technology for building applications as complex as those that are usually needed today. It can only be considered for very
special subfunctions where high speed is required.
Programmable Logic Devices (PLD) arethemodernform of wired logic, and areoften usedfor
combinatory and sequential logic. The biggest models allow intensive numeric processing, but
only on integer numbers. They use programming languages that do not belong to the family of
computer languages commonly used today.
The last two technologies are the microprocessor and the microcontroller. In principle, both
areverymuchalikeandtheyarebothwellsuitedtoprogrammeddataprocessing.Themain
difference between them is the size of the application.
The microprocessor is a component that includes mainly the computing core, and perhaps the
logic closely related to it like the clock generator, the interrupt controller, etc. Many more chips
must be added to it in order to make a functional application, memory chips in particular. Actually, this solution is only used in computers, either general-purpose computers like PCs, or
built-in to complex applications like industrial robots. It allows the designer to tailor his circu it
exactly to his needs.
The microcontroller i s defined as a complete programmed system i n one chip. This means
that one chip i s sufficient to fulfil the need, or that onl y a few m ore chips are required to
14/317
1 - Introduction
achieve the required computational power. These external chips may simply be interface components, to adapt the electric signals to the input-output pins of the microcontroller, or additional memory or peripheral components if the buses are available externally on the pins of the
microcontroller.
In any case, these components require two different but equally important jobs for putting
them to work: electroniccircuit design, and programming.
Both of these need be done as easily, quickly and economically as possible. A thorough study
of both aspects will be the basis for selecting the m ost a ppropriate model from the wide range
of products available today. Here are a few considerations related to these aspects.
1.4.1 Electronic circuitry
Thisiswhere thedesigners trivestoreducetheexternalcomponent count,andtocarefullyselect each one to get the best value. In order to satisfy this requirement, the various chip manufacturers offer for each family a choice of variants, to allow the designer to select the one that
best fits h is needs in terms of input-outputs and auxiliary circuitry.
Roughly speaking, a microcontroller variant that is loaded with features will allow a simpler external circuitry, at the ex pense of an increase in the microcontroller cost. The ideal choice
would be the variant that has the exact peripherals required by the application, and no more.
To illustrate this, we shall take a simple ex ample. Let us consider an application that requires,
asaninput, anumerickeypad, and asan output,agalvanometertoprovideananalogdisplay.
The ideal c ombination would call for an Analog to Digital Converter for the input, and a programmable timer with Pulse Width Modulat ion capability for the o utput. This would lead to the
following very simple schematic:
15/317
1 - Introduction
+5v
Analog input
GND
Micro
controller
Push pull
output with
PWM signal
Current
generator
Analog display
Array of
resistors
R
R
R
R
R
R
Analog keyboard
Exampleof simplified circuitry thanksto a microcontroller
01-anal
Such peripherals are typically available in many families. T his example shows how two pe ripherals properly selected can drastically reduce the component count and thus the printed circuit
area. The solution shown may or may not fit the needs, but it is difficult to imagine a simpler
design.
16/317
1 - Introduction
1.4.2 Choice of microcontroller model
The selected model of microcontrollermust meet the requirements in terms of computational
power. It must be able tohandle the input-outputs,processthe data in the required amountof
time, and have enough memory to store both theprogram and thedata.
An application is made of both hardware and software. So, there is a trade-off between the
processing done by hardware and that done by software. Using dumb peripherals requires
more computational power from the core; using sophisticated peripherals relieves the core
from time-consuming calculationsand thus allows a less powerful core to be chosen.
Determining the com putational power is a difficult ma tter since there is no inter nationally recognized measurement unit that expresses the speed of a microprocessor or similar device.
Some benchmarks that compare several products in the same application are available from
various so urces, but they only give an idea of the relative capability o f one product versus another one.
Thus a certain margin must be considered, or there would be a risk that some time in the development process that one comes to the conclusion that the selected microcontroller is unsuitable for the application. This event would have serious consequences, as costly tools may
have been invested to develop the application,notto mentionthe delay inthe product availability with its commercial consequences.
Also,even ifa microcontroller issuited to the productas itis first commercialized, this product
mayundergochangesduring its commerciallife. As a general rule, changes are always additions, never removals. If the chosen microcontroller matches c urrent needs too closely in
terms of capability, there is a risk that it could prevent the product from evolving to meet future
needs. This could make the product become obsolete sooner than expected.
To summarize, it is difficult to tell in advance whether a m icrocont roller will fit an application.
Asaresult, itiscurrentpracticetoselectamodelwithexcesspowerinordertoguaranteesuccessful performance initially, and also to allow for product upd ates.
1.4.3 Choice of development tools
Once the needed power has been determined, one must investigate the development tools
availablefor theapplicableproducts.Thefirststep istocomparetheirprices;but thisisnot the
consideratio n that will determine the choice.
The real issue is how the tools will help writing the software, test it, and pinpo int its flaws. The
hourly cost of a software engineer, who spends more time on software development because
of the lack of efficiency of the tools, easily outweighs any savings that could have been made
when investing in them.
Developm ent tools include all that isneeded to write the program, either inasse mbly language
or in high level language, then translate it into machine language and load it into the program
17/317
1 - Introduction
memory of the application. The tools are able to test both the hardware and the software, and
analyze any malfunctioning in order to allow corrections to be made. This can be done using
only a Personal Computer, or external instruments connected to the computer, such as an
emulator, analyzer, PROM programmer, etc. depending on the developmentphase. The diagram below shows where each phase takes place:
Source text editor
Compiler
Assembly software tool
Linkage software tool
Simulation or emulation software tool
PC
These software tools
are specific to a
microcontroller family
Debugging using an emulator
Emulation tool
Simulation
Probe
Application
Typingof the programsourcetex t
PC-based development environment
01-proc
The microcontroller itself, and the related development tools are described in Chapters 2 and
3.
18/317
2 - How does a typical microcontroller work?
2 HOW DOES A TYPICAL MICROCONTROLLER WORK?
There is a wide range of microcontrollers available on the market. They differ in their computational power, their internal organization, the number of their inputs and outputs, the type of
peripherals they provide. However, a microcontroller is always a complete system on a chip
that i ncludes a core connected to some memory and surrounded by peripherals. A typical
block diagram of a microcontroller is the following:
peripherals
EEPROM
internal
RAM
internal
ROM
(EPROM)
multifonction
timer(s)
general purpose and
dedicated registers,
accumulators
arithmetic
and logic unit
core
analogto
digital
converter
communication with the outer world of the microcontroller
instructions decoder
program counter
serial
interface
watchdog
timer
internal buses
stack
parallel input / output
ports
interrupt
controller
reset
generator
clo ck
generator
xtal
Typical block diagram of a microcontroller
02-basic
The peripherals shown here are only the most common that one can find in a microcontroller.
Other peripherals, designed for special tasks or communication protocols, may be found as
well. Let us mention just a few:
I2Cserialinterface
Radio Data System decoder
Liquid Crystal Display interface, etc.
We shall gain an overview of the main blocks in the remainder of this chapter.
19/317
2 - How does a typical microcontroller work?
2.1 THE CENTRAL PROCESSING UNIT
What is the Central Processing Unit(CPU)?
It is made up of the core, and auxiliary blocks like the clock generator, the reset circuitry, etc.
The CPU of a microcontroller is the actual programmed logic circuitry that is the heart of the
application based around the microcontroller. It is where all computation and decision-making
takes place. The CPU acts on data received from the outside world through the peripherals;
this data isprocessed ina pre det ermined way to pro duce more data that will act o n the the outside world.
The CPU is the part of a microcontroller that corresponds to what is us ually called a microprocessor. A microprocessor contains only the computing logic; it must be surrounded with
devices like memory and input-output interfaces. A microcontroller bundles all these in a
single chip . For simple projects, this allows an a pplication to be built with just one chip plus a
few components.Thishas beenmade possible by progress inthe scaleof integration that allows powerful chips to be manufactured at a relatively low cost. This has opened up a new and
very wide application fie ld: bringing the capabilities of a computer to even the che apest appliances. For example, nowadays hom e audio systems incorporate a radio receiver, a C D
player, two cassette decks and an amplifier andspeakers; all controlled by a commoncontrol
panel with a large display that shows the FM frequency, or the CD track number and elapsed
time, etc. Here, a single microcontroller performs the overall control, displays the data, respondstothe keys thatare pressedbytheuser to select the requiredradiochannel, CD track,
etc.
The word data, that is so commonly used, must be unders tood here in the w idest sense.
Though we may first think of data as numbers, data are not only numbers; they may be a wide
range of objects like binary values (the state of an on/off switch), the voltage at a terminal (the
wiper of a potentiometer), a characterstring (a piece of text), and many other things. The fact
that data is thought of as numbers just comes from the fact that we are discussing machines
based on binary signals. Virtually all the data processors in the world only process binary
digits. Thesebinarydigits(bits) are always grouped inpacks of variable lengths thatare processed in parallel, thus multiplying the processor throughput by the number of these bits processed at the same time.
The first microprocessors, historically, were four-bit machines. There are still four-bit microcontrollers sold today for simple application s like telephone s, wa shing machines, and others
requiring little processing power.
In the sense that is given to this word today, a microprocessor is at least a 8-bit wide machine.
The market is shared between machines of several types, with their power increasing along
with the number of bits they can pro cess in parallel. The following table gives an overview of
the main classes of microprocessors today.
20/317
Table 1. Table of the main processor sizes
2 - How does a typical microcontroller work?
Data size
Relative
power
Common applications
4 bitsLowestWatches,calculators, TV remote control,washing machines.
8 bitsLowIndustrial productsand home computers inthe '80s; most
microcontrollers are also becoming available commercially such as
automotive injec tion calculators.
64 bitsHighestOnly in mainframes; microcontrollers of this size are just coming out
from the laboratories.
2.2 HOW THE CPU AND ITS PERIPHERAL S MAKE UP A SYSTEM
The CPU cannot work alone.It is the central piece of a system that includes the following components:
2.2.1 CPU
It computes and coordinates. It controls almost all the other components of the system, except
in some cases like interrupts or direct memory access where some peripherals take the initiative.
2.2.2 Memory
It stores both the program, that tells the CPU what to do, and the data, that is temporarily
stored by the CPU like intermediate computation results,and the global state of thesystem.
In computers, there is only one memory to store both. This memory is volatile, so that a
supplementary, high-capacity and non-volatile storage is required to hold the contents of the
me mory when the system is not p owered-on, in most cases a hard magnetic disk. The cost
perbitstoredofthememorybeing muchhigherthanthat ofthehard disk,thecapacity ofthe
memory is usually much lower than that of the disk. Only a fraction of the disk contents
resides in memory at any time.
In microprocessor-based systems, the memory is the only storage, and various types of
memory are used according to its use: read-only memory for the program, read-write
memory for the data, and/or non-volatile solid-state memory for those data that must be
preserved from one s ession to the next, the system being powered-off between two
sessions.
21/317
2 - How does a typical microcontroller work?
The microcontroller has thus to handle two different kinds of things related to memory: the program, made of numbers that encodes the programming language instructions, and the data,
that are what the calculations act on, and the result of these calculations. Although they are
both mere numbers, they have completely different functions. Also, the characteristics of the
storage are different: while the program must be kept unchanged throughout the life of the
product, the data continuously change. This calls for a non-volatile, read only memory in the
first case, and aread-write memory that mayor maynot be volatile in the second case.
The difference in roles of these two memories has led to two different approaches in the
memory architecture:
The first one, named «Von Neumann» after the name of its inventor, provides only one addressable space. The program and the data are only distinguished by the address they occupy in thisspace. The ST7 belongs to thiscategory:
0000h
Data
memory
space
017Fh
RAM
Memory
bus
E000h
FFE0h
FFFFh
(Not used)
Program
memory
space
ROM
Interrupt &
resetvectors
16
Core
ST72251 memory space
a Von Neumann architecture
02-vonne
22/317
2 - How does a typical microcontroller work?
The second one, named «Harvard», provides separate addressing spaces for the program
and data. No instruction can thus write anything into the program space, protecting the program from accidentalchanges and doubling the total addressing range. Examples of t his architecture are the ST6, the ST9,and the 8051:
000h
00h
Program
memory
space
Program
memory
bus
Data
memory
bus
Data
memory
space
8
RAM
FFh
ROM
(EPROM)
Interrupt &
reset vectors
12
FFFh
Core
ST6 memory spaces :
a Harvard architecture
02-harvd
2.2.3 Input-Outputs
Often called peripherals, these are the point of contact between the system and the reality that
surrounds it and that the system is supposed to interact with. As stated above, the data from
and to the outside world are often of the analog type, and must be translated back and forth so
that the system, that is fully numeric, can process them. The peripherals can be just inputoutput gates, for some data that are of the numeric type in the external world; or they can be
somewhat complicated, if the data is either analog, or numeric but conforming to some stringent timing pattern. All the translation job performed by the peripherals saves the equivalent
load to the CPU. So the total throughput of a system does not merely rely on the power of the
CPU, but also on the efficiency of the peripherals.
23/317
2 - How does a typical microcontroller work?
2.2.4 Interrupt C ontroller
This is a piece of logic circuitry that manages the implementation of the interrupt concept described later in this chapter. Interrupts are the most common means of altering the normal
course oftheprogram, whenanunexpectedevent(oranexpectedone but occurringatanunexpected time) occurs. It may be more or less complicated according to the features it provides.
Main
Interrupt #1
The main
program
is
interrupted
Non maskable or
authorized
interrupt #1
requested
Return
to the main
program
Interrupt #2
requested
but masked
The main
Interrupt #2
enabled
program
is
interrupted
Return
to the main
program
Flowchart of a program with interrupt sub-routines
02-inter
Interrupt #2
24/317
2 - How does a typical microcontroller work?
Features provided may include queueing of interrupt requests, handling requests according to
their priorities, or even modification of priorities to increase the chance that l ow-priority requests will be eventua lly processed in a context where there are numerous requests.
2.2.5 Bus
The bus is the set of connections that links all the components of the system and allows all the
data moves, and the distribution of the address and control signals.
2.2.6 Clock Generator
This is the basic c oordination circuitry that supplies a set of calibrated clock s ignals, at a precise frequency, that schedules all the data movement along the bus and the computations in
the CPU. In some models, the clock frequency can be chosen by software.
2.2.7 Reset Generator
This circuit detects when the system has just been powered up, and resets it in a known state
from which the program execution will start. The reset ensures that each time t he system
starts, everything occurs exactly the same way . This is a m ajor condition for the reproducibility
of the behaviour of the system.
2.3 CORE
The main components of the core are:
2.3.1 Arithmetic and Logic Unit (ALU)
This is where all the computations take place. Depending on the microcontroller used, the
ALU provides a different set of operations. Roughly speaking, the basic set of operations
available to all ALUs is the following:
Addition and addition with carry, to provide for multiple precision calculations
Subtraction and subtraction with carry
Increment anddecrement
Bitwise shift, leftward or righ tward, straight or circular (the outgoing bit in re-injected at the
other end of the data word)
Logical bitwise OR, AND and EXclusive-OR
Logical complement
Some provideadditional operations like:
Multiplication
Division
and more
25/317
2 - How does a typical microcontroller work?
The ALU is connected to a register that holds the state of the last calculation done, with bits indicating (among other things) whether the result was zero, negative, or overflowed the capacity of the ALU. It thus provides a means of testing the data and changing the program flow
accordingl y. This register is called the status re gister.
2.3.2 Program Counter
This register holds the address of the next instruction to execute. It is initialized by the reset
generator to a known value, called the entry point of the program. The first instruction of the
program must thus be found at that address in the program memory.
2.3.3 Instruction Decoder
This circuit takes the instruction fetched fromthe program memoryandtranslates theirnative
code intoitsmeaning, determiningtheactionsperformed by the core. The instructionsfall into
the following categories:
Data processinginstructions:they givethetypeof operationto perform (add, subtract,shift,
etc.) and the address of the operand to be processed.
Program flow control instructions: these instructions modify the value of the program
counter, so that the next instruction executed will not be the one that follows the current one
in program memory. They are called jump and call instructions. In particular , some of these
instructions perform their action only if one or more bits of the status register have certain
values, so as to jump only if, for example, the last calculation produced a zero value, or
continue in sequence otherwise. These instructions provide the means of translating the
branching boxes inan algorithm.
2.3.4 Stack Pointer
Thestack isa storage area that hastheparticularity that the data put intoit ina certain order,
can only be retrieved in the opposite order. It is the mechanism used to handle temporary program flow disruptions, where the main flow of the program is temporarily put aside and resumed later. This is done using a pair of special instructions. The first one, named CALL, first
stores the address of the next instruction to execute into the stack, before jumping to some
other place. The reciprocal instruction, named RETurn, retrieves this address from the stack
andjumps tothe correspondinglocation, t hus resuming the program execution.
These f eatures give the system the capability to e xecute a program that reads data or binary
states from external sources, performs computations, detects particular characteristics in the
data, and reacts a predefined way to this before sending new data out. Using the interrupt mehanism, external events can suspend current processing and allow the incoming data to be
processed and then resume the processing that was interrupted.
26/317
2 - How does a typical microcontroller work?
2.4 PERIPHERALS
Theperipherals are theplaceswhere thecore,that executescomputercode,isincontact with
the real world that is represented by electrical signals.
These signals may just be binary levels that change relatively infrequently, in which case it is
easy to process them using a program. They also may change quickly, too fast for the program to handle them without imparing the computing power of the core.
In other cases, the signal is a value that belongs to a continuous range. This type of signal is
called an analog value; by nature, it cannot be processed by the core, and must be converted
into binarydata.
Ananalog value may have several shapes, but it eventually falls into one of two categories:
The data is represented by the time interval between two pulses, or by the frequency of an
AC signal,or by thenumber of pulses of a pulse train. Allthese cases can appropriately be
handled by a programmabletimeror a UART, for example.
The data is represented by the voltage of an inputsignal, or thevalue of a resistor that can
easily be converted into a voltage. This kind of data is handled by the Analog to Digital
Converter.
These considerations justify the presence of specialized peripherals, that include the required
circuitry for processing the data, convert it, etc. so that it is easier to handle for the core. The
less work thecore has to do, the more it is available for other tasks. According to the properties of the signal, the peripheral designed to process it (we say “interface it”) may be anything
from very simpl e to very sop histic ated. We shall give here an idea of some of the m os t
common periphera ls of the ST7, starting with the simplest.
2.4.1 Parallel Input-Outputs
When the data goingtoor coming from the outside world ismadeofgroups of bits, andifthey
can remain stable for a relatively long amount of time (at the scale of an electronic device, that
may be less than one millisecond), parallel input-output po rts are the right choice. They only
consist of a set of gates or latches that allow for communications between the inside and the
outside at times that the program chooses. This is used for example to read input switches
andkeyboards, and to output signals that drive lamps, motors, etc.
The capabilities of these input-outputs vary greatly from pro duct to product. In some products,
they are unidirectional or bidirectional TTL levels, fixed by hardware. In otherproducts, they
include a latch that can capture the state of the inputs on the transition of an auxiliary strobe
input.
Some manufacturers, including STMicroelectronics, provide configurable input-output pins.
These pins can be set as either inputs, with or without a pull-up resistor, or as an output either
27/317
2 - How does a typical microcontroller work?
push-pull or open drain. Some outputs also allow for a higher current to directly drive relays,
LEDs or opto-isolators.
Inaddition, these pinscanalsobe usedat the sametime as theinput-output pinsofother peripherals like Timers, Serial to Parallel Interfaces, or as inputs to the interrupt circuitry or an
Analog to Digital Converter.
The configurability of these pins helps reduc e the numb er of components in the schematic diagram, and thus the size of the circuit board.
2.4.2 Analog to Digital Converter
The ADC is a way of converting an incoming voltage into a number. The ADC is calibrated so
that the relationship between the voltage and the number is well known, which allows the program to process a representative measurement of thesignal.
2.4.3 ProgrammableTimer
This is a complex block based on a counter that can be used in many ways, so that it can either count pulses, or measure the duration of pulses or frequencies, or produce precisely
timed output pulses. This peripheral is so flexible that it is virtually impossible to describe all its
possible applications. In addition, the presence of a programmable timer leads t he circuitdesigner to use it intensively, since it is the peripheral that provides the highest accuracy, when
taken as a measuring device. Thus, when the measurement of a physical parameter (like a
temperature,a level,a pressure,etc.)isneeded, instead ofdesigning asensorthat outputsan
analog voltage, it is easier and more accurate to design it to produce a square signal with a
frequency that reflects the parameter. Such signals are also easier to transport than voltages
that may suffer from electromagnetic interference.
2.4.4 Serial Peripheral Interface
This interface is based on a shift register that can perform serial to parallel conversion and
vice-versa. Ittransmitseightbitsata time,usingonlytwo orthreepins.This savespins on the
the c hip, and also simplifies multiplexing when connecting a number of microcontrollers together.
It can also be used to interface serial-access memory chips that provide non-volatile storage
at low cost.
2.4.5 Watchdog Timer
The watchdog timer is a supplementary timer that can be used to protect the system against
failureseitherduetothe program itself(e.g. whenacertaincase has not beenconsideredand
the program cannot process it correctly); or a power supply brownout or electromagnetic interference has disturbed the normal working of the microcontroller. In both cases, the program
may crash and the system that is built on it will no longer be stable. This can have conse-
28/317
2 - How does a typical microcontroller work?
quences in applications where the microcontroller must keep in control, like in automotive applications or in security systems.
Various solutions have been imagined to prevent such situations. The most popular is the
watchdog timer. Thisisatimerthatissetforacertain durationatpower up.Theprogrammust
reset it to its start value periodically; failing to do so, the timer will overflow and this event generatesa hardware reset. This restoresthe system to the state itwas at power up.
Tousethewatchdogtimerproperly, the program mustreset itattheappropriatetime,in a periodicmanner.To do this efficiently requiressome care.Aword of adviceisgiven onthis subject in a later chap ter.
2.5 THE INTERRUPT M ECHANISM AND HOW TO USE IT
A m icrocontroller i s a programmed computer that ex ecutes a single string of state ments
known as «the program». Therefore, it apparently cannot perform more than one task at a
time.
However, most if not all applicatio ns require a single microcontroller t o handle many things at
once. Usually, for cost-effectiveness and simplicity, the designer of a microcontroller-based
system tries to pack as many functions as possible in a single chip.
Theanswers to this problem arebased both on hardwareand on software. The hardware approach is called «interrupt handling» and the software approach is called «multitasking».
2.5.1 Interrupt handling
An interrupt, in computer terminology, is a mechanism that allows the currently executing program to be interrupted, as the name implies, when an external event occurs. The c omputer
then starts to execute a specially-written piece of code that is intended to process the incoming event. Once this processing i s finished, the main program resumes exactly where i t
was interrupted. Nothing else happens to this program except that its execution is delayedby
the time it took to process the interrupt-triggered code.
29/317
2 - How does a typical microcontroller work?
The effect of the interrupt is shown in th e followin g diagram:
An interrupt is requested
and authorized
The current instruction is executed, the PC is incremented
The PC and a small number of registers are sa ved, they are
automatically pushed onto the stack. The regist ers to be saved
are defined by hardwar e: accumulator, code condition registe r
etc.
Depending on the type of micro controller, the lower
priority or all the maskable interrupt sources are masked
Done
by
hardware
The PC is loaded with the interrupt vector address which
is a pointer to the address of the interrupt sub-routine
The sub-routine is executed and ends with
the 'return from interrupt' instruction
The masked interrupt sources are authorized
The PC and predefined registers are popped from stack
The next instruction of the interrupted
program is fetched and executed
Interrupt processing flowchart
Done
by hardware
30/317
02-flow
2 - How does a typical microcontroller work?
2.5.1.1 Hardware mechanism
The hardware mechanism is important to understand. It is different for each product,so what
we shall describe here pertains specifically to the ST7.
An interrupt request is a binary signal (a flag) generated by several external sources. Most peripherals of theST7 can produce interrupt requests, for example the I/O ports, the timers, the
SPI, t he I
2
C interface, and so on. The external cause of the interrupt request depends on the
type of the peripheral: the I/O ports may have some bits configured to generate an interrupt,
either on low-level, falling edge, rising edge, or both. The timer may request an interrupt on
timer overflow, external capture or output comparison. The SPI may request an interrupt on
endof transmission, etc.
2.5.1.2 Hardware sources of interrupt
Thehardwareinterruptsources are summarized in the diagram below.
Input pin
Internal source
eg : timer overflow
Status register
of the peripheral
Interrupt flag bit
Control register
of the peripheral
Interrupt enable bit
Externalsource
edge detect
circuit
Other maskable
interrupt sources
eg : parallel input port pin
Global interrupt enable bit
interrupt sources
Diagram of the interrupt mechanism
Control register
of the CP U
Interrupt trigger
to the core
Non maskable
02-mec
31/317
2 - How does a typical microcontroller work?
2.5.1.3 Global interrupt enable bit
The various sources of interrupt may be inhibited as a whole using the I bit in the condition
code register. W hen this bit is s et, no interrupts are generated. However, the interrupt requests are not forgotten; t hey will be processed as soon as the I bit is reset.
2.5.1.4 Software interruptinstruction
Inaddition tothehardware s ources,a special instruction, TRAP, produces the sameeffect as
anexternally-generatedinterruptrequest, but underprogram control. Strange as it mayseem
(interrupts are provided for handling unexpected events, or at least, events whose time of occurrence is not known), the TRAP instruc tion utilizes the whole interrupt mechanis m withi n the
regular execution of the main program.
The trap instruction triggers the interrupt processing regardless of the state of the I bit in the
condition code register.
Anexample of the use of the TRAP instructionis the real-time debugger. W henthe user sets
a breakpoint somewhere in the program, the debugger replaces the instruction at which the
execution must stop with a TRAP instruction. The interrupt thus generated is processed by
displaying on the screen the state of themicrocontroller at that precise time. However, this instruction may be used in other ways as well.
2.5.1.5 Saving thestate of the interrupted program
When an interrupt request triggers an interrupt, the first task of the core (after completing the
current instruction), is to sa ve its curre nt state so it will be ab le to restore it after the inte rrupt
processing is finished. This is done by pushing all the core registers on the stack. For example, in the ST7, the Program Counter, the X-register, the Accumulator and the Condition
CodeRegister.It should be noted thattheYregisteris notsaved,(thisisbecausetheST7 has
evolved fromanarchitecture thatdidnot have a Y register).If needed,theYregistershould be
pushedexplicitly on the stackat the beginning ofthe interruptservice routine.
To protect the interrupt service routine from being interrupted, the I bit of the Condition Code
Register is set automatically.
At this point, the interrupt service routine may execute whatever instructions the programmer
chooses to write. The s tatus of the interrupted program is known and can be restored when
needed.
2.5.1.6 Interrupt vectorization
When the coredecidesto grant an interruptrequest, itmustknow the addressof thecode t hat
must be executed in such an event. This is the purpose of the interrupt vectors.
The interrupt vectors are a table of 16-bit words in program memory thatcontain the address
of the beginning of the various interrupt service routines.
32/317
2 - How does a typical microcontroller work?
Depending on thesource of the interrupt (I/O, timer, etc.),the core fetches, from a predefined
location in memory, the address of the interrupt service routine especially written to process
that event. The vectors are always located at the end of the addressing space. When the microcontroller is reset, these interrupt vectors are fetched together with the reset vector for getting the start address of the main program.
The following table shows the interrupt vectors:
Memory
address
FFE0
not used
Lower priority
FFE4
FFE6
FFEE
FFF0
FFF2
FFF4
FFF6
FFF8
FFFA
I²C
Bus Interface
not used
Timer B
not used
Timer A
Serial Peripheral
Interface
not used
Ports B and C
Port A
FFFC
FFFE
TRAP
Software Interrupt
Reset vector
Interrupt vector table of the ST72251
02-tabv
Higher priority
33/317
2 - How does a typical microcontroller work?
2.5.1.7 Interrupt service routine
When the processor has granted an interrupt request, and read the interrupt vector, it starts
executing the interrupt service routine. This routine is merely a segment of program, written
with exactly the same ease and constraints as the main program. It may be written using the
same languageand tools, orin anyother language.
Theinterruptserviceroutineissupposedtotake appropriate actionaccording to the source of
the interrupt. For example, if an input bit has changed its state, the service routine may change
the state of an output bit; if the interrupt was generated by the timer, this may produce the
transmission of a byte by the SPI, etc. according to the structure of the application as defined
by the programmer.
Eventually, the service routine is finished. Then the core may return to the main program. This
is done by executing the IRET instruction.
2.5.1.8 Interrupt Return instruction
As described above, an interrupt service routine looks a little bit like a subroutine. Like in a
subroutine, the return address is stored in the stack, and the execution of the RET instruction
returns to the calling program.
However, some more things have to be done before returning to the interrupted program. All
the core registers were pushed on the stack w hen the the interrupt request was granted (except the Y register). They must now be restored, so that the execution of the service routine
will not leave any trace in th e core. This is the r ole of the IRET inst ruction in th e ST7.
The IRET instruction proceeds by popping all the data off the stack that had previously been
pushed, namely the Condition Code register (at this point the I bit is also restored), the Accumulator, the X register and the Program Counter.
From this time on, execution of the interrupted program resumes.
2.5.2 Software precautions related to interrupt service routines
As described above, the interrupt mechanism is fairly simple to use, since it only consists of
setting the interrupt vectors to the address of the corresponding service routines, and writing
a piece of code that must end with a IRET instruction.
Actually, an interrupt service routine may do anything in the system, since it uses the regular
instruction set of the core and has access to the whole memory. It may thus affect the state of
the main program, even though the core registers have been preserved. The following paragraphs deal with the precautions to take when using interrupts.
2.5.2.1 Saving the Y register
(This point is s pecific to the S T7.) If the s ervice routine uses the Y register, one must remember that this register is not saved automatically by the interrupt granting mechanism .
34/317
2 - How does a typical microcontroller work?
Thus it is up to the programmer to s ave it, by pushing it to the stack at the beginning of t he
service routine, and popping it before executing the IRET statement.
2.5.2.2 Managing the stack
This is just a reminder, since it applies anywhere in the program. The s ervice routine must
tracktheusageit makesofthe stack, so asto pop at the end asmanybytes as it had pushed
at the beginning. This may look trivial, but if some pushes occur in some conditions and not
others (i .e. the service routine has conditional statem ents somewhere), the popping mus t
occur in exactly the reverse way, taking into account the same conditions as those that produced the pushing. Thismay not be very obvious to code.
2.5.2.3 Resetting the hardware interrupt request flags
In some peripherals, the hardware flag that produced the i nterrupt request i s automatically
cleared on servicing the interrupt. In thiscase,no special care need be taken.
On the contrary, in some other peripherals (such as the timer), the interrupt request flag keeps
its state after the interrupt is granted. This flag must be cleared anywhere in the interrupt
service routine, but necessarily before the I bit of the Condition Code Register is cleared (on
execution of the IRET instruction). O therwise, the interrupt service routine would be called
again immediately after executing the IRET instruction, and the core would loop indefinitely
through thisinterrupt serviceroutine,thus blocking the main program.
How to reset the interrupt request flag is described as part of the description of each peripheral.
2.5.2.4 Making an interrupt service routine interruptible
Oninterruptgranting,theIbitofthe ConditionCode Registerisset, to preventtheservice routine being interrupted by incoming interrupt requests. Further interrupt requests will then suffer
from a delay before they are serviced. This delay is called «interrupt latency». Actually this
termincludesthereactiontimeofthecoreitself,towhichthetimefortheservicinginprogress
must be added.
However, there are cases where it is necessary to allow an interrupt service routine to be itself
interrupted. This is the case if a service routine performs processing that takes a certain
amount of time, and another interrupt source requires that its request be processed immediately, i.e. the permitted latency is short.
The solution is then to allow the slow service routine to be interrupted. This may be done by resetting the I bit of the Condition Code Register. This must be done after the hardware interrupt
request flag that triggered the interrupt currently in progress is cleared, for the same reason as
explained above. Please note, however, that this must only be done when necessary, since
the size of the stack is often limited in small microcontrollers.
35/317
2 - How does a typical microcontroller work?
2.5.2.5 Data desynchronization and atomicity
This paragraph addresses the precautions that must be taken, in the main program or any
service routine that may be interrupted.
In many cases, data is organized in blocks in memory, that is, several bytes, successive or
not, make up a piece of data. Some coherence rules must be followed when using these data.
Failure toobserve theserules may produce unexpected results and,very likely,anapplication
crash.
When no interrupts are used, the main program can easily follow these rules by taking care to
perform all datachangesin the appropriateorder andrespecting the predefined relationships
between each of the bytes that constitute a piece of data.
When interrupts are used, respecting the coherence rules may become more complex. Actually, an interrupt is an asynchronous action that can occur at any time. Let us assume that the
main program is currently altering one piece of data that is made of several bytes. It first writes
some bytes, then more bytes until it is finished with a new data in memory.
If an interrupt occurs in the middle of the process of altering the data, the following risk may
appear. If the interrupt service routine uses the data that the main program i s writing, the
service routine may get data that fail to follow the coherence rules, since not all bytes have
been updated yet. The service routine may then be misled by an incorrect value that it cannot
handle properly, or just interpret that data differently from what it was expected to mean if it
hadbeenfully modified.This mayhave very serious consequences on theworking of theapplication. This circumstance is called «data desynchronization».
To avoid this, some precautions may be taken in cases where interrupt service routine may
find incoherent data. They al l ensure that all the data will be updated at once, and never used
unless completely updated. This condition is c alled «atomicity», from a Greek root meaning
«that cannot be cut». To properly handle multi-byte variables that are shared by a main program and an interrupt service routine, or by two interrupt service routines of which one may interrupt the other, thehandling mustbe made “atomic”.
36/317
2 - How does a typical microcontroller work?
The following example sho w s:
Whathappens when the data are desynchronized.
Let us assume the main program wants to increment the word variable
page zero), that currently contains
; word variable reg contains 42FF hex
; increment word variable reg by 1
inc reg+1; add 1 to the low byte; low
jrne endinc; increment high byte if carry
endinc : ...; here the program continues
; both bytes are incremented. reg = 4300 hex
42FF hex. The following code will be u sed:
byte is incremented. reg = 4200
hex
reg (16-bit register in
If an interrupt service routines uses the value of reg, and if the interruptrequest occurs for example at the f i rst line of the code above, the interrupt service routine will see that
reg is 4200
while it is actually either 42FF or 4300. This error may have serious consequences.
How to make the handling atomic.
Toavoidthis situation,itis sufficient to maskoutall theinterrupts,by changingthe codeasfollows:
; increment word variable X by 1
sim; prevent interrupts from
occurring
inc reg+1; add 1 to the low byte
jrne endinc; increment high byte if carry
endincrim; allow interrupts to occur
...; here the program continues
; both bytes are incremented. reg = 4300 hex, now the interrupt can be
performed
All interrupt requests that occur between the SIM and the RIM instructions are delayed for the
durationofthatpiece of code.Ifthiswould causeanexcessivelatencyforoneparticularinterrupt that does not use that data,it ispossible to mask out the specificinterruptsource whose
service routine ac tually use s this value.
This example mentions the case where the data is written by the main program, and read by
theinterruptserviceroutine.Actually,thereversecaseisalsoasourceofproblem:ifthemain
program reads the data, and the interrupt service routine writes it, the main program may start
37/317
2 - How does a typical microcontroller work?
reading the first bytes of the data, then the interrupt occurs; on return, the remainder of the
data are read, but unfortunately there may not be coherence between the first byte that was
read before the interrupt and those read after it.
2.5.3 Conclusion: the benefits of interrupts
The interrupt system is a very appropriate means of processing events that have the following
features:
Theyare triggeredbyahardwaresignalcoming fromoutside.Thesessignalsareconnected
to appropriate pins of the microcontroller; or they are the result of the working of internal
peripherals that reach a certain condition, for example the internal timer has overflowed.
Though the timer is built-in the same chip as the core, it is functionally considered external
to the core.
They occur at their own time, and thus unexpectedly for the main program.
Theyrequireaquickreactionfromthe core, eitherbecausetheyoccurfrequentlyorbecause
thestatusoftheexternaldevicethat requests the interrupt wouldnotkeep its meaning after
toolongadelay.
They do not require complex processing; typically, they require reading some data from
outside and storing it to memory, or transferring data from the memory to the external
circuitry.
38/317
2 - How does a typical microcontroller work?
2.6 AN APPLICATION USING INTERRUPTS: A MULT ITASKING KERNEL
The conclusion in the previous paragraph states that interrupts are well-suited for a c ertain
class of events to be processed. However, there are other cases outside this category. Some
of them are better addressed by the concept of multitasking.
In many applications, several processings are required that do not match the specificity of the
interrupt-driven processes. For example:
Two or more processes are continuously active, thateach take long processingtimes.
These processes are not (or notdirectly) started by externalevents.
They do not require a quick reaction time.
In such cases, the interrupt concept is obviously inappropriate. Actually, these processes
seem to require each a core of their own. However, considerations of cost may not allow for
multiple microcontrollers on the same board. Theconceptofmultitasking is the answer to this
requirement. It is a software solution that does not require extra components, and makes the
system believe the various tasks run on different cores, although it is simply the s ame core
that is shared between all the tasks at the expense of the computing power that is shared between this tasks, plus a cer tain waste produced by the specific mechanisms that provide for
the multitasking. This waste limits the frequency at which the tasks can be switched; if they are
switched too often, the proportion of the time taken to switch tasks becomes too large, and the
corresponding part of the microcontroller computing power is lost. The designer must check
whether the power remaining for each task is sufficient or not; if not, the type of microcontroller
is probably unsuitable for the project.
There are two kinds of multitasking, namely pre-emptive multitasking and non pre-emptive
multitaskin g. The second kind is also called cooperative multitasking.
2.6.1 Pre-emptive multitasking
Pre-emptive means that the computing power that is allocated to a task is withdrawn from i t
without notice, that is, that particular task is stopped at an unexpected place by brute force.
Then, the power is allocated to another task, until it is stopped in turn, and so on for all the
tasks;then,the first taskthatiscurrentlysleeping regainscontrol and continuesforsometime.
The task switching is do ne under control of an interrupt triggered by a timer. This allo ws the
core time to be partitioned at will between the various tasks. The time for which each task is allowed to run may be the sam e for all tasks; or it may b e decided to allow mo re time for some
more important (or time-consuming) tasks, and less for others. In a word, the multitasking
kernel may fine-tune the resource sharing between the tasks.
The main drawback of this system is that since the tasks are interrupted at any place in the
code,manyprecautionsmust be takento ensure the coherence ofthedata, just as explained
above about interrupts. In fact, if a task starts to write a piece of data and is put asleep in the
39/317
2 - How does a typical microcontroller work?
process of updating the data, and another task uses that data, there is a risk of desynchronization. The same typeof precautions must be taken to ensureatomicity of data updates.The
same problem may also occur if more than one task handles control sequences for an external
device. If this external device needs a precise control sequence that must be completed before a new sequence is started, there is a risk that a task may lose control before the sequence
is complete and control may be transferred to a task that attempts to use the same device. The
attempt may then fail or interfere with the unfinished sequence of the previous task. Here
again, a protection mechanism isrequired.
In summary, the advantage of pre-emptive multitasking is that task switching is done automatically and independently from the code of each task; the relative power attributed to each task
maybeadjustedtofittherequirementsofeachtask.
Thedrawback is the opposite of the advantage: since the taskswitching happensat any time
and any place in the code, the programmer must locate the critical areas of code where special protection mechanisms must be included. This may be more difficult than it might appear,
for it is no t always easy to find all the possible collisions and keep them from happening.
Fourth task
First task
Time
An allotted time
is assigned
to each task
Third task
Preemptive multitasking
02-preem
Second task
40/317
2 - How does a typical microcontroller work?
2.6.2 Cooperative multitasking
Cooperative multitasking drawsitsname fromthe factthat task switching is not spontaneous.
It only occurs when the task-switching function is called by the currently active task. This implies two facts:
Task switching occurs only when the code decides it. As a consequence, it is easy to avoid
data desynchronization and access collisions by placing the task switching calls at the
proper places.
The partitioning of the core time between tasks cannot be set at will, since it is not possible
either to insert into the code as many calls to the switching function as necessary or to put
them at the right placesto control the time intervalsallocated to that task.
The reader can easily see that the strong and the weak points of one type of multitasking are
the opposite to those of the other system. This explains why both are used, the type being
chosen to best match the application's requirements. In addition to theses features it is fair to
say that cooperative multitaskingiseasier to implementandless resource-consumingthan its
competitor.
Task 1
Task 2
Next task
(Yield)
Next task
(Yield)
Cooperative multitasking ; simplified example
Task 3
Next task
(Yield)
02-coop
41/317
2 - How does a typical microcontroller work?
2.6.3 Multitasking kernels
2.6.3.1 Advantages of programming with a multitasking kernel
The multitasking kernel is the piece of code that controls the multitasking. The way it does it,
and the flexibility it offers may vary greatly from one kernel to the othe r. It is generally supplied
ready made, and the programmer has to give his program the appropriate architecture to get
the benefits of it.
Writing an application with multitasking in mind is easy and leads to a clear, organized structure. The work to do is divided in tasks, and these tasks are written separately as procedures.
They e xchange data using either commun ica tion mec hanism s b ui lt-in to the kerne l, or
common data in memory, taking care to avoid collisions. The main difficulty is to identify what
atask actuallyis.Forexample,twoprocessings thatare always performedoneaftertheother,
and always in the same order, constitute a single task. On the contrary, two processings that
either may or must be performed at the same time are two separate tasks.
The features of a kernel v ary from product to product. One must first know which kernel is
being used, the type of multitasking (pre-emptive or cooperative), and the services provided
by the kernel. Some of these are discussed below.
2.6.3.2 The task declaration and allocation
The kernel must be aware of the existence of the tasks, thei r number and their start addresses. Some kernels expect this to be stated at compile time; in this case, the number of
tasks is known from the beginning of program execution and cannot change afterwards.
Some others allow tasks to be added (or created) while the program is running. This allows
tasks to be created when the need shows up, for example to process an incoming event and
then terminate. In this case , it is convenient to also have the ability to remove or kill the task.
Again, there are two op tions: a task may terminate when it decides to do so (kill itself or “suicide”); or it may be killed by any task, including itself.
2.6.3.3 Task sleeping and waking-up
A task may be alive but have nothing to do; in this case, to save computing power, it is wise to
completely stop allocating core time to it. The task is then asleep. This can be done by calling
a function often called Sleep, passing to it the identification of the task to be put asleep. A task
can put itself aslee p if it is waiting for some event.
Obviously, it is necessary to have a means of waking-up a sleeping task. This cannot of
course bedone by thesleeping taskitself, andcanonly be done eitherby othertasksor by an
interrupt service routine. For example, let us consider a task that processes the keystrokes
generated by a keypad. The hardware of the keypad may generate an interrupt when a key is
pressed. This interrupt may wake-up the k eypad task that reads the keycode and takes the
appropriate action. When this is done, the task may go asleep again. One might ask why it is
42/317
2 - How does a typical microcontroller work?
not simpler to perform the processing right in the interrupt service routine, instead of this apparent complexity. Actually, t he processing of the keystroke can take a long time, too long to
allow it to freez e th e remainder o f the application as happens when an in terrupt is being serviced.
Other s ervices may be supplied by the multitasking kernel, coping with priorities, intertask
communication, etc.
2.6.3.4 Multitasking kerneloverhead
The purpose of a multitasking kernel is to share the power of a single processor or core between several tasks. Obviously this sharing means less power for each task, except perhaps
ifall tasks but one are asleep.However, even inthatcase, the taskdoesnot benefit from the
whole computing power,since some of the core power is drawn off by the kernel itself. In addition, it is equally obvious thatthekernelis a piece ofcode thatoccupies a certainamount of
program memory as well as data memory. But overall, the main concern with memory requirements relates to the stack.
The stack is the place where the state of a program i s c ontinuously s tored. This amount of
data is often referred to as the “context”. Each task has its own context, which consists of all
the return addresses of all nested procedures and functions; most c ompilers also store the
function argumentsandlocal data in the stack. This can addup to a large amountofmemory,
not to mention that some free space must remain in the stack to handle interrupts that may
themselvesconsume a certain amountof s tack, in the same way as themainprogram.
This implies generally that the stack space must be very large, since the amount of data mentioned above must be multiplied by the number of tasks alive at the same time.
The ST7, being a small 8-bit core, provides for at most 256 bytes of stack. This allows fora
multitaskin g kernel with a limited num ber of tasks and services.
43/317
2 - How does a typical microcontroller work?
Common parts
of theprogram
Code of the
firsttask
Stack
pointer
Stack area
for task #1
1
Code of the
secondtask
Codeof the
last task
Interruptvector
table
Program memory
2
3
4
Selection of the task
1
the last data of the task to activate thatis stored
in the stack.
Activation of the task
2
the stack restores the tasksas it was before being
unselected.
Deselectionof thecurrent task
3
gramis saved in the stackbefore it is deselected.
: The stack pointer points to
: The poppingof the data off
Stack area
for task #2
Stack area
for the last task
Stack RAM
: The state of the pro-
44/317
Selection of the following task
4
pointsto the last data savedfromthe next tasks
to activate.
: The stack pointer
Working mechanism of a simplified multitasking kernel
02-task
3 - Programming a microcontroller
3 PROGRAMMING A MICROCONTROLLER
A microcontroller is basically a programmable component. This means that it can do almost
anything, when properly programmed.
Infact, the design of theelectricalschematic of a microcontroller-based application raises few
questions; the input and output pins of the microcontroller are simply connected to the binary
signals either produced or used by the external application. The designer only has to take care
to select the right pins, since some signals must be connected to special peripherals like the
Analog to Digital C onverter, the Timer, etc.
It is the program that configures the pins so that they have the correct electrical behaviour, and
that processes the data to produce the appropriate response to the input signals. Since the
board will be designed with as little electronic processing as possible, all the processing is
done by software.
This produces the flexibility that is the main feature of any programmed sy stem: unless ahardware problem arises, most of the fixes and c hanges done to a programmed system w ill be
done in software.
Programming the processor is thus the key activity of the designer, the one that will take the
largest part of his time. For this reason, the use of the right tool to program the application is
critical, since program design and testing time can vary greatly according to the to ols and the
language chosen.
This chapter addresses the two main issues the programmer faces: selecting the appropriate
language for the best productivity, then selecting the appropriate software tools that will allow
not only to program in that language, but also to test the program written in that language. We
will learn that an investment made prior to starting the design ca n prove very efficient in terms
of development time, and therefore, pay for itself.
3.1 ASSEMBLY LANGUAGE
3.1.1 When to use assembly language
Assembly language is the native language of each microprocessor. It used to be the only way
of progra mming a small microcontroller until high-level language compilers were made available. Programming in assembler was a job that required a lot of care and very many lines of
source code relative to the size of the application. It was justified when program memory was
small and assembly language was the only way to optimize the code size. Nowadays, microcontrollers, except for those at t he lowest-end, can afford enough memory to cope with the
code expansionfactor inherent in high-levellanguages. Thus,for reasonsexplained inthefollowing paragraph, a high-level language is strongly recommended and using assembly language should not be considered except when absolutely needed.
45/317
3 - Programming a microcontroller
Thereare,in almost allapplications,partsofthecodethat stillrequireassemblyprogramming.
These parts are, most of the time, small but have an important impact on the program. Here
area fewsuch cases:
The initi alization part of the program. All high-level languages provide for initialization o f the
coreandthememory.However,thebasic organisation of the memory(address of the R OM
and the RAM, reset and interrupt vectors ) and a few other kinds of initialization are supplied
as an assembly-language template, that has to be adaptedto suitthe actualapplication.
Someinterruptservice routines thatrequire very fast processing.
Some repetitive functions that are frequently invoked and whose optimization in terms of
speed has an important impact on the performance of the whole program.
The third case implies that the programmercarefully reads the implementation chapter of his
compiler's manual. The way arguments and return values are passed back and forth are specific to each compiler. Failure to comply with these conventions will prevent the assembly
code from working.
3.1.2 Development process in assembly language
Thedevelopment ofa program consistsofthreemainphases:analyzing,writing the code,debugging. In other words, the successive phases can be described as follows:
The first phase is when the programmer defines what the program should do. This is only
paperwork, evenifitis doneusing acomputerand awordprocessoror a spreadsheet. This
phase defines the main program blocks, the data inputs and outputs, the storage, and some
of the algorithms.
The second phase is the translation of the first one into the chosen computer language. The
result of it is the source code and a few files that drive the various programming tools. The
tools used in this phase are the text editor, to type and amend the source code, and the
assembler and the linker to check its syntactic correctness. The Make utility is also a
convenient tool, that helps keeping the program up-to-date, when any of its parts have been
changed,by processing onlythe changed s ource files.
The third phase consists of all that is needed to make the source code w ork. It involves
removing all programming errors, that is, the flaws in the first and second phases related to
logic, coordination, and data management. This third phase is by far the most difficult and
requires the mostdevelopment time. The tools used, the Simulator andIn-Circuit Emulator,
haveto be very powerful because many errors are difficult to find.
When the program is fully functional, it is often stored in an EPROM that is either external, or
asin theST7,internalto the microcontroller. Thisproduces a prototype ofthe microcontroller
that must be extensively tested before being launched to production, especially if, for large
46/317
3 - Programming a microcontroller
quantity production, the microcontroller includes a masked ROM programmed by the device
manufacturer and that cannot be altered afterwards.
3.1.2.1 Assembly language
Assembly language is merely a set of mnemonics that duplicates each instruction in a more
legible way, to help writing the programs. Machine language is just a series of numbers that
obeys a certain code to indicate to the core which instruction to execute and which data to use.
Assembly language provides acronyms that are easier to remember. The following example
shows an excerpt from an assembly lis ting. The first two columns show numeric data, which
represent the addresses of theinstructions and the machine-language code. The Source line
column shows the machine code in mnemonic language. It is obvious that, provided one has
learned that
ld means the instruction Load, and that, of the two operands of this instruction,
the destination operand comes first, it is easy to understand the first lines of source c ode as
documented in the commentcolumn:
LocObj. codeSource lineComment
------ --------------------------------000000 A6FFld A, #$FF; load accumulator with immediate
data FF (hex)
000002 AE64ld X, #100; load X register with value 100
000004 F7loop: ld (X), A; load location pointed to by X
with contents of A
000005 5Adec X; decrement X register
000006 26FCjrne loop; jump to label loop if X not equal
to zero
This short program is a loop that fills memory ad dresses 10 0 to 1 (de cimal) inclusive with the
value FF hex.
Programming in assemb ly language involves using a text ed itor to write a text file that ob eys
the syntax and conventions of the specific assembler that is to be used. It should be noted that
assembly languageis not standardized in any w ay, for two reasons:
The instruction set changes from one processor to another
For a specific processor or microcontroller, software tool sets from different suppliers e ach
have their own syntax, although two source files written for two different tool sets may seem
veryclose.
Thus, to write an assemblylanguage source file,theprogrammer must first know which processor or microcontroller will be cho sen for his project, then which software tool set he will use .
Then, he has to learn both the characteristics of the processor's instruction set (instruction
types, ad dressing modes, etc.) and the specific syntax of the assembler he will use.
47/317
3 - Programming a microcontroller
Then, once he mastersboth, he may start to write hissource file. Obviously, iflater he has to
dothe samejobwitha different processor, the source filew illbeofnousein the futureproject.
3.1.2.2 Assembler
The word assembler has usually two meanings. Properly used, it is a program that translates
a t ext file, written according certain rules, into a binary file that contains a series of instruction s
specific to a micropro cessor or a microcontroller. Ho wever, the word Assembler is often improperly used instead of “assembly language”, for example in the sentence: “this program is
written in assembler”. This paragraph introduces the translating tool, or “assembler”.
The assembler is a program that runs on w hatever computer is used by the programmer for
his regular job. It takes the source file, as explained above, as an input; then, after translation,
itoutputs,depending on the user-specifed options, any of the following files:
The object file, containing binary data intended forfurther processing. It can not be read by
man.
The listing file, is a report containing both the original source code and its numeric
translation, presentedin a tabulatedmanner. It can be read byman and used for reference
purposes.
In some cases, other files like, lists of variables and labels, or additional data. This varies
fromoneassemblertoanother.
If the assembler encounters an error in the syntax of the source file, or some ambiguity or lack
of information preventing it from completely processing the source file, it generates an error
report, this may be output in the listing, in a separate file, or directly on the computer console.
The error messages tell where the error is located, and, as much as possible, the cause of the
error, as in the following example:
TRIAL.ASM(6): ERROR: not a ST7 instruction or directive
48/317
3 - Programming a microcontroller
Here again, the format of all the above mentioned files is chosen by the assembler's manufacturer,and differs from one to another.
File.obj
File.asm
Source file
Assembler
Relocatable object file
File.lst
Listing file
Assembler invocation
03-asm
3.1.2.3 Linker
If the whole application program is small, it is easy to put the source text into a single file. The
assembler then produces an object file that contains the whole machine code ready for use.
This is called absolute assembling.
However, there a re very few applications so simple that their source text occupies only a few
pages. In most cases, the total source text amounts to thousands of lines that may represent
hundredsofpages. In suchacase,itwouldbe impracticaltoedita single large source file. Not
only would the assembly process take a long time but this time would be spent whenever a
changewas made to the text.
Itwould be better to divide the whole textinto severalfiles,and to assemble them separately.
This way, a change would affect only one of the files, which can be quickly re-assembled.
Working this way requires additional features:
A m eans of telling that a particular source file references a data variable or a label that is
defined in another source file, in order to prevent the assembler from merely stopping and
issuing an error message saying that something referred to has not been found defined in
thesamesourcefile.
A tool to glue all the generated object files into a single object file, ready for use.
The first issue is addressed by additional syntax features that typically provide declarative
statements such as “External” and “Public”. The “External” statement declares that a certain
label referenced in the sourc e file will intentionally not be found the re, since it comes from another source file. The “Public” statement declares that a label (or a variable) defined in this file
will be referenced by another source file.
49/317
3 - Programming a microcontroller
The tool that glues together all the object files, each the result of assembling the source files,
is called the Linker.
The linker performs the following tasks:
It takesall the object files, and merges them into a single object file by concatenating them
one after the other.
It corrects the address values in all the instruction operands that refer to objects whose
location in memory has been set or alteredby t he concatenation.
To do this, i n addition to the set of object files, the lin ker requir es a control file that tells it the
list o f the object files to link together, the order in which they must be put, and the absolute addresses a t which the result will be in stalled in the microcontroller's memory.
This may look complex; but actually, it make processing large programs easier and faster.
When a change has to be made to a particular source file, only this file must be edited. Then
only this one must be re-assembled, which saves time; then, all the object files must be linked
again. The linking process is fast, compared to assembly, since the files contain binary data
and their format is optimized to make the linker's job easier.
If a hardware change is made to the board that changes the address of some memory or a peripheral, it may be only necessary to alter the linker control file and link the program again.
Once the program is linked, the resulting object file contains the whole program. This file i s
said to be an absolute object file, meaning that all addresses are defined; as distinct from object files before the link process that are said to be relocatable, i .e. their addresses can be
changed later.
Theabsoluteobjectfilecanbeusedeithertobedownloadedintoanemulatortocheckand
debug the program; or into an EPROM programmer to program the chip that will hold the
code.
As for the assembler, the linker is built to process relocatable files produced by the assembler
frim the same tool set. It is usually not possible to mix the tools, like assembling with t he assembler from supp lier A then linking with the linker from supplier B.
50/317
File1.obj
3 - Programming a microcontroller
File.cod
or
File.abs
Absolute object file
File2.obj
File3.obj
Relocatable object files
Linker
File.sym
Symbol table
File.map
Map file
Linker invocation
03-link
3.1.2.4 The project builder/make utility
In the process introduced above, that relies on splitting-up the processing to save time, it is important to keep track of which sources have been altered, only re-assemble these and not the
others and then link all the object files. Forgetting to do this may waste a lot of time. For example, after making a correction, if a program still shows the same incorrect behavior as previously,one istemptedto suspect another part of thecode. Trying to identifywhich other part
of the program produced the problem will be a useless effort, if the real reason was that the file
containing the change had not been re-assembledand linked.
Thus, a tool that can guarantee that the programmer will never forget to reprocess his files is
an invaluable help. T his tool is called Ma ker or Make utility.
The maker is a tool that works under the control of a file that gives the names of the source
files, the name of the output object file, thenamesof the tools needed to process afileto another file (assembler, linker), and the dependency relationships between the files.
Forexample, the dependencyrelationships specify that the finalobject file isproduced by applying the linker tool to the files named in the linker control file; that each of the individual object files is produced by applying the assembler tool to the correspond ing source file, etc.
The maker works as follows:
51/317
3 - Programming a microcontroller
Each timea filehasasuccessorwith a date olderthan itspredecessor,thecorresponding tool
is run to update the successor. This is done in an orderly fashion, from the top of the hierarchy
(thesourcefiles)tothe bottom(theabsoluteobjectfile).Then,atagiventime, allthosesource
files that have been modified since thelast run of the makerarereprocessed, and only those
files. This both g uarantees that no file will be forgotten in the updating process (provided that
the con tro l fi le correc tly describes all the depen dencies ) , and that only the nec e ss ar y
processingwillbe done, to save time.
The maker is an essential component of any set o f programming tools. But unlike what was
said about matching the same brand of assembler and linker, any maker may be used in a
project, since all work the same way. The control file, in fact, uses a different syntax; but this
does not affect the overall result. So, if you buy a new set of software tools for a microcontroller, you can still keep the maker you are accustomed to.
3.1.2.5 EPROM burners
EPROM burners, or programmers, are tools that have a hardware interface with a zero-insertion force socket that matches the characteristics of the specific EPROM chip or microcontroller with built-in EPROM. They transfer the contents of an absolute object file into the physical programmable memory. Burner software usually accepts several input formats. This gives
some flex ibility to the user and can allow using a burner from one manufacturer with software
tools from another. Apart from accepting absolute object files generated by the linker in the
same tool set, burners also frequently accept one or other of the more widely-used printable
hexadecimal formats.
To use a hexadecimalformat, either the linker must be able to output an absolute file in that
format, or a code converter must be used that takes an absolute object file as an input, and
produces a hexadecimal file as an output. Such converters are often supplied with in the software tool set. The use of these converters may save you the price of a new burner if you already own one for the right type of programmable component.
52/317
3 - Programming a microcontroller
File.cod
or
File.abs
Absoluteobject file
Executable fil e
formatter
File.s19
Memory content
image file
microcontroller
with built-in EPROM
Eprom
programmer
Programming amicrocontroller
03-prom
3.1.2.6 Simulators
Asimulator isatoolthatpretends torunanabsolute executable program. Like theother tools,
it runs on the programmer's own PC. It interprets the machine code that is specific to the
chosen processor or microcontroller, and outputs the results on the PC screen, without the
need for actually building the application hardware or even obtaining a sample of the target microcontroller.
The simulator allows the p rogram to be run step-by-step (instruction-by-instruction), allowing
the programmer to watch the values changing in any register or memory location that result
from the execution of the instructions. It also makes it possible to put breakpoints in the program, which are traps that stop the execution it reaches the address of the instruction where
the breakpoint was put. This can be used to run some parts at full speed and then stop on
reaching parts that are not yet fully functional, to avoid walking step-by-step through a lot of instructions that have already proven to be correct.
The progress of the execution can be followed on the screen in a special window that shows
the source file, and a cursor indicating the next line to be executed. At the same time, other
windows may display items like a range of data mem ory, the registers, the values of selected
data in a selected format (byte,word, character string...).
The user is even allowed to alter the values of the registers of the core, of the input-outputs, or
in memory, for example to correct a programming mistake, and continue the execution with
53/317
3 - Programming a microcontroller
the correct values, so as to avoid having to edit and make the program each time an error is
found.
In fact, simulation is limited to pieces of code that do not access the input-outputs, since this
would require a complex program at simulator level to also simulate the behaviour of the external world that the ap plication is supposed to interact with. But still, most simulators can correctly emulate the operation of the built-in peripherals, in particular the programmabletimers,
and can trigger interrupts whose servicing can be monitored on screen.
Simulation, though limited in its possibilities, has the advantage that it allows to you start debugging the application program before the hardware becomes available,. It can speed up the
debugging process by ensuring that some pieces of code are already functional when the time
comes to testand debug the hardware.
3.1.2.7 In-circuit emulators
In-circuit emulatorsarecomplexand expensiveinstruments that,for theapplication hardware,
behave exactly like the intended microcontroller would do. From the user's point of view, an
emulator is an inspection device that shows the calculations in progress in the application
hardware and the state of the input-outputs, as well as the contents of the memory at any time.
It is the electronic equivalent of a spy in the real world: an intermediate entity that, while
playing its role correctly in the real world (the application hardware), at the same time informs
an externa l intelligence (the pr ogrammer) of every thing that happens in that world.
An emulator offersexactly the same features as a simulator does, in terms of running an application either at full speed or step-by-step, setting breakpoints, examining registers, memory
andinput-outputs. The major difference is that while running the program,themicrocontroller
actually interacts with the external world, producing actions on the product to be tested, and
acquiring real data thatit can processin a realistic way.
Thesimulator and the emulatoraresoclosetogether infunctionalitythatthe manufacturerendeavours to provide the same user interface, i.e. the same presentation on the screen and the
same controls through the keyboard and the mouse for both tools, so that the user has very
little additional learning to do when switching from t he simulator to the emulator.
One last feature that is found on top-range emulators (the very expensive ones) is so-called
real-time tracing. This is a hardware system that records all events on the buses (address,
control and data) and attaches a time tag to them. The memory capacity is at least one thousand events, and can exceed ten thousandin the most expensive emulators. This allows you
torun theprogramatfullspeed,record whatis goingon, thenquietlyanalyzetherecordtosee
what happened. In real-time applications, this may be the only way to understand what happens and the problems that occur, as most of these applications do not permit step-by-step
debugging, since the processor must follow the activities of the external world in real-time. In
54/317
3 - Programming a microcontroller
this type of situation, its a difficult task for the programmer to complete the debugging of the
application so that it can be validated.
3.2 C LANGUAGE
3.2.1 Why use C?
Many high-levellanguage exist; some have beenwritten specifically fora family of microcontrollers, w hile others are w idely-used languages from the computer world that have been
adapted to suit the needs of microcontrollers. Today, one language that prevails in microcontroller programming, that is C language.
The primary advantage of C is the ability to write very simple statements that actually involve
hundreds of machine instructions. As an example, the small sample of assembly source code
givenintheparagraph aboutthe assemblylanguage hasfivelines.It could be replacedby the
following line:
memset ( (void*)1, 0xFF, 100 ) ;
This example is not very impressive. However, a C-language statement like:
is easy to read and translates i nto about eighty instructions, without taking into account the
subroutines that perform multiplication and subtraction. We can see at a glance the productivity gainwe can expect from a high-level language.
C language was initially designed as the programming language that came along with the
UNIX operating system. The power and relative simplicity of it made it spread to many differentcores, until it became thestandard programming language for microcontrollers.
The advantage of C is that it is a language that, though being very powerful, remains very
close to the hardware. This is a key feature for microcontroller applications, especially where
parts of the code are written in assembler. Being close to the hardware means the ability for
the compiler to produce very optimized code by choosing the best instructions for a given job,
when several instructions are available. In particular, setting a port pin high or low must not
55/317
3 - Programming a microcontroller
take a long string of instructions, since the designer of the microcontroller has worked hard to
provide efficient instructions to do the job.
C is a structured language, meaning that c ode can easily be di vided into blocks that can
readily become functions, or the body of looping or conditional statements, keeping the source
code legible if the writer has taken some precautions in the layout of the source text and provided useful comments.
Sayingthat C isa powerful language meansthat a short statement, taking only a single lineof
source text, may perform complex operations, involving hundreds or thousands of basic instructions. Not only does this conciseness help keep the source text easy to read, but also it
guaranteesthe c orrect execution ofthecode it hides,since thiscode hasalready been extensively tested by the manufacturer of the compiler.
The availability of C on many compu ter s makes it possible for you write and test some parts of
the program directly on your PC. Most of the time, if the language constraints have been adhered to, a piece of code that works on aPC will work straight off on the target microcontroller.
This is a recommended method of development, since it allows you to start writing and testing
the program before the hardware of the application has actually been built. The less debugging is done directly on the hardware, the quicker the development takes.
The por tability of C is also a guaran tee for the future. T he microcomputer world ev olves so
fast, that it is not unusal to have to redesign an existing application for another microcontroller,
or to reuse parts of the code of a previous application for a future one. In such an event, the C
language allows you to reuse code with virtually no change from project to project. This feature alone, pays back the moderate investment the C compiler represents.
To remove any doubts you might have about the sincerity of these arguments and si nce
nothing is perfect, the drawbacks of C are be listed here.
The first drawback is that C was originally designed for mainframe computers. In these machines, there is only one memory space, that containsboth code and data. In the ST7, there
is also a single memory s pace that contains code, data and input-outputs, but the code resides in ROM and data in RAM. S tandard C has no provision for specifying the address
ranges of these parts of memory.
The interrupt service routines may, and if possible, should be written in C, like any other part
of the code. However, standard C does not know anything about interrupts.
Inputs and outputs are handled in a mainframe through the operating system. Thus standard
C has no special provision for handling them.
These drawbacks would totally prevent you from using C for microcontroller appilactions if the
various implementations of C available did not provide solutions for these cases. These solutions vary from implementation to implementation, and constitute the main cause of non-port-
56/317
3 - Programming a microcontroller
ability of programs to another m achine. You will have to tak e account of this, especially wh en
testing the codeonyour PC first assuggested above. Thiscan inmost cases solved bya declaration file that is included in the project and that exists in two versions, or uses conditional
compilation, to fill the gap between two different dialects of C. This point is actually the most
trickyand that which requires most care from the programmer.
Having read these pros and c ons, hopefully concluded that C is the language of choice for
today if you want to save time and keep the fruit of your efforts over several years. We have
kept the last argument for the conclusion, that will, undoubtedly, be decisive in the years to
come.
The pressure for quality products is growing more every day. In some types of application, like
medical apparatus and life-sustaining devices, equipment reliability has to be certified. More
and more products, through ISO9000 st andards or the constraints of product liability must be
ready for quality assurance certification. Software quality assurance is a very difficult subject;
it is not the purpose of this book to enter this field. But one thing is sure, only properly documented and structured software is likely to meet these quality assurance requirements.
3.2.2 Tools used with C language
Just lik e theassemblertranslates mnemonic languageinto machinecode, the C compilerisa
tool that translates a C-language source file into a relocatable object file. Here also, the application will be divided into files, also called modules, that are compiled separately. The whole
group of object files is then linked to produce an absolute object file, the same as with assembler-generated object f iles. Actually, there is virtually no difference between an assemblergenerated object file and one generated by a C compiler. This means that some modules may
be written in C, and some in assembler; you can select the language according to the advantages and drawbacks of each language for each part of the application,as explained earlier.
57/317
3 - Programming a microcontroller
C
File.c
compiler
C source file
(onsome
File.asm
compilers)
Assembler source file
File.obj
Relocatable object file
C compiler invocation
03-comp
3.2.3 Debugging i n C
DebugginginC is donethesame wayasexplainedforassembly language.However, thesimulator and debugger screensdesignedfor high-level languages canalsoshow the progressof
the execution directly in the C-language source text, while another window shows the corresponding assembly languagestatements. A cursor in each window keep the correspondence
between both.
Another powerful feature offered by high-level language debuggers is the capability of displaying the data of selected variables according to their type, even for complex types like
structures, arrays, strings, etc. This dramatically improves the productivity of the debugging
phase, in the same proportion as choosing a high-level language does, in terms of shrinking
thesourcecode.
Thus theadvantage of high-levellanguages is twofold:it reducesboth the programming time
and the debugging time. This is an invaluable benefit, as the resource that is probably the
scarcest now adays is ti me, even more than money. However, you are advised to check
whether of the programming tools you selected fully support C language from one end to the
other; just to mention a few essent ials:
A text-editor that provides features that are useful in C language, like auto-indenting,
bracketed block selection,syntax highlighting, andso on;
A compiler, an assembler and a linker that are really suited to working with the selected
microcontroller,offering flexible addressable space allocation, efficient access to the ports,
58/317
3 - Programming a microcontroller
easy interrupt declaration and servicing in both assember and C language; efficient
optimization that may be switched offat criticalplaces;
A simulator and a debugger that properly display the C source text, allowing you to easily
change the valuesofvariables or evencode in memory tomakepatches, and that correctly
synchronizes the timers during step-by-step execution.
These are just a few of the features that may make the difference between apparently equivalentcompetingproducts.
59/317
3 - Programming a microcontroller
3.3 DEVELOPMENT CHAIN SUMMARY
The development chain discussed above can be understood more clearly using a diagram.
Thediagrambelow shows the various files involved in the developmentprocessas cylinders;
the translators used to change one file type into another are shown as rectangles.
Relocatable
C source files
object files
program
include files
C module
include files
Assembler
sourcefiles
Assembler
include files
Assembler
Main
#1
m odule
#1
module
#2
C compiler
Assembler
Linker
Compiling, assembling and
linking instructions can be
written in a
Absolute
object file
(1) Linker
parameter file
make utility file
(1) Dependingon the
development tools chain,
this file which contains
the memory map of the
project,can be a source
file instead of a parameter
file for the linker
To the EPROM
programmer
or thedebugger
for simulation
or in-circuit
emulation
60/317
Typical software development tools chain
03-tchai
3 - Programming a microcontroller
3.4 APPLICATION BUILDERS
An application builder is a gr aphical language that allows you to define the function of the program by manipulating icons on a computer screen. Each icon represents a standard function,
like addit ion, integratio n, com parison, etc. Each icon has inputs and ou tputs, and by drawing
lines on the screen between the output of one icon and the input of another, you connect these
icons, that is, feed one program block with the output of the previous program block. This kind
of programming tool is becoming popular in laboratory and plant automation since it allows
you to build a complete application without leaving the block diagram conceptual level. Thi s
makes ita quick and easy-to-use programming tool for non-programmers.
An application builder for the ST6 and the ST7, the STRealizer, allows you to use graphical
input techniques and build programs based on functional block diagrams. Version 2.2 of t he
STRealizer is available on the ST7 CD-ROM.
3.5 FUZZY-LOGIC COMPILERS
Fuzzy logic is a mathematical theory that has been applied to cope with problems that are at
the border between logical and analog computation.It haslead tomanyarticles and booksto
explain both i ts basic theory and v arious methods of implementing it using microprocessors.
Although it is a very attractive theory, there is no evidence so far of a typical application domain, though q uite a few c laims ha ve been made about robots, washing mach ines and
vacuum cleaners, that have been said to be able to adapt their operation to the job they have
to do. One example was a washing machine able to determine the proper amount of water
needed for a certain weight of clothes--without using a scale to measurethe weight.
Several fuzzy-logic compilers are available today, in particular one for the ST6 family, however there is none yet for the ST7.
61/317
4 - Architecture of the ST7 core
4 ARCHITECTURE OF THE ST7 CORE
4.1 POSITION OF THE ST7 WITHIN THE S T MCU FAMILY
The STMicroelectronics range of microcontrollers is very wide, from proprietary architectures
like ST6 to ST 10 to second-source products like microprocessors for PCs and Digital Signal
Processors.
Theproprietary range can be summarized as follows:
TypeWord sizeMain featuresTypical applications
Very low power consumption, 1.2 to 8
ST68bits
ST78bits
ST98/16 bits
ST1016 bits
KB ROM,
timer, ADC, watchdog timer and more
depending on the subtype.
Industry-standard instruction set, 256 to
3K bytes RAM, 4 to 60 KB ROM, ADC,
SPI, 16-bit timer, and more depending
on the subtype.
250 ns instructions (on a 16-bit word),
many internal registers, powerful addressing modes, interrupt priority controller, DMA controller, plus a whole
range ofperipherals capable of complex
processing. 16 to 128 KB ROM, more
than 256 bytes RAM.
100nsinstructions (ona16-bitword),72
KB Flash EPROM,10+KBRAM, ADC,
16-bit timer, USART, and more.
Appliances, home automation (suitable
for direct power line supply)
TV remote control, car radio control,
RDS decoder, etc.
Automotive body applications and car
radio.
Engine management systems, air bags,
etc.
As the table shows, the ST7 is positioned towards the low-end. It provides an economical
trade-off between speed and price and i s suitable w here moderate computational power i s
needed together with a low-consumption device, like in TV remote control transmitters.
Alhough it is a low-end product, because the ST7 combines the world's best-selling 8-bit instruction set with a host of added functions from a range of s mart peripheral blocks, it is remarkably versatile for a microcontroller of its class. It has a wide choice of versions in order to
minimize the component c ount of each specific application.
62/317
4 - Architecture of the ST7 core
4.2 ST7 CORE
The ST7 core uses an extended version of an industry-standard instruction set. This set is
both exhaustive (almost all instructions are available, with the exception of division) and fairly
orthogonal (the instructions allow for most addressing modes). This makes the instruction set
of the ST7 both clear and easy to use when programming in assembler.
For those of you al ready familiar with the standard i nstruction set, the ex tension res ides
mainly in the following two points:
A second index register, Y, that can be used anywhere the X register is used (like indexed
addressing),or like
The indirect addressing modes, that come in addition to the direct, long,and indexed modes.
X, moved to any other register;
The core as described her e is limited to the processing unit, excluding the reset and interrupt
circuitry. They will be described in the chapter dealing with the peripherals. The block diagram
of the core and the addressing spaceis shown below:
63/317
4 - Architecture of the ST7 core
Core
Reset
CPU Clock
Interrupt
requests from
peripherals
Arithmetic
and logic
unit
CPU Control
Accumulator
Y index register
X index register
Stack pointer
Progra mcounter
Condition c oderegister
Page0
( 8 lines wide)
Data Memory
from0000h to 017Fh:
Peripheral registers
User RAM
Stack RAM
(16 lines wide)
Address bus
(16 lines wide)
Program Memory
from E000h to FFFFh
user ROM
Interrupt & reset vectors
( 8 lines wide)
The core and the addressing space of the ST72251
Data bus
64/317
04-core
4 - Architecture of the ST7 core
4.2.1 Addressing space
The ST7, as said earlier, is based on a Von Neumann architecture. This means that there is
only one addressing space in which the program, the data and the input-output peripherals are
mapped. The advantages are:
Access to any byte (of program, of data or of input-output) using the same instructions
No special instructions to access constant data in program memory or input-output
Ease of programming, due to simplification resulting from the first two advantages
As a typical 8-bit processor, the address bus of the ST7 is 16 bits wide, and thus able to address 65,536 bytes. This is enough for most applications within the range of the ST7.
To improve the efficiency of the code, the addressable space is actually divided in two parts:
Theaddresses ranging from 0 to 255 (
0FFh) are said to belong to page zero. An 8-bit address
is enough to reach them.
The remainder, from 256 (
80h)to65,535(0FFFFh), is accessed using 16-bit addresses.
The use of page zero can greatly improve the speed of the code i f the most frequently accessed data are locatedinpagezero. Also,in theST7, allinput-outputs are always located in
page zero.
4.2.2 Internal registers
The core uses only six registers:
A, X, Y, PC, SP and CC.
4.2.2.1 Accumulator (A)
The accumulator is the register where the arithmetic and logic operations are performed. To
perform a two-operand operation between two values stored in memory, one of the values
must first be moved to the accumulator, since the instruction code provides only one address.
It must be moved back to memory when the operation is done.
The instructions that require only one operand, like
ComPare, TestforNegative or Zero, Bit ComPare, and so on, can act on the accumulator, or di-
INCrement, DECrement, ComPLement,
rectly on the data in memory, if so desired.
4.2.2.2 Condition Code register (CC)
This register holds several bits that are actually more or less independent from one another.
These bits are set or reset (or left unchanged) after the execution of certain instructions. For
example, ifanadditionproduces a nullresult, the
is negative, the
N flag is set, otherwise it is reset and so on. The CC register remembers the
Z flagisset;otherwise,itis reset. Iftheresult
conditions after each instruction, and these conditions are used by the conditional jump instructions. The
CC is laid out as follo ws:
65/317
4 - Architecture of the ST7 core
1111HINZC
Condition code register
04-ccreg
The leftmost three bits, indicated as ones, are not used. When read, they yield ones.
Cbit
C bit isthecarry thatis generatedbyan additionorsubtraction. When adding 16-bit num-
The
bers, for example, we first add the two least-significant bytes together, then the most significant ones. If the result of the first addition yields a result greater than 255, it cannot fit in a byte.
Forexample, adding 1200 and 6230 in decimal yields 7430.In hexadecimal notation, thisis:
4B0 + 1856 = 1D06
Adding these numbers is performed in two steps. First, B0 is added to 56, yielding 06 wit h a
carry of one. Then,
4 isadded to18, yielding 1C, and with theadditionof the c arry we get 1D.
The role of the
additions. The first addition is performed using the
the
ADC instruction (add with carry) that increments the result of the addition if the C bitisaone.
C bit of the Condition Code register is to remember that carry between the two
ADD instruction, and the second must use
The instructions that affect the carry bit are mainly addition and subtraction, the shift and rotate instructions, and of course instructions that directly affect the
The instructions that usethe
C bit areADC and SBC (subtract with carry), the rotate instructions,
CC register.
and some conditional jump instructions.
Zbit
Thisbitissetto one to reflectthe fact thatavalueis zero, wheneverthe accumulator isloaded
or after any arithmetic or logical operation. If the value is not zero, the
structions that affect or use the
Z bit are the same as those for the C bit.
Z bit is cleared. The in-
Nbit
This bit is set to one to reflect the fact that a value is negative, in two’s complement notation.
A negative number has its most significantbitset to one; so the
N bit reflects the most signifi-
cant bit whenever the accumulator is loaded or after any arithmetic or logical operation. If the
value is positive, the bit
that affector use the
N is cleared. The value zero is considered positive. The instructions
N bit are the same as thosefor the C bit.
Ibit
This bit is the global interrupt mask. When this bit is set, all interrupts are ignored. However, if
an interrupt request is present, clearing the
66/317
I bitimmediately triggersan interrupt.
Hbit
4 - Architecture of the ST7 core
This bit is a similar to the
C bit, since it is set when a carry occurs. This time, it is the carry be-
tween the two nibbles of a byte. A byte is composed of two four-bit groups called nibbles. The
H bitis set whenever an arithmetic instruction produces a carrybetween bit 3 and bit 4 of the
accumulator.
This half-carry is used when performing decimal arithmetic. In this case, each nibble contains
a BCD digit, so that the bit pattern for 23 in decimal is 00100011, and reads also
23 in hexa-
decimal. This kind of coding is called Packed BCD. To correctly add two packed BCD numbers, some correction is necessary, which ismade possible by the H bit. Several cases must
then be considered:
First case: adding the numbers23 and 52.
OncecodedinpackedBCD,theyread
find 75. Actually, if we perform the ADD instructions on these numbers, we find
23h and 52h.Ifweaddthesenumbers,weexpectto
75h,asthe
rules for adding two binary numbers imply. We directly get the right answer in packed BCD.
No half-carryhas occurred.
Second case: adding the numbers 23 and 59.
OncecodedinpackedBCD,theyread
find 82. But if we perform the ADD instructions on these numbers, we find
for adding two binary numbers imply. This is because
23h and 59h.Ifweaddthesenumbers,weexpectto
7Ch,astherules
3 + 9 = C in hexadecimal. C is not an
acceptable digit inBCD. However, itis easy to see that if we add 6 to the total (the difference
between15and9),weget
82h, which is also the right answer in packed BCD. No half-carry
has occurred.
Third case: adding 28 and 59.
We expect to get 87. Once added as above, we get
This indicates that we must add 6 to the result, giving
81h. This time, a half-carry occurred.
87h, which is the right answer.
To summarize, if the addition of two packed BCD numbers gives no half-carry and if the leastsignificant nibb le is less than
0Ah, the result is correct as it is. Otherwise, adding 6 will correct
the result.
The same thing applies for the most-significant nibble: if it has a value less than
is no carry, the result is correct; otherwise, adding
60h will correct the result.
A,andthere
Complicatedasitmight seem, the handlingof packedBCD avoids having toconvert numbers
back and forth between binary anddecimal,although this may be easier in some cases.
4.2.2.3 Indexregisters (X and Y)
The index registers are meant to hold addresses, unlike the accumulator which is meant to
hold data. The value stored in
X or Y is involved in the effective address calculation insom e ad-
dressing modes. The availability o f two index registers allows for calculating and managing
67/317
4 - Architecture of the ST7 core
two addresses as is needed in a memory-to-memory data move, with or without alteration in
between. However, these registers may also be used to store temporary data.
4.2.2.4 Program Counter (PC)
The program counter is the register that controls the sequencing of the instructions. The program is w ritten as a series of instructions, and these instructions are stored in consecutive
cells of the program memory. The Program Countercontains the address of the nextinstruction to be executed. This instruction is read from memory, then executed, and the
PC is incre-
mented so that it then points to the nextinstruction in the sequence.
It is possible to alter the contents of the
PC while the pr ogram is exe cuting. In th is case, the
next instruction will not necessarily be the next in the sequenc e, but an instruction somewhe re
else in memory. Changing the course of the program is called jumping or branching.
Jump and Branch are the namesof instructionsthat actually c hangethecontents ofthe
PC by
setting it to a value specified with the instruct ion. Jum ps may also be conditional, that is, the
jump instruction effectively alters the contents of the
PC if certain conditions are met. These
conditions canbethevaluesofoneor more bits of theConditionCode Register. For example,
the
JREQ instructionchangesthePC to the specified address if the Z bitoftheCC register is set,
otherwise the program continues in sequence.
Another kind of jump is the Subroutine Call, that first saves the address of the next instruction
in sequence (the one that follows the jump instruction) before jumping. A special instruction,
RETurn, retrieves this address and puts it into the PC. The next instruction executed is once
again the one that follows the
CALL instr uction.
4.2.2.5 Stack Pointer (SP)
The stack is the part of the read-write memory where return addresses are stored by the
CALL
instructions and retrieved by the RET instruction.
68/317
4 - Architecture of the ST7 core
0140h
017Fh
Top of the stack
64 bytes of RAM
Bottom of the stack
(Reset value)
Stack organization of the ST72251
04-stack
When a value is stored using the stack pointer, the stack is decremented, so that the next
value stored will be placed at the address just below the previous one. This process of storing
and decrementing the pointer is called Pushing, and can be done either by a
or by a
CALL instructionthat pushes the return address.
PUSH instruction
When the data is read back from the stack, the
SP i s incremented so that the next data re-
trieved will be the one s ituated at the address above the previous value retrieved. This is
called popping the data, and can be done using the
POP instruction or the RET instruction that
pops one address off the stack and jumps to that address.
If several addresses are stored successively because several
sively, the first
RET instruction will pop the last address pushed, the second RET will po p the
CALLs were executed succes-
one-but-last address, and so on. This feature provides for the nesting of subroutines, where
the last called is the first exited.
Interrupts, being a kind of subroutine call, also use the stack to store the context of the interrupted process. Since interrupts occur at unexpected times, all the core registers must be
savedonentering theinterrupt serviceroutine. Thisis performedautomaticallybytheinterrupt
mechanism thatpushes in order
ferent instruction from the return from subroutine, where only the
tion
IRET is s upplied for this purpose, and res tores the initial values of these registers. It
should be noted that the
Y i ndex register is not saved automatically. The industry-standard
PC, X, A and CC. The return from interrupt must thus use a dif-
PC was saved. The instruc-
69/317
4 - Architecture of the ST7 core
core has no Y index register, so its instruction set does not take the Y index register into account. Ifneeded,itmustbe pushedonentering the interruptserviceroutineusinga
struction, and restored by putting a
POP Y just before the IRET.
PUSH Y in-
The stack pointer must be initialized at the start of the execution. The
RSP instruction resets it
to its bottom v alue, that differs from one variant of the ST7 to another depending on the
number of registers provided at the beginning of page zero.
Thevalueof the
SP may be transferred to A, X or Y or set from these registers. This allows you
to access the data i n the stack or to save the stack pointer. This is useful for example for
building multitasking kernels, as mentioned in Chapter 2 and illustrated in Chapter 7.
The
PUSH and POP instructions mentioned earlier in this paragraph may be used to temporarily
store a register that has to be reused later. This is very useful as the core has not many internal registers.
4.3 INSTRUCTION SET AND ADDRESSING MODES
4.3.1 A word a bout mnemonic language
Inthetext above,wehave givenexamples that use the mnemonic language.Forthoseof you
that are not familiar with the mnemonic language of the ST7, here is a refresher. More details
will be given in the paragraph that discusses addressing mode s and in the chapter about the
assembler.
Themnemonic languagespansthegap between machineswhose languageisexclusively numeric, and humans who are more comfortable with letters and words. Unlike high-level languages that provide for complex concepts that must be translated into machine language
using complex constructs, mnemonic language is easily translated into machine language
since there is almost a word-for-word correspondence between numeric machine language
and verbal mnemonic language.
Mnemonic language, also called assembly language, associates short names to the various
objects the programmer uses. A translation program, called Assembler, translates these
words into numbers. The words involved belong to the following classes:
Labels
Operation mnemonics
Operand names
Macro names
Numbers
Comments
70/317
4 - Architecture of the ST7 core
From the categories above, numbers can be distinguished because they s tart with a decimal
figure. For hexadecimal numbers that may start with a letter, there are two main conventions:
In the so-called Intel co nvention, a n umber will only be reco gnized as such if the first digit is a
figure; for example,
FAh is not considered a number; 0FAh is;
In the Motorola and and few other conventions, any hexadecimal number must start with a
special character, like $ for Motorola; no ambiguity is possible then. The ST7 tools use this
conventionby default.
All other categories except comments are made of single words that begin with a letter. For
example,
HERE is alegalname for a label.
The vocabulary of the Operation Mnemonic category is defined by the manufacturer. It contains the operation codes specific to the m icrocontrolle r, commonly called opcodes. There are
also other words that are not opcodes, but that have a similar function in the language. For
that reason, they are named pseudo-ops.
Opcodes are named after the abbreviation of the function of the instruction. Some are obvious, like
ADD; some abbreviated, like SUB (subtract); others are acronyms like TNZ (Test for
Negative or Zero).
Thepseudo-opsinclude commandsto theassemblyprogram,to direct itto make memoryres-
ervations, like
DS (reserve Data Storage) or DCW (Define C onstantWord), or othersimilarcom-
mands.
The labels are names that the programmer freely assigns to data in memory, constant values,
orpieces of code.This improvesthe clarityof the source text.Forexample, ifthe programmer
hasreservedabyteinmemory forthe resultofananalog todigital conversion,he usesthe following statement:
Voltage:DS 1; Voltage read back from input
He can then use t his name to load this value into the accumulator:
ld A, Voltage; Get value into accumulator
Which is easier to read than the numeric sequence:
C6 01 24
71/317
4 - Architecture of the ST7 core
That is the translation of the statement above, supposing the variable Voltage had been assigned to thememory address
124h.
In the examples of source lines above, the text that follows the semicolon (;) isa comment.It
isignored by the assembler, anditssolepurpose is to inform the human readerof the s ource
text, when he later reads it.
The last category of words listed above is the macro name. A macro is a piece of text the programmer may define freely and which he can give a name. Inserting the macro name in the
source text will replace that word by the whole predefined text, saving the programmer typing
effort.
4.3.2 Addressing modes
The ST7 has many addr ess ing m odes. In a ddi tion to those inherited from the industry standardarchitecture,there arethoseinvolvingthe secondindexregister,
addressing modes available with the
X index register, and all the indirect addressing modes.
Y, that duplicate the
Having a choice of addressing modes might seems surprising. Anyone might think that indicating the address of the source or destination of a data move should be a straightforward
matter. Actually, there are several cases to handle:
Iftheaddressofthebytetobereadorwrittenisknownatthetimetheprogramiswritten,the
direct addressing mode is used. This mode hastwo variants: short direct mode addresses
page zero; long direct mode addresses the whole range.
If the address of the byte is not known when the program is written, this means that the data
has the form of a record, a string, an array or any other structure that holds complex data.
Since the ST7 only processes bytes, it is necessary to process this kind of data byte-by-byte.
Then, the address of the byte to be read is computed when the program executes, and it is
this address that indicates which byte must be read. According to the structure of the data,
one addressing mode or another might prove more convenient, or fast, or efficient. The ST7
has a choice of addressing modes that take the address from an index register (indexed
addressing),or from the contents of a memory byte (indirect addressing),or a combination.
Instructions thatload constantsintoa register use immediate addressing, which meansthat
the data is located just after the instruction code in program memory. This data is skipped to
reach thenext instruction.
Jumpinstructionsoftenbranchtoanaddressthatisclosetotheaddressofthejump
instruction. If the distance of the jump is within the range -128 to +127 from the instruction
thatfollows the jump, relative addressing isefficient since the address of the destination of
thejump is obtainedbyaddingthesinglebytethat follows the jumpinstructiontothecurrent
value of the Program Counter. This byte is called displacement. This instruction thus saves
one byte of program memory.All conditional jumpsuse this addressingmode.
72/317
4 - Architecture of the ST7 core
The last mode, called inherent, means that the data involved in the instruction does not need
to be designated by an address, such as the instruction that increments the accumulator.
The many indexed and indirect modes available are useful for translating programs written in
C language, since these programs frequently use complex data structures.
4.3.3 Instruction set
The instruction set of the ST7 includes many instructions. They can be sorted in different
ways. Here is a grouping by number of addressing modes available. This kind of sorting may
seem arbitrary,butthere areactually groups of instructions that have a common functionand
also the same set of addressing modes.
Table 2.
No
operand
(system)
1
(inherent)
HALT
IRET
NOP
RCF
RET
RIM
RSP
SCF
SIM
TRAP
WFI
Table of the number of addressing modes versus the instruction types.
Theinstructions are codedusing bytes s tored in program memory.One instruction takes one
to fourbytes according to its type and the addressing mode. These bytes are, in order:
The prefix byte (optional); the operation code (opcode), and one or two bytes of address (optional).
4.3.4.1 Prefix byte
Theprefixbyteisusedtoextendtherangeofinstructions.Theopcodebeingasinglebyte,no
more than 256 combinations of an operation and an addressing mode may be coded. The
original industry-standard instruction set only uses one by te for the opcode. The ST7 i ncreased the choice of addressing modes so that it was no longer possible t o code them all
using a single byte. A prefix byte has been created. When this prefix is put before an opcode,
it changes the addressing mode of the opcode. There are three prefixes:
PDY (90h) means that the next instruction must use the Y index instead of the X index.
PIX (92h) means that the next instruction must change its addressing mode (whichever it is)
to the corresponding indirect addressing mode.
PIY (91h) is a combination of the above: the addressing mode is indirect, and the index
register used is
Y.
74/317
4 - Architecture of the ST7 core
4.3.4.2 Opcode byte
The opcode uses a bit-level coding to specify the type of operation to perform (add, subtract,
jump, etc.) and the addressing mode used (direct, indexed, indirect, etc.) in a single byte.
The tables below summarize the available instruction codes. The lines are the value of the
higher nibble of the opcode; the columns are the lower nibble. The grouping of the instructions
is clearly visible.
Lowdigit
High
digit
0
1
2JRAJRFJRUGTJRULEJRUGEJRULTJRNEJREQ
short3NEGCPLSRLSRARRCSLL
A4NEGMULCPLSRLSRARRCSLL
X5NEGCPLSRLSRARRCSLL
short, X6NEGCPLSRLSRARRCSLL
(X)7NEGCPLSRLSRARRCSLL
8IRETRETTRAPPOP APOP X
9
immediateASUBCP A,SBCCP X,ANDBCPLDA,
shortBSUBCP A,SBCCP X,ANDBCPLDA,
01234567
BTJT
m,0
BSET
m,0
BTJF
m,0
BRES
m,0
BTJT
m,1
BSET
m,1
BTJF
m,1
BRES
m,1
LD
X,Y
BTJT
m,2
BSET
m,2
LD
S,X
BTJF
m,2
BRES
m,2
LD
S,A
BTJT
m,3
BSET
m,3
POP
CC
LD
X,S
BTJF
m,3
BRES
m,3
LD
X,A
LD
m,A
LD
m,A
longCSUBCP A,SBCCP X,ANDBCPLDA,
long, (X)DSUBCP A,SBCCP X,ANDBCPLDA,
short, (X)ESUBCP A,SBCCP X,ANDBCPLDA,
(X)FSUBCP A,SBCCP X,ANDBCPLDA,
LD
m,A
LD
m,A
LD
m,A
LD
m,A
75/317
4 - Architecture of the ST7 core
Lowdigit
High
digit
0
1
2JRNHJRHJRPLJRMIJRNMJRMJRILJRIH
short3SLARLCDECINCTNZSWAPCLR
A4SLARLCDECINCTNZSWAPCLR
X5SLARLCDECINCTNZSWAPCLR
short, X6SLARLCDECINCTNZSWAPCLR
(X)7SLARLCDECINCTNZSWAPCLR
8
9RCFSCFRIMSIMNOP
immedi
ate
shortBXORADCORADDJPCALLLD X,
AXORADCORADDCALLRLD X,
89ABCDEF
BTJT
m,4
BSET
m,4
PUSH
A
BTJF
m,4
BRES
m,4
PUSH
X
BTJT
m,5
BSET
m,5
PUSH
CC
BTJF
m,5
BRES
m,5
BTJT
m,6
BSET
m,6
BTJF
m,6
BRES
m,6
BTJT
m,7
BSET
m,7
RSPHALTWFI
LD
A,S
BTJF
m,7
BRES
m,7
LD
A,X
LD
m, X
LD
m, X
longCXORADCORADDJPCALLLD X,
long, (X)DXORADCORADDJPCALLLD X,
short,
(X)
(X)FXORADCORADDJPCALLLD X,
EXORADCORADDJPCALLLD X,
LD
m, X
LD
m, X
LD
m, X
LD
m, X
As said about the prefix, this table changes to either Y index, or indirect, or both according to
the prefix byte. The letter m indicates «memory» in instructions such as
76/317
LD m, X.
4 - Architecture of the ST7 core
4.3.4.3 The addressing modesin detail
Immediate mode
When a register has to be loaded with a constant value that has been fixed in the program
source, that value is determined in the program source text and must be stored in the program
memory to make it fixed and permanent. In such a case, the most effective way to retrieve the
value is to use the immediate addressingmode. In this mode, it is not necessaryto supply the
address of the data. The processor expects the data to immediately follow the opcode in the
program memory. This saves both time and memory size.
Example: the instruction
LD A, #10h
A is loaded with a constant value between 00h and FFh.
loads the accumulator withthevalue10,not thevalue storedat address10. The codingof the
instruction is (in hexadecimal):
A6 10
This instruction takes two bytes of memory.
Directshort mode
There are two direct addressing modes: short and long. They are identical, except for the
number of bytes of the address of t he operand. Direct addressing means that the opcode is
followed by the address of the data in memory to be read or written. In the short version, the
address is situated between the addresses 0 and 255, and only one byte is used for it.
Example: the instruction
LD A, 10h
A is loaded with the value stored in an absolute memory address
in zero page.
loads the accumulator with the value stored in memory at address 10h. The coding of the instruction is (in hexadecimal):
B6 10
This instruction takes two bytes of memory.
Direct long mode
Thismodeworks likethedirectshort mode, exceptthatthefull16-bit address is supplied.The
address then takes two bytes instead of one, lengthening the instruction by one byte. This is
why directshortaddressing mode should be used as much as possibletospeed up execution
and save memory space. This means that the most frequently accessed data must be placed
77/317
4 - Architecture of the ST7 core
in memory below address 100h. The assembler automatically takes care of this, by selecting
the appropriate addressing mode when possible.
Example: the instruction
LD A, 1234h
A is loaded with the value stored in an absolute extended memory
address.
loads the accumu latorwith the value stored in memory at address 1234h. The coding of the instruction is (in hexadecimal):
C6 12 34
This instruction takes three bytes of memory. It should be noted that the most significant byte
of the addresscomes first.
Indexed mode
Inthis mode, the contents of register
X (or Y if the prefix is used) is used as the address of the
data to read or write. As the index register is only 8-bit, the address is lower than 100h.
Example: if the register
LD A, (X)
A is loaded with the value stored in a memory address in page
zero pointed to by the chosen index register.
X contains the value 26h, the instruction:
loads the accumulator with the value stored in memory at address 26h. The coding of the instruction is (in hexadecimal):
F6
This instruction takes only one byte of memory. This mode is used if the address of the operand is notknownat assembly time and must be calculatedaccording to some rule.
Indexed with short offset mode
This mode works like indexed mode, but the instruction isfollowed by a byte,called displacement or offset,whose value is added to the value in the indexto get the effective address.
Example: to access byte 4 of a character string starting at
the
X index with the value 4. Then, the instruction:
LD A, (23h,X)
23h in data memory, we first load
A is loaded with the value of the RAM address memory pointed
to by the sum of the specified 8-bit offset and the contents
of the chosen index register.
loads the accumulatorwiththevalue storedinmemory at address 27h (23 + 4).Thecodingof
the instruction is (in hexadecimal):
78/317
4 - Architecture of the ST7 core
E6 23
This instruction takes two bytes of memory. The farthest address that can be reached is 1FEh
(0FFh + 0FFh).
Caution:there mustbenospaceoneitherside of thecomma withintheparenthesis.Example:
(23h, X) is incorrect.
Indexed with long offset mode
This mode is similar to the indexed with s hort offset mode, but the offset is a 16-bit number
that takestwo bytes. Itallows anyaddress to be reached within thewhole addressing range.
Example: to access byte
load the
X index with the value 4523h. Then, the instruction
LD A, (4523h,X)
A is loaded with the value of the RAM address memory pointed
to by the 16-bit sum of the specified 16-bit offset and the
contents of the chosen index register. The whole memory can be
reached.
64h of a character string starting at 4523h in data memory, we first
loads the accumulator with the value stored in memory at address 4587h (4523h + 64h). The
coding of the instruction is (in hexadecimal):
D6 45 23
This instruction takes three bytes o f memory. If the sum of X and the offset exceeds 0FFFFh,
the effective address rolls over zero. For example, if
effective address will be
45h.
X contains 83h and the offset is FFC2h,the
Caution:there mustbenospaceoneitherside of thecomma withintheparenthesis.Example:
(4523h, X) is incorrect.
Relative direct mode
This addressing mode is only used in jump instructio ns. The opcode is followed by a byte that
represents the offset or the displacement of the destination of the jump, relative to the current
value of the Program Counter. This displacement is a 8-bit signed number, so that the range
of such a jump is limited to -128 to +127 from the instruction following the jump. This mode is
efficient in conditional jumps, since the pieces of code that correspond to opposite cases (test
was true or false) are oftenlocatedclose to eachother.Whenlongerconditionaljumpsarerequired , t he solution is to do a relative jump to a locatio n within t he reach of a relative jump,
where an absolute jump is made to the final destination.
These short-range jumps are usually called branches to contrast with the jump instruction that
uses long addressing mode and that can jump anywhere in the addressing space. In the ST7,
they are called relative jumps.
79/317
4 - Architecture of the ST7 core
Example:
At address 1200h, the following instruction:
JRA 11F1h
The absolute address supplied in the source code will be translated
into a relative displacement by the assembler.
is coded as:
20 EF
The two bytes of the instruction occupy addresses 1200h and 1201h.Thus, the nextinstruction
will be found at addres s
between
1202h yields 11F1, which is the address of the destination of the jump. It should be noted that
1202h and 11F1h is -11h . In 8-bit, two’s complement, this is noted EFh.AddingEFh to
1202h. The offset is calculated from this displacement. The distance
although the jump is relative, the operand of the jump instruction is the destination of the jump.
The assembler automatically calculates the difference. If the destination is out of reach, that is
farther than 127 bytesin either direction, the assembler generates an errormessage.
Relative indirect mode
This mode is also only used for Jump Relative instructions. The opcode is followed by a byte
that is the address in memory that contains the displacement.
Example: if the displacement
struction is stored at address
JRA [58h]
The value of the relative displacement is stored at the specified
memory address in page zero
EEh is storedin thememorybyteataddress 58h,the following in-
1200h:
is coded as:
92 20 58
The three bytes of the instruction occupy addresses 1200h to1202h. Thus, the next instruction
will be found at address
added to the Program Counter, giving
1203h. The byte at address 58h is read, giving EEh or -12h that is
1203h - 12h = 11F1h
In this mode, the operand of the jump instruction is the address of the displacement. This displacement mustbesupplied separately,ifnecessarybyan expression thatis calculatedatassembly time. Example:
Displ dc.b THERE - HERE
80/317
It is up to the programmer to supply the right expression
for the displacement, but the calculation with the actual
values will be performed by the assembler.
4 - Architecture of the ST7 core
where THERE and HERE are labels respectively designating the destination of the jump, and the
address of the instruction that follows the jump instruction. Here again, if the difference yields
a number that exceeds the range of a one-byte value, the assembler generates an error message.
Indirect shortmode
Inthis mode,theaddress that followsthe opcodeisthatofa memorybytecalleda pointer that
contains the addres s of the data to read or write. This allows the effective address to be
formed by the result of a previous calculation. For example,if the pointerat address
tains
79h,andthebyteataddress79h contains 0, the instruction
LD A,[23]
A is loaded with the value stored at the short address pointed
to by the specified memory address in page zero.
23h con-
loads the accumulator with the contents of address 79h (and not 23h) that is zero. The coding
of the instruction is (in hexadecimal)
92 B6 10
where the first byte is the PIX prefix. This instruction takes three bytes of memory.
Indirect long mode
This mode is similar to the indirect short mode, but the effective address contained in memory
is a 16-bit word. This allows the whole address range to be accessed. The pointer must still be
placed at an address below
Forexample,ifthepointerataddresses
7954h contains 0, the instruction
LD A,[23.w]
A is loaded with the value stored at the extended address pointed
to by the specified memory address anywhere in memory.
100h.
23h and 24h contains 7954h,andthebyteataddress
loads the accumulator with the contents of address 7954h (and not 23h) that i s zero. The
coding of the instruction is (in hexadecimal):
92 C6 10
wherethefirst byte isthePIX prefix.Thisinstructiontakes threebytesofmemory. Please note
the «
.w» that indicates that the long indirectmode must be used.
Theindirect short mode is similar tothe indexed mode, except that it is not necessary to load
the index registerwith the address of the operand; it may be used directly where it resides in
memory.
81/317
4 - Architecture of the ST7 core
Indexed with indirect short offset mode
This mode is simila r to the indirect short mode, in that the address that follows the instruction
is the address of a 8-bit pointer in memory that contains an address. The difference is that this
address is not used right away; it is first added to the contents of the index register, and the
sum is the effective add ress that will be read or written.
Taking the sameexampleas forthe indirectshort mode,ifthe pointer at address
79h, the index register X contains 5, and the byte at address 7Eh contains 0, the instruction
LD A, ([23],X)
A is loaded with the value stored at the address pointed to
by the sumof the 8-bit offset stored at the specified short
address and the contents of the chosen index register. The
range of this mode is 0 to 1FEh.
23h contains
reads the contents of the address 23h,thatis79h, and adds it to the contents of X,thatis5,
yielding the value
7Eh. This value is taken as the effective address whose contents are read,
giving is zero. The coding of the instruction is (in hexadecimal):
92 E6 23
where the first byte is the PIX prefix. This instruction takes three bytes of memory.
Indexed with indirect long offset mode
This mode takes a 16-bit index in memory, and adds its contents with the 8-bit contents of the
index register, yielding the effective 16-bit address of the operand.
For example, if the 16-bit pointer at address
5, and the byte at address
LD A, ([23.w],X)
794Ah contains 0, the instruction
23h contains 7945h, the index register X contains
A is loaded with the value stored at the address pointed to
by the sumof the 16-bit offset stored at the specified
extended address and the contents of the chosen index
register. Thus, the whole RAM memory space can be addressed.
reads the contents of address 23h, that is 7945h, and adds it to the contents of X,thatis5,
yielding the value
794Ah. This value is taken as the effective address whose contents are
read, giving zero. The coding of the instruction is (in hexadecimal):
92 D6 23
where the first byte is the PIX prefix. This instruction takes three bytes of memory.
4.4 ADVANTAGES OF T HE ST7 INSTRUCTIO N SET AND ADDRESSING MODES
In many programming applications, data may have complex forms. To ease data handling,
high-levellanguages have been created that simplify codingby allowing expressionslike:
82/317
4 - Architecture of the ST7 core
A[I] = B[J] + C[K]
Where A, B and C arearrays of numbers, and I, J and K the indexes to these arrays. The highlevel language compiler translates this so as to read the
Ith elementofarray A usingtheavail-
able machine-language instruction. If these are arrays of bytes whose base address is somewhereinpagezero,thefollowinginstructionsequencecanbeused:
LD X, I; Set Index register to value of index I of array A
LD A, ([A],X); Get value A[I]
LD X, J; Set Index register to value of index J of array B
ADD A, ([B],X); Add value of B[J]
LD X, K; Set Index register to value of index K of array C
LD ([C],X), A; Put result into C[K]
This is only one of the many examples where powerful addressing modes help translate highlevel languages efficiently. In this case, the whole addition is performed in 22 cycles, or 5.5 µs
at 8 MHz, and consumes 12 bytes of code.
83/317
5 - Peripherals
5 PERIPHERALS
5.1 CLOCK GENERATOR
The core of the ST7 is supplied with an internal c lock that comes from the division of the oscillator frequency. This division rate is pro grammab le, allowing you to se lect the best c ompromise between speed and power consumption.
Thischoice is programmedusingbitslocated in the MiscellaneousRegister. Thisregister also
contains bits used for other purposes; theirfunctionwill be detailed later in this chapter.
The Miscellaneous Register is laid out differently from one ST7 device type to another. We will
describe only two variants here.
5.1.1 ST72251 Miscellaneous Register
TheSMS (slow modeselect)bit, when set, placesthecore andtheperipheralsin slow mode.
This speed is 1/16 the normal speed, which is the oscillator frequency divided by 2.
The bit MC O (main cl ock out), w hen set, enables a clock signal with this frequency to be
outputon bit 2 of port C (PC2).
PC2
0 normal I/O
1Pc2=f
PEI3 PEI2
MC0
CPU
PEI1 PEI0
--
0 normal mode
1slowmode
SMS
ST72251
%16%2
f
CPU
normal I/O port
Main Clock Out and Slow Mode Select bits
of the ST72251 Miscellaneous Register
05-misc1
Os cillator
to the core a nd
peripherals
84/317
5-Peripherals
5.1.2 ST72311 Miscellaneous Register
TheSMS bit worksthe same wayasinthe ST72251(seepreviousparagraph), butinaddition,
the two bits PSM1 and PSM0 (prescaler for slow mode) select the supplementary division rate
between 2 and 16.
The bit MC O (main cl ock out), w hen set, enables a clock signal with this frequency to be
outputon bit 0 of port F (PF0).
PF0
0 normal I/O
1Pf0=f
PEI3 PEI2PEI1
CPU
MC0
ST72311
normal
I/O port
PEI0
PSM1
0 normal mode
1 slow mode
PSM2
%200
%801
%410
%16 11
f
CPU
SMS
to the core and
peripherals
Oscillator
%2
Main Clock Out, Slow Mode Select and Prescaler bits
of the ST72311 Miscellaneous Register
05-misc2
85/317
5 - Peripherals
5.2 INTERRUPT PROCESSING
Interruptrequests maybe generated by several external orinternal sources.Mostperipherals
of the ST7 can produce interrupt requests, such as the I/O ports, the timers or the SPI. The Interrupt request depends on the type of the peripheral: the I/O ports may have some bits configured to generate an interrupt, either on low-level, falling edge, rising edge, or both. The
timer may request an interrupt on timer overflow, external capture or output comparison. The
SPImay request an interrupt on end of transmission, etc.
Hardw are external sources
eg: I/O Ports,
Time r Input ca pture ...
Interrupt request
sent to the core
Special interrupt :The R eset V ector.
external : Reset pin,
internal :Power-on Re set,
W atchdog e nd of count
Hardw are internal so urces
eg:TimerOverflow,
Timer comparison,
SPI e nd of transmis si on...
Softwaresource:
TRAP interrupt
The various sources of interrupts
05-sourc
5.2.1 Interrupt sources and interrupt vectors
The interrupt sources are summarised in t he tables of the following paragraphs. There are
compared the interrupt-related information for the ST72251 and the ST72311. It is interesting
to see the differences.
Source BlockDescriptionRegisterVector addressPriority order
ResetResetN/AFFFEh- FFFFh
TrapSoftwareN/AFFFCh-FF FDh
Not usedFFFAh- FFFBh
Not usedFFF8h-FFF9h
EI0PA0-PA3N/AFFF6h-FFF7 h
EI1PF0-PF2N/AFFF4h-FFF5h
EI2PB0-PB3N/AFFF2h-FFF3 h
EI3PB4-PB7N/AFFF0h-FFF1 h
Not usedFFEEh-FFEFh
SPITr ansfer comp lete
Overrun
Not usedFFE4h-FFE5h
Not usedFFE2h-FFE3h
Not usedFFE0h-FFE1h
88/317
Lowest
5-Peripherals
As shown in the rightmost column of these tables, these sources are prioritized. This means
that if several interrupt request s are active at the same time, the interrupt controller will choose
toservice thehighestpriority request.When thisinterrupt isfully serviced,the nexthighestpriority request will be serviced.
Please note that the tables are not identical: the number of v ectors is different, and each
vector groups a different set of interrupt causes, in particular the external interrupts (EI) are
different. For other peripherals, such as the timer, SPI, etc. the grouping is identical, but the interrupt numbers and hence the priorities are different.
External interrupt inputs are further discussed in the paragraph about the parallel input-outputs.
5.2.2 Interrupt vectorization
When the core decides to grant an interrupt, it must know the address of the code to be executed when this eventoccurs. Thisis thepurpose of theinterrupt vectors.
The interrupt vectors are a table of 16-bit words in program memory thatcontain the address
of the beginning of the various interrupt service routines.
Accordingtothesource ofthe interrupt(I/O,timer,etc.), the corefetchesfroma predefined location inmemory,theaddressof the interrupt service routineespeciallywrittenforprocessing
that event. The vectors have a fixed location at the end of the addressing space. In addition to
the interrupt vectors, the vector table also contains the reset vector that is fetched when the
microcontroller is reset inorder to get the address of the beginningof the main program.
89/317
5 - Peripherals
An interruptis requested
Its relative pending bit is set
IstheIbitofthe
CC register reset ?
Yes
The core finishes itscurrent instruction.
PC, X, A,CC are pushed onto the stack.
The I bit is set.
The PC isloaded withthe addressof the interruptvector.
The interrupt program starts.
At the beginning of this program, you can
temporarily save data if needed, such as t he Y register.
You must restore them at the end.
Before returning, the pending bit must be cleared.
The iret instruction causes:
No
this interrupt will
be serviced when
the I bit is reset
- CC, A, X, PC to be popped from stack.
- The interruptedprogram to resume or another interrupt
program t o start.
The interrupt mechanism of the ST7 family
05-int
5.2.3 Global interrupt enable bit
RESET and T RAP (explained in the next paragraph) are non-miscible interrupt; the other
sources of interrupt may be inhibited as a whole thanks to the I bit of the condition c ode reg-
90/317
5-Peripherals
ister.When this bitis set,no interrupts are generated. However, the interruptrequests are not
forgotten; theywillbe processed as soon as theI bit is reset.
5.2.4 TRAP instruction
Inaddition tothehardware s ources,a special instruction, TRAP, produces the sameeffect as
an externally generated interrupt request, but under program control. Strange as this may
seems (interrupts are provided to handle unexpected events, or at least, events for which the
timeof occurrence is notknown), the TRAP instructionuses oftheinterruptmechanism within
the regular execution of the main program.
Thetrap instruction triggers interrupt processing regardless of the stateof the I bit in the ConditionCoderegister.
Anexample of the use of the TRAP instructionis the real-time debugger. W henthe user sets
a breakpoint somewhere in the program, the debugger replaces the instruction at which the
execution must stop with a TRAP instruction. The interrupt thus generated is processed by
displaying on the screen the state of the microcontroller at that precise time. However, other
uses of this instruction may be found as well.
5.2.5 Interrupt mechanism
5.2.5.1 Saving the interrupted program state
When the interrupt request triggers an interrupt, the first task of the core is to save its current
state so as it will be able to restore it after the interrupt processing is finished. This is done by
pushing all the core registers to the stack, namely the Program Counter, the X-register, t he
Accumulator and the Condition Code Register. It should be noted that the Y register is not
saved, for compatibility with the sta ndard instr uction set which the ST7 adheres to. If needed,
the Y register may be pushed explicitly to the stack at the beginning of the interrupt service
routine.
At this point (and with the restriction above mentioned about the Y register), the interrupt
service routine may execute freely. The status of the interrupted program is known and can be
restored when needed.
To protect the interrupt service routine from other interrupt requests, the I bit of the Condition
Code Register is then automatically set by hardware.
5.2.5.2 Interrupt service routine
When the processor has granted the interrupt request, and read the interrupt vector, it starts
executing the interrupt service routine. This routine is merely a segment of program, written
with exactly the same ease and constraints as the main program. It can be written using the
same languageand tools, orin anyother language.
91/317
5 - Peripherals
The interrupt s ervice routine is supposed to take the appropriate actions that will vary according to the interrupt source. For example, if an Input bit has changed its state, the service
routine maychange the state of an output bit; ifthe interrupt was generated by the timer, this
may produce the transmission of a byte by the SPI, etc. depending on the structure of the application as defined by the pr ogrammer.
Some interrupt vectors are commontoseveral interrupt sources (e.g.thetimersthathavefive
sources). In this case, the first task of the service routine must be to check which source has
requested the interrupt, before taking the appropriate action. This is done by testing the state
of the various bits in the peripheral’s Status Register.
Eventually, the service routine is finished. Then the core may return to the main program by
ecuting the IRET instruction.
5.2.5.3 Restoring the interrupted program state: The IRET instruction
As described above, an interrupt service routine looks a little bit like a subroutine. Like in a
subroutine, the return address is stored in the stack, and the execution of the RET instruction
returns to the calling program.
Here,morethingsareto be done before returning to the interruptedprogram. All the core registers have been pushed on granting the interrupt request (except the Y register). They must
now be restored, so that the ex ecution of the service routine will not leave any trace in the
core. This is the role of the IRET instruction.
The IRET instruction proceeds with popping off the stack all the data that had been pushed
previously, namelytheCondition Code (then the I bitis alsorestored), the Accumulator, the X
register and the Program Counter.
From this time on, execution of the interrupted program resumes.
5.2.6 Nesting the interrupt services
Some interrupts may require the quickest service possible, for example if they signal the availability of som e data th at it volatile, that is, will not remain for a long time. In such a case, the
fact that an interrupt service routine is not interruptible by default may be a problem, if the time
to service this interrupt is longer than the allowable latency for the interrupt requiring a quick
service. For so, it is possible to clear the global interr upt mask within an interrupt service ro utine.
At that time, one would probably like to restrain the interrupt request sources that may actually
interrupt the service routine in progress. Some prioritizing, here also, is needed. But this is not
the same priority mechanism as that mentioned above.
This priority mentioned about the interrupt sources is only taken into account when the core
has to decide between two concurrent requests. It does not apply when interrupts are re-ena-
92/317
5-Peripherals
bled during the service of an interrupt. In this case, all interrupts are validated and the service
routine may be itself interrupted by a request having a lower priority than it s own. If the service
routine must be interruptible only by certain requests and not others, the routine must first
clear the interrupt enable flags of all peripherals that are not allowed at that time, then clear the
global interrupt mask. It is wise to save the value of these flags before clearing them, if several
interrupts may interrupt each other and each selects a different set of allowed interrupt requests.
Another maskable interrupt (nested interrupt) is
serviced, within the current one, whatever its priority
A maskable
interrupt occurs
interrupt # j
Main :bit I=0
The I bit is set by hardware
** Note: before resetting the I bit, you should clear the pending bit that started the current
interrupt, otherwise an endless recursive interrupt service call will be performed !
interrupt # k
interrupt # j
Here, the programmer
resets theI bit **
Without the intervention
of the programmer, bit I =0;
the interrupt # j can again
be interrupted
Main :bit I=0
Nested interrupts
05-nest
This core is perfectly well able to handle nested interrupt servicing, with a limited nesting
depth.However,care must be taken about twothings:
The size of the stack. Each interrupt pushes five bytes on the stack, plus the interrupt service
routine maypush some bytesto protect any data in memory thatmay be usedglobally.
Theproblemof atomicityas explained inChapter 2. If an interruptibleserviceroutine handles
multi-byte data, it must take into account the possibility of being interrupted in the mi ddle of a
data read or write with theriskof data incoherence.
The applica tions describ ed in Chapters 9 and 10 illustrate several uses of interrupts, in conjunction with various peripherals.
93/317
5 - Peripherals
5.3 PARALLEL INPUT-OUTPUT PORTS
The purpose of the parallel input-outputs is basically to make binary signals either get into or
out of the core. For the core and once initialized, they appear as a memory location that can
be written or read. But in many cases, direct byte-wide input-output is not sufficient. Bit-oriented I/O is often required in s ystems driven by a microcontroller. This implies individually
reading or writing any of the bits of each port. In addition, some of the external signals of the
other peripherals (timers, UARTs, etc.) use an external connection withoutincreasing the pin
count by diverting some bits from the parallel I/O ports(alternate function).
The ST7 offers a very flexible feature on its parallel I/O that it shares with many other STMicroelectronics families: each bit can be independently configured as either an input with two
options (with or without pull-up resistor), or an output with also two options (open-drain or
push-pull).
Some pins are a lso available with high-current sink drivers, like Port A of the ST72251. These
pin may sink up to 15 mA, and Port A has only one output configuration: open drain.
Selecting these options is done through registers that are associated with each port. They are
memory-mapped, and are named Option Register (OR) and Data Direction Registers (DDR).
Some pins configured as input may also be connected to the external interrupt circuitry when
the corresponding bit of the Option Register is set. This allows an interrupt request to be triggered when the state of the pin goes low, rises, or falls, as configured in the Miscellaneous
Register already mentionedat the beginningofthis chapter and detailedon the diagrams that
follow. However some I/O pins can’t be interrupt inputs. See the tables below for the 72251
and the 72311 I/O configurations.
5.3.1 ST72251 I/O Ports
All bits of Port A are configurable as interrupt inputs when the corresponding bit of OR is set.
The option for the edge and level of these inputs is set by the bits PEI0 and PEI1 (external interrupt polarity option) of the miscellaneous register. The external interrupt source is EI0 and
its corresponding interrupt vector isin FFFAh-FFFBh.
Allbits of PortsB andC are configurable as interruptinputs whenthecorrespondingbit of OR
is set. The option for the edge and level of these inputs is set by the bits PEI2 and PEI3 in the
same register. The external interrupt source is EI1 and its corresponding interrupt vector is in
FFF8h-FFF9h.
94/317
Table 3. ST72251 I/O configuration
5-Peripherals
Port
Port A:
PA0-PA7
Port B:
PB0-PB7
Port C:
PC0-PC5
Input configuration
(DDR=0)
OR = 0OR = 1
Floating
Floating
Floating
Floating with
interrupt
Pull-up with
interrupt
Pull-up with
interrupt
External interrupt
source,
Polarity option bits
EI0
PEI0-PEI1
EI1
PEI2-PEI3
EI1
PEI2-PEI3
Output configuration
(DDR=1)
OR = 0OR = 1
True open
drain
Open drainPush-pull
Open drainPush-pull
Reserve d
In addition, some pins also serve as inputs for other peripherals, or may be held from their
normal output function and be taken as the output pins of some peripherals if those peripherals are specially configured to do so by setting a bit in one of their control registers. As an example, pin PB0 is also used as the capture input of Timer A, and pin PC1 is the output compare 1 pin of Timer B if the OC1E bit of register TCR2 of this timer is set. T he interaction with
the pins and the required precautions are discussed, when needed, in the paragraph related
to the corresponding peripheral.
Table 4. ST72251 I/O alternate functions
I/O pinAlternate function 1Alternate function 2
PA4SLC(I²C)
PA6SDA(I²C)
PB0ICAP1_A(Timer A)
PB1OC MP1_A(Timer A)
PB2ICAP2_A(Timer A)
PB3OC MP2_A(Timer A)
PB4M OSI(SPI)
PB5M ISO(SPI)
PB6SCK(SPI)
PB7SS(SPI)
PC0ICAP1_B(Timer B)Ain0(ADC)
PC1OCMP1_B(Timer B)Ain1(ADC)
PC2CL KOUT(Internal clock out)Ain2(ADC)
PC3ICAP2_B(Timer B)Ain3(ADC)
PC4OCMP2_B(Timer B)Ain4(ADC)
PC5EXTCLK_A(Timer A)Ain5(ADC)
Note: All pins of port C have two alternate functions.
95/317
5 - Peripherals
EI1: Ports B & C
vector address:
FFF8-FFF9
PEI3
PEI2
EI0: PortA
vector address:
FFFA-FFFB
PEI1 PEI0MC0
--
SMS
ST72251
00
10
01
11
Falling edge and low level (reset state)
Falling edge only
Rising edge only
Rising and falling edge
External interrupt polarit y Options EI0 and EI1
of the Miscellaneous register
05-EI251
5.3.2 ST72311 I/O Ports
Bits 0 to 3 of Port A andbits0 to 2 of Port F of are configurable as interrupt inputs. The option
for the edge and level of these inputs is set by bits PEI0 and PEI1 (external interrupt polarity
option) inthemiscellaneous register.Theinterruptvector for PortA isFFF6-FFF7,and FFF4FFF5for PortF.
All bits of Port B are configured by the PEI2 and PEI3 bits in the same register. However, bits
0 to 3 are assigned to the v ector at FFF2-FFF3, while bits 4 to 7 are assigned to t he vector at
FFF0-FFF1.
Note: PB5 to PB7 are not available on the smaller packages (J series).
Note: PA0-PA2, PB5-PB7, PD6-PD7 and PE4-PE7 are no t available on the ST72311 J version.
In addition, some pins also serve as inputs for other peripherals, or may be held from their
normal output function and be taken as the output pins of some peripherals if those peripherals are specially configured to do so by setting a bit in one of their control registers. As an example, the PC2 pin is also used as the c apture input of Timer A, and pin PC1 is the output
compare 1 pin of Timer B if the OC1E bit in the TCR2 register of this timer i s set. The interaction withthepins andtherequired precautionsarediscussed,whenneeded,intheparagraph
related t o the corresponding peripheral.
97/317
5 - Peripherals
Table 6. ST72311N I/O alternate functions
I/O pinAlternate function 1
PC0OCMP2_B(Timer B)
PC1OCMP1_B(Timer B)
PC2ICAP2_B(Timer B)
PC3ICAP1_B(Timer B)
PC4MISO(SPI)
PC5MOSI(SPI)
PC6SCK(SPI)
PC7SS(SPI)
PD0Ain0(ADC)
PD1Ain1(ADC)
PD2Ain2(ADC)
PD3Ain3(ADC)
PD4Ain4(ADC)
PD5Ain5(ADC)
PD6Ain6(ADC)
PD7Ain7(ADC)
PE0TDO(SCI)
PE1RDI(SCI)
PF0CLK OUT(Internal clock out)
PF4OC MP1_A(Timer A)
PF6ICAP1_A(Timer A)
PF7EXTCLK_A(TimerA)
Note:None of thepins have two alternate functions, unlike the ST72251.
Since the pins can produce interrupt requests in s omemodes,youmusttakecare, when programming the port configuration registers, to perform the transisitons in a particular order as
specifiedin the transition map in the datasheet.
All the applications described in this book (Chapters 6, 7, 9 and 10) give examples of using the
parallel ports in various combinations.
98/317
5-Peripherals
EI2: Pb0-Pb3
Vector address:
FFF2-FFF3
EI3: Pb4-Pb7
Vector address:
FFF0-FFF1
PEI3
PEI2
EI0: Pa0-Pa3
Vector address:
FFF6-FFF7
EI1: Pf0-Pf2
Vector address:
FFF4-FFF5
MC0
PEI1 PEI0
--
SMS
ST72311
00
10
01
11
Fallingedgeand low level(reset state)
Falling edge only
Rising edgeonly
Rising and falling edge
External interrupt polarity Options EI0, EI1, EI2 and EI3
of the Miscellaneous register
05-EI311
Note: Although the pinsoftheports may beindividually selectedasinterrupt inputs,thedirec-
tion of the edge or the active level is selected by groups in the Miscellaneous Register. This
implies that the electrical schematic takes this into account, and that signals that are risingedge active be wired to a different group from those either falling-edge active or level-active
5.4 WATCHDOG TIMER
5.4.1 Aim of the watchdog
Thewatchdogtimerisasafetydeviceratherthan aperipheral.Its purpose is not to handleexternal events, but to detect and correct internal malfunctions. However, it is implemented just
like a peripheral, andthis is why it has been included in this chapterwith the peripherals.
A microcontroller, or any programmed machine, is not an electronic brain, in spite of how it
was first introduced. Rather, it is an automaton that has a precise job to perform, taking into
account events and conditions that are considered when the program is written. However, not
all events can be taken into account; some occurrences are even neglected, since they are
supposed to never happen. Rightly or wrongly, the code is thus made shorter. If, however, either because the programmer made a mistake or because a hardware failure produced an un-
99/317
5 - Peripherals
foreseenevent, the program may be fooled and the wholeapplicationmay fail to work or even
produce harmful actions.
To prevent this, two actions may be taken.
Write better code. Check what happens if a neglected condition arises. Lead the execution to
a recoveryroutinein suchan event. Inshort,take all precautionsto preventtheprogram from
crashing in any event. This is actually a requirement, not a choice. But still, things may happen
that are totally out of the control of the author of the program. For example, an electromagnetic
aggression or a power brownout to the product that is controlled by the microcontroller. Then,
the proper working of the microcontroller may not be guaranteed and the system fails. This is
when the watchdog can playitspart.
Methods of detecting processor failure by electronic means are virtually non-existant. A popular method re lies on a timer that acts like an alarm-clock. The clock is wound up fo r a c ertain
delay. If it has not been rewound b eforetheexpiration of this delay, the clockperform a hardware reset to the microcontroller.
It is up to the program to periodically rewind the clock (the watchdog timer) to indicate that it is
still alive. A ctually, it is not a full protection, since some parts of the program may crash while
the part that has been elected to re wind the timer still func tions. It is up to the wise programmer to find the program segment that is very unlikely to still work while some other part
has crashed. Well implemented, this method gives rather good results. Of course, resetting
the program is not a good way to recover from a fault, since the crash may have sent commands to the external world that are themselves faulty. The watchdog timer is actually a last
ditch safe ty device, somewhat like a lifeboat in a ship wreck.
5.4.2 Watchdog Description
The ST7 watchdog timer is controlled by a register that includes two control bits (bits 7 and 6)
and six time-setting bits.
The general control bit, bit7, starts the watchdog activity if it is set to one. From that time on,
itcontinues to work, evenif one triestoreset itto zero.This isa safety measurethatprevents
the program from accidentally stopping it. The presence of this bit corresponds to what is commercially known as the “software activated watchdog”. This is the only option available for the
72251.
100/317
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.