Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (3 votes)
184 views

Embedded Microcomputer Systems Real Time Interfacing 3rd Edition Jonathan W. Valvano 2024 scribd download

Interfacing

Uploaded by

sieglelisiv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
184 views

Embedded Microcomputer Systems Real Time Interfacing 3rd Edition Jonathan W. Valvano 2024 scribd download

Interfacing

Uploaded by

sieglelisiv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Visit https://ebookgate.

com to download the full version and


explore more ebooks

Embedded Microcomputer Systems Real Time Interfacing


3rd Edition Jonathan W. Valvano

_____ Click the link below to download _____


https://ebookgate.com/product/embedded-microcomputer-
systems-real-time-interfacing-3rd-edition-jonathan-w-
valvano/

Explore and download more ebooks at ebookgate.com


Here are some recommended products that might interest you.
You can download now and explore!

Real Time Embedded Components and Systems 1st Edition Sam


Siewert

https://ebookgate.com/product/real-time-embedded-components-and-
systems-1st-edition-sam-siewert/

ebookgate.com

Real Time UML Workshop for Embedded Systems 2nd Edition


Bruce Powel Douglass

https://ebookgate.com/product/real-time-uml-workshop-for-embedded-
systems-2nd-edition-bruce-powel-douglass/

ebookgate.com

Real Time Systems Design and Analysis 3rd Edition Bruce


Fraser

https://ebookgate.com/product/real-time-systems-design-and-
analysis-3rd-edition-bruce-fraser/

ebookgate.com

Linux for embedded and real time applications 2nd Edition


Doug Abbott

https://ebookgate.com/product/linux-for-embedded-and-real-time-
applications-2nd-edition-doug-abbott/

ebookgate.com
Real time embedded multithreading using ThreadX Edward L
Lamie 2nd ed Edition Edward L. Lamie

https://ebookgate.com/product/real-time-embedded-multithreading-using-
threadx-edward-l-lamie-2nd-ed-edition-edward-l-lamie/

ebookgate.com

Real Time Systems Scheduling Analysis and Verification 1st


Edition Albert M. K. Cheng

https://ebookgate.com/product/real-time-systems-scheduling-analysis-
and-verification-1st-edition-albert-m-k-cheng/

ebookgate.com

A Real Time Approach to Process Control 3rd Edition


William Y. Svrcek

https://ebookgate.com/product/a-real-time-approach-to-process-
control-3rd-edition-william-y-svrcek/

ebookgate.com

Embedded Systems Design 2nd Edition Steve Heath

https://ebookgate.com/product/embedded-systems-design-2nd-edition-
steve-heath/

ebookgate.com

Real Time Systems Design and Analysis 4th Edition Tools


for the Practitioner Phillip A. Laplante

https://ebookgate.com/product/real-time-systems-design-and-
analysis-4th-edition-tools-for-the-practitioner-phillip-a-laplante/

ebookgate.com
Relationship between bits, bytes and alternatives as units of precision Common digital logic gates

Binary bits Bytes Alternatives Chip Function

8 1 256 ‘00 2 input NAND


10 1024 ‘02 2 input NOR
12 4096 ‘04 Digital NOT
16 2 65536 ‘05 Open collector NOT
20 1,048,576 ‘06 High voltage open collector NOT
24 3 16,777,216 ‘07 High voltage open collector buffer
30 1,073,741,824 ‘08 2 input AND
32 4 4,294,967,296 ‘10 3 input NAND
n [[n/8]] 2n ‘11 3 input AND
‘14 Schmitt trigger NOT
‘20 4 input NAND
Definition of decimal digits as a unit of precision ‘21 4 input AND
‘30 8 input NAND
Decimal digits Alternatives ‘32 2 input OR
3 1000 ‘125 4 tristate buffers
312 2000 ‘138 3 to 8 line decoder
314 4000 ‘139 2 to 4 line decoder
4 10000 ‘148 8 to 3 line encoder
412 20000 ‘163 4-bit counter
414 40000 ‘164 8-bit shift register
5 100000 ‘165 8-bit shift register
n 10n ‘244 8 tristate buffers
‘245 8 bidirectional drivers
‘374 8 D flip-flops
Data types in C ‘573 8 transparent latches
‘589 8-bit shift register
Data type Precision Range ‘595 8-bit shift register
‘676 16-bit shift register
unsigned char 8-bit unsigned 0 to 255
char 8-bit signed 128 to 127
unsigned int compiler-dependent
int compiler-dependent The 9S12DP512 has 91 I/O pins.
unsigned short 16-bit unsigned 0 to 65535
short 16-bit signed 32768 to 32767 Pin Shared Functions
unsigned long unsigned 32-bit 0 to 4294967295L
PAD15-PAD8 ADC
long signed 32-bit 2147483648L to 2147483647L
PAD7-PAD0 ADC
float 32-bit float 10  38 to 1038
PA7-PA0 Address/Data bus
double 64-bit float 10  308 to 10308
PB7-PB0 Address/Data bus
PE7-PE0 IRQ, XIRQ, bus
PH7-PH4 SPI2, key wakeup
The 9S12C32 has nine external I/O ports
PH3-PH0 SPI1, key wakeup
48-pin 80-pin Shared Functions PJ7-6, PJ1-0 CAN4, I2C, CAN0, key
PK7, PK5-PK0 Address bus
PA0 PA7-PA0 Address/Data Bus PM7-PM6 CAN3, CAN4
PB4 PB7-PB0 Address/Data Bus PM5-PM4 CAN2, CAN0, CAN4, SPI0
PE7,4,1,0 PE7-PE0 IRQ, XIRQ, bus PM3-PM2 CAN1, CAN0, SPI0
— PJ7, PJ6 Key wakeup PM1-PM0 CAN0, BDLC
PM5-PM0 PM5-PM0 SPI, CAN PP7-PP4 PWM, SPI2, key wakeup
PP5 PP7-PP0 PWM, key wakeup PP3-PP0 PWM, SPI1, key wakeup
PS1-PS0 PS3-PS0 SCI PS7-PS4 SPI0
PT7-PT0 PT7-PT0 Timer, PWM PS3-PS0 SCI1, SCI0
PAD7-PAD0 PAD7-PAD0 ADC, Digital I/O PT7-PT0 Timer

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Output parameters for various open collector gates 9S12 interrupt vectors and CodeWarrior numbers

Family Example VOL (V) IOL (A) Address Number Interrupt Source
Standard TTL 7405 0.4 0.016 $FFFE 0 Reset
Schottky TTL 74S05 0.5 0.02 $FFF8 3 Unimplemented Instruction Trap
Low power Schottky TTL 74LS05 0.5 0.008 $FFF6 4 SWI
High speed CMOS 74HC05 0.33 0.004 $FFF4 5 XIRQ
High voltage output TTL 7406 0.7 0.040 $FFF2 6 IRQ
High voltage output TTL 7407 0.7 0.04 $FFF0 7 Real Time Interrupt, RTIF
Silicon monolithic IC 75492 0.9 0.25 $FFEE 8 Timer Channel 0, C0F
Silicon monolithic IC 75451–75454 0.5 0.3 $FFEC 9 Timer Channel 1, C1F
Darlington switch ULN-2074 1.4 1.25 $FFEA 10 Timer Channel 2, C2F
MOSFET IRF-540 varies 28 $FFE8 11 Timer Channel 3, C3F
$FFE6 12 Timer Channel 4, C4F
$FFE4 13 Timer Channel 5, C5F
$FFE2 14 Timer Channel 6, C6F
Output parameters for various open emitter gates
$FFE0 15 Timer Channel 7, C7F
Family Example VCE (V) ICE (A) $FFDE 16 Timer Overflow, TOF
$FFDC 17 Pulse Acc. Overflow, PAOVF
Silicon monolithic IC 75491 0.9 0.05 $FFDA 18 Pulse Acc. Input Edge, PAIF
Darlington switch ULN-2074 1.4 1.25 $FFD8 19 SPI0, SPIF or SPTEF
MOSFET IRF-540 varies 28 $FFD6 20 SCI0, TDRE TC RDRF IDLE
$FFD4 21 SCI1, TDRE TC RDRF IDLE
$FFD2 22 ATD Sequence Complete, ASCIF
H-bridge drivers $FFCE 24 Key Wakeup J, PIFJ
$FFCC 25 Key Wakeup H, PIFH
Chip Current Comment $FFC0 31 I2C, IAAS TCF IBAL
$FFBE 32 SPI1, SPIF or SPTEF
MC3479 0.35 A Stepper driver $FFBC 33 SPI2, SPIF or SPTEF
L293D 0.6 A Dual, diodes $FFB2 38 CAN receive
L293 1A Dual $FFB0 39 CAN transmit
TPIC0107 3A Direction, fault status $FF8E 56 Key Wakeup P, PIFP[7:0]
L6203 5A Dual

Parameters of typical transistors used by microcomputer to source or sink current

Type NPN PNP Package Vbe(SAT) Vce(SAT) hfe min/max Ic

General purpose 2N3904 2N3906 TO-92 0.85 V 0.2 V 100 10 mA


General purpose PN2222 PN2907 TO-92 1.2 V 0.3 V 100 150 mA
General purpose 2N2222 2N2907 TO-18 1.2 V 0.3 V 100/300 150 mA
Power transistor TIP29A TIP30A TO-220 1.3 V 0.7 V 15/75 1A
Power transistor TIP31A TIP32A TO-220 1.8 V 1.2 V 25/50 3A
Power transistor TIP41A TIP42A TO-220 2.0 V 1.5 V 15/75 3A
Power Darlington TIP120 TIP125 TO-220 2.4 V 2.0 V 1000 min 3A

General specification of various types of resistor components1

Type Range Tolerance Temperature coef Max power

Carbon composition 1  to 22 M 5 to 20% 0.1%/°C 2W


Wire-wound 1  to 100 k 0.0005% 0.0005%/°C 200 W
Metal film 0.1  to 1010  0.005% 0.0001%/°C 1W
Carbon film 10  to 100 M 0.5% 0.05%/°C 2W
1
Wolf and Smith, Student Reference Manual, Prentice Hall, pg. 272, 1990.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Embedded
Microcomputer Systems
Real Time Interfacing
Third Edition

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content may
be suppressed. Editorial review has deemed that any suppressed content does not materially affect the overall
learning experience. The publisher reserves the right to remove content from this title at any time if subsequent rights
restrictions require it. For valuable information on pricing, previous editions, changes to current editions, and
alternate formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for
materials in your areas of interest.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Embedded
Microcomputer Systems
Real Time Interfacing
Third Edition

Jonathan W. Valvano
University of Texas at Austin

Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Embedded Microcomputer Systems: © 2011, 2007 Cengage Learning
Real Time Interfacing, Third Edition
ALL RIGHTS RESERVED. No part of this work covered by the copyright herein
Jonathan W. Valvano
may be reproduced, transmitted, stored, or used in any form or by any means
Publisher, Global Engineering: graphic, electronic, or mechanical, including but not limited to photocopying,
Christopher M. Shortt recording, scanning, digitizing, taping, web distribution, information networks,
or information storage and retrieval systems, except as permitted under
Acquisitions Editor: Swati Meherishi
Section 107 or 108 of the 1976 United States Copyright Act, without the prior
Assistant Development Editor: written permission of the publisher.
Yumnam Ojen Singh
Editorial Assistant: Tanya Altieri For product information and technology assistance, contact us at
Team Assistant: Carly Rizzo Cengage Learning Customer & Sales Support, 1-800-354-9706.
Marketing Manager: Lauren Betsos For permission to use material from this text or product,
submit all requests online at www.cengage.com/permissions.
Media Editor: Chris Valentine
Further permissions questions can be e-mailed to
Content Project Manager: D. Jean Buttrom permissionrequest@cengage.com.
Production Service: RPK Editorial Services, Inc.
Copyeditor: Shelly Gerger-Knechtl Library of Congress Control Number: 2010938462
Proofreader: Becky Taylor ISBN 13: 978-1-111-42625-5
Indexer: Shelly Gerger-Knechtl
ISBN-10: 1-111-42625-2
Compositor: Glyph International Ltd.
Senior Art Director: Michelle Kunkler Cengage Learning
Cover Designer: Andrew Adams 200 First Stamford Place, Suite 400
Cover Image: © Cybrain/Shutterstock Stamford, CT 06902
USA
Internal Designer: Carmela Periera
Senior Rights Acquisitions Specialist:
Cengage Learning is a leading provider of customized learning solutions with
Mardell Glinski-Schultz
office locations around the globe, including Singapore, the United Kingdom,
Text and Image Permissions Researcher: Australia, Mexico, Brazil, and Japan. Locate your local office at:
Kristiina Paul international.cengage.com/region.
First Print Buyer: Arethea L. Thomas
Cengage Learning products are represented in Canada by Nelson Education, Ltd.
For your course and learning solutions, visit www.cengage.com/engineering.
Purchase any of our products at your local college store or at our preferred
online store www.cengagebrain.com.

Printed in the United States of America


1 2 3 4 5 6 7 14 13 12 11 10

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface

Embedded computer systems, which are electronic systems that include a microcomputer to
perform a specific dedicated application, are ubiquitous. Every week millions of tiny com-
puter chips come pouring out of factories like Freescale, Atmel, Maxim, Texas Instruments,
STMicroelectronics, Renesas, Microchip, Silicon Labs, and Mitsubishi and find their way into
our everyday products. Our global economy, food production, transportation system, military
defense, communication systems, and even quality of life depend on the efficiency and effec-
tiveness of these embedded systems. As electrical and computer engineers we play a major
role in all phases of this effort: planning, design, analysis, manufacturing, and marketing.
This book is unique in several ways. Like any good textbook, it strives to expose un-
derlying concepts that can be learned today and applied later in practice. The difference lies
in the details. You will find that this book is rich with detailed case studies that illustrate the
basic concepts. After all, engineers do not simply develop theories but rather continue all
the way to an actual device. During my years of teaching, I have found that the combination
of concepts and examples is an effective method of educating student engineers. Even as a
practicing engineer, I continue to study actual working examples whenever I am faced with
learning new concepts.
Also unique to this book is its simulator, called Test Execute and Simulate (TExaS).
This simulator, like all good applications, has an easy learning curve. It provides a self-
contained approach to writing and testing microcomputer hardware and software. It differs
from other simulators in two aspects. If enabled, the simulator shows you activity internal
to the chip, like the address/data bus, the instruction register, and the effective address
register. In this way the application is designed for the educational objectives of under-
standing how a computer works. On the other end of the spectrum, you have the ability to
connect such external hardware devices as switches, keyboards, LEDs, LCDs, serial port
devices, motors, and analog circuits. Logic probes, voltmeters, oscilloscopes, and logic an-
alyzers are used to observe the external hardware. The external devices together with the
microcomputer allow us to learn about embedded systems. The simulator supports many
of the I/O port functions of microcomputers like interrupts, serial port, output compare,
input capture, key wake up, timer overflow, and the ADC. You will find the simulator on
the CD that accompanies this book. Get the CD out now, run the Readme.htm, install
TExaS, and follow the tutorial example. In particular, double-click the tut.uc file in the
MC9S12 subdirectory and run the tutorial on the simulator. If you are still having fun, then
run the other four tutorials: tut2.* shows the simple serial I/O functions, tut3.* is an ADC
data acquisition example, tut4.* shows interrupting serial I/O functions, and tut5.* is an
interrupting square-wave generator. Although many programs are included in the appli-
cation, these five give a broad overview of the capabilities of the simulator. The screen shot
in Figure P.1 was obtained when running the tut2.rtf example. Notice these features in the
figure: (1) address/data bus activity, (2) embedded figures in the source code, (3) external
hardware, (4) voltmeters and logic probes, and (5) an oscilloscope.

v
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
vi 䡲 Preface

Figure P.1 The TExaS simulator can be used to design, implement, and test embedded systems.

P.1 General Objectives


This book constitutes an in-depth treatment of the design of embedded microcomputer sys-
tems. It includes the hardware aspects of interfacing, advanced software topics like inter-
rupts, and a systems approach to typical embedded applications. The book is unique to
other microcomputer books because of its in-depth treatment of both the software and hard-
ware issues important for real-time embedded applications. The specific objectives of the
book include the understanding of:
1. Advanced architecture
䡲 Timing diagrams
䡲 Memory and I/O device interfacing to the address/data bus
2. Interfacing external devices to the computer
䡲 Switches and keyboards
䡲 LED and LCD displays

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
䡲 Preface vii

䡲 DC motors, servos, relays, and stepper motors


䡲 Amplifiers, analog filters, DAC, and ADC
䡲 Synchronous and asynchronous serial ports
䡲 Microphones, speakers, and thermostors
3. Advanced programming
䡲 Hardware/software synchronization
䡲 Debugging of real time embedded systems
䡲 Interrupts and real time events
䡲 Signal generation and timing measurements
䡲 Threads and semaphores
4. Embedded applications
䡲 Data acquisition systems with digital filters
䡲 Sound recording and playback
䡲 Linear and fuzzy logic control systems
䡲 Simple communication networks

P.2 Changes in the 3rd Edition


Removing the 6811 material has significantly improved how students can use this book.
Because the book focuses on just the 9S12, reading and using the book is very easy. In
other words, the organizational flow is much smoother than the 2nd Edition. Students can
read entire chapters because all parts apply to the 9S12. Conversely, students can pick and
choose individual sections about specific topics. Once a student has selected a topic, the
student can read the entire section, because the entire section is a complete well-contained
treatment of a particular topic.
One of the strengths of this book has been its wealth of practical examples. In the
3rd Edition, material is dearly separated into fundamental concepts and example designs.
In particular, each example design begins with a visual marker, followed by a concise but
clear problem specification. The solution is then developed in a logical top-down manner.
After the complete solution is presented and explained, another visual marker shows the
reader that the example has ended and the subsequent material is fundamental again. Many
new example designs are included.
There are 200 new homework exercises and 14 new labs. Exercises are divided into sim-
ple short answer and detailed design problems. Short answer questions are meant to rein-
force the reading. Design questions involve design, creativity, application, and integration
and are meant to be solved with paper and pencil. Lab assignments also involve design, cre-
ativity, application, and integration, but also include debugging and analysis.
There are many new topics added to the 3rd edition. The section on real time oper-
ating systems has more fundamentals and more examples. There is discussion on a design
and analysis of file systems for embedded systems. There is a section on how to use the flash
EEPROM for dynamic storage. The requirements document is described as an important
component of the design process. MOS circuit models are used to explain interfacing concepts.
There are many new sections on low power design, including regulators and battery chargers.
Transmission line theory is incorporated in the discussion of serial interfaces. The section
on flow charts is expanded to explain parallel and concurrent programming. There is a new
section on recursion. There are new debugging techniques. For example, there are many
figures of actual logic analyzer measurements to show students how the logic analyzer can
be used. There is a new section on theoretical aspects of modular programming. Synchro-
nization and interthread communication is presented in a formal way using semaphores,
mailboxes, and FIFO queues. Pseudo vectors are explained, along with the impact they have
on interrupt latency. There are new sections on time jitter, how to measure it, and how to re-
duce it. There is a new section on the physics of motor electromagnetics, and its implica-
tions on interfacing. There are new sections on brushless DC motors and servo motors.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
viii 䡲 Preface

There are sections on interfacing microphones and speakers. There are new audio labs. A
PWM DAC is presented. There are both fundamental theories and practical examples of
wireless communication for embedded systems. The DFT is presented and used for de-
signing FIR digital filters.
A number of sections have been moved to provide a more logical reading flow. The
LCD interface was moved from Chapter 8 to Chapter 3 because it is simple and matches
educational goals of Chapter 3. Tuning equations and timing diagrams were moved from
Chapter 9 into Chapter 3, because many schools skip chapter 9, but timing is an important
part of interfacing. EC was moved from Chapter 14 to Chapter 7, because I2C is like SPI
and used to interface the microcontroller to a peripheral. USB was moved from Chapter 14
to Chapter 7, because USB is like SCI and used to interface the microcontroller to the PC.

P.3 Prerequisites and Supplements


This book is intended for a junior- or senior-level course in microcomputer programming
and interfacing. We assume the student has knowledge of:
䡲 MC programming functions, variables, numbers, and contial structures
䡲 Basic digital logic (multiplexers, Karnaugh maps, tristate logic)
䡲 Data structures in C (queues, stacks, linked lists)
䡲 Test equipment like multimeters and oscilloscopes
䡲 Discrete analog electric circuits (resistors, capacitors, inductors, and transistors)
Although this book focuses on how to design embedded systems, extensive tutorials on the CD
help students with the important issues of how to program in assembly language and how to
program in C. A section later in this preface contains more information about what is on the CD.
To access all additional course materials for both instructors and students, please
visit www.cengagebrain.com. At the CengageBrain.com home page, search for the ISBN
of your title (from the back cover of your book) using the search box at the top of the page.
This will take you to the product page where these resources can be found.

P.4 Structure of the Book


We will use this font whenever displaying either assembly language or high-level code
written in C. For the most part, software that is encapsulated in a box has equivalent exam-
ples for assembly and C. The program number in the caption will assist you in finding the
software on the CD. All programs in an entire chapter are grouped together into one file.
For example, the assembly and C programs in Chapter 1 can be found on the CD as files
Chap1.asm and Chap1.c.
The C code in this book was written compiled and tested using the Metrowerks Code-
Warrior for the 9S12. We have been very successful transporting these software examples to
other compilers with only minor syntax modifications required. The major differences be-
tween the compilers are the syntax for embedded assembly and defining interrupt handlers;
we have tried using various free SmallC compilers, but the software in this book is too com-
plex to be compiled using SmallC. The biggest limitation of SmallC is its lack of support for
data structures. In other words, substantial editing would be required to use SmallC in a course
based on this book. Gnu C and Imagecraft ICC12 compilers are available for the 9S12.
We assume you have access to the Freescale programming reference guides for your par-
ticular microcomputer that show the details of each assembly instruction. You should also have
the microcomputer technical reference manuals, which detail the I/O ports you will be using.
For example, if you are using input capture to measure periods on the Freescale 9S12C32, you
will find basic principles and examples in this book, but you need to access the 9S12C32 Tech-
nical Summary for a complete list of all the details. In other words, you should to use this book

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
䡲 Preface ix

along with the manuals from Freescale. Although these reference manuals are available as pdf
documents on the CD, it might be better to order physical documents from Freescale’s liter-
ature center, or to download the latest version from the Freescale website.
Although software development is a critical aspect of embedded system design, this
book is not intended to serve as an introduction to C programming. Consequently, you will
find it convenient to have a C programming reference available. Fortunately, located on the
CD that accompanies this book, there is a small reference called Developing Embedded
Software in C using Metrowerks written as an HTML document. Although this reference is
not as complete a programming guide as some books on C, it is specific for writing em-
bedded software for the 9S12.
In this book we will discuss programming style, and develop debugging strategies spe-
cific to embedded real time systems from both an assembly language and a C perspective.
Due to the nature of single-chip computers (they are very slow and have very very little
RAM when compared to today’s desktop microcomputers) most of the available C compil-
ers for the single-chip microcomputers used in this book do not support objects, or float-
ing-point. Floating-point should be used only in situations where the range of values spans
many orders of magnitude or where the range of values is unknown at software design time.
Our experience is that numbers used in embedded systems usually have a narrow and
known range, so integer math is sufficient. On the other hand, there is some interest for ap-
plying object-oriented approaches of C⫹⫹ to embedded system design. A few illustrations
of object-oriented design can be found in this book.
Chapters 1 and 2 can serve as an introduction to assembly language programming. Most
embedded systems engineers agree that a working knowledge of assembly is necessary even
when virtually all of our software is written in C. In specific, we believe we must know
enough assembly language to be able to follow the assembly listing files generated by our
compiler. This understanding of assembly language is vital when debugging, writing inter-
rupt handlers, calculating real time events, and considering reentrancy. Consequently, de-
tailed information on assembly language programming is included on the CD. In particular
you will find microcomputer data sheets, interactive on-line help as part of the TExaS sim-
ulator, and a short introduction to assembly language programming as an HTML document.
The electrical components used in this book span a wide range. Examples include
the 2764 PROM, 1N914 diode, 2N2222 transistor, 7406 open collector TTL driver,
74LS74 LSTTL flip flop, 74HC573 high speed CMOS transparent latch, Max494 op
amp, L293 interface driver, Hitachi 44780 LCD driver, IRF540 MOSFET, 6N139 opto-
coupler, Max232 driver, and Analog Devices DAC8043 digital-to-analog converters. It
is unrealistic for each student to have a personal library that contains the data books for
all these devices. On the other hand it is appropriate for the company or university to
establish a reference library that can be accessed by all the students. The circuit dia-
grams in this book usually include chip numbers and component values, but not pin
numbers or circuit board layout information. Consequently, with the appropriate data
sheets available, most circuits can be readily built.

P.5 How to Teach a Course Based on This Book


The first step in the design of any course is to create a list of educational objectives, along
with an understanding of the topics taught in previous classes and the topics needed as pre-
requisites to subsequent classes. Some important topics like computer architecture and
modular software design may be included in multiple courses. Armed with this list, the in-
structor (or department committee) searches for a book that covers most of the topics in an
effective manner. It is unrealistic to teach the entire contents of this book in a single
one-semester class, but the rationale in writing this book was to cover a wide range of pos-
sible classes. There are two approaches to selecting a subset of material from this book
to cover. The first approach is to pick a microcomputer and programming language. For

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
x 䡲 Preface

example, one could teach just assembly language or just C programming. In this situation,
one simply skips the other cases.
The other approach to selecting the appropriate subset is to pick and choose topics. For
example, a junior-level laboratory class might introduce the student to microcomputer in-
terfacing. This class might focus on interfacing techniques and may cover Chapters 1 to 4,
6 to 8 and a little bit of Chapters 11 to 13. For these students, the remaining parts of the
book become a resource to them for projects later in school or on the job. Another possi-
bility is a senior-level project laboratory class. The objectives of this class might focus on
the systems aspect of real time embedded systems. In this situation, some microcomputer
programming has been previously taught, so this course might cover the advanced inter-
facing techniques in Chapters 5, 9, 10, and 15 and the applications in Chapters 12 to 14. For
these students, the first half of the book becomes a review, allowing them to properly inte-
grate previously learned concepts to solve complex embedded system applications.
In most departments analog circuit design (for example, op amps and analog filters) is
taught in separate classes, so Chapter 11 will be a review chapter. Specific and detailed in-
formation about analog circuit design was included in this book to emphasize the system
integration issues when designing embedded systems. In other words, developing embed-
ded systems does not rely solely on the tools of computer and software engineering but
rather involves all of electrical, computer, and software engineering.
The next important decision to make is the organization of the student laboratory. As
engineering educators we appreciate the importance of practical “hands on” experiences in
the educational process. On the other hand, space, staff, and money constraints force all of
us to compromise, doing the best we can. Consequently, we present two laboratory possi-
bilities that range considerably in cost. Indeed, you may wish to mix two or more ap-
proaches into a hybrid simulated/physical laboratory configuration. We do believe that the
role of simulation is becoming increasingly important as the race for technological superi-
ority is run with shorter and shorter design cycle times. On the other hand, we should ex-
pose our students to all the phases of engineering design, including problem specification,
conceptualization, simulation, construction, and analysis.
In the first laboratory configuration, we use the traditional approach to an interfacing
laboratory. A physical microcomputer development board is made available for each labo-
ratory group of two students. There are numerous possibilities here. Companies such as
Technological Arts, Axiom, Wytec, and National Instruments produce development sys-
tems. In addition to the microcomputer board, each group will need a power supply, a pro-
totyping area to build external circuits, and the external I/O devices themselves. A number
of shared development/debugging stations will also have to be configured. It is on these
dedicated PC-compatible computers that the assembler or compiler is installed. If you de-
velop software in assembly, then the TExaS simulator can be used to edit, assemble, down-
load, and debug on a real 9S12 board. In most cases, when programming in C, a current
version of a C cross-compiler is greatly preferable. As mentioned earlier, the one possibil-
ity ImageCraft’s ICC12 (ImageCraft Inc. 2625 middlefield Rd. #685, Palo Alto, CA 94306
http://www.imagecraft.com). The Metrowerks CodeWarrior with educational license is also
an excellent choice for developing 9S12 software (Freescale, www.freescale.com). Test
equipment like an oscilloscope, a digital multimeter, and a signal generator are required at
each station. Expensive equipment like logic analyzers and printers can be shared. Some
mail-order companies sell used or surplus electronics that can be configured into laboratory
experiments (for possibilities, see my website http://users.ece.utexas.edu/~valvano). Many
laboratory assignments are available using this traditional configuration. For universities
that adopt this book, you will be allowed to download these assignments in Microsoft Word
format, then rewrite, print out, and distribute to your students laboratory assignments based
on these example laboratory assignments. Because of the detailed and specific nature of the
laboratory setup, rewriting will certainly be necessary. The 9S12C32 board from Techno-
logical Arts and the Metrowerks cross-compiler is the specific configuration presented in the

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
䡲 Preface xi

example laboratory assignments, but the assignments are appropriate for most microcom-
puter development boards based on the 9S12.
The second laboratory configuration is based entirely on the TExaS simulator. Each
book comes with a CD that allows the student to install the application on a single computer.
Students, for the most part, work off campus and come to a teaching assistant station for help
or laboratory grading. In this configuration you can either develop software in assembly us-
ing the TExaS assembler or develop C programs using the free version of CodeWarrior. The
simulator itself becomes the platform on which the laboratory assignments are developed
and tested. The educational license of Metrowerks CodeWarrior supports code up to 32 K.
Laboratory assignments are also available using the simulator. Again, for universities that
adopt this book, you will be allowed to download these assignments in Microsoft Word for-
mat, then rewrite, print out, and distribute to your students laboratory assignments based on
these example laboratory assignments.
The exercises at the end of each chapter can be used to supplement the laboratory assign-
ments. In actuality, these exercises, for the most part, were collected from old quizzes and final
examinations. Consequently, these exercises address the fundamental educational objectives
of the chapter, without the overwhelming complexity of a regular laboratory assignment.

P.6 What’s on the CD?


The Readme.htm contains a few introductory tutorials about TExaS. These movies do not
need to be copied to your hard drive; you can simply watch the movies from the CD itself.
TExaS is a complete editor, assembler, and simulator for the 9S12 microcomputer. It sim-
ulates external hardware, I/O ports, interrupts, memory, and program execution. It is intended
as a learning tool for embedded systems. This software is not freeware, but the purchase of
the book entitles the owner to install one copy of the program. The Texas directory contains
the installer. You must install the software before using the application. Performing a typi-
cal installation, TExaS creates the following three subdirectories:
䡲 MC9S12 containing 9S12C32 assembly examples
䡲 MC9S12DP containing 9S12DP512 assembly examples
䡲 9S12C32 containing 9S12C32 CodeWarrior C examples
The Custom installation allows you to pick and choose among many choices. The sub-
directory ICC11 also contains the ImageCraft freeware compiler. You can run the existing
ICC12 examples, but to edit and recompile you will need the commercial C compiler. The
Metrowerks CodeWarrior or the Gnu GCC12 require separate installations.
The PDF directory contains many data sheets in Adobe pdf format. This information
does not need to be copied to your hard drive; you can simply read the data sheets from the
CD itself. In particular there are data sheets for microcomputers, digital logic, memory
chips, op amps, ADCs, DACs, timer chips, and interface chips.
The example directory contains software from the book. For example, all the assem-
bly language programs from Chapter 1 can be found in the file “Chap.1.asm.” Similarly,
all the C language programs from Chapter 1 can be found in the file “Chap1.c.”
The assmbly directory contains an HTML document describing how to program in as-
sembly for embedded systems using the TExaS application. This document does not need
to be copied to your hard drive; you can simply read the HTML document from the CD
itself. (Note also that the TExaS application itself contains a lot of information about as-
sembly language development as part of its on-line help).
The embed directory contains an HTML document describing how to program in C for
embedded systems. This document does not need to be copied to your hard drive; you can
simply read the HTML document from the CD itself.
The lab directory contains software that could be used in a laboratory setting.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
xii 䡲 Preface

The Metrowerks directory contains an educational version of the 9S12 C compiler.


This limited version can be used to develop small programs that are less than 32 K bytes
of object code. This application must be installed before it can be used.

P.7 Acknowledgments
Many shared experiences contributed to the development of this book. First, I would like to
acknowledge the many excellent teaching assistants I have had the pleasure of working with.
Some of these hard-working, underpaid warriors include Pankaj Bishnoi, Rajeev Sethia, Adson
da Rocha, Bao Hua, Raj Randeri, Santosh Jodh, Naresh Bhavaraju, Ashutosh Kulkarni, Bryan
Stiles, V. Krishnamurthy, Paul Johnson, Craig Kochis, Sean Askew, George Panayi, Jeehyun
Kim, Vikram Godbole, Andres Zambrano, Ann Meyer, Hyunjin Shin, Anand Rajan, Anil Kot-
tam, Chia-ling Wei, Jignesh Shah, Icaro Santos, David Altman, Nachiket Kharalkar, Robin
Tsang, Byung Geun Jun, John Porterfield, Daniel Fernandez, James Fu., Deepak Panwar, Jacob
Egner, Sandy Hermawan, Usman Tariq, Sterling Wei, Seil Oh, Antonius Keddis, Lev Shuha-
tovich, Glen Rhodes, Geoffrey Luke, and Karthik Sankar. I dreamed of writing this book the
first time I taught microcomputer interfacing on the old Motorola MC6809 in 1981. Over the
intervening years my teaching assistants have contributed greatly to the contents of this book,
particularly to its laboratory assignments. In a similar manner, my students have recharged
my energy each semester with their enthusiasm, dedication, and quest for knowledge.
I would also like to thank the reviewers of the second edition who provided such excel-
lent feedback including N. Alexandridis, George Washington University; David W. Capson,
McMaster University; Lee D. Coraor, The Pennsylvania State University; Subra Ganesan,
Oakland University; Voicu Groza, University of Ottawa; and William R. Murray, California
Polytechnic State University, San Luis Obispo.
I would like to thank the reviewers of this third edition who also provided excellent feed-
back including John M. Acken, Oklahoma State University; William Bishop, University of
Waterloo; David W. Capson, McMaster University; James M. Conrad, University of North
Carolina, Charlotte; and John Seng, California Polytechnic State University, San Luis Obispo.
Next, I appreciate the patience and expertise of my fellow faculty members at the Uni-
versity of Texas at Austin. From a personal perspective, Dr. John Pearce has provided
much needed encouragement and support throughout my career. Also, Dr. John Cogdell
and Dr. Francis Bostick helped me with analog circuit design, and Dr. Baxter Womack and
Dr. Robert Flake provided good information about control systems. The book and accompa-
nying software include many finite-state machines derived from the digital logic examples
explained to me by Dr. Charles Roth. I continue to appreciate the encouragement and sup-
port of Dr. G. Jack Lipovski. An outside observer might conclude that Dr. Jack and I enjoy
taking opposite sides of every issue. In actuality, this friendly competition makes us organ-
ize our otherwise erratic thoughts, and in the process everything we do is the better for it.
Over the last few years, I have enjoyed teaching embedded systems with Dr. William
Bard. Bill has contributed to both the excitement and substance of our laboratory based on
this book. With pushing from Bill and TAs Robin, Glen, Lev, and John, we have added low
power, PCB layout, systems level design, surface mount soldering, and wireless communi-
cation to our lab experience. You can see descriptions and photos of our EE345L design
competition at http://users.ece.utexas.edu/~valvano/.
Last, I appreciate the valuable lessons of character and commitment taught to me by
my grandparents and parents. Most significantly, I acknowledge the love, patience, and
support of my entire family, especially my wife Barbara and my children, Ben, Dan, and Liz.
By the grace of God, I am truly the happiest man on the planet, because I am sur-
rounded by these fine people.

Good luck! JONATHAN W. VALVANO

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Contents

1 Microcomputer-Based 2 Design of Software


Systems 1 Systems 60
1.1 Computer Architecture 2 2.1 Quality Programming 60
1.2 Embedded Computer Systems 7 2.1.1 Quantitative Performance
1.3 The Design Process 11 Measurements 61
1.3.1 Top-Down Design 11 2.1.2 Qualitative Performance
1.3.2 Bottom-Up Design 15 Measurements 61
1.4 Digital Logic and Open Collector 16 2.2 Assembly Language
1.5 Digital Representation of Numbers 22 Programming 62
1.5.1 Fundamentals 22 2.2.1 Introduction 62
1.5.2 8-Bit Numbers 25 2.2.2 Assembly Language Syntax 64
1.5.3 Character Information 26 2.2.3 Memory and Register Transfer
1.5.4 16-Bit Numbers 27 Operations 66
1.5.5 Fixed-Point Numbers 28 2.2.4 Indexed Addressing Mode 68
2.2.5 Arithmetic Operations 71
1.6 Common Architecture
2.2.6 Extended Precision Arithmetic
of the 9S12 30 Instructions on the 9S12 76
1.6.1 Registers 31 2.2.7 Shift Operations 77
1.6.2 Terminology 32 2.2.8 Logical Operations 79
1.6.3 Addressing Modes 33 2.2.9 Subroutines and the Stack 80
1.6.4 Numbering Scheme Used 2.2.10 Branch Operations 83
by Freescale 36 2.2.11 Assembler Pseudo-ops 85
1.7 9S12 Architecture Details 36 2.2.12 Memory Allocation 89
1.7.1 9S12C32 Architecture 37 2.3 Self-Documenting Code 92
1.7.2 9S12DP512 Architecture 39
2.3.1 Comments 92
1.7.3 9S12E128 Architecture 44
2.3.2 Naming Convention 95
1.7.4 Operating Modes 45
2.4 Abstraction 96
1.8 Phase-Lock-Loop (PLL) 46
2.4.1 Definitions 96
1.9 Parallel I/O Ports 47 2.4.2 9S12 Timer Details 97
1.9.1 Basic Concepts of Input and Output 2.4.3 Time Delay Software Using the Built-in
Ports 47 Timer 98
1.9.2 Introduction to I/O Programming and
the Direction Register 49
2.5 Modular Software Development 104
2.5.1 Variables 104
1.10 Choosing a Microcontroller 55
2.5.2 Modules 111
1.11 Exercises 56 2.5.3 Dividing a Software Task into
1.12 Lab Assignments 58 Modules 115
xiii
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
xiv 䡲 Contents

2.5.4 Rules for Developing Modular Software in


Assembly Language 120 4 Interrupt
2.6 Layered Software Systems 121 Synchronization 189
2.7 Device Drivers 123
4.1 What Are Interrupts? 190
2.7.1 Basic Concept of Device Drivers 123
4.1.1 Interrupt Definition 190
2.7.2 Design of a Serial Communications Interface
4.1.2 Interrupt Service Routines 191
(SCI) Device Driver 124
4.1.3 When to Use Interrupts 192
2.8 Object-Oriented Interfacing 126 4.1.4 Interthread Communication 192
2.8.1 Encapsulated Objects Using 4.2 Reentrancy and Critical Sections 199
Standard C 126
2.8.2 Object-Oriented Interfacing
4.3 First-In–First-Out Queue 206
Using C⫹⫹ 127 4.3.1 Introduction to FIFOs 206
2.8.3 Portability Using Standard C 4.3.2 Two-Pointer FIFO Implementation 207
and C⫹⫹ 128 4.3.3 Two-Pointer/ Counter FIFO
Implementation 210
2.9 Threads 130
4.3.4 FIFO Dynamics 211
2.9.1 Single-Threaded Execution 130
2.9.2 Multithreading and Reentrancy 130
4.4 General Features of Interrupts
2.10 Recursion 132 on the 9S12 212
2.11 Debugging Strategies 134 4.5 Interrupt Vectors and Priority 215
2.11.1 Debugging Tools 135 4.6 External Interrupt Design
2.11.2 Debugging Theory 136 Approach 217
2.11.3 Functional Debugging 138 4.7 Polled versus Vectored Interrupts 219
2.11.4 Performance Debugging 140 4.8 Pseudo-Interrupt Vectors 221
2.11.5 Profiling 143 4.9 Key Wake-Up Interrupt
2.12 Exercises 144 Examples 222
2.13 Lab Assignments 147 4.10 Power System Interface Using XIRQ
Synchronization 227
4.11 Interrupt Polling Using
3 Interfacing Methods 150 Linked Lists 228
3.1 Introduction 150 4.12 Interrupt Priority 230
3.1.1 Performance Measures 150 4.13 Round-Robin Polling 233
3.1.2 Synchronizing the Software with the State 4.14 Periodic Interrupts 234
of the I/O 151 4.15 Low Power Design 239
3.1.3 Variety of Available I/O Ports 154 4.16 Exercises 241
3.1.4 Timing Equations 156
4.17 Lab Assignments 249
3.1.5 Timing Diagrams 158
3.2 Key Wake-Up 160
3.3 Blind Cycle Counting
Synchronization 162
5 Real-Time Operating
3.3.1 Blind Cycle Printer Interface 162 Systems 251
3.4 Gadfly or Busy-Wait 5.1 Introduction 252
Synchronization 163
5.2 Round-Robin Scheduler 257
3.3.2 Blind Cycle ADC Interface 163
5.3 Semaphores 264
3.5 Parallel I/O Interface Examples 166
5.3.1 Spin-Lock Semaphore Implementation 265
3.6 Serial Communications Interface (SCI) 5.3.2 Blocking Semaphore Implementation 267
Device Driver 173 5.4 Thread Synchronization and
3.6.1 Transmitting in Asynchronous Mode 173
Communication 270
3.6.2 Receiving in Asynchronous Mode 174
5.4.1 Thread Synchronization or Rendezvous 270
3.6.3 9S12 SCI Details 175
5.4.2 Resource Sharing, Nonreentrant Code or
3.6.4 SCI Device Driver 176
Mutual Exclusion 271
3.7 Parallel Port LCD Interface with the 5.4.3 Thread Communication Between Two
HD44780 Controller 178 Threads Using a Mailbox 271
3.8 Exercises 180 5.4.4 Thread Communication Between
3.9 Lab Assignments 187 Many Threads Using a FIFO Queue 271

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
䡲 Contents xv

5.5 Fixed Scheduling 272 7.5.2 Receiving in Asynchronous Mode 347


5.6 OS Considerations for 7.5.3 9S12 SCI Details 350
I/O Devices 277 7.6 Synchronous Transmission and Receiving
5.6.1 Board Support Package 277 Using the SPI 357
5.6.2 Path Expression 278 7.6.1 SPI Fundamentals 357
5.7 Exercises 280 7.6.2 MC9S12C32 SPI Details 360
7.6.3 9S12DP512 Module Routing Register 363
5.8 Lab Assignments 286
7.7 Inter-Integrated Circuit (I2C)
Interface 368
6 Timing Generation 7.7.1 The Fundamentals of the I2C 368
7.7.2 I2C Synchronization 371
and Measurements 288 7.7.3 9S12 I2C Details 373
6.1 Input Capture 288 7.7.4 9S12 I2C Single Master Example 376
6.1.1 Basic Principles of Input Capture 288 7.8 Logic Level Conversion 377
6.1.2 Input Capture Details 289 7.9 Universal Serial Bus (USB) 378
6.1.3 Period Measurement 293 7.9.1 Introduction 378
6.1.4 Pulse-Width Measurement 298 7.9.2 Modular USB Interface 382
6.2 Output Compare 302 7.9.3 Integrated USB Interface 383
6.2.1 General Concepts 302 7.10 Exercises 384
6.2.2 Output Compare Details 304 7.11 Lab Assignments 388
6.2.3 Pulse-Width Modulation 307
6.2.4 Delayed Pulse Generation 309
6.3 Frequency Measurement 310 8 Parallel Port Interfaces 390
6.3.1 Frequency Measurement Concepts 310
8.1 Input Switches and Keyboards 390
6.4 Conversion Between Frequency
8.1.1 Interfacing a Switch to the Computer 390
and Period 312
8.1.2 Hardware Debouncing Using
6.4.1 Using Period Measurement to Calculate
a Capacitor 392
Frequency 312
8.1.3 Software Debouncing 395
6.4.2 Using Frequency Measurement to Calculate
8.1.4 Basic Approaches to Interfacing
Period 313
Multiple Keys 401
6.5 Pulse Accumulator 316 8.2 Output LEDs 410
6.5.1 9S12 Pulse Accumulator Details 316
8.2.1 Single LED Interface 411
6.5.2 Frequency Measurement 317
8.2.2 Seven-Segment LED Interfaces 413
6.5.3 Pulse-Width Measurement 318
8.3 Liquid Crystal Displays 422
6.6 Pulse-Width Modulation on the
8.3.1 LCD Fundamentals 422
MC9S12C32 318 8.3.2 Simple LCD Interface with
6.7 Exercises 322 the MC14543 423
6.8 Lab Assignments 327 8.3.3 Scanned LCD Interface with the MC145000,
MC145001 424
8.4 Transistors Used for Computer-
7 Serial I/O Devices 330 Controlled Current Switches 427
7.1 Introduction and Definitions 330 8.5 Computer-Controlled Relays, Solenoids,
7.2 RS232 Specifications 337 and DC Motors 429
7.3 RS422/USB/RS423/RS485 Balanced 8.5.1 Introduction to Relays 429
Differential Lines 339 8.5.2 Electromagnetic Relay Basics 430
7.3.1 RS422 Output Specifications 342 8.5.3 Reed Relays 432
7.3.2 RS422 Input Specifications 342 8.5.4 Solenoids 432
7.3.3 RS485 Half-Duplex Channel 343 8.5.5 Solid-State Relays 442
7.4 Other Communication Protocols 344 8.6 Stepper Motors 443
7.4.1 Current Loop Channel 344 8.6.1 Basic Operation 446
7.4.2 Introduction to Modems 344 8.6.2 Stepper Motor Hardware Interfaces 449
7.4.3 Optical Channel 345 8.6.3 Stepper Motor Shaft Encoder 451
7.4.4 Digital Logic Channel 345 8.7 Servo Motors 452
7.5 Serial Communications Interface 346 8.8 Exercises 454
7.5.1 Transmitting in Asynchronous Mode 346 8.9 Lab Assignments 456

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
xvi 䡲 Contents

9 Memory Interfacing 458 10.7 File System Management


10.7.1 Introduction 519
519

9.1 Introduction 458 10.7.2 File System Allocation 519


9.2 Address Decoding 461 10.7.3 Simple File System 521
9.2.1 Full-Address Decoding 461 10.7.4 File Allocation Table 523
9.2.2 Minimal-Cost Address Decoding 463 10.7.5 Internal Fragmentation 524
9.2.3 Special Cases When Address 10.7.6 External Fragmentation 524
Decoding 466 10.8 Exercises 525
9.3 General Memory Bus Timing 467 10.9 Lab Assignments 529
9.3.1 Synchronous Bus Timing 468
9.3.2 Partially Asynchronous Bus Timing 469
9.3.3 Fully Asynchronous Bus Timing 469
11 Analog Interfacing 531
9.4 External Bus Timing 471 11.1 Resistors and Capacitors 531
9.4.1 Synchronized Versus Unsynch- 11.1.1 Resistors 531
ronized Signals 471 11.1.2 Capacitors 532
9.4.2 Freescale MC9S12C32 External 11.2 Operational Amplifiers
Bus Timing 472 (Op Amps) 534
9.5 General Approach to 11.2.1 Op Amp Parameters 534
Interfacing 480 11.2.2 Threshold Detector 537
9.5.1 Interfacing to a 9S12 in Expanded 11.2.3 Simple Rules for Linear Op Amp
Narrow Mode 480 Circuits 537
9.5.2 Interfacing to a 9S12 in Expanded 11.2.4 Linear Mode Op Amp Circuits 539
Wide Mode 480 11.2.5 Instrumentation Amplifier 544
9.6 9S12 Paged Memory 489 11.2.6 Current-to-Voltage Circuit 545
9.7 Programming Flash EEPROM 492 11.2.7 Voltage-to-Current Circuit 545
11.2.8 Integrator Circuit 545
9.8 Dynamic RAM (DRAM) 496
11.2.9 Derivative Circuit 546
9.9 Exercises 497 11.2.10 Voltage Comparators with
9.10 Lab Assignments 498 Hysteresis 546
11.2.11 Analog Isolation 547
11.3 Analog Filters 548
10 High-Speed I/O 11.3.1 Simple Active Filter 548
Interfacing 500 11.3.2 Butterworth Filters 549
11.3.3 Bandpass and Band-Reject Filters 550
10.1 The Need for Speed 500 11.4 Digital-to-Analog Converters 551
10.2 High-Speed I/O Applications 501 11.4.1 DAC Parameters 551
10.2.1 Mass Storage 501 11.4.2 DAC Using a Summing Amplifier 553
10.2.2 High-Speed Data Acquisition 502 11.4.3 Three-Bit DAC with an R-2R Ladder 554
10.2.3 Video Displays 503 11.4.4 Twelve-Bit DAC with a DAC8043 556
10.2.4 High-Speed Signal Generation 503 11.4.5 DAC Selection 557
10.2.5 Network Communications 503 11.4.6 DAC Waveform Generation 560
10.3 General Approaches to High-Speed 11.4.7 PWM DAC 563
Interfaces 504 11.5 Analog-to-Digital Converters 564
10.3.1 Hardware FIFO 504 11.5.1 ADC Parameters 564
10.3.2 Dual Port Memory 505 11.5.2 Two-Bit Flash ADC 565
10.3.3 Bank-Switched Memory 505 11.5.3 Successive Approximation ADC 566
10.4 Fundamental Approach to DMA 506 11.5.4 Sixteen-Bit Dual Slope ADC 567
10.4.1 DMA Cycles 506 11.5.5 Sigma Delta ADC 568
10.4.2 DMA Initiation 507 11.5.6 ADC Interface 569
10.4.3 Burst Versus Cycle Steal DMA 507 11.6 Sample and Hold 570
10.4.4 Single-Address versus Dual-Address 11.7 BiFET Analog Multiplexer 571
DMA 508 11.8 ADC System 573
10.4.5 DMA Programming 510 11.8.1 ADC Block Diagram 573
10.5 LCD Graphics 511 11.8.2 Power and Grounding for the ADC
10.5.1 LCD Graphics Controller 511 System 575
10.5.2 Practical LCD Graphics Interface 514 11.8.3 Input Protection for CMOS Analog
10.6 Secure Digital Card Interface 515 Inputs 575
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
䡲 Contents xvii

11.9 Power 575 13.3 Simple Closed-Loop Control


11.9.1 Regulators 575 Systems 655
11.9.2 Low Power Design 576 13.4 PID Controllers 659
11.9.3 Battery Power 578 13.4.1 General Approach to a PID
11.10 Multiple-Access Circular Queue 580 Controller 659
11.11 Internal ADCs 582 13.4.2 Design Process for a PID
11.11.1 9S12 ADC System 582 Controller 662
11.11.2 ADC Software 585 13.5 Fuzzy Logic Control 668
11.12 Exercises 586 13.6 Exercises 681
11.13 Lab Assignments 589 13.7 Lab Assignments 684

12 Data Acquisition
Systems 591 14 Simple Networks 686
14.1 Introduction 686
12.1 Introduction 591
12.1.1 Accuracy 593 14.2 Communication Systems Based on the
12.1.2 Resolution 595 SCI Serial Port 690
12.1.3 Precision 595 14.3 Design and Implementation
12.1.4 Reproducibility or Repeatability 596 of a Controller Area Network
12.2 Transducers 596 (CAN) 692
12.2.1 Static Transducer Specifications 596 14.3.1 The Fundamentals of CAN 692
12.2.2 Dynamic Transducer Specifications 600 14.3.2 Details of the 9S12C32 CAN 695
12.2.3 Nonlinear Transducers 601 14.3.3 9S12C32 CAN Device Driver 698
12.2.4 Position Transducers 601 14.4 Wireless Communication 701
12.2.5 Velocity Measurements 603 14.5 Modem Communications 705
12.2.6 Force Transducers 605 14.5.1 FSK Modem 705
12.2.7 Temperature Transducers 606 14.5.2 Phase-Encoded Modems 708
12.3 DAS Design 611 14.5.3 Quadrature Amplitude
12.3.1 Introduction and Definitions 611 Modems 709
12.3.2 Using Nyquist Theory to Determine 14.6 Exercises 710
Sampling Rate 612
14.7 Lab Assignments 714
12.3.3 How Many Bits Does One Need
for the ADC? 615
12.3.4 Specifications for the Analog Signal
Processing 615 15 Digital Filters 716
12.3.5 How Fast Must the ADC Be? 620
15.1 Basic Principles 717
12.3.6 Specifications for the S/H 620
15.2 Simple Digital Filter
12.4 Analysis of Noise 621
Examples 719
12.4.1 Thermal Noise 621
12.4.2 Shot Noise 624 15.3 Impulse Response 726
12.4.3 1/f, or Pink, Noise 624 15.4 High-Q 60-Hz Digital Notch
12.4.4 Galvanic Noise 624 Filter 729
12.4.5 Motion Artifact 624 15.5 Effect of Time Jitter on Digital
12.4.6 Electromagnetic Field Induction 625 Filters 734
12.4.7 Techniques to Measure Noise 625
15.6 Discrete Fourier Transform 736
12.4.8 Techniques to Reduce Noise 627
15.7 FIR Filter Design 736
12.5 Data Acquisition Case Studies 629
15.8 Direct-Form Implementations 739
12.6 Exercises 639
15.9 Exercises 740
12.7 Lab Assignments 647
15.10 Lab Assignments 742
13 Microcomputer-Based
Control Systems 648 Appendix 1 744
13.1 Introduction to Digital Control Appendix 2 766
Systems 648
13.2 Open-Loop Control Systems 649 Index 781
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1 Microcomputer-Based
Systems

Chapter 1 objectives are to introduce:


c Embedded systems
c Practical aspects of digital logic
c Architecture of the Freescale MC9S12 family
c Parallel port input/output operations

The overall objective of this book is to teach the design of embedded systems. It
is an effective approach to learn new techniques by doing them. But, the dilemma
in teaching a laboratory-based topic such as embedded systems is that there is a
tremendous volume of details that first must be learned before microcomputer
hardware and software systems can be designed. The approach taken in this book
is to learn by doing, starting with very simple problems and building up to more
complex systems later in the book.
We will begin with a short section introducing some terminology and the
basic components of a computer system. In order to understand the context of
our designs, we will overview the general characteristics of embedded systems.
It is in these discussions that we develop a feel for the range of possible
embedded applications. Because courses taught using this book typically have a
lab component, we will review some practical aspects of digital logic. We then
introduce the specific architectures of the Freescale MC9S12 family. For more
detailed information concerning your specific microcomputer, refer to the
respective Freescale manual. Data sheets for the devices we will use can be
found in PDF format at http://users.ece.utexas.edu/~valvano. At the end of
the chapter, we will discuss prototyping methods to build embedded systems
and present a simple example with binary inputs and outputs.
Even though we will design systems based specifically on the MC9S12C32,
these solutions can, with little effort, be implemented on other versions of the
MC9S12 family. If your overall goal is to develop assembly language software,
then the C code can serve to clarify the software algorithms. If your overall
goal is to develop C code, then I strongly advise you to learn enough assembly
language so that you can understand the machine code that your compiler
generates. From this understanding, you can evaluate, debug, and optimize
your system.

1
Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
2 1 䡲 Microcomputer-Based Systems

1.1 Computer Architecture


A computer system combines a processor, random access memory (RAM), read only
memory (ROM), and input/output (I/O) ports, as shown in Figure 1.1. Software is an
ordered sequence of very specific instructions that are stored in memory, defining exactly
what and when certain tasks are to be performed. The processor executes the software by
retrieving and interpreting these instructions one at a time. A microprocessor is a small
processor, where small refers to size (i.e., it fits in your hand) and not computational abil-
ity. For example, the Intel Pentium and the PowerPC are microprocessors. A microcom-
puter is a small computer, where again small refers to size (i.e., you can carry it) and not
computational ability. For example, a desktop PC is a microcomputer. A very small micro-
computer, called a microcontroller, contains all the components of a computer (processor,
memory, I/O) on a single chip. The Freescale MC9S12C32 used in this book is a micro-
controller. Because a microcomputer is a small computer, this term can be confusing
because it is used to describe a wide range of systems from an 8-bit 6811 running at 2 MHz
with 512 bytes of memory to a personal computer with a state-of-the-art 64-bit processor
running at multi-GHz speeds having terabytes of storage.

Figure 1.1
Computer Bus
The basic components of
a computer system
Processor
include processor,
Input Input
memory, and I/O. signals
ports External Physical
RAM circuits devices
Output Output
ports signals
ROM
Control
Address
Data

The computer can store information in RAM by writing to it, or it can retrieve previ-
ously stored data by reading from it. Most RAMs are volatile, meaning if power is inter-
rupted and restored, the information in the RAM is lost. Information is programmed into
ROM using techniques more complicated than writing to RAM. On the other hand, retriev-
ing data from a ROM is identical to retrieving data from RAM. ROMs are nonvolatile,
meaning if power is interrupted and restored, the information in the ROM is retained. Some
ROMs are programmed at the factory and can never be changed. A Programmable ROM
(PROM) can be erased and reprogrammed by the user, but the erase/program sequence is
typically 10000 times slower than the time to write data into a RAM. Some PROMs are
erased with ultraviolet light and programmed with voltages, whereas electrically erasable
PROMs (EEPROM) are both erased and programmed with voltages. Flash ROM is a popu-
lar type of EEPROM. For most of the systems in this book, we will store instructions and
constants in ROM and place variables and temporary data in RAM.
Checkpoint 1.1: What are the differences between a microcomputer, a micro-
processor, and a microcontroller?

The external devices attached to the computer provide functionality for the system.
An input port is hardware on the computer that allows information about the external

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.1 䡲 Computer Architecture 3

world to be entered into the computer. The computer also has hardware called an output
port to send information out to the external world. An interface is defined as the collec-
tion of the I/O port, external electronics, physical devices, and the software, which com-
bine to allow the computer to communicate with the external world. An example of an
input interface is a switch, where the operator moves the switch, and the software can
recognize the switch position. An example of an output interface is a light-emitting
diode (LED), where the software can turn the light on and off, and the operator can see
whether or not the light is shining. There is a wide range of possible inputs and outputs,
which can exist in either digital or analog form. In general, we can classify I/O inter-
faces into four categories
parallel—binary data is available simultaneously on a group of lines
serial—binary data is available one bit at a time on a single line
analog—data is encoded as an electrical voltage, current, or power
time—data is encoded as a period, frequency, pulse width, or phase shift

Checkpoint 1.2: What are the differences between an input port and an input
interface?

Checkpoint 1.3: List three input interfaces available on a personal computer.

Checkpoint 1.4: List three output interfaces available on a personal computer.

In this book, numbers that start with $ (e.g., $64) are specified in hexadecimal, which
is base 16. In C, we start hexadecimal numbers with 0x (e.g., 0x64). Intel assembly lan-
guage adds an “H” at the end to specify hexadecimal (e.g., 64H). Texas Instruments uses
“h” (e.g., 64h).
In a system with memory-mapped I/O, as shown in Figure 1.1, the I/O ports are con-
nected to the processor in a manner similar to memory. I/O ports are assigned addresses,
and the software accesses I/O using reads and writes to the specific I/O addresses. The soft-
ware inputs from an input port using the same instructions as it would if it were reading
from memory. Similarly, the software outputs from an output port using the same instruc-
tions as it would if it were writing to memory. The processor, memory, and I/O are con-
nected together by an address bus, a data bus, and a control bus. Together, these buses direct
the data transfer between the various modules in the computer. A bus is defined as a col-
lection of signals, which are grouped for a common purpose. For example, the address bus
on the 9S12 is 16 signals (A15-A0), which together specify the memory address ($0000 to
$FFFF) that is currently being accessed. The address specifies both which module (input,
output, RAM or ROM) as well as which cell within the module will communicate with the
processor. The data bus contains the information that is being transferred, which on the
9S12 is 16 bits (D15-D0), but it can transfer either 8-bit or 16-bit data. The control bus spec-
ifies the timing and the direction of the transfer. We call a complete data transfer a bus cycle.
In a simple computer system, like the 9S12, only two types of transfers are allowed, as
shown in Table 1.1. In this simple system, the processor always controls the address (where
to access), the direction (read or write), and the control (when to access.) The MC9S12C32
has 2048 bytes of RAM located at addresses $3800 to $3FFF. Figure 1.2 illustrates how the

Table 1.1 Type Address Driven by Data Driven by Transfer


Simple computers
generate two types of Memory Read Cycle Processor RAM, ROM Data copied to
cycles. or Input processor
Memory Write Cycle Processor Processor Data copied to Output
or RAM

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
4 1 䡲 Microcomputer-Based Systems

processor fetches the 8-bit contents of location $3800 using a read cycle. Assume memory
at address $3800 has the value $98. The processor first places the RAM address $3800 on
the address bus, then the processor issues a read command on the control bus. The memory
will respond by placing its $98 information on the data bus, and lastly the processor will
accept the data and terminate the read command.

Figure 1.2
A memory read cycle $98
copies data from RAM, $3800 Memory read cycle
ROM, or an input device R
into the processor. Processor
Input Input
ports signals
RAM $98
Output Output
ports signals
ROM
Control
Address
Data

Figure 1.3 illustrates how the processor stores the 8-bit value $25 into RAM location
$3800 using a write cycle. The processor first places the RAM address $3800 on the address
bus. Next, the processor places the $25 information on the data bus, and then the processor
issues a write command on the control bus. The memory will respond by storing the $25
information into the proper place, and after the processor is sure the memory has captured
the data, it will terminate the write command.

Figure 1.3
A memory write cycle $25
copies data from the $3800 Memory write cycle
processor into RAM or W
$25
an output device. Processor
Input Input
ports signals
RAM
Output Output
ports signals
ROM
Control
Address
Data

You see that if we wish to transfer data from an input device into RAM, we must first
transfer it from input to the processor, then from the processor into RAM. In some micro-
controllers, such as the ARM Cortex-M3 and in all desktop PCs, we can transfer data
directly from input to RAM or from RAM to output using direct memory access (DMA).
The bandwidth of an I/O device is the number of information bytes/sec that can be trans-
ferred. Because DMA is faster, we will use this method to interface high bandwidth devices
such as disks and networks. During a read DMA cycle (Figure 1.4), data flows directly from
the memory to the output device. Many systems that support DMA also allow data to be
transferred from memory to memory (See Chapter 10).

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.1 䡲 Computer Architecture 5

Figure 1.4
A DMA read cycle copies $98
data from RAM, ROM, $3800 DMA read cycle
or an input device into R
an output device. Processor
Input Input
ports signals
RAM $98
Output Output
ports signals
ROM
Control
Address
Data

During a write DMA cycle (Figure 1.5) data flows directly from the input device to
memory.

Figure 1.5
A DMA write cycle $25
copies data from the $3800 DMA write cycle
input device into RAM or W
an output device. Processor
Input Input
$25
ports signals
RAM
Output Output
ports signals
ROM
Control
Address
Data

Input/output devices are important in all computers, but they are especially signifi-
cant in an embedded system. In a computer system with I/O-mapped I/O, the control bus
signals that activate the I/O are separate from those that activate the memory devices.
These systems have a separate address space and separate instructions to access the I/O
devices. The original Intel 8086 had four control bus signals: MEMR, MEMW, IOR, and
IOW. MEMR and MEMW were used to read and write memory, while IOR and IOW
were used to read and write I/O. The Intel x86 refers to any of the processors that Intel
has developed based on this original architecture. Even though we do not consider the
personal computer (PC) an embedded system, there are embedded systems developed on
this architecture. One such platform is called the PC/104 Embedded-PC. The Intel x86
processors continue to implement this separation been memory and I/O. Currently, there
are 32 to 64 memory address lines, but only 16 of those lines are used to access I/O
devices. The other address lines are not used during an I/O bus cycle. Rather than use the
regular memory access instructions, the Intel x86 processor uses special in and out
instructions to access the I/O devices. The advantages of I/O-mapped I/O are that soft-
ware can not inadvertently access I/O when it thinks it is accessing memory. In other
words, it protects I/O devices from common software bugs, such as bad pointers, stack
overflow, and buffer overflows. In contrast, systems with memory-mapped I/O are easier
to design, and the software is easier to write.
The processor within the 9S12 microcontroller has four major components, as illus-
trated in Figure 1.6. The bus interface unit (BIU) reads data from the bus during a read
cycle, and writes data onto the bus during a write cycle. The 9S12 has a single processor and

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
6 1 䡲 Microcomputer-Based Systems

does not support DMA. Therefore, the BIU always drives the address bus and the control
signals of the bus. The effective address register (EAR) contains the memory address used
to fetch the data needed for the current instruction.

Figure 1.6 Embedded system


The four basic the
Microcontroller 9S12
components of 9S12 Electrical,
processor. Processor Bus interface unit RAM mechanical,
Registers EAR ROM chemical,
CCR or
A:B optical
X I/O Ports devices
Y Control unit ALU
SP
PC IR ADC Analog
signals
Address/data/control bus

The control unit (CU) orchestrates the sequence of operations in the processor. The CU
issues commands to the other three components. The instruction register (IR) contains the oper-
ation code (or opcode) for the current instruction. Most 9S12 opcodes are 8 bits wide, but some
are 16 bits. Most instructions have two parts, the opcode that defines the function to perform,
and an operand that specifies the data to be used. In an embedded system the software is con-
verted to machine code, which is a list of instructions, and stored in nonvolatile memory. When
the system is running, instructions one at a time are fetched from memory and executed.
The registers are high-speed storage devices located in the processor. Registers do not
have addresses like regular memory, but rather they have specific functions explicitly
defined by the instruction. Accumulators are registers that contain data. Index registers con-
tain addresses. The program counter (PC) points to the memory containing the instruction
to execute next. In an embedded system, the PC usually points into nonvolatile memory
(e.g., ROM, EPROM, or EEPROM). The information stored in nonvolatile memory (e.g.,
the instructions) is not lost when power is removed. The stack pointer (SP) points to the
RAM and defines the stack. The stack is an extremely important component of software
development and can be used to pass parameters, save temporary information, and imple-
ment local variables. The internal RAM of the 9S12 is volatile memory, meaning its infor-
mation is lost when power is removed. On some systems, such as calculators and PDAs, a
separate battery powers the RAM, creating nonvolatile RAM. The condition code register
(CCR) contains the status of the previous operation, as well as some operating mode flags
such as the interrupt enable bit. This register is called the flag register on the Intel computers.
The arithmetic logic unit (ALU) performs arithmetic and logic operations. Addition,
subtraction, multiplication, and division are examples of arithmetic operations. And, or,
exclusive or, and shift are examples of logical operations.
Checkpoint 1.5: For what do the acronyms CU DMA BIU ALU stand?

In general, the execution of an instruction goes through four phases. First, the computer
fetches the machine code for the instruction by reading the value in memory pointed to by
the program counter (PC). Some instructions are only one byte long, while others are two or
more bytes. After each byte of the instruction is fetched, the PC is incremented. At this time,
the instruction is decoded, and the effective address is determined (EAR). Many instructions
require additional data, and during phase 2, the data is retrieved from memory at the effec-
tive address. Next, the actual function for this instruction is performed. Often, the computer
bus is idle at this time, because no additional data is required. During the last phase, the
results are written back to memory. All instructions have a phase 1, but the other three phases

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.2 䡲 Embedded Computer Systems 7

may or may not occur for any specific instruction. Each of the phases may require one or
more bus cycles to complete. Each bus cycle reads or writes one piece of data. The 9S12 bus
cycle can transfer 8-bit or 16-bit data.

Phase Function R/W Address Comment


1 Instruction fetch read PC++ Put into IR,
2 Data read read EAR Data passes through ALU,
3 Operation none ALU operations, set CCR
4 Data store write EAR Results stored in memory

1.2 Embedded Computer Systems


An embedded computer system is an electronic system that includes a microcomputer such
as the Freescale 9S12 that is configured to perform a specific dedicated application, drawn
previously as Figure 1.6. To better understand the expression embedded microcomputer
system, consider each word separately. In this context, the word embedded means “hidden
inside so one can’t see it.” The software that controls the system is programmed or fixed
into ROM and is not accessible to the user of the device. Even so, software maintenance,
which is verification of proper operation, updates, fixing bugs, adding features, extending
to new applications, updating end user configurations, is still extremely important. In this
book, we will develop techniques that facilitate this important aspect of system design.
Embedded systems have these four characteristics.
First, embedded systems typically perform a single function. Consequently, they solve
only a limited range of problems. For example, the embedded system in a microwave oven
may be reconfigured to control different versions of the oven within a similar product line.
Still, a microwave oven will always be a microwave oven, and you can’t reprogram it to be
a dishwasher. What makes each embedded system unique are the I/O ports of the micro-
controller and the external devices interfaced to them.
Second, embedded systems are tightly constrained. There are typically very specific per-
formance parameters within which the system must operate. For example, a cell-phone car-
rier typically gets 832 radio frequencies to use in a city, a hand-held video game must cost less
than $50, an automotive cruise control system must operate the vehicle within 3 mph of the
set-point speed, and a portable MP3 player must operate for 12 hours on one battery charge.
Third, many embedded systems must operate in real time. In a real-time computer
system, we can put an upper bound on the time required to perform the input-calculation-
output sequence. A real-time system can guarantee a worst-case upper bound on the response
time between when the new input information becomes available and when that information
is processed. Another real-time requirement that exists in many embedded systems is the exe-
cution of periodic tasks. A periodic task is one that must be performed at equal time intervals.
A real-time system can put a small and bounded limit on the interval between when a task
should be run and when it is actually run. Because of the real-time nature of these systems,
microcontrollers like the 9S12 have a rich set of features to handle all aspects of time.
The fourth characteristic of embedded systems is their small memory requirements.
There are exceptions to this rule, such as those that process video or audio, but most have
memory requirements measured in thousands of bytes.
There have been two trends in the microcontroller field. The first trend is to make
microcontrollers smaller, cheaper, and with lower power. The Microchip PIC and Texas
Instruments MSP430 families are good examples of this trend. Size, cost, and power are
critical factors for high-volume products, where the products are often disposable. On the
other end of the spectrum is the trend of larger RAM and ROM, faster processing, and
increasing integration of complex I/O devices, such as Ethernet, radio, graphics, and audio.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
8 1 䡲 Microcomputer-Based Systems

It is common for one device to have multiple microcontrollers, where the operational tasks are
distributed and the microcontrollers are connected in a local area network (LAN). These high-
end features are critical for consumer electronics, medical devices, automotive controllers, and
military hardware, where performance and reliability are more important than cost. However,
small size and low power continue as important features for all embedded systems.
Checkpoint 1.6: What is an embedded system?

The computer engineer has many design choices to make when building a real-time
embedded system. Often, defining the problem, specifying the objectives, and identifying
the constraints are harder than actual implementations. In this book, we will develop com-
puter engineering design processes, introducing fundamental methodologies for problem
specification, prototyping, testing, and performance evaluation.
In this book, we will refer to devices such as the Freescale MC9S12C32 simply as 9S12.
The different versions of the microcomputers contain varying amounts of memory and
input/output (I/O) devices. A typical automobile now contains an average of ten microcon-
trollers. In fact, upscale homes may contain as many as 150 microcontrollers, and the average
consumer now interacts with microcontrollers up to 300 times a day. As shown in Figure 1.7,
the general areas that employ embedded microcomputers encompass every field of engineering:
䡲 Communications
䡲 Automotive
䡲 Military
䡲 Medical
䡲 Consumer
䡲 Machine control

Medical
Automotive

Communications
Military

Comsumer Industrial

Figure 1.7
Example embedded computer systems.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.2 䡲 Embedded Computer Systems 9

Table 1.2 presents typical embedded microcomputer applications and the function per-
formed by the embedded microcomputer. Each microcomputer accepts inputs, performs
calculations, and generates outputs. We must also learn how to interface a wide range of
inputs and outputs that can exist in either digital or analog form.
Checkpoint 1.7: There is a microcontroller embedded in an alarm clock. List three
operations the software must perform.

In contrast, a general-purpose computer system typically has a keyboard, disk, and


graphics display and can be programmed for a wide variety of purposes. Typical general-
purpose applications include word processing, electronic mail, business accounting, scien-
tific computing, and data base systems. General-purpose computers have the opposite of the
four characteristics previously listed. First, they can perform a wide and dynamic range

Table 1.2 Function Performed by the Microcomputer


Embedded system
applications. Consumer:
Washing machine Controls the water and spin cycles
Exercise equipment Measures speed, distance, calories, heart rate
Remote controls Accepts key touches, sends infrared pulses
Clocks and watches Maintains the time, alarm, and display
Games and toys Entertains the user, joystick input, video output
Audio/video electronics Interacts with the operator, enhances performance
Communication:
Phone answering machines Plays outgoing and saves incoming messages
Telephone system Switches signals and retrieves information
Cellular phones, pagers Interacts with key pad, microphone, and speaker
Automotive:
Automatic braking Optimizes stopping on slippery surfaces
Noise cancellation Improves sound quality, removing noise
Theft deterrent devices Allows keyless entry, controls alarm
Electronic ignition Controls sparks and fuel injectors
Power windows and seats Remembers preferred settings for each driver
Instrumentation Collects and provides necessary information
Military:
Smart weapons Recognizes friendly targets
Missile guidance systems Directs ordnance at the desired target
Global positioning systems Determines where you are on the planet
Surveillance Collects information about enemy activities
Industrial:
Point-of-sale systems Accepts inputs and manages money
Set-back thermostats Adjusts day/night thresholds saving energy
Traffic control systems Senses car positions, controls traffic lights
Robot systems Inputs from sensors, controls the motors
Inventory systems Inputs from bar code readers, prints labels
Automatic sprinklers Controls the wetness of the soil
Medical:
Infant apnea monitors Detects breathing, alarms if stopped
Glucose monitors Measures blood sugar levels in diabetics
Cardiac monitors Measures heart function, alarms if problem
Drug delivery Administers proper doses
Cancer treatments Controls doses of radiation, drugs, or heat
Pacemakers Sends pulses to the heart to make it beat
Prosthetic devices Increases mobility for the handicapped

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
10 1 䡲 Microcomputer-Based Systems

of functions. Because the general-purpose computer has a removable disk or network


interface, new programs can easily be added to the system. The user of a general-purpose
computer does have access to the software that controls the machine. In other words, the
user decides which operating system to run and which applications to launch. Second,
they are loosely constrained. For example, the Java machine used by a web browser will
operate on a extremely wide range of computer platforms. Third, general-purpose
machines do not run in real time. Yes, we would like the time to print a page on the printer
to be fast, and we would like web page to load quickly, but there are no guaranteed
response times for these types of activities. In fact, the real-time tasks that do exist (such
as sound recording, burning CDs, and graphics) are actually performed by embedded
systems built into the computer. Fourth, general-purpose computers employ billions, if
not trillions, of memory cells.
The most common type of general-purpose computer is the personal computer (e.g.,
the Pentium-based IBM-PC compatible and Macintosh). Computers more powerful than
the personal computer can be grouped in the workstation ($10,000 to $50,000 range) or the
supercomputer categories (above $50,000). See the web site www.top500.org for a list of
the fastest computers on the planet. These computers often employ multiple processors and
have much more memory than the typical personal computer. The workstations and super-
computers are used for handling large amounts of information (business applications), run-
ning large simulations (weather forecasting), searching (www.google.com), or performing
large calculations (scientific research). This book will not cover the general-purpose com-
puter, although many of the basic principles of embedded computers do apply to all types
of systems.
The I/O interfaces are a crucial part of an embedded system because they provide nec-
essary functionality. Most personal computers have the same basic I/O devices (mouse,
keyboard, display, CD, USB, etc.) In contrast, there is no common set of I/O that all
embedded system have. The software together with the I/O ports and associated interface
circuits give an embedded computer system its distinctive characteristics. A device driver
is a set of software functions that facilitate the use of an I/O port. Another name for device
driver is application programmer interface (API). In this book we will study a wide range
of I/O ports supported by the Freescale microcomputers. Parallel ports provide for digital
input and/or outputs. Serial ports include the synchronous Serial Peripheral Interface
(SPI) and asynchronous Serial Communications Interface (SCI), which have a wide range
of software selectable baud rates and are optimized to minimize CPU overhead. The SPI
also enables synchronous communication between the microcontroller and peripheral
devices such as

Sensors
Liquid Crystal Display (LCD) and light emitting diode (LED) displays
Analog to digital converters (ADC) and digital to analog converters (DAC)
Other microprocessors

Analog to digital converters convert analog voltages to digital numbers, and they are avail-
able on the 9S12 with 8-bit and 10-bit resolution. The timer features on the Freescale micro-
computers include

Fixed periodic rate interrupts


Computer Operating Properly (COP) protection against software failures
Pulse accumulator for external event counting or gated time accumulation
Pulse Width Modulated outputs (PWM)
Event counter system for advanced timing operations
Input capture used for period and pulse width measurement
Output compare used for generating signals and frequency measurement

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.3 䡲 The Design Process 11

1.3 The Design Process


1.3.1 In this section, we introduce the design process. The process is called top-down, because
Top-Down we start with the high-level designs and work down to low-level implementations. The basic
Design approach is introduced here, and the details of these concepts are presented throughout the
remaining chapters of the book. As we learn software/hardware development tools and
techniques, we can place them into the framework presented in this section. As illustrated
in Figure 1.8, the development of a product follows an analysis-design-implementation-
testing cycle. For complex systems with long life-spans, we traverse multiple times around
the development cycle. For simple systems, a one-time pass may suffice.

Figure 1.8 • Specifications


System development • Constraints High
• Block diagrams
cycle. level
• Data flow graphs
New requirements Analyze design
the
New constraints problem
Engineering
Not done design

Done • Call graphs


Testing • Hardware • Data structures
• Software Implement- • I/O interfaces
ation

During the analysis phase, we discover the requirements and constraints for our pro-
posed system. We can hire consultants and interview potential customers in order to gather
this critical information. A requirement is a general parameter that the system must satisfy.
We begin by rewriting the system requirements, which are usually written in general form,
into a list of detailed specifications. In general, specifications are detailed parameters
describing how the system should work. For example, a requirement may state that the
system should fit into a pocket, whereas a specification would give the exact size and weight
of the device. For example, suppose we wish to build a motor controller. During the analy-
sis phase, we would determine obvious specifications such as range, stability, accuracy, and
response time. There may be less obvious requirements to satisfy, such as weight, size,
battery life, product life, ease of operation, display readability, and reliability. Often,
improving the performance of one parameter can be achieved only by decreasing the per-
formance of another. This art of compromise defines the tradeoffs an engineer must make
when designing a product. A constraint is a limitation, within which the system must oper-
ate. The system may be constrained as to such factors as cost, safety, compatibility with
other products, use of specific electronic and mechanical parts as employed in other
devices, interfaces with other instruments and test equipment, and development schedule.
The following measures are often considered during the analysis phase of a project:
Safety: The risk to humans or the environment
Accuracy: The difference between desired and actual parameter performance
Precision: The number of distinguishable measurements
Resolution: The smallest change that can be reliably detected
Response time: The time difference between triggering event and resulting action
Bandwidth: The amount of information processed per time unit
Maintainability: The flexibility with which the device can be modified
Testability: The ease with which proper operation of the device can be verified

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
12 1 䡲 Microcomputer-Based Systems

Compatibility: The conformity of the device to existing standards


Mean time between failure: The reliability of the device
Size and weight: The physical space required by the system
Power: The amount of energy it takes to operate the system
Nonrecurring engineering cost (NRE cost): The one-time cost to design and test the
product
Unit cost: The cost required to manufacture one additional product
Time-to-prototype: The time required to design, build, and test an example system
Time-to-market: The time required to deliver the product to the customer
Human factors: The degree to which our customers enjoy or appreciate the product

Checkpoint 1.8: What’s the difference between a requirement and a specification?

The following is one possible outline of a software requirements document. IEEE


publishes a number of templates that can be used to define a project (IEEE STD 830-
1998). A requirements document states what the system will do. It does not state how
the system will do it. The main purpose of a requirements document is to serve as an
agreement between you and your clients describing what the system will do. This agree-
ment can become a legally binding contract. Write the document so that it is easy to
read and understand by others. It should be unambiguous, complete, verifiable, and
modifiable.
1. Overview
1.1. Objectives: Why are we doing this project? What is the purpose?
1.2. Process: How will the project be developed?
1.3. Roles and Responsibilities: Who will do what? Who are the clients?
1.4. Interactions with Existing Systems: How will it fit in?
1.5. Terminology: Define terms used in the document.
1.6. Security: How will intellectual property be managed?
2. Function Description
2.1. Functionality: What will the system do precisely?
2.2. Scope: List the phases and what will be delivered in each phase.
2.3. Prototypes: How will intermediate progress be demonstrated?
2.4. Performance: Define the measures and describe how they will be determined.
2.5. Usability: Describe the interfaces. Be quantitative if possible.
2.6. Safety: Explain any safety requirements and how they will be measured.
3. Deliverables
3.1. Reports: How will the system be described?
3.2. Audits: How will the clients evaluate progress?
3.3. Outcomes: What are the deliverables? How do we know when the system
is done?
During the high-level design phase, we build a conceptual model of the hardware and
software system. It is in this model that we employ as much abstraction as appropriate. The
project is broken in modules or subcomponents. Modular design will be presented in
Chapter 2. During this phase, we estimate the cost, schedule, and expected performance
of the system. At this point we can decide whether the project has a high enough potential
for profit. A data flow graph is a block diagram of the system, showing the flow of infor-
mation. Arrows point from source to destination. The rectangles represent hardware com-
ponents and the ovals are software modules. We use data flow graphs in the high-level
design, because they describe the overall operation of the system while hiding the details
of how it works. Issues such as safety (e.g., Isaac Asimov’s first Law of Robotics: “A robot
may not harm a human being, or, through inaction, allow a human being to come to harm”)
and testing (e.g., we need to verify that our system is operational) should be addressed
during the high-level design.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.3 䡲 The Design Process 13

An example data flow graph for a motor controller is shown in Figure 1.9. The require-
ment of the system is to deliver power to a motor so that the speed of the motor equals the
desired value set by the operator using a keypad. In order to make the system easier to use
and to assist in testing, a liquid crystal display (LCD) is added. The sensor converts motor
speed into an electrical voltage. The amplifier converts this signal into the 0 to 5V voltage
range required by the ADC. The ADC converts analog voltage into a digital sample. The
ADC routines, using the ADC and timer hardware, collect samples and calculate voltages.
Next, this software uses a table data structure to convert voltage into measured speed. The
user will be able to select the desired speed using the Keypad interface. The desired and
measured speed data are passed to the Controller software, which will adjust the power
output in such a manner as to minimize the difference between the measured speed and the
desired speed. Finally, the power commands are output to the actuator module. The actua-
tor interface converts the digital control signals to power delivered to the motor. The meas-
ured speed and speed error will be sent to the LCD module. The solution to this problem will
be presented in Chapter 13.

Figure 1.9
A data flow graph Speed
Sensor Voltage Analog Voltage ADC
showing how signals amplifier
pass through a motor Motor Timer
controller.
Power Voltage Digital Digital
Actuator Interface control sample

ADC
ASCII routines
Keypad Desired Measured
Keypad Interface speed speed
routines

Controller
software Table
ASCII Speeds lookup
LCD Interface LCD
routines

The next phase is engineering design. We begin by constructing a preliminary design.


This system includes the overall top-down hierarchical structure, the basic I/O signals,
shared data structures, and the overall software scheme. At this stage there should be a
simple and direct correlation between the hardware/software systems and the conceptual
model developed in the high-level design. Next, we finish the top-down hierarchical struc-
ture, and build mock-ups of the mechanical parts (connectors, chassis, cables, etc.) and user
software interface. Sophisticated 3-D CAD systems can create realistic images of our
system. Detailed hardware designs must include mechanical drawings. It is a good idea to
have a second source, which is an alternative supplier that can sell us our parts if the first
source can’t deliver on time. Call-graphs are a graphical way to define how the soft-
ware/hardware modules interconnect. A hierarchical system will have a tree-structured call
graph. Data structures include both the organization of information and mechanisms to
access the data. Again safety and testing should be addressed during this low-level design.
A call-graph for this motor controller is shown in Figure 1.10. Again, rectangles rep-
resent hardware components and ovals show software modules. An arrow points from the
calling routine to the module it calls. The I/O ports are organized into groups and placed at
the bottom of the graph. A high-level call-graph, like the one shown in Figure 1.10, shows
only the high-level hardware/software modules. A detailed call-graph would include each
software function and I/O port. Normally, hardware is passive and the software initiates
hardware/software communication, but as we will learn in Chapter 4, it is possible for the
hardware to interrupt the software and cause certain software modules to be run. In this
system, the timer hardware will cause the ADC software to collect a sample at a regular rate.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
14 1 䡲 Microcomputer-Based Systems

Figure 1.10
A call flow graph for a Controller
motor controller. software
Timer

ADC Actuator LCD Keypad


routines routines routines routines

ADC Actuator LCD Keypad

The Controller software calls the Keypad routines to get the desired speed, calls the ADC
software to get the motor speed at that point, determines what power to deliver to the motor,
and updates the actuator by sending the power value to the Actuator interface. The
Controller software calls the LCD routines to display the status of the system. As we will
see in Chapters 11–15, acquiring data, calculating parameters, and outputting results at a
regular rate is strategic when performing digital processing in embedded systems.
Checkpoint 1.9: What confusion could arise if two software modules were allowed
to access the same I/O port? This situation would be evident on a call-graph if the two
software modules had arrows pointing to the same I/O port.

Observation: If module A calls module B, and B returns data, then a data flow graph
will show an arrow from B to A, but a call-graph will show an arrow from A to B.

The next phase is implementation. An advantage of a top-down design is that imple-


mentation of subcomponents can occur concurrently. During the initial iterations of the
development cycle, it is quite efficient to implement the hardware/software using simula-
tion. One major advantage of simulation is that it is usually quicker to implement an initial
product on a simulator than to construct a physical device out of actual components. Rapid
prototyping is important in the early stages of product development. This allows for more
loops around the analysis-design-implementation-testing cycle, which in turn leads to a
more sophisticated product.
Recent software and hardware technological developments have made significant
impacts on the software development process for embedded microcomputers. The simplest
approach is to use a cross-assembler or cross-compiler to convert source code into the
machine code for the target system. The machine code can then be loaded into the target
machine. Debugging embedded systems with this simple approach is very difficult for two
reasons. First, the embedded system lacks the usual keyboard and display that assist us
when we debug regular software. Second, the nature of embedded systems involves the
complex and real-time interaction between the hardware and software. These real-time
interactions make it impossible to test software with the usual single-stepping and print
statements.
The next technological advancement that has greatly affected the manner in which
embedded systems are developed is simulation. Because of the high cost and long times
required to create hardware prototypes, many preliminary feasibility designs are now per-
formed using hardware/software simulations. A simulator is a software application that
models the behavior of the hardware/software system. If both the external hardware and soft-
ware program are simulated together, even through the simulated time is slower than the clock
on the wall, the real-time hardware/software interactions can be studied.
During the testing phase, we evaluate the performance of our system. First, we debug
the system and validate basic functions. Next, we use careful measurements to optimize

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.3 䡲 The Design Process 15

performance, such as static efficiency (memory requirements), dynamic efficiency (execu-


tion speed), accuracy (difference between truth and measured), and stability (consistent
operation). Debugging techniques are presented in Chapter 2.
Maintenance is the process of correcting mistakes, adding new features, optimizing
for execution speed or program size, porting to new computers or operating systems, and
reconfiguring the system to solve a similar problem. No system is static. Customers may
change or add requirements or constraints. To be profitable, we probably will wish to tailor
each system to the individual needs of each customer. Maintenance is not really a separate
phase, but rather involves additional loops around the development cycle.

1.3.2 Figure 1.8 describes top-down design as a cyclic process, beginning with a problem state-
Bottom-Up ment and ending up with a solution. With a bottom-up design we begin with solutions and
Design build up to a problem statement. Many innovations begin with an idea, “what if . . .?” In a
bottom-up design, one begins with designing, building, and testing low-level components.
Figure 1.11 illustrates a two-level process, combining three subcomponents to create the
overall product. This hierarchical process could have more levels and/or more components
at each level. The low-level designs can occur in parallel. The design of each component is
cyclic, iterating through the design-build-test cycle until the performance is acceptable.
Bottom-up design may be inefficient because some subsystems may be designed, built, and
tested but never used. As the design progresses the components are fit together to make the
system more and more complex. Only after the system is completely built and tested does
one define the overall system specifications. The bottom-up design process allows creative
ideas to drive the products a company develops. It also allows one to quickly test the feasi-
bility of an idea. If one fully understands a problem area and the scope of potential solu-
tions, then a top-down design will arrive at an effective solution most quickly. On the other
hand, if one doesn’t really understand the problem or the scope of its solutions, a bottom-up
approach allows one to start off by learning about the problem.

Observation: A good engineer knows both bottom-up and top-down design meth-
ods, choosing the approach most appropriate for the situation at hand.

Figure 1.11 • Specifications


System development • Constraints Done No
process illustrating Analyze Testing
bottom-up design.

• Block diagrams
High
• Data flow graphs
level Done
design
Done
Done
Testing Testing

• Hardware No Testing No
No
• Software
Implement- Implement-
ation Implement- ation
• Call graphs
• Data structures ation
• I/O interfaces
Engineering Engineering
design Engineering design
Idea
design Idea
Idea

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
16 1 䡲 Microcomputer-Based Systems

1.4 Digital Logic and Open Collector


Normal digital logic has two states: high and low. There are four currents of interest, as
shown in Figure 1.12, when analyzing whether the inputs of the next stage are loading the
output. IIH and IIL are the currents required of an input when high and low, respectively.
Similarly, IOH and IOL are the maximum currents available at the output when high and low.
In order for the output to properly drive all the inputs of the next stage, the maximum avail-
able output current must be larger than the sum of all the required input currents for both
the high and low conditions.

Figure 1.12
Sometimes one output |I | ≥ Σ |I |
OL IL and |I | ≥ Σ |I |
OH IH

must drive multiple IIH IIL


Input Input
inputs. IIH IIL
Output IOH Output IOL
Input Input
when IIH when IIL
high Input high Input
IIH IIL
Input Input

When we design circuits using devices all from a single logic family, we can define fan
out as the maximum number of inputs one output can drive. For transistor-transistor logic
(TTL) logic we can calculate fan out from the input and output currents:
fan out = minimum ((IOH/IIH), (IOL/IIL))

The fan out of high speed complementary metal-oxide semiconductor (CMOS)


devices like the MC9S12C32 is determined by capacitive loading and not by the currents.
Figure 1.13 shows a simple model of a CMOS interface. The ideal voltage of the output
device is labeled V1. For interfaces in close proximity, the resistance R results from the
output impedance of the output device, and the capacitance C results from the input
capacitance of the input device. However, if the interface requires a cable to connect the
two devices, both the resistance and capacitance will be increased by the cable. The volt-
age labeled V2 is the effective voltage as seen by the input. The slew rate of a signal is
the slope of the voltage versus time during the time when the logic level switches between
low and high. A similar parameter is the transition time, which is the time it takes for an
output to switch from one logic level to another. In Figure 1.13, the transition time is
defined as the time it takes V2 to go from 1.75 to 3.25 V. There is a capacitive load for
each CMOS input connected to a CMOS output. As this capacitance increases, the slew
rate decreases, which will increase the transition time. The time constant of this simple
circuit is τ = R*C. Let T be the pulse width of the digital signal. If T is large compared

Figure 1.13 Slew rate


Output R Input
Capacitance loading is 5 V1
an important factor V2
3.25 –τ/(RC)
when interfacing CMOS V1 C V2 = 5 – 5e
V2
1.75
devices. V1
0
0 T
Time
Transition time

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.4 䡲 Digital Logic and Open Collector 17

to τ, then the CMOS interface functions properly. For circuits that mix devices from one
family with another, we must look individually at the input and output currents, voltages,
and capacitive loads. Table 1.3 shows typical current values for the various digital logic
families. The MC9S12C32 allows full drive (a low R providing 10 mA) and reduced drive
(a larger R providing a smaller 2 mA) modes.

Table 1.3 Family Example IOH IOL IIH IIL Fan Out
The input and output
currents of various Standard TTL 7404 0.4 mA 16 mA 40 µA 1.6 mA 10
digital logic families and Schottky TTL 74S04 1 mA 20 mA 50 µA 2 mA 10
microcomputers. Low-power Schottky TTL 74LS04 0.4 mA 4 mA 20 µA 0.4 mA 10
High-speed CMOS 74HC04 4 mA 4 mA 1 µA 1 µA
Freescale microcomputer MC68HC11E 0.8 mA 1.6 mA 1 µA 1 µA
Freescale microcomputer MC9S12C32 10 mA 10 mA 1 µA 1 µA
Intel microcomputer 87C51 P0 7 mA 3.2 mA 10 µA 10 µA
87C51 P1,P2,P3 60 µA 1.6 mA 50 µA

Observation: For TTL devices the logic low currents are much larger than the logic
high currents.

Figure 1.14 compares the input and output voltages for many of the digital logic
families. VIL is the voltage below which an input is considered a logic low. Similarly,
VIH is the voltage above which an input is considered a logic high. VOH is the output
voltage when the signal is high. In particular, if the output is a logic high, and the cur-
rent is less than IOH, then the voltage will be greater than VOH. Similarly, VOL is the
output voltage when the signal is low. In particular, if the output is a logic low and the
current is less than IOL, then the voltage will be less than VOL. The maximum output
current specification on the 9S12 is 25 mA, which is the current above which it will

Figure 1.14 5.0 VCC 5.0 VCC 5.0 VCC 5.0 VCC
Voltage thresholds for
various digital logic 4.44 VOH
4.2 VOH
families.

3.5 VIH 3.3 VCC 3.3 VCC


3.25 VIH

2.5 VCC
2.5 Vt 2.9 VOH
2.4 VOH 2.4 VOH 2.4 VOH
2.2 VIH 2.3 VOH
1.6 VIH 2.0 VIH 2.0 VIH
1.75 VIL 1.7 VIH
1.5 VIL 1.5 Vt 1.5 Vt 1.5 Vt
1.4 VIL 1.2 Vt
1.1 VIL
0.5 VOL 0.8 VIL 0.8 VIL
0.5 VOL 0.7 VIL
0.4 VOL 0.4 VOL 0.4 VOL 0.4 VOL
0.2 VOL
0.0 Gnd 0.0 Gnd 0.0 Gnd 0.0 Gnd 0.0 Gnd 0.0 Gnd 0.0 Gnd
5V 9S12 5V CMOS ETL 5V TTL 3.3V 9S12 LVTTL 2.5V CMOS
HC, AHC, AC ABTE LS, TTL, S, ALS, LVT, LVC, ALVC, ALVT
AS, F, BCT, ABT, LV, ALB
HCT, AHCT, ACT ALVT

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
18 1 䡲 Microcomputer-Based Systems

cause damage. Normally, we design the system so the output currents are less than IOH
and IOL. Vt is the typical threshold voltage, which is the voltage at which the input usu-
ally switches between logic low and high. Formally however, an input is considered as
indeterminate for voltages between VIL and VIH. The five parameters that affect our
choice of logic families are
䡲 Power supply voltage (e.g., 5 V, 3.3 V etc.)
䡲 Power supply current (e.g., will the system need to run on batteries?)
䡲 Speed (e.g., clock frequency and propagation delays)
䡲 Output drive, IOL, IOH (e.g., does it need to drive motors or lights?)
䡲 Noise immunity (e.g., electromagnetic field interference)
䡲 Temperature (e.g., 0 to 70 C)
Common error: If the voltage applied to a high-speed CMOS input pin exists
between VIL and VIH for extended periods of time, permanent damage may occur.

Checkpoint 1.10: The 9S12 is an HC device. How will the 9S12 interpret an input pin
as the input voltage changes from 0, 1, 2, 3, 4, to 5V? That is, for each voltage, will it
be considered as a logic low, as a logic high, or as indeterminate?

Checkpoint 1.11: Considering both voltage and current, can the output of a
74HC04 drive the input of a 74LS04?

Checkpoint 1.12: Considering both voltage and current, can the output of a 74LS04
drive the input of a 74HC04?

A very important concept used in computer technology is tristate logic, which has
three output states: high, low, and off. Other names for the off state are HiZ, floating,
and tristate. As shown in Figure 1.15, the 74HC245 chip has eight bidirectional tristate
drivers. The triangle shape, drawn with a signal on the top or the bottom of the trian-
gle, is used to specify tristate control output in logic diagrams. The 74HC245 chip is
active when the output enable, OE, input is low, and the direction is controlled by the
DIR input. For example, if OE0 and DIR0, then the B1–B8 are inputs and A1–A8
are outputs, and each output An equals the corresponding Bn input. Conversely, if
OE0 and DIR1, then the A1-A8 are inputs and B1-B8 are outputs, and each output
Bn equals the corresponding An input. When OE is high, all the outputs will be off
(floating). Devices like the 74HC245 are used in microcomputer systems because of
the large output current and bidirectional tristate outputs. Tables 1.4 and 1.5 illustrate
the wide range of technologies available for digital logic design. Not all logic families
have the same choice of logic functions. tpd is the propagation delay from input to
output.

Figure 1.15
Block diagram of a DIR
74HC245 tristate driver.
OE

A1 B1

A8 B8

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.4 䡲 Digital Logic and Open Collector 19

Family Technology VIL VIH VOL VOH IOL IOH ICC tpd

LVT—Low-Voltage BiCMOS LVTTL LVTTL 64 32 190 3.5


ALVC—Advanced Low-Voltage CMOS LVTTL LVTTL 24 24 40 3.0
LVC—Low-Voltage CMOS LVTTL LVTTL 24 24 10 4.0
ALB—Advanced Low-Voltage BiCMOS LVTTL LVTTL 25 25 800 2.0
AC—Advanced CMOS CMOS CMOS 12 12 20 8.5
AHC—Advanced high-Speed CMOS CMOS CMOS 4 4 20 11.9
LV—Low-Voltage CMOS LVTTL LVTTL 8 8 20 14
Units mA mA µA ns

Table 1.4
Comparison of the output drive, power supply current, and speed of various 3.3 V logic ‘245 gates.

Family Technology VIL VIH VOL VOH IOL IOH ICC tpd

AHC—Advanced High-Speed CMOS CMOS CMOS 8 8 0.04 7.5


AHCT—Advanced High-Speed CMOS TTL CMOS 8 8 0.04 7.7
AC—Advanced CMOS CMOS CMOS 24 24 0.04 6.5
ACT—Advanced CMOS TTL CMOS 24 24 0.04 8.0
HC—High-Speed CMOS Logic CMOS CMOS 6 6 0.08 21
HCT—High-Speed CMOS Logic TTL CMOS 6 6 0.08 30
ABT—Advanced BiCMOS TTL TTL 64 32 0.25 3.5
74F—Fast Logic TTL TTL 64 15 120 6.0
BCT—BiCMOS TTL TTL 64 15 90 6.6
AS—Advanced Schottky Logic TTL TTL 64 15 143 7.5
ALS—Advanced Low-Power Schottky TTL TTL 24 15 58 10
LS—Low Power Schottky logic TTL TTL 24 15 95 12
S—Schottky Logic TTL TTL 64 15 180 9
TTL—Transistor-Transistor Logic TTL TTL 16 0.4 22 22
Units mA mA mA ns

Table 1.5
Comparison of the output drive, power supply current, and speed of various 5 V logic ‘245 gates.

The 74LS04 is a low-power Schottky NOT gate, as shown in Figure 1.16. It is called
Schottky logic because the devices are made from Schottky transistors. The output is high
when the transistor Q4 is active, driving the output to 5V. The output is low when the tran-
sistor Q5 is active, driving the output to 0.
The 74HC04 is a high-speed CMOS NOT gate, as shown in Figure 1.17. The output is
high when the transistor Q1 is active, driving the output to 5V. The output is low when
the transistor Q2 is active, driving the output to 0. Since the 9S12 is made with high-speed
CMOS logic, its outputs behave like the Q1/Q2 “push/pull” transistor pair. The 9S12
output ports are not inverting. That is, when you write a “1” to an output port, then the
output voltage goes high. Similarly, when you write a “0” to an output port, then the output
voltage goes low. Analyses of the circuit in Figure 1.17 reveal some of the basic properties
of high-speed CMOS logic. First, because of the complementary nature of the P-channel
(the one on the top) and the N-channel (the one on the bottom) transistors, when the input
is constant (continuously high or continuously low), the supply current, Icc, is very low.
Second, the gate will require supply current only when the output switches from low to high
or from high to low. This observation leads to the design rule that the power required to run
a high-speed CMOS system is linearly related to the frequency of its clock, because the fre-
quency of the clock determines the number of transitions per second. Along the same lines,

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
20 1 䡲 Microcomputer-Based Systems

Figure 1.16 Vcc


Transistor
implementation of a
low-power Schottky 8 kΩ 120 kΩ
NOT gate.

74LS04 20 kΩ
Q2
A B

Q4
A Q1 4 kΩ
B B
12 kΩ
Q5
3 kΩ
1.5 kΩ

Q3

Figure 1.17 Vcc


Transistor 74HC04
implementation of a Q1
high-speed CMOS NOT A B
A B
gate.
Q2

we see that if the voltage on input A exists between VIL and VIH for extended periods of
time, then both Q1 and Q2 are partially active, causing a short from Vcc to ground. This con-
dition can cause permanent damage to the transistors. Third, since the input A is connected
to the gate of the two MOS transistors, the input currents will be very small (1 µA). In other
words, the input impedance (input voltage divided by input current) of the gate is very high.
Normally, a high input impedance is a good thing, except when the input is not connected.
If the input is not connected, then it takes very little input currents to cause the logic level
to switch.
Common error: If unused input pins on a CMOS microcontroller are left uncon-
nected, then the input signal may oscillate at high frequencies depending on the EM
fields in the environment, wasting power unnecessarily.

Maintenance tip: It is a good design practice to connect unused CMOS inputs to


ground or connect them to 5 V.

Open collector logic has outputs with two states: low and off. The 7405 is a TTL open
collector NOT gate, as shown in Figure 1.18. When drawing logic diagrams, we add the “x”
on the output to specify open collector logic. It is called open collector because the collec-
tor pin of Q3 is not connected, or left open. The output is off when there is no active tran-
sistor driving the output. In other words, when the input is low, the output floats. This “not
driven” condition is called the open collector state. The output is low when the transistor
Q3 is active, driving the output to 0.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.4 䡲 Digital Logic and Open Collector 21

Figure 1.18 Vcc


Transistor
implementation of a
regular TTL open 4 kΩ 1.6 kΩ
collector NOT gate. 7405
A B Q2 B
A Q1
Q3
1 kΩ

The 74HC05 is a high-speed CMOS open collector NOT gate, as shown in Figure 1.19.
The output is off when there is no active transistor driving the output. In other words, when the
input is low, the output floats. The output is low when the transistor Q2 is active driving the
output to 0. Technically, the 74HC05 implements open drain rather than open collector,
because it is the drain pin of Q2 that is left open. In this book, we will use the terms open col-
lector and open drain interchangeably to refer to digital logic with two output states (low and
off). The data sheets of the 9S12 refer to open collector logic as wire or mode (WOM).

Figure 1.19 74HC05


Transistor A B
implementation of a A B
high-speed CMOS open Q2
collector NOT gate.

Because of the multiple uses of open collector, many microcomputers can implement
open collector logic. All the ports of the Intel 8051 are inherently open collector. The 9S12
PORTS also supports open collector outputs by setting the SWOM bit.
Observation: The 7405 and 74HC05 are inverting open collector examples, but most
microcomputer output ports are not inverting. That is, when you write a “1” to an
open-collector output port, then the output floats, and when you write a “0” to an
open-collector output port, then the output voltage goes low.

In general, we can use an open collector NOT gate to control the current to a device,
such as a relay, a light emitting diode (LED), a solenoid, a small motor, or a small light. We
used the open collector NOT gate in the LED interface shown in Figure 1.20 to control the
current to our diode. When input to the 7405 is high (p  1, which means 5 V), the output
is low (q0, which means 0 V). In this state, a 10 mA current is applied to the diode,
and it lights up. But, when the input is low (p  0, which means 0 V), the output floats
(q  HiZ, which is neither high or low). This floating output state causes the LED current
to be zero, and the diode is dark. The resistor choice will be explained in Chapter 8.

Figure 1.20 μC
+5 V
Open collector used to 200 Ω
interface a light emitting LED
Output port p q
diode. PB3
7405

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
22 1 䡲 Microcomputer-Based Systems

When needed for digital logic, we can convert an open collector output to a digital
signal using a pull-up resistor from the output to 5V. In this way, when the open collec-
tor output floats, the signal will be a digital high. How do we select the value of the pullup
resistor? In general the smaller the resistor, the larger the IOH it will be able to supply when
the output is high. On the other hand, a larger resistor does not waste as much IOL current
when the output is low. One way to calculate the value of this pull-up resistor is to first
determine the required output high voltage, Vout, and output high current, Iout. To supply a
current of at least Iout at a voltage above Vout, the resistor must be less than:
R  (5  Vout)/Iout

As an example, we will calculate the resistor value for the situation where the circuit needs
to drive five regular TTL loads. We see from Figure 1.14 that Vout must be above VIH (2V)
in order for the TTL inputs to sense a high logic level. We can add a safety factor and set
Vout at 3 V. In order for the high output to drive all five TTL inputs, Iout must be more than
five IIH. From Table 1.3, we see that IIH is 40 µA, so Iout should be larger than 5•40 µA or
0.2 mA. For this situation the resistor must be less than 10 kΩ.
Another example of open collector logic occurs when interfacing switches to the micro-
controller. The circuit in the left of Figure 1.21 shows a mechanical switch with one terminal
connected to ground. In this circuit, when the switch is pressed, the voltage r is zero. When
the switch is not processed, the signal r floats. The circuit in the middle of Figure 1.21 shows
the mechanical switch with a 10 k pull-up resistor attached the other side. When the switch is
pressed, the voltage at s still goes to zero, because the resistance of the switch (less than 0.1 Ω)
is much less than the pull-up resistor. But now, when the switch is not pressed, the pull-up
resistor creates a 5 V at s. This circuit is shown connected to an input pin of the microcon-
troller. The software, by reading the input port, can determine whether or not the switch is
processed. If the switch is pressed, the software will read zero, and if the switch is not pressed,
the software will read one. The circuit on the right of Figure 1.21 also interfaces a mechani-
cal switch to the microcontroller, but it implements positive logic using a pull-down resistor.
The signal t will be high if the switch is pressed and low if it is released.

Figure 1.21 +5 V +5 V
Switch interface. μC μC
10 kΩ
r s Input port t Input port
PA0 PA0
10 kΩ

Observation: Some of the ports on the 9S12 implement pull-up or pull-down resis-
tors, so the interfaces shown in Figure 1.21 can be made without the resistor.

1.5 Digital Representation of Numbers


1.5.1 Information is stored on the computer in binary form. A binary bit can exist in one of
Fundamentals two possible states. In positive logic, the presence of a voltage is called the 1, true,
asserted, or high state. The absence of a voltage is called the 0, false, not asserted, or low
state. Figure 1.22 shows the output of a typical complementary metal-oxide semicon-
ductor (CMOS) circuit. The left side shows the condition with a true bit, and the right
side shows a false bit. The output of each digital circuit consists of a p-type transistor
“on top of” an n-type transistor. In digital circuits, each transistor is essentially on or off.
If the transistor is on, it is equivalent to a short circuit between its two output pins. Con-
versely, if the transistor is off, it is equivalent to an open circuit between its outputs pins.

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
1.5 䡲 Digital Representation of Numbers 23

Figure 1.22
True Equivalence False +5 V Equivalence
A binary bit is true if a +5V
voltage is present and p-type +5 V p-type +5 V
false if the voltage is 0. on short off open
Out = 5 V Out = 0 V
Out = 5 V Out = 0 V
n-type n-type
off open on short

On a 9S12 powered with 5 V supply, a voltage between 3.25 and 5 V is considered high,
and a voltage between 0 and 1.75 V is considered low. Separating the two regions by
1.5 V allows digital logic to operate reliably at very high speeds. The design of transistor-
level digital circuits is beyond the scope of this book. However, it is important to know
that digital data exist as binary bits and encoded as high and low voltages.
Numbers are stored on the computer in binary form. In other words, information is
encoded as a sequence of 1’s and 0’s. On most computers, the memory is organized into
8-bit bytes. This means each 8-bit byte stored in memory will have a separate address.
Precision is the number of distinct or different values. We express precision in alterna-
tives, decimal digits, bytes, or binary bits. Alternatives are defined as the total number of
possibilities. For example, an 8-bit number scheme can represent 256 different numbers.
An 8-bit digital to analog converter (DAC) can generate 256 different analog outputs. An
8-bit analog to digital converter (ADC) can measure 256 different analog inputs. We use
the expression 41/2 decimal digits to mean 20,000 alternatives and the expression 43⁄4
decimal digits to mean 40,000 alternatives. The 1⁄2 decimal digit means twice the number
of alternatives or one additional binary bit. The 3⁄4 decimal digit means four times as
many alternatives or two additional binary bits. For example, a voltmeter with a range of
0.00 to 9.99 V has a three decimal digit precision. Let the operation [[x]] be the greatest
integer of x. E.g., [[2.1]] is rounded up to 3. Tables 1.6 and 1.7 illustrate various repre-
sentations of precision.

Table 1.6
Binary Bits Bytes Alternatives
Relationship between
bits, bytes, and 8 1 256
alternatives as units of 10 1024
precision. 12 4096
16 2 65536
20 1,048,576
24 3 16,777,216
30 1,073,741,824
32 4 4,294,967,296
n [[n/8]] 2n

Table 1.7
Decimal Digits Alternatives
Definition of decimal
digits as a unit of 3 1000
precision. 31/2 2000
33/4 4000
4 10000
41/2 20000
43/4 40000
5 100000
n 10n

Copyright 2010 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Random documents with unrelated
content Scribd suggests to you:
“Some of your new friends,” wrote Jefferson,[129] “are attacking
your old ones, out of friendship for you, but in a way to render you
great injury.... Mr. Nicholson’s Resolutions will be passed this week,
probably by a majority of one hundred Republicans against fifteen
Republicans and twenty-seven Federalists. When passed, I shall join
Mr. Pinkney of Maryland as your associate for settling our differences
with Great Britain. He will depart on a fortnight’s notice, and will be
authorized to take your place whenever you think yourself obliged to
return.”

Two days later he wrote again.[130] In the interval Nicholson’s


Resolution had been adopted by a vote of eighty-seven to thirty-five,
and Randolph’s minority of Republican members had been reduced,
beyond the President’s hope, to a mere half-dozen grumblers.
“Mr. R. withdrew before the question was put,” wrote Jefferson. “I
have never seen a House of Representatives more solidly united in
doing what they believe to be the best for the public interest. There
can be no better proof than the fact that so eminent a leader should at
once, and almost unanimously, be abandoned.”
At the same moment Randolph wrote to Monroe that the
Republican party was broken in pieces, and that the “old
Republicans” were united in the support of Monroe against Madison
for the Presidency.[131] Randolph complained bitterly of the
atmosphere of intrigue which surrounded the Administration; but as
regarded him at least, Jefferson’s retort was plausible that he had
never found fault with intrigue so long as he had a share in it. After
challenging the contest with Madison, he had only himself to blame if
the President, who was a master of intrigue, used the weapon freely
to defend his favorite and himself.
To detach Randolph’s friends from their leader was an object
which the President pursued with zeal and success. He was a little
disposed to overawe Monroe; but he was glad to conciliate Joseph
Nicholson, next to Randolph the most formidable “old Republican” in
public life. Nicholson was torn by conflicting sympathies; he loved
Randolph, and he did not love Madison. On the other hand he was
attached to Gallatin by marriage and respect. A poor man, with a
large family, Nicholson found the life of a Congressman unprofitable;
and when he was offered a seat on the Bench as Judge of the Sixth
Maryland Circuit, he accepted the appointment. April 9, 1806, his
letter of resignation was read to the House, and the democrats knew
that Randolph had lost his strongest friend.
The Speaker remained to be dealt with. To overawe Macon was
impossible; to buy him was out of the question; to crush him was
only a last resort; no other resource was left than to coax him.
“Some enemy, whom we know not, is sowing tares between us,”
wrote the President to the Speaker, at the moment when he was
warning Monroe and Nicholson escaped to the bench.[132] “Between
you and myself nothing but opportunities of explanation can be
necessary to defeat these endeavors. At least, on my part, my
confidence in you is so unqualified that nothing further is necessary
for my satisfaction.”
Jefferson never was more sincere than in making this advance to
a friend from whom the course of events threatened to part him: but
unfortunately the point of doubt was not so much Jefferson’s
confidence in Macon as it was Macon’s confidence in Jefferson. At
bottom remained the unpleasant thought that Jefferson had ceased
to be either a Virginian or a Republican; had chosen other friends
and advisers than Macon, other objects and ambitions than Macon
pursued.
Even Randolph was treated with delicacy. Jefferson would gladly
have won him back, had Randolph admitted a hope that he would
accept Madison’s candidacy; but on that point no compromise could
be conceived. Madison’s fate was trembling in the balance. Sacrifice
of Madison was impossible to the President, and nothing short of
sacrifice would satisfy Randolph. The “old Republican” schism must
therefore be left to itself; the schismatics were too honest and
respectable to be dealt with. The President exhausted his power
when he won back the wavering, fixed Gallatin in allegiance to
Madison, and carried Nicholson out of the arena; but although gentle
and forbearing in regard to these honest, and as he thought,
misguided men, Jefferson did not think it necessary to show equal
deference to the merely selfish interests which had made use of this
moment of confusion in order to exact terms from the Government.
He showed that he could punish, by making an example of General
and Senator Samuel Smith.
Robert Smith in the Cabinet was so near to his brother Samuel in
the Senate that Jefferson could no longer trust his secrets to the
Cabinet itself. After crushing in the House Randolph’s opposition to
the Spanish policy, and after yielding to Smith and the Senate in
regard to a special English mission, the President was required to
make certain appointments, one of which was that of a new minister
to aid and succeed Monroe in London, whence it was supposed that
Monroe wished to return. General Smith’s wider plan assumed that
Monroe was on his way home, and would be succeeded by a regular
minister, assisted, for commercial negotiations, by a special envoy.
The special envoy was to be himself; the permanent minister was to
be his brother-in-law Wilson Cary Nicholas. He had even written to
assure Nicholas of the appointment, when his project was defeated
by the secret and unexpected interference of the President.
April 1, 1806, Samuel Smith wrote to his brother-in-law an
account of his hopes and disappointment:[133]
“Monroe had written that he would leave Great Britain in
November; therefore a mission of two,—one to remain as minister, the
other a merchant of some distinction and of general information to go
as envoy extraordinary,—was desired by all; and here, this proposal
generally—I may say universally—meant S. S. Two only exceptions:
As Monroe will remain until the whole business shall be settled, many
wish now an able merchant to join him; in either case to make a
commercial treaty with Great Britain. To such a treaty there is a rooted
aversion in the mind of the President and Mr. Madison. I ought to
apologize for leading you into error. I still do believe that you were
originally intended for London. A good Federalist is to succeed
Monroe, and has been privately written to by the President without the
knowledge of any of his Cabinet; they appeared astonished when he
mentioned what he had done.”
The good Federalist thus put over Smith’s head was William
Pinkney, a prominent lawyer of Smith’s city of Baltimore. Such a step
without consulting the Smiths, and against their personal interests,
was a strong measure on the part of Jefferson, quite out of keeping
with his ordinary practice. Offence of tried friends in order to
conciliate Federalists was little to his taste; but General Smith’s
conduct had become so factious as to warrant reproof. Smith was
reduced to submission. He had not shared in Randolph’s bitterness
against the Spanish policy, but he had attempted to make use of the
old Republican schism for his personal objects; and after Randolph’s
overthrow, Smith could no longer venture upon open opposition.
Though beaten by only one vote in his attack on Armstrong’s
nomination, Smith felt that his defeat was made final by the collapse
of Randolph’s rebellion. He admitted to Nicholas that no effective
resistance could be made to the Florida purchase, and that nothing
remained but obedience to the President’s will:—
“The question was simply, Buy or fight! Both Houses by great
majorities said, Buy! The manner of buying appears a little
disagreeable. Politicians will believe it perfectly honest to induce
France ‘by money’ to coerce Spain to sell that which she has
absolutely declared was her own property, and from which she would
not part. Mr. Randolph expects that this public explosion of our views
and plans will render abortive this negotiation, and make the
Executive and poor little Madison unpopular. Against this last he vents
his spleen. However, he spares nobody, and by this conduct has
compelled all to rally round the Executive for their own preservation.
From the Potomac north and east, the members adhere to the
President; south they fall daily from their allegiance.”
Thus, after four months of confusion, victory declared itself on the
President’s side.[134] Randolph’s violence, even more than
Jefferson’s dexterity, was fatal to the old Republican uprising. As
early as April 1 discipline was restored, with Madison stronger than
ever before. The few remaining days of the session only confirmed
the result.
CHAPTER VIII.
The President’s triumph was decided as early as March 17, for
on that day General Smith’s assault upon Armstrong was defeated in
the Senate by Vice-President Clinton’s casting vote; and in the
House, Randolph’s resistance to the non-importation policy against
England ended in his discomfiture and withdrawal; but although even
at that early moment no one could doubt Jefferson’s irresistible
strength, yet no one who knew John Randolph could suppose that
either the President or his Secretary of State was in future to sleep
on roses.
The session ended April 21; and during the few weeks that
intervened between Randolph’s defeat, March 17, and the
adjournment, the exasperated Virginian developed a strange and
unequalled genius. His position was new. The alternation of threat
and entreaty, of lofty menace and reluctant obedience, which marked
the conduct of the State Department in its dealings with France and
England, had no real admirer in the United States. When Randolph
denounced the change in Spanish policy, not a voice was raised in
its defence, and the public wondered that so powerful a President
should be left an unprotected victim to assaults so furious. In truth
Madison himself must have been tongue-tied; no resource of logic
could excuse his sudden abandonment of the determination “to
extinguish in the French government every hope of turning our
controversy with Spain into a French job, public or private.” Even had
he succeeded in excusing himself, his success must have proved
that Randolph’s crime consisted in maintaining the ground which had
been taken and held by President, secretary, and plenipotentiaries
down to the moment, Oct. 23, 1805, when without explanation the
ground was abandoned. Silence and numbers were the only
arguments in defence of such a change, and to these forms of logic
the followers of the Administration at first resorted. “It is a matter of
great astonishment to me,” wrote Wilson Cary Nicholas to Jefferson
April 2, “that such a philippic as we have seen could have been
uttered in Congress, and not one word said in justification of the
Administration.”[135] Toward the end of the session this silence
ceased; the majority made great efforts to answer Randolph; but the
answers were weaker than the silence.
Besides this difficulty in the nature of the case, the majority felt
more than ever the advantage enjoyed by Randolph in his vigor and
quickness of mind. For two months he controlled the House by
audacity and energy of will. The Crowninshields, Varnums, and
Bidwells of New England, the Sloans, Smilies, and Findleys of the
Middle States, could do nothing with him; but by the time he had
done with them they were bruised and sore, mortified, angry, and
ridiculous. The consciousness of this superiority, heightened to
extreme arrogance by the need of brushing away every moment a
swarm of flies which seemed never to know they were crushed,
excited Randolph to madness. He set no bounds to the expression
of his scorn not only for the Northern democrats, but for the House
itself and for the whole government. At one member he shook his
fist, and imperiously bade him sit down or to go down the back-
stairs; another member he called an old toothless driveller,
superannuated, and mumbling in second dotage.[136] He flung
Madison’s pamphlet with violent contempt on the floor of the House;
and he told the House itself that it could not maintain a decision two
hours together against the Yazoo lobby.
Sloan of New Jersey, a sort of butt in the party, who could not
forgive Randolph’s allusion to the “vegetable specific,” retorted that
Randolph behaved like “a maniac in a strait-jacket accidentally broke
out of his cell.” No doubt his conduct was open to the charge; but
none the less the maniac gave great trouble and caused extreme
confusion. Even after three fourths of the House came to share
Sloan’s opinion, and began the attempt to control Randolph by every
means in their power, they found the task beyond them.
The Non-importation Bill, framed on Nicholson’s Resolution, was
quickly reported, and March 25 the House agreed to fix November
15 as the date on which the Act should go into operation. Randolph
could not prevent its passage, but he could make it contemptible, if it
was not so already; and he could encourage the Government and
people of England to treat it with derision.
“Never in the course of my life,” he cried,[137] “have I witnessed
such a scene of indignity and inefficiency as this measure holds forth
to the world. What is it? A milk-and-water Bill! A dose of chicken-broth
to be taken nine months hence!... It is too contemptible to be the
object of consideration, or to excite the feelings of the pettiest State in
Europe.”
The Bill immediately passed by a vote of ninety-three to thirty-
two; but every man on the floor felt that Randolph was right, and
every foreign minister at Washington adopted his tone.
Two days afterward he called up certain Resolutions denouncing
as unconstitutional the union of civil and military authority in the
same person, and declaring that a contractor under Government was
a civil officer, and as such incapable of holding a seat in the House.
These Resolutions struck in every direction; they were a reproof to
the House, to the President, and to individual members like Matthew
Lyon, who had taken mail contracts, or John Smith, the senator from
Ohio, who was a large contractor for army supplies. General
Wilkinson at St. Louis held civil and military powers; the new territory
about to be organized under the name of Michigan was to have a
governor of the same sort. A vote against Randolph’s Resolutions
contravened one of the cardinal principles of the Republican party; a
vote for them censured the party itself and embarrassed
Government. Beaten by very large majorities on these two
declaratory points, Randolph succeeded in carrying through the
House a Bill that rendered military and naval officers incapable of
holding also any civil office. This measure slept quietly on the table
of the Senate.
Hardly a day passed without bringing the House into some similar
dilemma. March 29 the Senate sent down a Bill for settling the Yazoo
claims; it had passed the Senate by a vote of nineteen to eleven
soon after the death of its hottest opponent, Senator James Jackson
of Georgia. Randolph exultingly seized upon the Bill in order to
plaster it, like the hue-and-cry after a runaway thief, against the very
doors of the White House:—
“This Bill may be called the Omega, the last letter of the political
alphabet; but with me it is the Alpha. It is the head of the divisions
among the Republican party; it is the secret and covert cause of the
whole.... The whole weight of the Executive government presses it on.
We cannot bear up against it. The whole Executive government has
had a bias to the Yazoo interest ever since I had a seat here. This is
the original sin which has created all the mischiefs which gentlemen
pretend to throw on the impressment of our seamen, and God knows
what. This is the cause of those mischiefs which existed years ago.”
The Yazoo sin, he said, had been one principal cause of his
failure in the impeachment of Justice Chase; the secret mechanism
of Government would be so powerfully brought to bear on members
that if the Bill were postponed over Sunday he would not give a
farthing for the issue; gentlemen would come in with speeches ready
cut-and-dried until a majority dwindled to nothing. Exasperating and
insulting as this language was, the House did not resent it; and a
motion that the Bill be rejected passed by a vote of sixty-two to fifty-
four, while Randolph exulted over its fate.
March 31 Randolph, aided by the Federalists and some thirty
Republicans, succeeded in removing the injunction of secrecy from
the Spanish proceedings. No sooner was the Journal published, and
he found that it did not contain the President’s secret message of
Dec. 6, 1805, then he seized this chance to make public all that had
occurred in secret session. April 5, after moving that the injunction of
secrecy should be taken from the Message, he entered into the
history of His own relations with the President and Secretary of State
in the tangled thread of Spanish negotiations. His remarks that day,
though severe, were comparatively temperate; but when the debate
was renewed April 7, he announced that he meant to oppose the
Government, because he had to choose between opposition and
dishonesty. He charged that Madison had tried to get money from
the Treasury for this negotiation without waiting for a vote of
Congress; and he declared that the documents, “if published, would
fix a stain upon some men in the government and high in office
which all the waters in the ocean would not wash out.” His
denunciations began to rouse passion; if his opponents could not
equal him in debate, they could in violence of temper. Madison’s
brother-in-law, John G. Jackson of Virginia, took up his charges in a
high tone, and several expressions passed which foreshadowed a
duel. On the vote Randolph was beaten by a majority of seventy-four
to forty-four; but he had published the secrets of Madison’s friends,
and their refusal to print the Message showed the want of courage
with which they were chiefly charged.
On every point of real importance Randolph’s authority overawed
the House. The President in his Annual Message had talked much of
defences, and had even hinted his readiness to build seventy-fours.
A committee of the House reported Resolutions advising that the
sum of one hundred and fifty thousand dollars should be spent in
fortifying harbors; that two hundred and fifty thousand dollars should
be appropriated to build fifty gunboats; and that six hundred and
sixty thousand dollars should be voted toward building six line-of-
battle ships. When these Resolutions were brought up March 25,
only thirty members could be found to vote for the seventy-fours.
April 15 the subject came up again in connection with the Bill for
fortifying harbors and building gunboats. Josiah Quincy made a
strong argument, warning Congress that in the sacrifice of
commercial interests which lay at the bottom of its policy, there was
danger not only to the prosperity but to the permanence of the
Union. He remarked that while seventeen millions had been voted to
buy Louisiana and Florida for the sake of securing the South and
West; while in this single session four hundred and fifty thousand
dollars must be voted for Indian lands,—yet the entire sum expended
since the foundation of the government in fortifications for the nine
capital harbors of the Union was only seven hundred and twenty-four
thousand dollars. The city of New York, with at least one hundred
million dollars of capital in deposit, might at any moment be laid
under contribution by two line-of-battle ships. Quincy begged the
House to bear in mind that the ocean could not be abandoned for the
land by the people of New England, of whom thousands would rather
see a boat-hook than all the sheep-crooks in the world:—
“Concerning the land of which the gentleman from Virginia
[Randolph] and the one from North Carolina [Macon] think so much,
they think very little. It is in fact to them only a shelter from the storm,
a perch on which they build their eyrie and hide their mate and their
young while they skim the surface or hunt in the deep.”
Quincy’s speech was far superior to the ordinary level of
Congressional harangues, and its argument was warmly supported
by a democrat as extreme as Matthew Lyon; but barely thirty votes
could be mustered against Randolph’s economy; and although the
New England democrats joined hands with the New England
Federalists in supporting an appropriation for building two new
frigates in place of others which had been lost or condemned, they
could muster only forty-three votes against Randolph’s phalanx.
Probably no small part of Randolph’s hostility to the navy was
due to his personal dislike for Robert Smith the secretary, and for his
brother Samuel the senator. This enmity already showed signs of
serious trouble in store. Gallatin struggled in vain with Robert Smith’s
loose habit of accounts. Joseph Nicholson, closely allied to Gallatin,
naturally drew away from the Smiths, whose authority in Maryland
roused ill-feeling. Randolph took sides with Gallatin and Nicholson,
the more because Samuel Smith had undertaken to act an
independent part in the politics of the session, and had too plainly
betrayed selfish motives. When Randolph, after delaying the navy
estimates as long as he could, moved the appropriations April 10, he
took the opportunity to be more than usually offensive. He said that
an Appropriation Bill was a mere matter of form; that the items might
as well be lumped together; that the secretary would spend twice the
amount if he chose, as he had done the year before, and that the
House would have to make up the deficiency. “A spendthrift,” said
he, “can never be supplied with money fast enough to anticipate his
wants.”
The Bill passed, of course; but the navy was reduced to the
lowest possible point, and fifty gunboats were alone provided in
response to the President’s strong recommendations. Randolph and
his friends believed only in defence on land, and their theory was no
doubt as sound as such theories could ever be; but it was the curse
of “old Republican” principles that they could never be relaxed
without suicide, and never enforced without factiousness. For
defence on land nothing was so vital as good roads. A million dollars
appropriated for roads to Sackett’s Harbor, Erie, Detroit, St. Louis,
and New Orleans would have been, as a measure of land defence,
worth more than all the gunboats and forts that could be crowded
along the Atlantic; but when the Senate sent down a Bill creating
commissioners to lay out the Cumberland road to the State of Ohio,
although this road was the result of a contract to which Congress
had pledged its faith, so many Republicans opposed it under one
pretext or another, with John Randolph among them, that a change
of four votes would have defeated the Bill. No more was done for
national defence by land than by water, although the echo of
Nelson’s guns at Trafalgar was as loud as the complaints of
plundered American merchants, and of native American seamen
condemned to the tyranny and the lash of British boatswains.
The drift of Randolph’s opposition was easily seen; he wanted to
cover the Administration with shame for having taken a warlike tone
which it never meant to support. His tactics were calculated to make
Madison contemptible at home and abroad by inviting upon him the
worst outrages of foreign governments. That he succeeded so far as
foreign governments were concerned was almost a matter of course,
since even without his aid Spain, France, and England could hardly
invent an outrage which they had not already inflicted; but at home
Randolph’s scheme failed, because Madison could be degraded only
by making the American people share in his humiliation. The old
Republicans relieved Madison of responsibility for national disgrace,
and made Congress itself answerable for whatever disasters might
follow,—a result made clear by Randolph’s last and most
mischievous assault. To meet the five millions required for the
purchase of Florida, at a moment when the Non-importation Act
threatened to cut down the revenue, Gallatin needed all the existing
taxes, including the Mediterranean Fund, which ceased by law after
the peace with Tripoli. April 14 Randolph suddenly, without the
knowledge or consent of Gallatin, moved to repeal the duty on salt.
This heavy and unpopular tax produced about half a million dollars,
and its repeal was so popular that no one dared oppose it. The next
day Randolph brought in a Bill repealing the salt tax and continuing
the Mediterranean Fund. By that time members had become aware
of his factious motives, and denounced them; but so far from
disavowing his purpose, the chairman of the Committee of Ways and
Means proclaimed that since he could not force the Government to
keep within the limit of specific appropriations he meant to sequester
the revenue so as to leave but a scanty surplus. After his speech the
Bill was engrossed without opposition, the Federalists being pleased
to embarrass Government, and the Republicans afraid of sacrificing
popularity. April 17 the Bill passed by a vote of eighty-four to eleven
and was sent to the Senate. The part which related to the salt tax
was there struck out; but when, April 21, the last day of the session,
the Bill so mutilated came again before the House, Randolph exerted
to the utmost his powers of mischief, not so much in order to repeal
the salt tax as to destroy the Senate Bill, and so deprive Government
of its still greater resource, the Mediterranean Fund, which produced
nearly a million. He induced the House to insist upon its own Bill. A
committee of conference was appointed; the Senate would not
recede; Randolph moved that the House adhere. Angry words
passed; ill-temper began to prevail; and when at last Randolph was
beaten by the narrow vote of forty-seven to forty, his relative Thomas
Mann Randolph, the President’s son-in-law, suddenly rose and
spoke of his namesake in terms intended for a challenge; while
Sloan of New Jersey occupied part of the night with a long diatribe
against the chairman of the Ways and Means Committee.
Never had worse temper been seen at Washington than in the
last weeks of this session. Madison’s friends, conscious that their
attitude was undignified, became irritable, and longed for a chance to
prove their courage. Randolph was not the only enemy who devoted
the energy of personal hatred to the task of ruining the Secretary of
State. In the case of Randolph Madison was not to blame, and
neither challenged nor wished a contest. Even the policy which
Randolph so violently assailed was less the policy of the secretary
than of the President. Madison did nothing to invite the storm, and
could have done nothing to escape it; but another tempest raged, to
which he voluntarily exposed himself.
The Marquis of Casa Yrujo passed the autumn of 1805 in
Philadelphia, and in obedience to instructions tried to renew friendly
relations with the Secretary of State. During Madison’s stay in the
city Yrujo induced the secretary to accept an invitation to dinner to
meet Governor McKean, Yrujo’s father-in-law. The marquis paid no
attention to the hints sent him from the President that he would
confer a favor on the United States government by returning to Spain
without delay. He was well aware that he had nothing to gain by
conferring more favors on Jefferson; and the conduct of Turreau and
Merry was not such as to deter a Spanish minister from defying to
his heart’s content the authority of the President.
On the appearance of the Annual Message, which contained a
general and loose statement of grievances against Spain, Yrujo
wrote Dec. 6, 1805, a keen note to the Secretary of State, criticising,
not without justice, the assertions made by the President. To Yrujo’s
note, as to the St. Domingo note of Turreau, the secretary made no
reply. He held that the contents of an Executive communication to
Congress were not open to diplomatic discussion,—a doctrine
doubtless correct in theory and convenient to the Executive, but
offering the disadvantage that if foreign governments or their envoys
chose to disregard it, the Secretary of State must either enforce
discipline or submit to mortification. Madison accepted the challenge;
he meant to enforce discipline, and aimed at expelling Yrujo from the
country. The Cabinet decided that Yrujo, pending the request for his
recall, should receive no answer to his letters, and should not be
permitted to remain in Washington.
Backed by the President’s authority and by the power of the
government, Madison might reasonably expect an easy victory over
the Spaniard, and he acted as though it were a matter of course that
Yrujo should accept his fate; but Yrujo seemed unconscious of peril.
Although the Spanish minister’s presence at the capital was well
known not to be desired by the President, the society of Washington
was startled Jan. 15, 1806, by learning that the marquis had arrived.
The same evening Yrujo, dining with General Turreau, received a
formal note which roused him to passion only equalled by the temper
of John Randolph. The exasperating letter, signed by Madison, said
that as the President had requested Yrujo’s recall, and as Cevallos
had intimated that the marquis wished to return to Spain on leave, it
had been supposed that the departure would have taken place at
once, and therefore his appearance at Washington was a matter of
surprise:—
“Under these circumstances the President has charged me to
signify to you that your remaining at this place is dissatisfactory to
him; and that although he cannot permit himself to insist on your
departure from the United States during an inclement season, he
expects it will not be unnecessarily postponed after this obstacle has
ceased.”
A routine diplomatist would have protested and obeyed; but Yrujo
was not a routine diplomatist. Not in order to learn correct
deportment had he read the “Aurora” or studied the etiquette of
Jefferson’s pêle-mêle. Minister and marquis as he was, he had that
democratic instinct which always marked the Spanish race and
made even the beggars proud; while his love of a fray shocked
Turreau and caused Merry to look upon his Spanish colleague as a
madman. At that moment Madison was little esteemed or feared by
any one; the recoil of his foreign policy had prostrated him, and
Randolph was every day, in secret session, overwhelming him with
contempt. Yrujo had no reason to fear the result of a contest; but
even had there been cause for fear, he was not a man to regard it.
Turreau in vain attempted to restrain him; nothing would satisfy
Yrujo but defiance. January 16, the day after receiving Madison’s
letter, the Spanish minister answered it.
“As the object of my journey is not with a view to hatch plots,” said
he, with a side-blow at Madison which the secretary soon understood,
“my arrival here is an innocent and legal act, which leaves me in the
full enjoyment of all my rights and privileges, both as a public
character or a private individual. Making use therefore of these rights
and privileges, I intend remaining in the city, four miles square, in
which the Government resides, as long as it may suit the interest of
the King my master or my own personal convenience. I must at the
same time add that I shall not lose sight of these two circumstances
as respects the period and season in which our mutual desires for my
departure from the United States are to be accomplished.”
Having thus retaliated Madison’s insult, Yrujo next made his
revenge public. January 19 he sent to the Department a formal
protest, couched in language still more offensive than that of his
letter:—
“Having gone through the personal explanations which for just
motives I was compelled to enter into in my first answer to your letter
of the 15th inst., I must now inform you, sir, what otherwise would then
have constituted my sole reply; namely, that the envoy extraordinary
and minister plenipotentiary of his Catholic Majesty near the United
States receives no orders except from his sovereign. I must also
declare to you, sir, that I consider both the style and tenor of your
letter as indecorous, and its object an infraction of the privileges
attached to my public character.”
Finally he sent to his colleagues copies of this correspondence,
which soon afterward was printed in every Federalist newspaper,
together with the note criticising the Annual Message, the reception
of which had never been acknowledged by the Secretary of State.
Thus far Madison gained no credit in the scuffle, but merely
called upon his own head one more intolerable insult. Perhaps in
Yrujo’s apparent madness some share of method might be detected;
for he knew the character of Madison,—his willingness to irritate and
his reluctance to strike. At all events, the Spaniard remained at
Washington and defied the Government to do its worst. The Cabinet
consulted, examined into the law, inquired for precedents, and at last
decided that the Government could not expel him. Merry took Yrujo’s
part, and Turreau had much to do with moderating the President’s
measures and with checking interference from Congress.[138] The
Government in all its branches was overawed, and even the
senators were alarmed. “The marquis’s letters last published seem
to have frightened many of them so that probably nothing will be
done.”[139] So wrote a member of the Senate who alone exerted
himself to strengthen the President’s hands. Yrujo remained a
fortnight or more at Washington, and after carrying his point returned
at his leisure to Philadelphia. The only measure which Madison
ventured to take was that of refusing to hold any communication with
him or to receive his letters; but even this defence was turned by
Yrujo into a vantage-ground of attack.
Among other adventurers then floating about the world was one
Francesco de Miranda, a native of Caraccas, who for twenty years
had been possessed by a passion for revolutionizing his native
province, and for becoming the Washington of Spanish America.
Failing to obtain in England the aid he needed, he came to New York
in November, 1805, with excellent letters of introduction. Miranda
had a high reputation; he was plausible and enthusiastic; above all,
he was supposed to represent a strong patriot party in Spanish
America. War with Spain was imminent; the President’s Annual
Message seemed almost to declare its existence. In New York
Miranda instantly became a hero, and attracted about him every
ruined adventurer in society, among the rest a number of Aaron
Burr’s friends. Burr himself was jealous, and spoke with contempt of
him; but Burr’s chief ally Dayton, the late Federalist senator from
New Jersey, was in Miranda’s confidence. So was John Swartwout
the marshal, Burr’s devoted follower; so was William Steuben Smith,
surveyor of the port, one of the few Federalists still left in office.
These, as well as a swarm of smaller men, clustered round the
Spanish American patriot, either to help his plans or to further their
own. By Smith’s advice Miranda hired the ship “Leander,” owned by
one Ogden and commanded by a Captain Lewis; with Smith’s active
aid Miranda next bought arms and supplies, and enlisted men.
Meanwhile Miranda went to Washington. Arriving there in the first
days of the session, before the pacific secret message and its
sudden change of policy toward Spain were publicly known, he
called upon the Secretary of State. December 11 he was received by
the secretary at the Department; then invited to dine; then he put off
his departure in order to dine with the President at the White House,
—at a time when he was engaged, in conjunction with the surveyor
of the port of New York, in fitting out a warlike expedition against
Spanish territory. What passed between him and Madison became
matter of dispute. The secretary afterward admitted that Miranda told
of his negotiations with the British government, and made no secret
of his hopes to revolutionize Colombia; to which Madison had replied
that the government of the United States could not aid or
countenance any secret enterprise, and was determined to interfere
in case of any infraction of the law. Miranda’s account of the
secretary’s conversation was very different; he wrote to Smith, from
Washington, letters representing Madison to be fully aware of the
expedition then fitting out, and to be willing that Smith should join it.
He made a parade of social relations with the President and
secretary, and on returning to New York was open in his allusions to
the complicity of Government. Doubtless his statements were false,
and those of Madison were alone worthy of belief; but the Secretary
of State was not the less compromised in the opinion of his enemies.
Miranda quickly returned to New York; and when about a month
later the “Leander” was ready to sail, he wrote a letter to Madison
announcing his intended departure, and taking a sort of formal and
official leave, as though he were a confidential emissary of the
President. He had the assurance to add that “the important matters”
which he had communicated “will remain, I doubt not, in the deepest
secret until the final result of this delicate affair. I have acted here on
that supposition, conforming myself in everything to the intentions of
the Government, which I hope I have seized and observed with
exactitude and discretion.”[140]
Ten days afterward the “Leander” sailed with a party of filibusters
for the Spanish main, and the Secretary of State awoke to the
consciousness that he had been deceived and betrayed. Fortunately
for Madison, Miranda had not left behind him a copy of this letter, but
had merely told his friends its purport. The letter itself remained
unseen; but the original still exists among the Archives of the State
Department, bearing an explanatory note in Madison’s handwriting,
that Miranda’s “important” communications related to “what passed
with the British government,” and that in saying he had conformed in
New York to the President’s intentions, Miranda said what was not
true.
Then Madison, after receiving and entertaining Miranda at
Washington while a high government official was openly enlisting
troops for him at New York, ordered the Spanish minister to leave the
Federal city, and refused to receive the minister’s communications
on any subject whatever. He had driven Casa Calvo and Morales
from Louisiana, and at the same time allowed a notorious Spanish
rebel to organize in New York a warlike expedition against Spanish
territory.
Madison could hardly suppose that Yrujo would fail to make him
pay the uttermost penalty for a mistake so glaring. Never before had
the Spaniard enjoyed such an opportunity. After defying the
secretary at Washington, Yrujo returned to Philadelphia, where he
arrived on the evening of February 4. As he stepped from his
carriage letters were put into his hand. Three of these letters were
from the Spanish consul at New York, and contained only the notice
that the “Leander” was about to sail.[141] Serious as this news was, it
did not compare in importance with information furnished by
Jonathan Dayton. For reasons of his own Dayton kept Yrujo
informed of events unknown even to Merry and Turreau, and
unsuspected by the President or his Cabinet. In some cases he
probably tried to work on Yrujo’s credulity.
“The Secretary of State,” according to Dayton’s story, “with whom
Miranda had two conferences, doubtless suspecting the origin of this
mission, had at first treated him with reserve; but at last had opened
himself so far as to say that he did not know whether the United
States would or would not declare war against Spain, because this
step must depend on Congress; that in this uncertainty he could not
permit himself to offer Miranda the aid asked; but that if private
citizens in the United States chose to advance their funds for the
undertaking, as Miranda had suggested, the Government would shut
its eyes to their conduct, provided that Miranda took his measures in
such a way as not to compromise the Government. At the same time
the secretary coincided in Miranda’s idea that in case the United
States should determine upon war with Spain, this undertaking would
prove to be a diversion favorable to the views of the American
government.”

This had been told to Yrujo, and reported by him to his


Government before the visit to the capital. In the excitement caused
by Madison’s order to leave Washington, Yrujo confided in General
Turreau, and went so far as to hint to Madison himself his knowledge
that Madison was engaged in “hatching plots” against Spain.
Dayton’s latest information was still more serious. Besides exact
details in regard to the force and destination of Miranda, Dayton said
it had been agreed between Madison and Miranda that the
Government should use the pretext of asking Yrujo’s recall in order
to refuse to receive communications from him, and thus prevent him
from claiming official interference against the “Leander.”
No sooner did the idea of a profound intrigue effect a lodgment in
the Spaniard’s mind, than he turned it into a means of wounding the
Secretary of State. After writing letters the whole night, and sending
off swift-sailing pilot-boats to warn the Spanish authorities of
Miranda’s plans, the marquis turned his attention to the secretary. He
sent a letter to the Department, complaining that the “Leander” had
been allowed to sail; but knowing that the Department would decline
to receive his letter, he took another measure which secured with
certainty a hearing. He wrote a similar letter to Turreau, begging his
interference.[142]
Turreau could not refuse. No sooner did he receive Yrujo’s letter,
February 7, than he went to the Department and had an interview
with the secretary, which he reported to Yrujo on the same day:[143]

“I was this morning with Madison. I imparted to him my suspicions
and yours. I sought his eyes, and, what is rather rare, I met them. He
was in a state of extraordinary prostration while I was demanding from
him a positive explanation on the proceedings in question. It was with
an effort that he broke silence, and at length answered me that the
President had already anticipated my representations by ordering
measures to be taken against the accomplices who remained in the
country and against the culprits who should return. I leave you to
judge whether I was satisfied by this answer, and I quitted him
somewhat abruptly in order to address him in writing. I am occupied in
doing so.”
Madison might well show disturbance. To conciliate Turreau and
Napoleon had been the chief object of his policy since the preceding
October. For this he had endured arrogance such as no other
American secretary ever tolerated. The Florida negotiation had not
yet begun; John Randolph had delayed it and declaimed against it
until Madison’s reputation was involved in its success. Turreau held
its fate in his hand; and suddenly Turreau appeared, demanding that
Madison should prove himself innocent of charges that involved a
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookgate.com

You might also like