ST ST7 User Manual

ST7
8-BIT MCU FAMILY
USER GUIDE
JANUARY 1999
1
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.
Table of Contents
1INTRODUCTION........................................................12
1.1 WHOISTHISBOOKWRITTENFOR? .................................12
1.2 ABOUTTHEAUTHORS.............................................12
1.3 HOWISTHISBOOKORGANIZED? ...................................12
1.4 WHYAMICROCONTROLLER?.......................................13
1.4.1 Electroniccircuitry......................................................15
1.4.2 Choiceofmicrocontrollermodel...........................................17
1.4.3 Choiceofdevelopmenttools .............................................17
2HOWDOESATYPICALMICROCONTROLLERWORK? .......................19
2.1 THE CENTRAL PROCESSING UNIT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.2 HOW THE CPU AND ITS PERIPHERALS MAKE UP A SYSTEM . . . . . . . . . . . . 21
2.2.1 CPU ................................................................21
2.2.2 Memory..............................................................21
2.2.3 Input-Outputs . . . ......................................................23
2.2.4 InterruptController .....................................................24
2.2.5 Bus .................................................................25
2.2.6 ClockGenerator .......................................................25
2.2.7 ResetGenerator.......................................................25
2.3 CORE ...........................................................25
2.3.1 ArithmeticandLogicUnit(ALU) ...........................................25
2.3.2 Program Counter ......................................................26
2.3.3 InstructionDecoder.....................................................26
2.3.4 StackPointer .........................................................26
2.4 PERIPHERALS ....................................................27
2.4.1 Parallel Input-Outputs ...................................................27
2.4.2 AnalogtoDigitalConverter...............................................28
2.4.3 ProgrammableTimer ...................................................28
2.4.4 SerialPeripheralInterface ...............................................28
2.4.5 Watchdog Timer . ......................................................28
2.5 THEINTERRUPTMECHANISMANDHOWTOUSEIT ....................29
2.5.1 Interrupthandling ......................................................29
2.5.1.1 Hardware mechanism . .............................................31
2.5.1.2 Hardwaresourcesofinterrupt ........................................31
2.5.1.3 Global interrupt enable bit ...........................................32
3/317
1
Table of Contents
2.5.1.4 Softwareinterruptinstruction .........................................32
2.5.1.5 Savingthestateoftheinterruptedprogram .............................32
2.5.1.6 Interruptvectorization ..............................................32
2.5.1.7 Interruptserviceroutine.............................................34
2.5.1.8 InterruptReturninstruction ..........................................34
2.5.2 Softwareprecautionsrelatedtointerruptserviceroutines .......................34
2.5.2.1 SavingtheYregister ...............................................34
2.5.2.2 Managing the stack . . . .............................................35
2.5.2.3 Resetting the hardware interrupt request flags ...........................35
2.5.2.4 Makinganinterruptserviceroutineinterruptible ..........................35
2.5.2.5 Datadesynchronizationandatomicity..................................36
2.5.3 Conclusion: the benefits of interrupts . . . ....................................38
2.6 AN APPLICATION USING INTERRUPTS : A MUL TITASKING KE RNEL . . . . . . . 39
2.6.1 Pre-emptivemultitasking ................................................39
2.6.2 Cooperative multitasking . . . .............................................41
2.6.3 Multitaskingkernels ....................................................42
2.6.3.1 Advantagesofprogrammingwithamultitaskingkernel ....................42
2.6.3.2 Thetaskdeclarationandallocation ....................................42
2.6.3.3 Tasksleepingandwaking-up ........................................42
2.6.3.4 Multitasking kernel overhead .........................................43
3PROGRAMMINGAMICROCONTROLLER...................................45
3.1 ASSEMBLY LANGUAGE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.1.1 When to use assembly language ..........................................45
3.1.2 Development process in assembly language .................................46
3.1.2.1 Assembly language . . . .............................................47
3.1.2.2 Assembler .......................................................48
3.1.2.3 Linker...........................................................49
3.1.2.4 Theprojectbuilder/makeutility .......................................51
3.1.2.5 EPROMburners ..................................................52
3.1.2.6 Simulators .......................................................53
3.1.2.7 In-circuitemulators ................................................54
3.2 CLANGUAGE.....................................................55
3.2.1 WhyuseC? ..........................................................55
3.2.2 Tools used with C language . .............................................57
3.2.3 Debugging in C . . ......................................................58
3.3 DEVELO P MENT CHAI N S UMMARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
3.4 APPLICATIONBUILDERS...........................................61
317
3.5 FUZZY-LOGICCOMPILERS .........................................61
4/317
1
Table of Contents
4ARCHITECTUREOFTHEST7CORE.......................................62
4.1 POSITIONOFTHEST7WITHINTHESTMCUFAMILY....................62
4.2 ST7CORE........................................................63
4.2.1 Addressingspace......................................................65
4.2.2 Internalregisters.......................................................65
4.2.2.1 Accumulator(A)...................................................65
4.2.2.2 Condition Code register (CC) ........................................65
4.2.2.3 Index registers (X and Y) ............................................67
4.2.2.4 Program Counter (PC) . .............................................68
4.2.2.5 StackPointer(SP).................................................68
4.3 INST RUCT ION SET AN D ADDRESSING MODES . . . . . . . . . . . . . . . . . . . . . . . . 70
4.3.1 A word about mnemonic language .........................................70
4.3.2 Addressingmodes .....................................................72
4.3.3 Instructionset .........................................................73
4.3.4 Coding of the instructions and the address ..................................74
4.3.4.1 Prefixbyte .......................................................74
4.3.4.2 Opcodebyte .....................................................75
4.3.4.3 The addressing modes in detail . . . ....................................77
4.4 ADVANTAGES OF THE ST7 INSTRUCTION SET AND ADDRESSING MODES 82
5PERIPHERALS.........................................................84
5.1 CLOCKGENERATOR ..............................................84
5.1.1 ST72251 Miscellaneous Register ..........................................84
5.1.2 ST72311 Miscellaneous Register ..........................................85
5.2 INTERRUPT PROCESSIN G . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
5.2.1 Interruptsourcesandinterruptvectors......................................86
5.2.1.1 InterruptssourcesfortheST72251 ....................................87
5.2.1.2 InterruptsourcesfortheST72311.....................................88
5.2.2 Interruptvectorization ...................................................89
5.2.3 Globalinterruptenablebit................................................90
5.2.4 TRAPinstruction.......................................................91
5.2.5 Interrupt mechanism ....................................................91
5.2.5.1 Savingtheinterruptedprogramstate ..................................91
5.2.5.2 Interruptserviceroutine.............................................91
5.2.5.3 Restoringtheinterruptedprogramstate:TheIRETinstruction ...............92
5.2.6 Nestingtheinterruptservices.............................................92
5.3 PARALLELINPUT-OUTPUTPORTS ..................................94
5/317
1
Table of Contents
5.3.1 ST72251 I/O Ports .....................................................94
5.3.2 ST72311 I/O Ports .....................................................96
5.4 WATCHDO G TIMER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
5.4.1 Aim of the watchdog ....................................................99
5.4.2 Watchdog Description ..................................................100
5.4.3 Using the Watchdog to protect an application ...............................103
5.5 16-BITTIMER ....................................................103
5.5.1 Timerclock ..........................................................104
5.5.2 Free running counter ..................................................105
5.5.2.1 Reading the free running counter . ...................................105
5.5.2.2 Resetting the free running counter ...................................106
5.5.2.3 TheTOFflag ....................................................107
5.5.3 Input capture operation .................................................108
5.5.4 Output compare operation . . ............................................110
5.5.5 One-pulsemode......................................................113
5.5.6 Pulse-Width Modulation mode ...........................................115
5.6 ANALOGTODIGITALCONVERTER .................................117
5.6.1 Description ..........................................................117
5.6.2 UsingtheAnalogtoDigitalConverter......................................118
5.6.3 Theproblemoftheconverter'saccuracy ...................................119
5.6.4 Using the ADC to convert positive and negative voltages; increasing its resolution . .120
5.6.4.1 Measuring negative and positive voltages ..............................120
5.6.4.2 Increasingtheresolution ...........................................121
5.6.4.3 ApplicationExamples .............................................124
5.7 SERIALPERIPHERALINTERFACE ..................................125
5.8 SERIALCOMMUNICATIONINTERFACE ..............................128
5.8.1 Bit rate generator .....................................................128
5.8.2 Send and receive mechanism ...........................................129
5.8.3 Statusregister........................................................132
5.8.4 ControlRegister2.....................................................132
5.8.5 Using the Wake-Up feature in a multiprocessor system ........................133
5.8.6 Handling the interrupts .................................................133
6STMICROELECTRONICSPROGRAMMINGTOOLS ..........................135
6.1 ASSEMBLER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .135
6.1.1 Anoverviewoftheassemblerfunction.....................................135
6.1.2 Instructioncoding .....................................................137
6/317
1
317
Table of Contents
6.1.3 Declaringvariables....................................................138
6.1.4 Declaringconstants ...................................................140
6.1.4.1 Constantdata ...................................................140
6.1.4.2 Symboldefinition .................................................141
6.1.5 Relocation commands .................................................142
6.1.5.1 Whatisrelocation? ...............................................142
6.1.5.2 Segmentdefinition................................................143
6.1.5.3 UsingtheSegmentdirectiveinthesourcefile...........................145
6.1.5.4 Segmentallocation ...............................................146
6.1.5.5 Initializationofvariablesatpower-on..................................148
6.1.5.6 Referencing symbols and labels between modules .......................151
6.1.6 Conditional assembly ..................................................154
6.1.7 Macros .............................................................156
6.1.7.1 Replaceableparameters ...........................................157
6.1.7.2 Localsymbols ...................................................158
6.1.7.3 Conditional statements in macros . ...................................160
6.1.8 Some miscellaneous features ............................................162
6.1.8.1 EQUandCEQUpseudo-ops........................................162
6.1.8.2 #DEFINE pseudo-op . . ............................................162
6.1.8.3 Numberingsyntaxdirectives ........................................163
6.1.9 Objectandlistingfiles..................................................163
6.1.9.1 Objectfiles......................................................164
6.1.9.2 Listingfiles......................................................164
6.2 LINKERANDASCII-HEXCONVERTER ...............................165
6.2.1 Thelinkingprocess....................................................165
6.2.2 Hexfiletranslator .....................................................167
6.2.3 The back-annotation pass of the assembler .................................168
6.3 INSTALLINGWINEDITANDTHESOFTWARETOOLS ...................168
6.3.1 WinEdittexteditor.....................................................168
6.3.1.1 InstallingWinEdit .................................................168
6.3.1.2 ConfiguringWinEdit...............................................169
6.3.2 InstallingtheSTMicroelectronicsSoftwareTools.............................169
6.4 BUILDINGADEMONSTRATIONPROGRAM ...........................170
6.4.1 Purposeofthedemonstrationprogram ....................................170
6.4.2 Inventoryoftheprogramfiles............................................170
6.4.3 Descriptionoftheprogramfiles ..........................................171
6.4.3.1 The PROJECT.WPJfile ..........................................171
6.4.3.2 The main source file,
MAIN.ASM and the timer source file, TIMER500.ASM . . .
173
6.4.3.3 The REG72251.ASM file andthe REGISTER.INC file .................176
6.4.3.4 The
MAP72251.ASM file .........................................178
7/317
1
Table of Contents
6.4.3.5 The CATERPIL.BAT file ..........................................179
6.4.4 Using WinEdit to change and compile the files ...............................180
7DEBUGGERANDPROMPROGRAMMERTUTORIALFORST72251 ............183
7.1 STMICROELECTRONICS HARDWARE TOOLS . . . . . . . . . . . . . . . . . . . . . . . . . 183
7.1.1 EPROMProgrammingBoards ...........................................183
7.1.2 StarterKits ..........................................................184
7.1.3 DevelopmentKits .....................................................184
7.1.4 Emulators ...........................................................184
7.2 EPROMPROGRAMMERBOARDS ...................................184
7.2.1 EPROMprogrammerInstallation .........................................185
7.2.2 UsingtheEPROMERsoftware...........................................185
7.3 EMULATORANDDEBUGGER ......................................189
7.3.1 Introducing the emulator and the debugger .................................189
7.3.2 Installing the emulator and the debugger ...................................189
7.3.3 Using the debugger ...................................................193
7.3.3.1 Loading the application ............................................193
7.3.3.2 Running the application ............................................195
7.3.3.3 Watchingtheregistersandvariables..................................195
7.3.3.4 UsingInspectandWatch...........................................197
7.3.3.5 Usingbreakpoints ................................................199
7.3.3.6 Watchingthecontentsofthestack ...................................200
7.3.3.7 Watchingtheexecutiontrace .......................................201
7.3.3.8 Morefeaturestocomelater.........................................202
7.4 PURPOSEOFTHETUTORIAL ......................................202
7.5 SCHEMATICDRAWINGOFTHEPRINTEDCIRCUITBOARD .............204
7.6 DEVELOPING THE PROGRAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
7.6.1 Peripherals used to implement the solution .................................204
7.6.2 Thealgorithmofeachtask ..............................................205
7.6.3 AsimplemultitaskingkernelfortheST7 ...................................206
7.6.3.1 StartTasks routine ...............................................206
7.6.3.2 The
7.6.4 Thesourcecodeoftheapplication........................................211
7.6.4.1 Main file (
7.6.4.2 ADC source file(
7.6.4.3 Kernel source file (
Yield routine.................................................208
Multitsk.a sm) ...........................................212
Acana.asm) .......................................216
Littlk.asm)..................................217
317
7.7 RUNNING THE APPLICATION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .219
8/317
1
Table of Contents
7.8 SUMMARY REMARKS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
8CLANGUAGEANDTHECCOMPILER ....................................221
8.1 CLANGUAGEEXTENSIONSFORMICROCONTROLLERS ...............221
8.2 DESCRIPTION AND INSTALLATION OF THE HICROSS TOOL CHAIN . . . . . . 222
8.3 USINGTHECCOMPILER ..........................................226
8.3.1 Memoryallocation.....................................................226
8.3.1.1 Read-only constants . . ............................................227
8.3.1.2 EEPROMnon-volatilestorage.......................................228
8.3.1.3 PageZerovariables...............................................229
8.3.1.4 Far and near pointers . ............................................229
8.3.2 Initializationofvariablesandconstantvariables..............................230
8.3.3 Inputs and outputs ....................................................230
8.3.3.1 First method: using macros .........................................231
8.3.3.2 Second method: defining variables ...................................231
8.3.4 Interrupthandling .....................................................232
8.3.5 Limitations put on the full implementation of C language .......................232
8.4 USING THE ASSEMBLER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .233
8.4.1 UsingIn-lineassemblerstatementswithinaCsourcetext .....................233
8.4.1.1 Single-statementassemblerblock....................................233
8.4.1.2 Multiple-statementassemblerblock ..................................234
8.4.2 UsingtheHiwareassembler.............................................235
8.5 USINGTHELINKER...............................................235
8.6 USING THE EPROM BURN ER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 37
8.7 PROJECTDIRECTORYSTRUCTURE ................................239
8.7.1 Configdirectory.......................................................239
8.7.2 Objectdirectory.......................................................241
8.7.3 Sourcesdirectory .....................................................241
8.8 HINTSONCWRITINGSTYLEFORTHEST7 ..........................242
8.8.1 Accessingindividualbitsinregisters ......................................242
8.8.2 Settingconfigurationregisters ...........................................245
8.8.3 Usingmacrostodefineexternaldevices ...................................245
8.8.4 Optimizingresourceusage..............................................246
8.8.4.1 Define a function when a group of statements is repeated several times ......247
8.8.4.2 Useshiftsinsteadofmultiplicationanddivision..........................247
8.8.4.3 Limitthesizeofvariablestotheveryminimum..........................248
9/317
Table of Contents
8.9 CONCLUSION....................................................248
9 A CARR IER- CURRENT SYSTEM FOR DOMESTIC REMOTE CO NT ROL . . . . . . . . . 249
9.1 CARRIER CURRENT CONTROL AND THE X-10 STANDARD . . . . . . . . . . . . . 250
9.2 TRANSMITTER ...................................................255
9.2.1 Instructionsforuse ....................................................255
9.2.2 Descriptionoftheelectroniccircuit........................................255
9.2.3 Descriptionofthesoftware..............................................259
9.2.3.1 Themainprogram ................................................259
9.2.3.2 TimerACaptureinterruptserviceroutine ..............................262
9.2.3.3 TheTimerBoverflowinterruptserviceroutine ..........................269
9.3 RECEIVER ......................................................272
9.3.1 Instructionsforuse ....................................................272
9.3.2 Electroniccircuitry.....................................................272
9.3.3 Software ............................................................276
9.3.3.1 Interruptfunctions ................................................276
9.3.3.2 Mainprogram....................................................279
9.4 CONCLUSION....................................................285
10SECONDAPPLICATION:ASAILINGCOMPUTER ..........................286
10.1THEORYOFTHECOMPUTATION ...................................288
10.2INTERFACINGTHEMEASUREMENTDEVICES ........................291
10.2.1 Frequency-type devices: speedometer and wind gauge .......................291
10.2.1.1 Interfacing the speedometer ........................................291
10.2.1.2 Interfacing the wind gauge ..........................................291
10.2.1.3 Using a common timer for both speed measurement devices ...............292
10.2.2Interfacingtheweathervane ............................................293
10.3INTERFACINGTHEDISPLAY .......................................294
10.3.1Displaycircuit ........................................................295
10.3.2Push-buttoncircuit ....................................................298
10.3.3LEDcircuit ..........................................................299
10.4INTERFACINGTHEOPTIONALPERSONALCOMPUTER ................299
10.5PROGRAMARCHITECTURE........................................300
10.5.1 Reading and conversion of the speeds . ...................................300
10.5.2Refreshingofthedisplay ...............................................302
317
10/317
Table of Contents
10.5.3Pollingthepush-buttons................................................304
10.5.4 Reading and filtering the wind direction . ...................................305
10.5.5Theperiodicinterruptserviceroutine ......................................306
10.5.6Computationoftheresults ..............................................307
10.5.7 Handling of the serial interface ...........................................309
10.5.8 Initialization of the peripherals and the parameters . ..........................310
10.6 MEMORY ALLOCATION AND COMPILE AND LINK OPTIONS . . . . . . . . . . . . 3 12
10.7CONCLUSION....................................................314
11SOMELASTREMARKS ...............................................315
11/317
1 - Introduction

1 INTRODUCTION

1.1 WHO IS THIS BOOK WRITTEN FOR?

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 au­tomation 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 as­pects.
Chapters 4 through 7 describe the ST7 and its programming tools, taking only assembly lan­guage into account.
Chapter 8 discusses the C language and techniques forusing the C Compiler for the ST7 mi­crocontroller, its strengths and also its limitations.
Chapters 9 and 10 describe application projects using the ST72251 and the ST72311 mem­bers 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 com­petes 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 type Advantages Drawbacks
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 sys­tems
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 applica­tions 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. Ac­tually, 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 com­ponents, to adapt the electric signals to the input-output pins of the microcontroller, or addi­tional 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,andtocarefullyse­lect each one to get the best value. In order to satisfy this requirement, the various chip man­ufacturers 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 ex­ternal 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 pro­grammable 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 riph­erals 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 rec­ognized 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 an­other one.
Thus a certain margin must be considered, or there would be a risk that some time in the de­velopment process that one comes to the conclusion that the selected microcontroller is un­suitable 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 availa­bility 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 addi­tions, 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, itiscurrentpracticetoselectamodelwithexcesspowerinordertoguaranteesuc­cessful 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 dia­gram 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 compu­tational 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 out­side world.
The CPU is the part of a microcontroller that corresponds to what is us ually called a micro­processor. 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 al­lows 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 appli­ances. 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, re­spondstothe 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 proc­essed in parallel, thus multiplying the processor throughput by the number of these bits proc­essed at the same time.
The first microprocessors, historically, were four-bit machines. There are still four-bit micro­controllers 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 bits Lowest Watches,calculators, TV remote control,washing machines. 8 bits Low Industrial products and home computers in the '80s; most
microcontrollers todaywherelittlenumeric computationisrequired.
16 bits Medium As a microprocessor, the former PCs; as a microcontroller,
industrial and automotive products used in car bodies.
32 bits High All PCs use this size of microprocessor today; some
microcontrollers are also becoming available commercially such as automotive injec tion calculators.
64 bits Highest Only 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 com­ponents:
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 initia­tive.
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 pro­gram, 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 ad­dressable space. The program and the data are only distinguished by the address they oc­cupy 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 pro­gram from accidentalchanges and doubling the total addressing range. Examples of t his ar­chitecture 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 input­output 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 strin­gent 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 de­scribed later in this chapter. Interrupts are the most common means of altering the normal course oftheprogram, whenanunexpectedevent(oranexpectedone but occurringatanun­expected time) occurs. It may be more or less complicated according to the features it pro­vides.
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 re­quests 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 pre­cise 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 in­dicating (among other things) whether the result was zero, negative, or overflowed the ca­pacity 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 pro­gram flow disruptions, where the main flow of the program is temporarily put aside and re­sumed 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 me­hanism, 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 pro­gram 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 proper­ties 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 pe­ripherals 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 di­agram, 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 pro­gram 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 ei­ther 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 circuitde­signer 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 to­gether.
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 inter­ference 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 ap­plications 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 gen­eratesa hardware reset. This restoresthe system to the state itwas at power up.
Tousethewatchdogtimerproperly, the program mustreset itattheappropriatetime,in a pe­riodicmanner.To do this efficiently requiressome care.Aword of adviceisgiven onthis sub­ject 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 ap­proach 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 pro­gram 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 in­coming 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