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
Loading...
+ 287 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.