E M B E D D E D S Y S T E M S :
Introduction to
ARM
®
CORTEX
-M
MICROCONTROLLERS
Volume 1
Fifth Edition
June 2014
Jonathan W. Valvano
Fifth edition
2nd printing
June 2014
ARM and uVision are registered trademarks of ARM Limited. Cortex and Keil are trademarks of ARM Limited. Stellaris and Tiva are registered trademarks Texas Instruments. Code Composer Studio is a trademark of Texas Instruments. All other product or service names mentioned herein are the trademarks of their respective owners.In order to reduce costs, this college textbook has been self-published. For more
information about my classes, my research, and my books, see
http://users.ece.utexas.edu/~valvano/
For corrections and comments, please contact me at: [email protected]. Please
cite this book as: J. W. Valvano, Embedded Systems: Introduction to ARM ® Cortex
-
M Microcontrollers, Volume 1, http://users.ece.utexas.edu/~valvano/, ISBN: 978-1477508992.
Copyright © 2014 Jonathan W. Valvano
All rights reserved. No part of this work covered by the copyright herein may be
reproduced, transmitted, stored, or used in any form or by any means graphic, electronic,
or mechanical, including but not limited to photocopying, recording, scanning, digitizing,
taping, web distribution, information networks, or information storage and retrieval,
except as permitted under Section 107 or 108 of the 1976 United States Copyright Act,
without the prior written permission of the publisher.
ISBN-13: 978-1477508992
ISBN-10: 1477508996
Table of Contents
Preface to the Fifth Edition
Preface
Acknowledgements
1. Introduction to Computers and Electronics
1.1. Review of Electronics
1.2. Binary Information Implemented with MOS transistors
1.3. Digital Logic
1.4. Digital Information stored in Memory
1.5. Numbers
1.6. Character information
1.7. Computer Architecture
1.8. Flowcharts and Structured Programming
1.9. Concurrent and Parallel Programming
1.10. Exercises
2. Introduction to Embedded Systems
2.1. Embedded Systems
2.2. Applications Involving Embedded Systems
2.3. Product Life Cycle
2.4. Successive Refinement
2.5. Quality Design
2.5.1. Quantitative Performance Measurements
2.5.2. Qualitative Performance Measurements
2.5.3. Attitude
2.6. Debugging Theory
2.7. Switch and LED Interfaces
2.8. Introduction to C
2.9. Exercises
3. Introduction to the ARM
Cortex
-M Processor
3.1. Cortex
-M Architecture
3.1.1. Registers
3.1.2. Reset
3.1.3. Memory
3.1.4. Operating Modes
3.2. The Software Development Process
3.3. ARM Cortex-M Assembly Language
3.3.1. Syntax
3.3.2. Addressing Modes and Operands
3.3.3. Memory Access Instructions
3.3.4. Logical Operations
3.3.5. Shift Operations
3.3.6. Arithmetic Operations
3.3.7. Stack
3.3.8. Functions and Control Flow
3.3.9. Assembler Directives
3.3.10. First Example Project
3.4. Simplified Machine Language Execution
3.5. CISC versus RISC
3.6. Details Not Covered in this Book
3.7. Exercises
4. Introduction to Input/Output
4.1. Texas Instruments Microcontroller I/O pins
4.1.1. Texas Instruments LM3S1968 I/O pins
4.1.2. Texas Instruments TM4C123 LaunchPad I/O pins
4.1.3. Texas Instruments TM4C1294 Connected LaunchPad I/O
pins
4.2. Basic Concepts of Input and Output Ports
4.2.1. I/O Programming and the Direction Register
4.2.2. Switch Inputs and LED Outputs
4.3. Phase-Lock-Loop
4.4. SysTick Timer
4.5. Standard I/O Driver and the printf Function
4.6. Debugging monitor using an LED
4.7. Performance Debugging
4.7.1. Instrumentation
4.7.2. Measurement of Dynamic Efficiency
4.8. Exercises
4.9. Lab Assignments
5. Modular Programming
5.1. C Keywords and Punctuation
5.2. Modular Design using Abstraction
5.2.1. Definition and Goals
5.2.2. Functions, Procedures, Methods, and Subroutines
5.2.3. Dividing a Software Task into Modules
5.2.4. How to Draw a Call Graph
5.2.5. How to Draw a Data Flow Graph
5.2.6. Top-down versus Bottom-up Design
5.3. Making Decisions
5.3.1. Conditional Branch Instructions
5.3.2. Conditional if-then Statements
5.3.3. switch Statements
5.3.4. While Loops
5.3.5. Do-while Loops
5.3.6. For Loops
5.4. *Assembly Macros
5.5. *Recursion
5.6. Writing Quality Software
5.6.1. Style Guidelines
5.6.2. Comments
5.6.3. Inappropriate I/O and Portability
5.7. How Assemblers Work
5.8. Functional debugging
5.8.1. Stabilization
5.8.2. Single Stepping
5.8.3. Breakpoints with Filtering
5.8.4. Instrumentation: Print Statements
5.8.5. Desk checking
5.9. Exercises
5.10. Lab Assignments
6. Pointers and Data Structures
6.1. Indexed Addressing and Pointers
6.2. Arrays
6.3. Strings
6.4. Structures
6.5. Finite State Machines with Linked Structures
6.5.1. Abstraction
6.5.2. Moore Finite State Machines
6.5.3. Mealy Finite State Machines
6.6. *Dynamically Allocated Data Structures
6.6.1. *Fixed Block Memory Manager
6.6.2. *Linked List FIFO
6.7. Matrices and Graphics
6.8. *Tables
6.9. Functional Debugging
6.9.1. Instrumentation: Dump into Array without Filtering
6.9.2. Instrumentation: Dump into Array with Filtering.
6.10. Exercises
6.11. Lab Assignments
7. Variables, Numbers, and Parameter Passing
7.1. Local versus global
7.2. Stack rules
7.3. Local variables allocated on the stack
7.4. Stack frames
7.5. Parameter Passing
7.5.1. Parameter Passing in C
7.5.2. Parameter Passing in Assembly Language
7.5.3. C Compiler Implementation of Local and Global Variables
7.6. Fixed-point Numbers
7.7. Conversions
7.8. *IEEE Floating-point numbers
7.9. Exercises
7.10. Lab Assignments
8. Serial and Parallel Port Interfacing
8.1. General Introduction to Interfacing
8.2. Universal Asynchronous Receiver Transmitter (UART)
8.2.1. Asynchronous Communication
8.2.2. LM3S/TM4C UART Details
8.2.3. UART Device Driver
8.3. Synchronous Serial Interface, SSI
8.4. Nokia 5110 Graphics LCD Interface
8.5. Scanned Keyboards
8.6. Binary actuators
8.6.1. Interface
8.6.2. Electromagnetic and Solid State Relays
8.6.3. Solenoids
8.7. *Pulse-width modulation
8.8. *Stepper motors
8.9. Exercises
8.10. Lab Assignments
9. Interrupt Programming and Real-time Systems
9.1. I/O Synchronization
9.2. Interrupt Concepts
9.3. Interthread Communication and Synchronization
9.4. NVIC on the ARM Cortex-M Processor
9.5. Edge-triggered Interrupts
9.6. SysTick Periodic Interrupts
9.7. Timer Periodic Interrupts
9.8. Hardware debugging tools
9.9. Profiling
9.9.1 Profiling using a software dump to study execution pattern
9.9.2. Profiling using an Output Port
9.9.3. *Thread Profile
9.10. Exercises
9.11. Lab Assignments
10. Analog I/O Interfacing
10.1. Approximating continuous signals in the digital domain
10.2. Digital to Analog Conversion
10.3. Music Generation
10.4. Analog to Digital Conversion
10.4.1. LM3S/TM4C ADC details
10.4.2. ADC Resolution
10.5. Real-time data acquisition
10.6. Exercises
10.7. Lab Assignments
11. Communication Systems
11.1. Introduction
11.2. Reentrant Programming and Critical Sections
11.3. Producer-Consumer using a FIFO Queue
11.3.1. Basic Principles of the FIFO Queue
11.3.2. FIFO Queue Analysis
11.3.3. FIFO Queue Implementation
11.3.4. Double Buffer
11.4. Serial port interface using interrupt synchronization
11.5. *Distributed Systems.
11.6. Exercises
11.7. Lab Assignments
11.8. Best Practices
Appendix 1. Glossary
Appendix 2. Solutions to Checkpoints
Appendix 3. How to Convert Projects from Keil to CCS
Appendix 4. Assembly Reference
Index
Preface to the Fifth Edition
This fifth edition includes the new TM4C1294-based LaunchPad. Most of the code in the book is specific for the TM4C123-based LaunchPad. However, the book website includes corresponding example projects for the LM3S811, LM3S1968, LM4F120, and TM4C1294,which are ARM ® Cortex™-M microcontrollers from Texas Instruments. There are now two lost-cost development platforms called Tiva LaunchPad. The EK-TM4C123GXL LaunchPad retails for $12.99, and the EK-TM4C1294XL Connected LaunchPad retails for $19.99. The various LM3S, LM4F and TM4C microcontrollers are quite similar, so this book along with the example code on the web can be used for any of these microcontrollers. Compared to the TM4C123, the new TM4C1294 microcontroller runs faster, has more RAM, has more ROM, includes Ethernet, and has more I/O pins. This fifth edition switches the syntax from C to the industry-standard C99.Preface
Embedded systems are a ubiquitous component of our everyday lives. We interact with hundreds of tiny computers every day that are embedded into our houses, our cars, our toys, and our work. As our world has become more complex, so have the capabilities of the microcontrollers embedded into our devices. The ARM ® Cortex™-M family represents a new class of microcontrollers much more powerful than the devices available ten years ago. The purpose of this book is to present the design methodology to train young engineers to understand the basic building blocks that comprise devices like a cell phone, an MP3 player, a pacemaker, antilock brakes, and an engine controller. This book is the first in a series of three books that teach the fundamentals of embedded systems as applied to the ARM ® Cortex™-M family of microcontrollers. This first book is an introduction to computers and interfacing focusing on assembly language and C programming. The second book Embedded Systems: Real-Time Interfacing to ARM Cortex-M Microcontrollers focuses on hardware/software interfacing and the design of embedded systems. The third book Embedded Systems: Real-Time Operating Systems for ARM Cortex-M Microcontrollers is an advanced book focusing on operating systems, high-speed interfacing, control systems, and robotics. The third volume could also be used for professionals wishing to design or deploy a real-time operating system onto an ARM platform. This first book is an introductory book that could be used at the college level with little or no prerequisites. An embedded system is a system that performs a specific task and has a computer embedded inside. A system is comprised of components and interfaces connected together for a common purpose. This book is an introduction to embedded systems. Specific topics include microcontrollers, fixed-point numbers, the design of software in assembly language and C, elementary data structures, programming input/output including interrupts, analog to digital conversion, digital to analog conversion. In general, the area of embedded systems is an important and growing discipline within electrical and computer engineering. In the past, the educational market of embedded systems has been dominated by simple microcontrollers like the PIC, the 9S12, and the 8051. This is because of their market share, low cost, and historical dominance. However, as problems become more complex, so must the systems that solve them. A number of embedded system paradigms must shift in order to accommodate this growth in complexity. First, the number of calculations per second will increase from millions/sec to billions/sec. Similarly, the number of lines of software code will also increase from thousands to millions. Thirdly, systems will involve multiple microcontrollers supporting many simultaneous operations. Lastly, the need for system verification will continue to grow as these systems are deployed into safety critical applications. These changes are more than a simple growth in size and bandwidth. These systems must employ parallel programming, high-speed synchronization, real-time operating systems, fault tolerant design, priority interrupt handling, and networking. Consequently, it will be important to provide our students with these types of design experiences. The ARM platform is both low cost and provides the high-performance features required in future embedded systems. In addition, the ARM market share is large and will continue to grow. Furthermore, students trained on the ARM will be equipped to design systems across the complete spectrum from simple to complex. The purpose of writing these three books at this time is to bring engineering education into the 21st century. This book employs many approaches to learning. It will not include an exhaustive recapitulation of the information in data sheets. First, it begins with basic fundamentals, which allows the reader to solve newproblems with new technology. Second, the book presents many detailed design examples. These examples illustrate the process of design. There are multiple structural components that assist learning. Checkpoints, with answers in the back, are short easy to answer questions providing immediate feedback while reading. Simple homework, with answers to the odd questions on the web, provides more detailed learning opportunities. The book includes an index and a glossary so that information can be searched. The most important learning experiences in a class like this are of course the laboratories. Each chapter has suggested lab assignments. More detailed lab descriptions are available on the web. Specifically for this volume, look at the lab assignments for EE319K. For Volume 2, refer to the EE445L labs, and for Volume 3, look at the lab assignments for EE445M/EE380L.6. There is a web site accompanying this book http://users.ece.utexas.edu/~valvano/arm. Posted here are ARM Keil™ uVision® and Texas Instruments Code Composer Studio™ projects for each of the example programs in the book. You will also find data sheets and Excel spreadsheets relevant to the material in this book. The book will cover embedded systems for ARM ® Cortex™-M microcontrollers with specific details on the TM4C123 and TM4C1294. The web site includes corresponding examples for the LM3S811, LM3S1968, and LM3S8962. In these books the terms LM3S and TM4C will refer to families of microcontrollers with the Texas Instruments Stellaris ® and Tiva ® lines. Although the solutions are specific for the LM3S and TM4C families, it will be possible to use these books for other ARM derivatives.
Acknowledgements
I owe a wonderful debt of gratitude to Daniel Valvano. He wrote and tested most of the software examples found in these books. Secondly, he created and maintains the example web site, http://users.ece.utexas.edu/~valvano/arm. Lastly, he meticulously proofread this manuscript. 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 Kottam, Chia-ling Wei, Jignesh Shah, Icaro Santos, David Altman, Nachiket Kharalkar, Robin Tsang, Byung Geun Jun, John Porterfield, Daniel Fernandez, Deepak Panwar, Jacob Egner, Sandy Hermawan, Usman Tariq, Sterling Wei, Seil Oh, Antonius Keddis, Lev Shuhatovich, Glen Rhodes, Geoffrey Luke, Karthik Sankar, Tim Van Ruitenbeek, Raffaele Cetrulo, Harshad Desai, Justin Capogna, Arindam Goswami, Jungho Jo, Mehmet Basoglu, Kathryn Loeffler, Evgeni Krimer, Nachiappan Valliappan, Razik Ahmed, Sundeep Korrapati, Peter Garatoni, Manan Kathuria, Jae Hong Min, Pratyusha Nidamaluri, Dayo Lawal, Aditya Srikanth, Kurt Fellows, James Beecham, Austin Blackstone, Brandon Carson, Kin Hong Mok, Omar Baca, Sam Oyetunji, Zack Lalanne, Nathan Quang Minh Thai, Paul Fagen, Zhuoran Zhao, Sparsh Singhai, Saugata Bhattacharyya, Chinmaya Dattathri, Emily Ledbetter, Kevin Gilbert, Siavash Kamali, Yen-Kai Huang, Michael Xing, Katherine Olin, Mitchell Crooks, Prachi Gupta, Mark Meserve, Sourabh Shirhatti, Dylan Zika, Kelsey Ball, Greg Cerna, Sabine Francis, Ahmad El Youssef, and Wooseok Lee. These teaching assistants have contributed greatly to the contents of this book and particularly to its laboratory assignments. Since 1981, I estimate I have taught embedded systems to over 5000 students. Spring 2014, Professor Yerraballi and I taught a massive open online class (MOOC) based on this book. We had over 40,000 students register, and over 5,000 students finished at least one lab on the hardware platform. We plan to rerun this MOOC Spring 2015. My students have recharged my energy each semester with their enthusiasm, dedication, and quest for knowledge. I have decided not to acknowledge them all individually. However, they know I feel privileged to have had this opportunity. Next, I appreciate the patience and expertise of my fellow faculty members here at the University of Texas at Austin. From a personal perspective Dr. John Pearce provided much needed encouragement and support throughout my career. In addition, Drs. John Cogdell, John Pearce, and Francis Bostick helped me with analog circuit design. The book and accompanying software include many finite state machines derived from the digital logic examples explained to me by Dr. Charles Roth. The educational content presented in this book is result of the combined efforts of the entire teaching staff of EE319K: Drs. Ramesh Yerraballi, Mattan Erez, Andreas Gerstlauer, Nina Telang, William Bard and I. This team has created an educationally rich lab course that is both engaging and achievable for the freshman engineer. Each time we teach EE319K, we create a capstone design experience centered on a class competition. You can see descriptions and photos of our class design competitions at http://users.ece.utexas.edu/~valvano/.I have a special appreciation for all those who reviewed the first edition. Joe Bungo passed chapters around to fellows at ARM. In particular, the suggestions and corrections from Chris Shore and Drew Barbier were totally awesome. Cathy Wicks and Larissa Swanland from Texas Instruments supported these books with money, development kits, and chips. Bill Bard and Ramesh Yerraballi gave valuable feedback on how to make this book an effective teaching tool for freshmen. Austin Blackstone has been a constant contributor to these books. In particular, he created and debugged the Code Composer Studio™ versions of the example programs posted on the web. Sincerely, I appreciate the valuable lessons of character and commitment taught to me by my parents and grandparents. I recall how hard my parents and grandparents worked to make the world a better place for the next generation. Most significantly, I acknowledge the love, patience and support of my wife, Barbara, and my children, Ben Dan and Liz. In particular, Dan designed and tested most of the LM3S and TM4C software presented in this book. By the grace of God, I am truly the happiest man on the planet, because I am surrounded by these fine people. Jonathan W. Valvano The true engineering experience occurs not with your eyes and ears, but rather with your fingers and elbows. In other words, engineering education does not happen by listening in class or reading a book; rather it happens by designing under the watchful eyes of a patient mentor. So, go build something today, then show it to someone you respect! Good luck
1. Introduction to Computers and Electronics
Chapter 1 objectives are to:
• Present brief reviews of electronics and Ohm’s Law •Present a brief review of computer fundamentals • Review digital logic and information
• Introduce software design using flowcharts
The overall objective of this book is to teach the fundamentals of embedded systems. It is an effective approach to learn new techniques by doing them. But, the dilemma in learning a laboratory-based topic like embedded systems is that there is a tremendous volume of details that first must be learned before hardware and software systems can be designed. The approach taken in this book is to learn by doing. One of the advantages of a bottom-up approach to learning is that the student begins by mastering simple concepts. Once the student truly understands simple concepts, he or she can then embark on the creative process of design, which involves putting the pieces together to create a more complex system. True creativity is needed to solve complex problems using effective combinations of simple components. Embedded systems afford an effective platform to teach new engineers how to program for three reasons. First, there is no operating system. Thus, in a bottom-up fashion the student can see, write, and understand all software running on a system that actually does something. Second, embedded systems involve input/output that is easy for the student to touch, hear, and see. Third, embedded systems are employed in many every-day products, motivating students by showing them how electrical and computer engineering processes can be applied in the real world. Rather than introduce the voluminous details in an encyclopedic fashion, the book is organized by basic concepts, and the details are introduced as they are needed. We will start with simple systems and progressively add complexity. The overriding themes for Chapters 1 and 2 will be to present the organizational framework with which embedded systems will be designed. Chapter 3 explains how the computer works. Chapter 4 is an introduction to I/O. Chapters 5, 6, and 7 present the details of software development on an embedded system. Interfacing I/O devices to build embedded systems is presented in Chapters 8, 9, 10, and 11.1.1. Review of Electronics
Most readers of this book will have had some prior training in electronics. However, this brief section will provide an overview of the electronics needed to understand electric circuits in this book. Current (I) is defined as the movement of electrons. In particular, 1 ampere (A) of current is 6.241×1018 electrons per second, or one coulomb per second. Current is directional and measured at one point as the number of electrons travelling per second. Current has an amplitude and a direction. Because electrons are negatively charged, if the electrons are moving to the left, we define current as flowing to the right. Voltage (V) is an electrical term representing the potential difference between two points. The units of voltage are volts (V), and it is always measured as a difference. Voltage is the electromotive force or potential to produce current. We will see two types of conducting media: a wire and a resistor. Wires, made from copper, will allow current to freely flow, but forcing current to flow through a resistor will require energy. The electrical property of a resistor is resistance in ohms (Ω). Ideally, a wire is simply a resistor with a resistance of 0 Ω. The basic relation between voltage, current, and resistance for a resistor is known as Ohm’s Law, which can be written three ways:V = I * R Voltage = Current *
Resistance
I
= V / R Current = Voltage / ResistanceR
= V / I Resistance = Voltage /Current
The left side of Figure 1.1 shows a circuit element representation of a resistor, of resistance R. Whenever we define voltage, we must clearly specify the two points across which the potential is defined. Typically we label voltages with + and –, defining the voltage V as the potential to produce current from the + down to the –. When defining current we draw an arrow signifying the direction of the current. If the voltage V is positive, then the current I will be positive meaning the current is down in this figure. However, because electrons have negative charge, the electrons are actually flowing up. According to the passive sign convention, we define positive current as the direction of the flow of positive charge (or the opposite direction of the flow of negative charge). The middle of Figure 1.1 shows a circuit with a 1 kΩ resistor placed across a 3.7 V battery. According to Ohm’s Law, 3.7 mA of current will flow down across the resistor. In this circuit, current flows clockwise from the + terminal of the battery, down across the resistor, and then back to the – terminal of the battery.Figure 1.1. The voltage and current definitions; a circuit with a battery; and a
drawing of a resistor.
Checkpoint 1.1: There is 1 V across a resistor, and 2 mA is flowing. What is the resistance? Checkpoint 1.2: There is 5V across a 100 Ω resistor. How much current is flowing?Checkpoint 1.3: What happens if you place a wire directly from + terminal to the –terminal of a battery? There are two analogous physical scenarios that might help you understand the concept of voltage, current, and resistance. The first analogy is flowing water through a pipe. We place a large reservoir of water in a tower, connect the water through a pipe, and attach a faucet at the bottom of the pipe, see Figure 1.2. In this case pressure is analogous to voltage, water flow is analogous to current, and fluid resistance of the faucet is analogous to electrical resistance. Notice that water pressure is defined as the potential to cause water to flow, and it is measured between two places. Pressure has a polarity, and water flow has a direction. If the faucet is turned all the way off, its resistance is infinite, and no water flows. If the faucet is turned all the way on, its resistance is not zero, but some finite amount. As we turn the faucet we are varying the fluid resistance. The fluid resistance will determine the amount of flow:
Flow =
Pressure/Resistance
Figure 1.2. Three analogous physical systems demonstrating Ohm’s Law.
Checkpoint 1.4: If pressure is measured in Newtons/m2 (Pascal) and flow measured in m3/sec, what are
the units of fluid resistance? A second analogy is heat flow across a solid. If we generate a temperature gradient across a solid, heat will flow from the hot side to the cold side (right side of Figure 1.2). This solid could be a glass window on a house or the wall of your coffee cup. In this case temperature gradient is analogous to voltage, heat flow is analogous to current, and thermal resistance of the solid is analogous to electrical resistance. Notice that potential is defined as the temperature difference between two places. Heat flow also has a direction. If the coffee cup is made from metal, its thermal resistance is low, lots of heat will flow, and the coffee cools off quickly. If the coffee cup is made of Styrofoam, its resistance is high, little heat will flow, and the coffee remains hot for a long time. The thermal resistance of the material the amount of flow:
Flow = (T1-T2)/Resistance
Checkpoint 1.5: If heat flow is measured in watts (Joules/sec) and temperature measured in ºC, what are the units of thermal resistance?The R-value of insulation put in the walls and ceiling of a house is usually given in units per square area, e.g., m2∙ºC/W. The amount of heat flow across a wall is:
Flow = Area
*(T1-T2)/R-value
Anotherimportant parameter occurring when current flows through a resistor is power. The power (P in watts) dissipated in a resistor can be calculated from voltage (V in volts), current (I in amps), and resistance (R in ohms). Interestingly, although voltage has a polarity (+ and –) and current has a direction, power has neither a polarity nor a direction.
P = V * I Power = Voltage * Current
P
= V2/ R Power = Voltage
2 / ResistanceP
= I2* R
Power = Current
2* Resistance
Checkpoint 1.6: There is 1 V across a resistor, and 2 mA is flowing. How much power is being dissipated?
The energy (E in joules) stored in a battery can be calculated from voltage (V in volts), current (I in amps), and time (t in seconds). Energy has neither polarity nor direction. E = V * I * t Energy = Voltage * Current * time E = P * t Energy = Power * time A switch is an element used to modify the behavior of the circuit (Figure 1.3). If the switch is pressed, its resistance is 0, and current can flow across the switch. If the switch is not pressed, its resistance is infinite, and no current will flow. In reality, the ON-resistance of a switch is less than 0.1Ω, but this is so close to zero, we can assume the ideal value of 0 in most cases. Similarly, the OFF-resistance is actually greater than 100MΩ, but this is so close to infinity that we can again assume the ideal value of infinity. The classic electrical circuit involves a battery, a light bulb (modeled in this circuit as a 100Ω resistor), and a switch.
Figure 1.3. When the switch is open, no current can flow, and the bulb does not
emit light. When the switch is closed, 90 mA of current will flow, and the bulb emits
light.
Checkpoint 1.8: If the switch is on, how much power is being dissipated in the bulb? There are a few basic rules that allow us to solve for voltages and currents within a circuit comprised with batteries, switches, and resistors. Current always flows in a loop. In Figure 1.3 when the switch is pressed, current flows out of the + side of battery, across the switch, through the light and back to the – side of the battery. When there is no loop, no current can flow. In Figure 1.3 when the switch is off, the loop is broken, and no current will flow. Kirchhoff's Voltage Law (KVL). The sum of the voltages around the loop is zero. For a battery, we label the + and – sides exactly the way the battery is labeled. For a resistor, we label the current arrow and the voltage + – like the left side of Figure 1.1. The important step is the direction of the current arrow must match the polarity of the corresponding voltage. It is common practice to draw arrows in the direction the currents actually flow, so the voltages will be positive. However, sometimes we don’t know which way the current will flow, so we can just guess. If we happen to guess wrong, both the current and voltage will calculate to be negative and the correct behavior will still be obtained. We can think of the switch as a resistor of either 0 or infinity resistance, so it too can be labeled with a current arrow and a voltage polarity. Figure 1.4 shows the light circuit redrawn to show voltages and currents. As we are going around a circle and pass from + to –, we add that voltage. However, if we pass across an element from – to + we subtract that voltage.Figure 1.4. The voltages around a loop will sum to zero (KVL).
Kirchhoff's Current Law (KCL). The sum of the currents into a node equal the sum of the currents leaving a node as shown in Figure 1.5. To solve circuits using KCL and KVL, the current arrow across a resistor goes from the + voltage to the – voltage. Conversely, the current arrow across a battery goes from the – voltage to the + voltage. This is the same thing as saying current comes out of the battery’s + terminal and into the battery’s – terminal. At Node A, there is one incoming current and one outgoing current. This is a simple but important fact that I1 = I2. At Node B, there is one incoming current and two outgoing currents. Therefore, I3 = I4+I5. There are two currents into NodeC and two currents out of NodeC; thus, I6+I7 = I8+I9.
Figure 1.5. The sum of the currents into a node will equal the sum of the currents
leaving (KCL).
Observation: If at all possible, draw the circuit so current flows down across the resistors and switches. As a secondary rule have currents go left to right across resistors and switches. Series resistance. If resistor R1 is in series with resistor R2, this combination behaves like one resistor with a value equal to R1+R2. See Figure 1.6. This means if replace the two series resistors in a circuit with one resistor at R= R1+R2, the behavior will be the same. The V equals V1+V2. By KCL, the currents through the two resistors are the same. These two facts can be used to derive the voltage divider rule V2 = I*R2 = (V/R)*R2 = V*R2/(R1+R2)Figure 1.6. The series combination of two resistors, R1 R2, is equivalent to one
resistor at R1+R2.
Checkpoint 1.9: Using Figure 1.6, assume I is 1mA, R1 is 1k Ω and R2 is 2k Ω , what is V? Checkpoint 1.10: Using Figure 1.6, assume V is 6V, R1 is 1k Ω and R2 is 2k Ω , what is V2?
Parallel resistance. If resistor R1 is in parallel with resistor R2, this combination behaves like one
See Figure 1.7. This means we can replace the two parallel resistors in a circuit with one resistor at R= R1*R2/(R1+R2). The voltages across R1 and R2 will be the same because of KVL. Due to KCL, I=I1+I2. These facts can be used to derive the current divider rule I1 = V/R1= (I*R)/R1 = I* (R1*R2/(R1+R2))/R1 = I*R2/(R1+R2) I2 = V/R2= (I*R)/R2 = I*(R1*R2/(R1+R2))/R2 = I*R1/(R1+R2) I = I1+I2
Figure 1.7. The parallel combination of two resistors, R1 R2, is equivalent to one
resistor at R1*R2/(R1+R2).
Checkpoint 1.11: Using Figure 1.7, assume I is 1mA, R1 is 2k Ω and R2 is 3k Ω , what is V? Checkpoint 1.12: Using Figure 1.7, assume V is 6V, R1 is 2k Ω and R2 is 3k Ω , what is I2?
1.2. Binary Information Implemented with MOS
transistors
Information is stored on the computer in binary form. A binary bit can exist in one of 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.8 shows the output of a typical complementary metal oxide semiconductor (CMOS) circuit. The left side shows the condition with a true bit at the output, and the right side shows a false at the output. 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. Conversely, if the transistor is off, it is equivalent to an open circuit between its outputs pins.Figure 1.8. A binary bit at the output is true if a voltage is present and false if the
voltage is 0.
Every family of digital logic is a little different, but on the Cortex-M microcontrollers from TI powered with 3.3 V supply, a voltage between 2 and 5 V is considered high, and a voltage between 0 and 1.3 V is considered low, as drawn in Figure 1.9. Separating the two regions by 0.7 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.Figure 1.9. Mapping between analog voltage and the corresponding digital
meaning on the LM3S/TM4C.
If the information we wish to store exists in more than two states, we use multiple bits. A collection of 2 bits has 4 possible states (00, 01, 10, and 11). A collection of 3 bits has 8 possible states (000, 001, 010, 011, 100, 101, 110, and 111). In general, a collection of n bits has 2n states. For example, a byte contains eight bits, and is built by grouping eight binary bits into one object, as shown in Figure 1.10. Another name for a collection of eight bits is octet (octo is Latin and Greek meaning 8.) Information can take many forms, e.g., numbers, logical states, text, instructions, sounds, or images. What the bits meandepends on how the information is organized and more importantly how it is used. This figure shows one byte in the state representing the binary number 01100111. Again, the output voltage 3.3V means true or 1, and the output voltage of 0V means false or 0.
Figure 1.10. A byte is comprised of 8 bits, in this case representing the binary
number 01100111.
1.3. Digital Logic
In order to understand how the computer works, we will need some understanding of digital logic. Transistors made with metal oxide semiconductors are called MOS. In the digital world MOS transistors can be thought of as voltage controlled switches. Circuits made with p-type and n-type MOS transistors are called complementary metal oxide semiconductors or CMOS. The 74HC04 is a high-speed CMOS NOT gate, as shown in Figure 1.11. There are just a few rules one needs to know for understanding how CMOS transistor-level circuits work. Each transistor acts like a switch between its source and drain pins. In general, current can flow from source to drain across an active p-type transistor, and no current will flow if the switch is open. From a first approximation, we can assume no current flows into or out of the gate. For a p-type transistor, the switch will be closed (transistor active) if its gate is low. A p-type transistor will be off (its switch is open) if its gate is high.Figure 1.11. CMOS implementation of a NOT gate.
The gate on the n-type works in a complementary fashion, hence the name complementary metal oxide semiconductor. For an n-type transistor, the switch will be closed (transistor active) if its gate is high. An n-type transistor will be off (its switch is open) if its gate is low. Therefore, consider the two possibilities for the circuit in Figure 1.11. If the input A is high (+3.3V), then the p-type transistor is off and the n-type transistor is active. The closed switch across the source-drain of the n-type transistor will make the output low (0V). Conversely, if A is low (0V), then p-type transistor is active and the n-type transistor is off. The closed switch across the source-drain of the p-type transistor will make the output high (+3.3V). The AND, OR, EOR digital logic takes two inputs and produces one output; see Figure 1.12 and Table 1.1. We can understand the operation of the AND gate by observing the behavior of its six transistors. If both inputs A and B are high, both T3 and T4 will be active. Furthermore, if A and B are both high, T1 and T2 will be off. In this case, the signal labeled ~(A&B) will be low because the T3–T4 switch combination will short this signal to ground. If A is low, T1 will be active and T3 off. Similarly, if B is low, T2 will be active and T4 off. Therefore if either A is low or if B is low, the signal labeled ~(A&B) will be high because one or both of the T1, T2 switches will short this signal to +3.3V. Transistors T5 and T6 create a logical complement, converting the signal ~(A&B) into the desired result of A&B. We can use the and operation to extract, or mask, individual bits from a value.A B AND NAND OR NOR EOR Ex NOR
0 0 0 1 0 1 0 1
0 1 0 1 1 0 1 0
1 1 1 0 1 0 0 1 Symbol A&B ~
(A&B)
A|B ~(A|B) A^B ~(A^B)
Table 1.1. Two-input one-output logical operations. We can understand the operation of the OR gate by observing the behavior of its six transistors. If both inputs A and B are low, both T1 and T2 will be active. Furthermore, if A and B are both low, T3 and T4 will be off. In this case, the signal labeled ~(A|B) will be high because the T1–T2 switch combination will short this signal to +3.3V. If A is high, T3 will be active and T1 off. Similarly, if B is high, T4 will be active and T2 off. Therefore if either A is high or if B is high, the signal labeled ~(A|B) will be low because one or both of the T3, T4 switches will short this signal to ground. Transistors T5 and T6 create a logical complement, converting the signal ~(A|B) into the desired result of A|B. We use the or operation to set individual bits. When writing software we will have two kinds of logic operations. When operating on numbers (collection of bits) we will perform logic operations bit by bit. In other words, the operation is applied independently on each bit. In C, the logic operator for AND is & . For example, if number A is 01100111 and number B is 11110000 then
A = 01100111
B = 11110000
A & B 01100000
The other type of logic operation occurs when operating on Boolean values. In C, the condition false is represented by the value 0, and true is any nonzero value. In this case, if the Boolean A is 01100111 and B is 11110000 then both A and B are true. The standard value for true is the value1. In C, the Booleanoperator for AND is && . Performing Boolean operation yields
A = 01100111
B = 11110000
A && B 1
In C, the logic operator for OR is | . The operation is applied independently on each bit . E.g.,
A =
01100111
B = 11110000
A | B 11110111
In C, the Boolean operator for OR is || . Performing Boolean operation of true OR true yields true. Although 1 is the standard value for a true, any nonzero value is considered as true.A = 01100111
B = 11110000
A || B 1
Figure 1.12. Logical operations can be implemented with discrete transistors or
digital gates.
Checkpoint 1.13: Using just the 74HC gates shown in Figure 1.12, design a three-input one-output logic function (called a three-input AND) such that the output is high if and only if all inputs are high. In other words, the output is low if one or more inputs are low. Checkpoint 1.14: Using just the 74HC gates shown in Figure 1.12, design a three-input one-output logic function (called a three-input OR) such that the output is high if one or more inputs are high. In other words, the output is low if and only if all inputs are low. Observation: In C, (5&2) will be zero because (0101&0010)=0000. However, (5&&2) will be true, because 5 means true, 2 means true, and true&&true is true.. Other convenient logical operators are shown as digital gates in Figure 1.13. The NAND operation is defined by an AND followed by a NOT. If you compare the transistor-level circuits in Figures 1.12 and 1.13, it would be more precise to say AND is defined as a NAND followed by a NOT. Similarly, the OR operation is a NOR followed by a NOT. The exclusive NOR operation implements the bit-wise equals operation.Figure 1.13. Other logical operations can also be implemented with MOS
transistors.
Boolean Algebra is the mathematical framework for designing digital logic. Some fundamental laws of Boolean Algebra are listed below. A & B = B & A Commutative Law A | B = B | A Commutative Law (A & B) & C = A & (B & C) Associative Law (A | B) | C = A | (B | C) Associative Law (A | B) & C = (A & C) | (B & C) Distributive Law (A & B) | C = (A | C) & (B | C) Distributive Law A & 0 = 0 Identity of 0 A | 0 = A Identity of 0 A & 1 = A Identity of 1 A | 1 = 1 Identity of 1 A | A = A Property of OR A | (~A) = 1 Property of OR A & A = A Property of AND A & (~A) = 0 Property of AND ~(~A) = A Inverse ~(A | B) = (~A) & (~B) De Morgan’s Theorem ~(A & B) = (~A) | (~B) De Morgan’s Theorem When multiple operations occur in a single expression, precedence is used to determine the order of operation. Usually NOT is evaluated first, then AND, and then OR. This order can be altered using parentheses. There are multiple ways to symbolically represent the digital logic functions. For example, ~A A’ !A and ⌐A are five ways to represent NOT(A). One can use the pipe symbol (|) or the plus sign to represent logical OR: A|B A+B. In this book we will not use the plus sign to represent OR to avoid confusion with arithmetic addition. One can use the ampersand symbol (&) or a multiplication sign (* • × ) to represent logical AND: A&B A•B. In this book we will not use the multiplication sign to represent AND to avoid confusion with arithmetic multiplication. Another symbolic rule is adding a special character (* n \) to a name to signify the signal is negative logic (0 means true and 1 means false). These symbols do not signify an operation, but rather are part of the name used to clarify its meaning. E.g., Enable* is a signal than means enable when the signal is zero. Digital storage devices are used to make registers and memory. The simplest storage device is the set-reset latch. One way to build a set-reset latch is shown on the left side of Figure 1.14. If the inputs are S*=0 and R*=1, then the Q output will be 1. Conversely, if the inputs are S*=1 and R*=0, then the Q output will be 0. Normally, we leave both the S* and R* inputs high. We make the signal S* go low, then back high to set the latch, making Q=1. Conversely, we make the signal R* go low, then back high to reset the latch, making Q=0. If both S* and R* are 1, the value on Q will be remembered or stored. This latch enters an unpredictable mode when S* and R* are simultaneously low. The gated D latch is also shown in Figure 1.14. The front-end circuits take a data input, D, and a control signal, W, and produce the S* and R* commands for the set-reset latch. For example, if W=0, then the latch is in its quiescent state, remembering the value on Q that was previously written. However, if W=1, then the data input is stored into the latch. In particular, if D=1 and W=1, then S*=0 and R*=1, making Q=1. Furthermore, if D=0 and W=1, then S*=1 and R*=0, making Q=0. So, to use the gated latch, we first put the data on the D input, next we make W go high, and then we make W go low. This causes the data value to be stored at Q. After W goes low, the data does not need to exist at the D input anymore. If the D input changes while W is high, then the Q output will change correspondingly. However, the last value on the D input is remembered or latched when the W falls, as shown in Table 1.2.
The D flip-flop, shown on the right of Figure 1.14, can also be used to store information. D flip-flops are the basic building block of RAM and registers on the computer. To save information, we first place the digital value we wish to remember on the D input, and then give a rising edge to the clock input. After the rising edge of the clock, the value is available at the Q output, and the D input is free to change. The operation of the clocked D flip-flop is defined on the right side of Table 1.2. The 74HC374 is an 8-bit D flip-flop, such that all 8 bits are stored on the rising edge of a single clock. The 74HC374 is similar in structure and operation to a register, which is high-speed memory inside the processor. If the gate (G) input on the 74HC374 is high, its outputs will be HiZ (floating), and if the gate is low, the outputs will be high or low depending on the stored values on the flip-flop. The D flip-flops are edge-triggered, meaning that changes in the output occur at the rising edge of the input clock.
Figure 1.14. Digital storage elements.
D W Q D clock Q 0 0 Qold 0 0 Qold 1 0 Qold 0 1 Qold 0 1 0 1 0 Qold 1 1 1 1 1 Qold 0 ↓ 0 0 ↑ 0 1 ↓ 1 1 ↑ 1Table 1.2. D flip-flop operation. Qold is the value of the D input at the time of fall of W or rise of clock. The tristate driver, shown in Figure 1.15, can be used dynamically control signals within the computer. It is called tristate because there are three possible outputs: high, low, and HiZ. The tristate driver is an essential component from which computers are built. To activate the driver, we make its gate (G*) low. When the driver is active, its output (Y) equals its input (A). To deactivate the driver, we make its G* high. When the driver is not active, its output Y floats independent of A. We will also see this floating state with the open collector logic, and it is also called HiZ or high impedance. The HiZ output means the output is neither driven high nor low. The operation of a tristate driver is defined in Table 1.3. The 74HC244 is an 8-bit tristate driver, such that all 8 bits are active or not active controlled by a single gate. The 74HC374 8-bit D flip-flop includes tristate drivers on its outputs. Normally, we can’t connect two digital outputs together. The tristate driver provides a way to connect multiple outputs to the same signal, as long as at most one of the gates is active at a time.
Figure 1.15. A 1-bit tristate driver and an 8-bit tristate driver (G* is in negative
logic).
Table 1.3 describes how the tristate driver in Figure 1.15 works. Transistors T1 and T2 create the logical complement of G*. Similarly, transistors T3 and T4 create the complement of A. An input of G*=0 causes the driver to be active. In this case, both T5 and T8 will be on. With T5 and T8 on, the circuit behaves like a cascade of two NOT gates, so the output Y equals the input A. However, if the input G*=1, both T5 and T8 will be off. Since T5 is in series with the +3.3V, and T8 in series with the ground, the output Y will be neither high nor low. I.e., it will float. A G* T1 T2 T3 T4 T5 T6 T7 T8 Y0 0 on off on off on off on on 0
1 0 on off off on on on off on 1
0 1 off on on off off off on off HiZ
1 1 off on off on off on off off HiZ
Table 1.3. Tristate driver operation. HiZ is the floating state, such that the output is not high or low. The output of an open collector gate, drawn with the ‘×’, has two states low (0V) and HiZ (floating) as shown in Figure 1.16. Consider the operation of the transistor-level circuit for the 74HC05. If A is high (+3.3V), the transistor is active, and the output is low (0V). If A is low (0V), the transistor is off, and the output is neither high nor low. In general, we can use an open collector NOT gate to switch current on and off to a device, such as a relay, a light emitting diode (LED), a solenoid, or a small motor. The 74HC05, the 74LS05, the 7405, and the 7406 are all open collector NOT gates. 74HC04 is high-speed CMOS and can only sink up to 4 mA when its output is low. Since the 7405 and 7406 are transistor-transistor-logic (TTL) they can sink more current. In particular, the 7405 has a maximum output low current (IOL) of 16 mA, whereas the 7406 has a maximum IOL of 40 mA.
Figure 1.16. Two transistor implementations of an open collector NOT gate.
In the computer, we can build an 8-bit storage element, shown logically as Figure 1.10, by combining 8 flip-flops. This basic storage element is called a register, as shown in Figure 1.17. A bus is a collection of wires used to pass data from one place to another. In this circuit, the signals D7–D0 represent the data bus. Registers on the Tiva ® microcontrollers are 32-bits wide, but in this example we show an 8-bit register. We call it storage because as long the circuit remains powered, the digital information represented by the eight voltages Q7–Q0 will be remembered. There are two operations one performs on a register: write and read. To perform a write, one first puts the desired information on the 8 data bus wires (D7–D0). As you can see from Figure 1.17, these data bus signals are present on the D inputs of the 8 flip-flops. Next, the system pulses the Write signal high then low. This Write pulse will latch or store the desired data into the 8 flip-flops. The read operation will place a copy of the register information onto the data bus. Notice the gate signals of the tristate drivers are negative logic. This means if the Read* signal is high, the tristate drivers are off, and this register does not affect signals on the bus. However, the read operation occurs by setting the Read* signal low, which will place the register data onto the bus.1.4. Digital Information stored in Memory
Memory is a collection of hardware elements in a computer into which we store information, as shown in Figure 1.18. For most computers in today’s market, each memory cell contains one byte of information, and each byte has a unique and sequential address. The memory is called byte-addressable because each byte has a separate address. The address of a memory cell specifies its physical location, and its content is the data. When we write to memory, we specify an address and 8, 16, or 32 bits of data, causing that information to be stored into the memory. Typically data flows from processor into memory during a write cycle. When we read from memory we specify an address, causing 8, 16, or 32 bits of data to be retrieved from the memory. Typically data flows from memory into the processor during a read cycle. Read Only Memory, or ROM, is a type of memory where the information is programmed or burned into the device, and during normal operation it only allows read accesses. Random Access Memory (RAM) is used to store temporary information, and during normal operation we can read from or write data into RAM. The information in the ROM is nonvolatile, meaning the contents are not lost when power is removed. In contrast, the information in the RAM is volatile, meaning the contents are lost when power is removed. The system can quickly and conveniently read data from a ROM. It takes a comparatively long time to program or burn data into a ROM. Writing to Flash ROM is a two-step process. First, the ROM is erased, causing all the bits to become 1. Second, the system writes zeroes into the ROM as needed. Each of these two steps requires around 1 ms to complete. In contrast, it is fast and easy to both read data from and write data into a RAM. Writing to RAM is about 100,000 times faster (on the order of 10 ns). ROM on the other hand is much denser than RAM. This means we can pack more ROM bits into a chip than we can pack RAM bits. Most microcontrollers have much more ROM than RAM. The TM4C123 has 32,768 bytes of RAM and 262,144 bytes of ROM.Figure 1.18. Memory is a sequential collection of data storage elements.
A great deal of confusion exists over the abbreviations we use for large numbers. In 1998 the International Electrotechnical Commission (IEC) defined a new set of abbreviations for the powers of 2, as shown in Table 1.4. These new terms are endorsed by the Institute of Electrical and Electronics Engineers (IEEE) and International Committee for Weights and Measures (CIPM) in situations where the use of a binary prefix is appropriate. The confusion arises over the fact that the mainstream computer industry, such as Microsoft, Apple, and Dell, continues to use the old terminology. According to the companies that market to consumers, a 1 GHz is 1,000,000,000 Hz but 1 Gbyte of memory is 1,073,741,824 bytes. The correct terminology is to use the SI-decimal abbreviations to represent powers of 10, and the IEC-binary abbreviations to represent powers of 2. The scientific meaning of 2 kilovolts is 2000 volts, but 2 kibibytes is the proper way to specify 2048 bytes. The term kibibyte is a contraction of kilo binary byte and is a unit of information or computer storage, abbreviated KiB.
1 KiB = 2
10bytes = 1024 bytes 1 MiB = 2
20bytes = 1,048,576 bytes 1 GiB = 2
30bytes =
1,073,741,824 bytes
These abbreviations can also be used to specify the number of binary bits. The term kibibit is a contraction of kilo binary bit, and is a unit of information or computer storage, abbreviated Kibit. A mebibyte (1 MiB is 1,048,576 bytes) is approximately equal to a megabyte (1 MB is 1,000,000 bytes), but mistaking the two has nonetheless led to confusion and even legal disputes. In the engineering community, it is appropriate to use terms that have a clear and unambiguous meaning. Value SI Decimal SI Decimal Value IEC Binary IEC Binary 10001 k kilo- 10241 Ki kibi-10002 M mega- 10242 Mi mebi-10003 G giga- 10243 Gi gibi-10004 T tera- 10244 Ti tebi-10005 P peta- 10245 Pi pebi-10006 E exa- 10246 Ei exbi-10007 Z zetta- 10247 Zi zebi-10008 Y yotta- 10248 Yi yobi-Table 1.4. Common abbreviations for large numbers.1.5. Numbers
To solve problems using a computer we need to understand numbers and what they mean. Each digit in a decimal number has a place and a value. The place is a power of 10 and the value is selected from the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}. A decimal number is simply a combination of its digits multiplied by powers of 10. For example 1984 = 1 • 103+ 9 • 102+ 8 • 101+ 4 • 100 Fractional values can be represented by using the negative powers of 10. For example, 273.15 = 2 • 102+ 7 • 101+ 3 • 100+ 1 • 10-1+ 5 • 10-2 In a similar manner, each digit in a binary number has a place and a value. In binary numbers, the place is a power of 2, and the value is selected from the set {0, 1}. A binary number is simply a combination of its digits multiplied by powers of 2. To eliminate confusion between decimal numbers and binary numbers, we will put a subscript 2 after the number to mean binary. Because of the way the microcontroller operates, most of the binary numbers in this book will have 8, 16, or 32 bits. An 8-bit number is called a byte, and a 16-bit number is called a halfword. For example, the 8-bit binary number for 106 is 011010102 = 0 • 27+ 1 • 26+ 1 • 25+ 0 • 24+ 1 • 23+ 0 • 22+ 1 • 21+ 0 • 20 = 64+32+8+2 Checkpoint 1.15: What is the numerical value of the 8-bit binary number 111111112? Binary is the natural language of computers but a big nuisance for us humans. To simplify working with binary numbers, humans use a related number system called hexadecimal, which uses base 16. Just like decimal and binary, each hexadecimal digit has a place and a value. In this case, the place is a power of 16 and the value is selected from the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F}. As you can see, hexadecimal numbers have more possibilities for their digits than are available in the decimal format; so, we add the letters A through F, as shown in Table 1.5. A hexadecimal number is a combination of its digits multiplied by powers of 16. To eliminate confusion between various formats, we will put a 0x or a $ before the number to mean hexadecimal. Hexadecimal representation is a convenient mechanism for us humans to define binary information, because it is extremely simple for humans to convert back and forth between binary and hexadecimal. Hexadecimal number system is often abbreviated as “hex”. A nibble is defined as 4 binary bits, or one hexadecimal digit. Each value of the 4-bit nibble is mapped into a unique hex digit, as shown in Table 1.5. Hex Digit Decimal Value Binary Value 0 0 0000 1 1 0001 2 2 0010 3 3 0011 4 4 0100 5 5 0101 6 6 01107 7 0111 8 8 1000 9 9 1001 A or a 10 1010 B or b 11 1011 C or c 12 1100 D or d 13 1101 E or e 14 1110 F or f 15 1111 Table 1.5. Definition of hexadecimal representation. For example, the hexadecimal number for the 16-bit binary 0001 0010 1010 1101 is 0x12AD = 1 • 163+ 2 • 162+ 10 • 161+ 13 • 160 = 4096+512+160+13 = 4781 Observation: In order to maintain consistency between assembly and C programs, we will use the 0x format when writing hexadecimal numbers in this book. Checkpoint 1.16: What is the numerical value of the 8-bit hexadecimal number 0xFE? As illustrated in Figure 1.19, to convert from binary to hexadecimal we can: 1) Divide the binary number into right justified nibbles, 2) Convert each nibble into its corresponding hexadecimal digit.
Figure 1.19. Example conversion from binary to hexadecimal.
Checkpoint 1.17: Convert the binary number 010001112 to hexadecimal. Checkpoint 1.18: Convert the binary number 1101101010112 to hexadecimal. As illustrated in Figure 1.20, to convert from hexadecimal to binary we can: 1) Convert each hexadecimal digit into its corresponding 4-bit binary nibble, 2) Combine the nibbles into a single binary number.Figure 1.20. Example conversion from hexadecimal to binary.
Checkpoint 1.19: Convert the hex number 0x49 to binary. Checkpoint 1.20: Convert the hex number 0xBEEF to binary. Checkpoint 1.21: How many binary bits does it take to represent 0x12345?Computer programming environments use a wide variety of symbolic notations to specify the numbers in hexadecimal. As an example, assume we wish to represent the binary number 011110102. Some assembly languages use $7A. Some assembly languages use 7AH. The C language uses 0x7A. Patt’s LC-3 simulator uses x7A. We will use the 0x7A format. Precision is the number of distinct or different values. We express precision in alternatives, decimal digits, bytes, or binary bits. Alternatives are defined as the total number of possibilities. For example, an 8-bit number format 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. Table 1.6illustrates the relationship between precision in binary bits and
precision in alternatives. The operation [[ x ]] is defined as the greatest integer of x . E.g., [[2.1]] [[2.9]] and [[3.0]] are all equal to 3. The Bytes column in Table 1.6 specifies how many bytes of memory it would take to store a number with that precision assuming the data were not packed or compressed in any way.
Binary bits Bytes Alternatives
8 1 256 10 2 1024 12 2 4096 16 2 65536 20 3 1,048,576 24 3 16,777,216 30 4 1,073,741,824 32 4 4,294,967,296 n [[n/8]] 2n Table 1.6. Relationship between bits, bytes and alternatives as units of precision. Checkpoint 1.22: How many bytes of memory would it take to store a 60-bit number?
Decimal digits are used to specify precision of measurement systems that display results as numerical values, as defined in Table 1.7. A full decimal digit can be any value 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9. A digit that can be either 0 or 1 is defined as a ½ decimal digit. The terminology of a ½ decimal digit did not arise from a mathematical perspective of precision, but rather it arose from the physical width of the light emitting diode (LED) or liquid crystal display (LCD) module used to display a blank or ’1’as compared to the width of a full digit. Notice in Figure 1.21 that the 7-segment modules capable of displaying 0 to 9 are about 1 cm wide; however, the corresponding 2-segment modules capable of being blank or displaying a 1 are about half as wide. Similarly, we define a digit that can be + or - also as a half decimal digit, because it has 2 choices. A digit that can be 0,1,2,3 is defined as a ¾ decimal digit, because it is wider than a ½ digit but narrower than a full digit. We also define a digit that can be -1, -0, +0, or +1 as a ¾ decimal digit, because it also has 4 choices. We use the expression 4½ decimal digits to mean 20,000 alternatives and the expression 4¾ decimal digits to mean 40,000 alternatives. The use of a ½ decimal digit to mean twice the number of alternatives or one additional binary bit is widely accepted. On the other hand, the use of ¾ decimal digit to mean four times the number of alternatives or two additional binary bits is not as commonly accepted. For example, consider the two ohmmeters shown in Figure 1.21. As illustrated in the figure, both are set to the 0 to 200 kΩ range. The 3½ digit ohmmeter has a resolution of 0.1 kΩ with measurements ranging from 0.0 to 199.9 kΩ. On the other hand, the 4½ digit ohmmeter has a resolution of 0.01 kΩ with measurements ranging from 0.00 to 199.99 kΩ. Observation: A good rule of thumb to remember is 210 • n ≈ 103 • n. Decimal digits Alternatives 3 1000 3½ 2000 3¾ 4000 4 10000 4½ 20000 4¾ 40000 n 10n n½ 2•10n n¾ 4•10n Table 1.7. Definition of decimal digits as a unit of precision.
Figure 1.21. Two ohmmeters: the one on the left has 3½ decimal digits and the one
on the right has 4½.
Checkpoint 1.23: How many binary bits is equivalent to 3½ decimal digits?Checkpoint 1.24: About how many decimal digits is 64 binary bits? You can answer this without a calculator, just using the “rule of thumb”.
A byte contains 8 bits as shown in Figure 1.22, where each bit b7,...,b0 is binary and has the value 1 or 0.
We specify b7 as the most significant bit or MSB, and b0 as the least significant bit or LSB. In C, the
specifier char means 8 bits or 1 byte.In C99, the specifiers uint8_t and int8_t mean 8 bits or 1 byte.In this book, we will use char to store ASCII characters and we will use uint8_t and int8_t to store 8-bit numbers.
Figure 1.22. 8-bit binary format.
If a byte is used to represent an unsigned number, then the value of the number is N = 128 • b7 + 64 • b6+ 32 • b5+ 16 • b4+ 8 • b3+ 4 • b2+ 2 • b1 + b0 Notice that the significance of bit n is 2n. There are 256 different unsigned 8-bit numbers. The smallest unsigned 8-bit number is 0 and the largest is 255. For example, 000010102 is 8+2 or 10. Other examples are shown in Table 1.8. The least significant bit can tell us if the number is even or odd. Furthermore, if the bottom n bits are 0, the number is divisible by 2n.binary hex Calculation decimal
00000000 2 0x00 0 01000001 2 0x41 64+1 65 00010110 2 0x16 16+4+2 22 10000111 2 0x87 128+4+2+1 135 111111112 0xFF 128+64+32+16+8+4+2+1 255 Table 1.8. Example conversions from unsigned 8-bit binary to hexadecimal and to decimal. Checkpoint 1.25: Convert the binary number 011010112 to unsigned decimal. Checkpoint 1.26: Convert the hex number 0x46 to unsigned decimal. The basis of a number system is a subset from which linear combinations of the basis elements can be used to construct the entire set. The basis represents the “places” in a “place-value” system. For positive integers, the basis is the infinite set {1, 10, 100, …}, and the “values” can range from 0 to 9. Each positive integer has a unique set of values such that the dot-product of the value vector times the basis vector yields that number. For example, 2345 is the dot-product (…, 2,3,4,5) • (…, 1000,100,10,1), which is 2*1000+3*100+4*10+5. For the unsigned 8-bit number system, the basis elements are {1, 2, 4, 8, 16, 32, 64, 128} The values of a binary number system can only be 0 or 1. Even so, each 8-bit unsigned integer has a unique set of values such that the dot-product of the values times the basis yields that number. For example, 69=0x45is (0,1,0,0,0,1,0,1) (128,64,32,16,8,4,2,1), which equals 0*128+1*64+0*32+0*16+0*8+1*4+0*2+1*1. Conveniently, there is no other set of 0’s and 1’s, such that set of values multiplied by the basis is 69. In other words, each 8-bit unsigned binary representation of the values 0 to 255 is unique.
One way for us to convert a decimal number into binary is to use the basis elements. The overall approach is to start with the largest basis element and work towards the smallest. More precisely, we start with the most significant bit and work towards the least significant bit. One by one, we ask ourselves whether or not we need that basis element to create our number. If we do, then we set the corresponding bit in our binary result and subtract the basis element from our number. If we do not need it, then we clear the corresponding bit in our binary result. We will work through the algorithm with the example of converting 100 to 8-bit binary, see Table 1.9. We start with the largest basis element (in this case 128) and ask whether or not we need to include it to make 100? Since our number is less than 128, we do not need it, so bit 7 is zero. We go the next largest basis element, 64 and ask, “do we need it?” We do need 64 to generate our 100, so bit 6 is one and we subtract 100 minus 64 to get 36. Next, we go the next basis element, 32 and ask, “do we need it?” Again, we do need 32 to generate our 36, so bit 5 is one and we subtract 36 minus 32 to get 4. Continuing along, we do not need basis elements 16 or 8, but we do need basis element 4. Once we subtract the 4, ourworking result is zero, so basis elements 2 and 1 are not needed. Putting it together, we get 011001002, 100 = 64+32+4. Checkpoint 1.27: In this conversion algorithm, how can we tell if a basis element is needed? Observation: If the least significant binary bit is zero, then the number is even. Observation: If the right-most n bits (least sign.) are zero, then the number is divisible by 2n. Observation: Bit 7 of an 8-bit number determines whether it is greater than or equal to 128.
Number Basis Need it? bit Operation
100 128 no bit 7=0 none
100 64 yes bit 6=1 subtract 100-64
36 32 yes bit 5=1 subtract 36-32
4 16 no bit 4=0 none
4 8 no bit 3=0 none
4 4 yes bit 2=1 subtract 4-4
0 2 no bit 1=0 none 0 1 no bit 0=0 none Table 1.9. Example conversion from decimal to unsigned 8-bit binary to hexadecimal. Checkpoint 1.28: Give the representations of the decimal 45 in 8-bit binary and hexadecimal. Checkpoint 1.29: Give the representations of the decimal 200 in 8-bit binary and hexadecimal. One of the first schemes to represent signed numbers was called one’s complement. It was called one’s complement because to negate a number, we complement (logical not) each bit. For example, if 25 equals 000110012in binary, then –25 is 11100110 2. An 8-bit one’s complement number can vary from -127 to +127. The most significant bit is a sign bit, which is 1 if and only if the number is negative. The difficulty with this format is that there are two zeros +0 is 000000002, and –0 is 111111112. Another problem is that one’s complement numbers do not have basis elements. These limitations led to the use of two’s complement.