Advanced_microelectronics_microcontrollers_in_practice_257 (1)_2418698_20220222_115229

pdf 257 trang Gia Huy 20/05/2022 3170
Bạn đang xem 20 trang mẫu của tài liệu "Advanced_microelectronics_microcontrollers_in_practice_257 (1)_2418698_20220222_115229", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pdfadvanced_microelectronics_microcontrollers_in_practice_257_1.pdf

Nội dung text: Advanced_microelectronics_microcontrollers_in_practice_257 (1)_2418698_20220222_115229

  1. Springer Series in advanced microelectronics 18
  2. Springer Series in advanced microelectronics Series Editors: K. Itoh T. Lee T. Sakurai W. M. C. Sansen D. Schmitt-Landsiedel The Springer Series in Advanced Microelectronics provides systematic information on all the topics relevant for the design, processing, and manufacturing of microelectronic devices. The books, each prepared by leading researchers or engineers in their fields, cover the basic and advanced aspects of topics such as wafer processing, materials, device design, device technologies, circuit design, VLSI implementation, and subsys- tem technology. The series forms a bridge between physics and engineering and the volumes will appeal to practicing engineers as well as research scientists. 18 Microcontrollers in Practice By I. Susnea and M. Mitescu 19 Gettering Defects in Semiconductors By V.A. Perevoshchikov and V.D. Skoupov 20 Low Power VCO Design in CMOS By M. Tiebout Volumes 1–17 are listed at the end of the book.
  3. M. Mitescu I. Susnea Microcontrollers in Practice With 117 Figures, 34 Tables and CD-Rom 123
  4. Marian Mitescu Ioan Susnea Razoare Street 2 Brailei Street 179 6200 Galati 800578 Galati Romania Romania mitescum@yahoo.com isusnea@yahoo.com Series Editors: Dr. Kiyoo Itoh Hitachi Ltd., Central Research Laboratory, 1-280 Higashi-Koigakubo Kokubunji-shi, Tokyo 185-8601, Japan Professor Thomas Lee Stanford University, Department of Electrical Engineering, 420 Via Palou Mall, CIS-205 Stanford, CA 94305-4070, USA Professor Takayasu Sakurai Center for Collaborative Research, University of Tokyo, 7-22-1 Roppongi Minato-ku, Tokyo 106-8558, Japan Professor Willy M. C. Sansen Katholieke Universiteit Leuven, ESAT-MICAS, Kasteelpark Arenberg 10 3001 Leuven, Belgium Professor Doris Schmitt-Landsiedel Technische Universitọt Mỹnchen, Lehrstuhl fỹr Technische Elektronik Theresienstrasse 90, Gebọude N3, 80290 Mỹnchen, Germany ISSN 1437-0387 ISBN-10 3-540-25301-7 Springer Berlin Heidelberg New York ISBN-13 978-3-540-25301-3 Springer Berlin Heidelberg New York Library of Congress Control Number: 2005927903 This work is subject to copyright. All rights are reserved, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilm or in any other way, and storage in data banks. Duplication of this publication or parts thereof is permitted only under the provisions of the German Copyright Law of September 9, 1965, in its current version, and permission for use must always be obtained from Springer-Verlag. Violations are liable to prosecution under the German Copyright Law. Springer is a part of Springer Science+Business Media. springeronline.com â Springer Berlin Heidelberg 2005 Printed in Germany The use of general descriptive names, registered names, trademarks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use. Typesetting and production: LE-TEX Jelonek, Schmidt & Vửckler GbR, Leipzig, Germany Cover design: design & production GmbH, Heidelberg Printed on acid-free paper SPIN: 11327721 57/3141/YL - 5 4 3 2 1 0
  5. This book is dedicated to the great inventor John W. Halpern, who taught me that life can be re-invented, and to Simona, who taught me that it’s worth doing so. Ioan Susnea To my sons George Dan and Cosmin Marian Mitescu
  6. Preface The Aim of this Book The manufacturers of microcontrollers report annual sales of hundreds of millions of units. To support this massive market demand, they offer tens of thousands of pages of free, good quality technical documentation: data sheets, application notes, articles, etc. The problem is that the more information is available on this subject, the harder it is to find the information useful for you. Therefore, the need for synthesis seems to be growing. While the vast majority of the literature available is monographic, dedicated to a specific circuit, this book tries to emphasize that various microcontrollers have many common structural characteristics; in fact they are all implementations of the same concept. When starting with the big picture, it’s easier to focus on details from time to time, than to build the big picture, starting from details. Throughout this book, we present three different families of microcontrollers: HC11, AVR, and 8051 and we aim to make reading of this book more rewarding for the reader than reading three monographs dedicated to each of the above families. If you have ever studied one microcontroller, by reading this book you will discover that you already know a lot of things about all microcontrollers. Another important aim of this book is to help the reader to make the small, yet decisive step between theory and practice. The book presents the design of three development boards, one for each microcontroller discussed, which can serve as platforms for a large number of experimental projects. The design examples presented demonstrate that, regardless of the microcontroller selected, and the complexity of the project, the software applications can be built according to the same general structure.
  7. VIII Preface What’s in this Book The book is structured into three sections. Chapters 1–8 aim to create a detailed overview of microcontrollers, by presenting their subsystems starting from a general functional block diagram, valid for most microcontrollers on the market. In each case, we describe the distinctive features of that specific subsystem for HC11, 8051 and AVR. This whole section has a more theoretical approach, but, even here, many practical examples are presented, mainly regarding the initializations required by each subsystem, or the particular use of the associated interrupts. The purpose of this section is to create a perspective that views the microcontroller as a set of resources, easy to identify and use. Chapters 9–16 contain eight complete projects, described from the initial idea, to the printed circuit board and detailed software implementation. Here too, we permanently focus on the similarities between the microcontrollers discussed, from the hardware and software perspectives. All chapters contain exercises, suggesting modifications or improvements of the examples in the book. Most exercises have solutions in the book; for the others the solutions can be found on the accompanying CD. Finally, the appendices contain additional information intended to help the reader to fully understand all the aspects of the projects described in the previous sections. We chose to present these details separately in these appendices, in order to avoid fragmentation of the flow of the main text. Who Should Read this Book Most of the available books on microcontrollers are either “guides for idiots”, as- suming that the reader knows nothing on the subject, or “rocket science books” for a limited academic audience. Little is offered to the majority of readers that are in between. This book is primarily aimed at students of technical universities, but can be rewarding reading for anyone having a reasonable dose of “technical common sense”, like service technicians, hobbyists, inventors, etc. We assume that the reader knows the fundamentals about binary representation of numbers, Boolean algebra, logic functions, and logic circuits, and knows how to locate and read data sheets and other technical literature supplied by the manufacturers. We also assume that he has the basic skills required to use a personal computer, and knows how to install a software application, how to view and create text files, etc. Thus, we can spare the space needed for explaining these notions for more substantial projects. However, eliminating puerile explanations doesn’t mean that we give up all explanations. Don’t let yourself be intimidated by projects that seem very complex, like the “fuzzy logic temperature controller”. Even the most complex projects presented in this book are built according to the same structure as the simplest, LED flashing type projects.
  8. Preface IX How to Read this Book The chapters are intended to be self-contained, so that advanced users can, in principle, read the chapters individually as they choose. However, the density of information requires permanent contact with practice in order to consolidate the knowledge acquired. We strongly recommend downloading and installing the software tools needed to test the examples and exercises presented in the book. For your convenience, all the source files for the examples and exercises presented in the book have been included on the accompanying CD. This CD also contains the schematic files and the PCB layout drawings for the main projects described in the book. In our opinion, PCB design skills are equally important as good knowledge of the software, and therefore we recommend that you download and install the freeware version of the Eagle™ layout editor, from CadSoft, so that you can view and edit the projects included. The information in this book is not intended to replace the manufacturers’ data sheets; therefore it is a good idea to keep at hand the data sheets for the microcon- trollers discussed here: 68HC11F1, AT90S8535, and AT89C51. If you encounter new terms, try using the glossary of terms included in the appendices, which contains short definitions for the most common terms used in the book. No special conventions have been used in writing this book. The only notation worth mentioning here is that the names of active LOW signals are written using a backslash as terminator, e. g. RD\, WR\, etc. Disclaimer The information in this book is for educational purposes only. Although we have made every effort to provide accurate information, the examples in this book should not be interpreted as a promise or a guarantee that you will be able to reach a certain level of knowledge or skills by reading this material. The author and publisher shall in no event be held liable to any party for any direct, indirect, punitive, special, incidental or other consequential damages arising directly or indirectly from any use of this material, which is provided “as is”, and without warranties. All internet links indicated are for information purposes only and are not war- ranted for content, accuracy or any other implied or explicit purpose.
  9. Contents 1 Resources of Microcontrollers 1 1.1 In this Chapter 1 1.2 Microcontroller Architectures . . 1 1.3 TheMemoryMap 3 1.4 CPU Registers 5 1.4.1 The CPU Registers of HC11 . . 5 1.4.2 The CPU Registers of AVR . . . 6 1.4.3 The CPU Registers of 8051 . . . 7 1.5 The Peripheral Interfaces 8 1.6 The Interrupt System. . . . 9 1.6.1 General Description of the Interrupt System 9 1.6.2 Distinctive Features of the Interrupt System of HC11 . . . . . . 11 1.6.3 Distinctive Features of the Interrupt System of AVR 12 1.6.4 Distinctive Features of the Interrupt System of 8051 12 1.7 Expanding the Resaurces of Microcontrollers 12 1.7.1 HC11 Operating with External Bus . . 13 1.7.2 AT90S8515 Operating with External Bus . . 14 1.7.3 8051 Operating with External Bus . . . 14 1.8 Exercises 15 2 Using the Digital I/O Lines 19 2.1 In this Chapter 19 2.2 Overview of the Parallel I/O System . . 19 2.3 Electrical Characteristics of the I/O Lines . . . 21 2.4 Controlling the I/O Lines by Software 23 2.5 Exercises 24 3 Using the Asynchronous Serial Interface 27 3.1 In this Chapter 27 3.2 Synchronous vs. Asynchronous Communication . . . 27
  10. XII Contents 3.3 Error Detection in Asynchronous Communication 29 3.4 The General Structure of the Asynchronous Serial Communication Interface 30 3.5 The Serial Communication Interface of 68HC11F1 30 3.6 The Asynchronous Serial Communication Interface of AVR Microcontrollers . . 35 3.7 The Asynchronous Serial Interface of 8051 . . 36 3.8 Programming the Asynchronous Serial Interface . . 37 3.8.1 ProgrammingtheSCIofHC11 38 3.8.2 Programming the UART of AT90S8535 . . . 40 3.8.3 Programming the UART of 8051 41 3.9 Hardware Interfaces for Serial Communication . . . . 42 3.9.1 TheRS232Interface 42 3.9.2 Differential Communication. The Interfaces RS422 and RS485 43 3.9.3 The Current Loop Interface . . . 44 3.10 Basic Principles of Networking with Microcontrollers, Using the Asynchronous Serial Interface . . 45 3.11Exercises 46 4 Using the Synchronous Serial Interface SPI 49 4.1 In this Chapter 49 4.2 General Description of the SPI . 49 4.3 The SPI of HC11 Microcontrollers . . . 50 4.4 The SPI of the AVR Microcontrollers . 53 4.5 Examples of Using The SPI 55 4.5.1 Using the SPI To Connect Two Microcontrollers . . 55 4.5.2 Expanding the I/O Space Using the SPI. . . . 56 4.6 Exercises 59 5 Using The I2C Bus 61 5.1 In this Chapter 61 5.2 The Principles of Implementation of the I2C Bus . . 61 5.2.1 The Start Transfer Condition . . 62 5.2.2 TheDataTransferontheI2CBuS 62 5.2.3 TheACKBit 62 5.2.4 The STOP Condition . . . 63 5.3 A Software Implementation of the I2C Protocol . . . 63 5.4 Accessing 24C256 Memory Devices . 64 5.5 Exercises 66 6 Using the MCU Timers 67 6.1 In this Chapter 67 6.2 The General Structure and Functions of the Timer System 67
  11. Contents XIII 6.3 Distinctive Features of the General-Purpose Timer of HC11 69 6.3.1 The Control and Status Registers of the HC11 Timer . . . . . . 69 6.3.2 Exercises Regarding the Use of the General-Purpose Timer ofHC11 73 6.4 Distinctive Feature of the Timer of the AVR Microcontrollers . . . . . 75 6.4.1 The 8-Bit Timer/Counter Timer0 76 6.4.2 The 16-Bit Timer/Counter Timer1 . . . 76 6.4.3 Synopsis of the Timer I/O Registers of AT90S8115 . 78 6.4.4 Summary of the Unique Features of the AVR Timer 79 6.4.5 Exercises Regarding the Use of AVR Timers 79 6.5 Distinctive Features of the Timer System of the 8051 Microcontrollers 81 6.5.1 The Control and Status Registers of the Timer 82 6.5.2 Description of the Timer Operating Mode 0 83 6.5.3 Description of the Timer Operating Mode 1 83 6.5.4 Description of the Timer Operating Mode 2 84 6.5.5 Description of the Timer Operating Mode 3 84 6.5.6 Using Timer1 as a Baud Rate Generator . . . 85 6.5.7 Exercises for Programming the 8051 Timer 85 6.6 PWM Timers. Principles of Operation 87 6.7 Watchdog Timers. . 89 6.7.1 The Watchdog of HC11 . 89 6.7.2 The Watchdog of AT90S8515 . 90 7 Interfacing to Analog Signals 93 7.1 In This Chapter . . . 93 7.2 TheAnalogComparator 93 7.3 The General Structure of the A/D Converter Subsystem. . . 95 7.4 The A/D Converter of the HC11 Family of Microcontrollers . . . . . . . 96 7.5 ExercisesonProgrammingtheA/DConverterofHC11 98 7.6 The A/D Converter of the AVR Microcontrollers . . 100 7.7 Exercises on Programming the A/D Converter AT90S8535 101 7.8 Digital-to-Analog Converters . . . 102 7.8.1 The Principles of the D/A Conversion 102 7.8.2 Exercise on Using MX7224 . . 104 8 Using the Internal EEPROM Memory 107 8.1 In this Chapter 107 8.2 Overwiew of the EEPROM Subsystem 107 8.3 The EEPROM Memory and the CONFIG Register of HC11 107 8.3.1 The Registers Controlling the EEPROM of HC11 . 108 8.3.2 Software Routines to Erase and Write the EEPROM 109 8.3.3 The CONFIG Register . . 110 8.4 The EEPROM Memory of the AVR Microcontrollers 111 8.4.1 The Registers of the Interface with the EEPROM Memory . . 111 8.4.2 Software Routines to Read and Write EEPROM . . 112
  12. XIV Contents 9 HC11 Development Board 115 9.1 In this Chapter 115 9.2 Description of the Hardware Module . 115 9.3 Assembling and Testing the Module . . 117 9.4 Description of the Software Components . . . . 119 9.5 Exercises 129 10 AVR Development Board 131 10.1 In this Chapter 131 10.2TheHardware 131 10.3 Testing the Circuit 134 10.4TheSoftware 134 10.5Exercises 144 11 8051 Development Board 145 11.1 In this Chapter 145 11.2Hardware 145 11.3TheSoftware 148 11.3.1 Installing the Cross-Assembler 148 11.3.2 Writing and Testing Simple 8051 Programs 149 11.3.3 Loading and Executing Programs in the External Ram Memory 152 11.4Exercises 154 12 Digital Voltmeter with RS232 Interface 157 12.1 In this Chapter 157 12.2TheHardware 157 12.3TheSoftware 157 12.4Exercises 162 13 Simple RS485 Network with Microcontrollers 163 13.1 In this Chapter 163 13.2TheHardware 163 13.2.1 The RS232-to-RS485 Converter . 164 13.2.2 The Digital Input Module 165 13.2.3 The Analog Input Module 166 13.2.4 Using the AVR Development Board to Emulate Thel SLD and SLA Modules. 166 13.3TheSoftware 167 13.3.1 Description of the Communication Protocol 167 13.3.2 The Software for the SLD Module . . . 169 13.3.3 TheSoftwarefortheMASTERDevice 171 13.4Exercises 172
  13. Contents XV 14 PI Temperature Controller 173 14.1 In this Chapter 173 14.2BasicConcepts 173 14.3 Hardware Implementation of a Microcontroller-Based Temperature Controller . . . 177 14.4 Software Implementation of a PI Temperature Controller . 179 15 Fuzzy Logic Temperature Controller 185 15.1 In this Chapter 185 15.2 The Principles of Fuzzy Control 185 15.3 A Microcontroller Implementation of a Fuzzy Controller . 189 16 Remote Relay Controller over Telephone Lines 193 16.1 In this Chapter 193 16.2 Description of the Hardware Solution 193 16.3 Description of the Software 197 A.1 Glossary of Terms . 203 Appendix 202 A.2 Description of the Registers of 68HC11F1 . . . 213 A.3 HC11 Instruction Set . . . 215 A.4 An Example of Expanded Structure with HC11 . . . 219 A.5 Using HC11 in Bootstrap Mode 221 A.6 The Registers of AT90S8535 . . . 224 A.7 AVR Instruction Set 225 A.8 AT90S8515 Operating with External RAM . . 228 A.9 In-system Programming the AVR AT90S8535 229 A.10 The Special Function Registers of 8051 232 A.11 8051 Instruction Set 233 A.12 An Example of 8051 Operating with External Bus . 237 A.13 Programming the Internal Memory of 8051 . . 238 A.14 SPI Seven-Segment Display Units . . . 240 A.15 Description of the Software Utility ASMEDIT 243 B.1 Contents of the Accompanying CD . . . 245 B.2 Recommended Readings and Web References. 247 Index 249
  14. 1 Resources of Microcontrollers 1.1 In this Chapter This chapter is a presentation of the main subsystems of microcontrollers, seen as resources, organized according to one of the fundamental architectures:Von Neumann and Harvard. It also contains a description of the internal CPU registers, the general structure of a peripheral interface, and an overview of the interrupt system. 1.2 Microcontroller Architectures A microcontroller is a structure that integrates in a single chip a microprocessor, a certain amount of memory, and a number of peripheral interfaces. The Central Processing Unit (CPU) is connected to the other subsystems of the microcontroller by means of the address and data buses. Depending on how the CPU accesses the program memory, there are two possible architectures for microcontrollers, called Von Neumann, and Harvard. Figure 1.1 shows the structure of a computer with Von Neumann architecture, where all the resources, including program memory, data memory, and I/O registers, are connected to the CPU by means of a unique address and data bus. Address bus Data bus DATA PROGRAM I/O CPU MEMORY INTERFACES MEMORY Interrupt logic Fig. 1.1. Block diagram of Von Neumann architecture
  15. 2 1 Resources of Microcontrollers A typical microcontroller having Von Neumann architecture is 68HC11 from Motorola. In HC11, all resources are identified by unique addresses in the same address space, and can be accessed using the same instructions. For example, in case of the instruction: LDAA ;load accumulator a from the operand indicated by the label can be any of the microcontroller’s resources, from I/O ports, to ROM constants. This way of accessing resources allows the existence of complex instructions like this: ASL 35,x ;arithmetic shift left the memory ;location with the address ;obtained by adding 35 to the ;index register X. Therefore, the Von Neumann microcontrollers tend to have a large instruction set, including some really complex instructions. This is the reason why computers having the Von Neumann architecture are often called CISC, or Complex Instruction Set Computers. The main disadvantage of this architecture is that the more complex the instruc- tion, the longer it takes to fetch, decode, execute it, and store the result. The instruction in the above example takes six machine cycles to execute, while the instruction for integer divide, IDIV, needs no less than 41 machine cycles to complete. The Harvard architecture was created to increase the overall speed of computers in the early years, when very slow magnetic core memory was used to store the program. It includes an additional, separate bus to access the program memory (refer to Fig. 1.2). The presence of the second bus makes the following things possible: • While an instruction is executed, the next instruction can be fetched from the program memory. This technique is called pipelining and brings a significant increase of computer speed. • The program memory can be organized in words of different size from, and usually larger than, the data memory. Wider instructions mean a greater data flow to the CPU, and therefore the overall speed is higher. Address bus Data bus Address bus PROGRAM I/O DATA MEMORY CPU INTERFACES MEMORY Data bus Interrupt logic Fig. 1.2. Block diagram of Harvard architecture
  16. 1.3 The Memory Map 3 Such architecture, along with reducing and optimizing the instruction set, mean that most instructions execute in a single machine cycle. Since the Harvard archi- tecture is often accompanied by the reduction of the size and complexity of the instruction set, computers with this architecture are also called Reduced Instruction Set Computers (RISC). For example, some PIC microcontrollers have an instruction set of only 35 instructions, compared to more than 100 for HC11. The speed increase is even higher. The separate bus for the program memory makes the access of the program to constants (such as tables, strings, etc.) located in ROM more complicated and more restrictive. For example, some PIC microcontrollers have the program memory organized in 14-bit wide words, which makes locating and accessing a constant presented as a byte possible only by embedding the constant in a special instruction. For this purpose, the instruction “RETLW k” (Return from subprogram with constant k in register W) has been provided. The AVR microcontrollers have the program memory organized into 16-bit words, which makes the task of accessing constants in program memory easier, because each 16-bit word can store two 8-bit constants. A special instruction LPM (Load from Program Memory) allows access to ROM constants. 1.3 The Memory Map From the programmer’s point of view, a microcontroller is a set of resources. Each resource is identified by one or more addresses in an address space. For example, the 68HC11E9 microcontroller has its internal RAM memory organized as 512 locations, having addresses in the range $0000–$01FF, the ROM memory occupies the addresses in the range $D000–$FFFF (12288 locations), and the I/O register block takes the address form $1000–$103F (64 locations). The memory map is a graphic representation of how the resources are associated with addresses (see Fig. 1.3 for an example of a memory map). Obviously, not all addresses are related to existing resources – in some cases it is possible to add external memory or I/O devices, to which we must allocate distinct addresses in the address space. Normally, the memory map is determined by the hardware structure formed by the microcontroller and the external devices (if any), and cannot be dynamically modified during the execution of a program. However, there are situations when, by writing into some special configuration registers, the user can disable resources (such as the internal ROM memory, or the EEPROM memory) or can relocate resources in a different area of the address space. But even in these cases, the access to the configuration registers is restricted, and the modification becomes effective after the next RESET. Figures 1.3 and 1.4 show the memory maps for a microcontroller with Von Neumann architecture, MC68HC11E9, operating in single-chip mode, and for a RISC microcontroller, the AVR AT90S8535.
  17. 4 1 Resources of Microcontrollers $0000 $01FF Internal RAM $1000 Register block $103F $B600 $B7FF Internal EEPROM $D000 Internal ROM $FFFF Fig. 1.3. Memory map for 68HC11E9 operating in single-chip mode CPU $0000 register $0020 I/O register $0060 Internal $0000 RAM $025F Program $0000 memory Not used EEPROM $0FFF $FFFF $01FF Fig. 1.4. Memory map for AT90S8515 operating in single-chip mode Note, for the AVR microcontroller, the presence of three different address spaces, one for data memory and I/O registers, and two more for the program memory and the EEPROM. The 8051 microcontrollers are considered to belong to the Harvard architecture, but they are CISC, and do not allow pipelining; therefore they look more like Von Neumann computers with the capability to access program memory, and data memory as different pages. The two distinct memory pages are accessed through the same physical bus, at different moments time in. Fig. 1.5 shows the memory map for an 8051 MCU operating in single-chip mode. There are two address spaces here too, one for the program memory and the other for data memory and special function registers. CPU $0000 registers Bit $0020 memory $0030 Internal $0000 RAM Internal $0080 program memory SFRs $1FFF $00FF Fig. 1.5. Memory map for 8051 operating in single-chip mode
  18. 1.4 CPU Registers 5 One unique feature of this microcontroller is the presence of a RAM area, located in the address range $0020–$002F, which is bit addressable, using special instructions. This artifice allows the release of RAM memory by assigning some Boolean variables to individual bits in this area, rather than using a whole byte for each variable, because 8051 is low on this resource: only 80 RAM locations are available for variables and stack. Standard 8051 microcontrollers do not have internal EEPROM memory. 1.4 CPU Registers The good thing about CPU registers is that they are part of the CPU, and an operand located in these registers is immediately available as input to the arithmetic and logic unit (ALU). Since the instructions having operands in the registers of the CPU are executed faster, the microcontrollers designed for higher speed tend to have more internal registers. While HC11 has only two accumulator registers, the AVR family has as many as 32 such registers. 1.4.1 The CPU Registers of HC11 HC11 has seven internal registers, plus the CPU status register, called the Condition Code Register (CCR). The accumulator registers A and B are general-purpose 8-bit registers. They can be concatenated to form a 16-bit register called D, where A is the most significant byte, and B is the least significant byte. This feature creates a remarkable flexibility for 16-bit arithmetic operations. The index registers X and Y are 16-bit registers, which can also be used as storage registers, 16-bit counters; and most important, they can store a 16-bit value, which, added with an 8-bit value contained in the instruction itself, form the effective address of the operand when using the indexed addressing mode. The Stack Pointer (SP) register is a 16-bit register, that must be initialized by software with the ending address of a RAM memory area, called the stack.SP automatically decrements each time a byte is pushed to the stack, and increments when a byte is pulled from stack. Thus, SP always points to the first free location of the stack. The stack is affected in the following situations: • During the execution of the instructions BSR, JSR (Branch or Jump to Subrou- tine), the return address is automatically pushed on to the stack and the SP is adjusted accordingly. The instruction RTS (Return from Subroutine) pulls this value from the stack and reloads it into the program counter. • During the execution of push and pull type instructions, used to save and restore the contents of the CPU registers to the stack. • During the execution of an interrupt, and when returning from an interrupt service routine upon the execution of the RTI (Return from Interrupt) instruction.
  19. 6 1 Resources of Microcontrollers SP may be directly accessed by means of the LDS (load SP) and STS (Store SP) instructions or indirectly, using transfer instructions like TXS, TYS (Transfer X/Y to SP) or TSX, TSY (Transfer SP to X/Y). The Program Counter (PC) register is a 16-bit register, that contains the address of the instruction following the instruction currently executed. The Condition Code Register (CCR) is an 8-bit register with the following struc- ture: CCR 76543210 S X H I N Z V C RESET11010000 The bits C (Carry/Borrow), V (Overflow), Z (Zero), N (Negative) and H (Half Carry) are status bits, set or cleared according to the result of the arithmetic and logic instructions. Refer to the data sheet for details on how these bits are affected by each instruction. The bits I (General Interrupt Mask), X (XIRQ Interrupt Mask), and S (Stop disable) are control bits used to enable/disable the interrupts, or the low-power op- erating mode. When I = 1 all maskable interrupts are disabled. X = 1 disables the non-maskable interrupt XIRQ, and S = 1 blocks the execution on the STOP instruc- tion, which is treated like a NOP. Some CCR bits (C, V, I) can be directly controlled by means of the instructions SEC (Set Carry), CLC (Clear Carry), SEV (Set Overflow Bit), CLV (Clear Overflow Bit), SEI (Set Interrupt Mask), and CLI (Clear Interrupt Mask). The CCR as a whole may be read or written using the instructions TPA (Transfer CCR to A) and TAP (Transfer A to CCR) 1.4.2 The CPU Registers of AVR The CPU of the AVR microcontrollers has 32 general-purpose registers, called R0– R31. The register pairs R26–R27, R28–R29, R30–R31 can be concatenated to form the X, Y, Z , registers, which can be used for indirect addressing (R26 is XL – lower byte of X, R27 is XH – higher byte of X, R28 is YL, R29 is YH, R30 is ZL and R31 is ZH). The registers R16–R31 may be the destination of immediate addressed operands like LDI (Load Register Immediate) or CPI (Compare Immediate). Unlike HC11, the CPU registers of AVR are present with distinct addresses in the memory map. The Program Counter (PC) has functions similar to those of the PC register of HC11. The difference is that the size of PC is not 16 bits, and is limited to the length required to address the program memory (in case of AT90S8515 only 12 bits are needed to address the 4K of program memory). PC is cleared at RESET. The Stack Pointer (SP) has 16 bits, and is placed in the I/O register address space, which makes it accessible to the programmer only by means of the IN and OUT instructions, as two 8-bit registers SPH, and SPL.
  20. 1.4 CPU Registers 7 The CPU status register is called SREG and has the following structure: SREG 76543210 I T H S V N Z C RESET00000000 The meaning of the bits in SREG is slightly different from those of HC11: The I bit – Global Interrupt Enable/Disable Bit – has an opposite action: when set to 1 the interrupts are enabled. The instructions that control this bit have the same mnemonic SEI (Set I bit) and CLI (Clear I bit). T – Bit Copy Storage. The status of this bit can be modified by the instructions BST (Bit Store) and BLD (Bit Load), thus allowing the program to save the status of a specific bit from a general-purpose register, or transfer this information to a bit from another register. There is also a pair of conditional branch instructions which test this bit: BRTS (Branch if T bit is Set), and BRTC (Branch if T bit is Clear) S –Sign Bit – It is the exclusive OR between N and V The other bits in SREG (C, Z, N, V, H) have the same meaning described for HC11. The AVR microcontrollers have distinct SET–CLEAR instructions for each of the SREG bits. 1.4.3 The CPU Registers of 8051 The accumulator A is a general-purpose 8-bit register, used to store operands or results in more than a half of the instruction set of 8051. The R0–R7 registers are 8-bit registers, similar to the registers R0–R31, described for the AVRfamily of microcontrollers. There are four sets (or banks) of such registers, selected by writing the bits [RS1:RS0] in the CPU status register PSW, described below. The four sets of eight registers each occupy 32 addresses in the address space of data memory, at the addresses [0000h–0007h], [0008h–000Fh], [0010h–0017h], [0018h–001Fh] (refer to Fig. 1.4). The accumulator B is another general-purpose 8-bit register, having functions similar to the R0–R7 registers. Besides that, the accumulator B is used to store one of the operands in the case of the arithmetic instructions MUL AB and DIV AB. The Data Pointer Register (DPTR) is a 16-bit register, used for indirect addressing of operands, in a similar way to the X, Y, Z registers of AVR. The Program Counter (PC) is a 16-bit register similar to the PC of HC11. PC is cleared at RESET, thus all programs start at the address 0000h. The Stack Pointer (SP) has the following distinctive features, compared to HC11 and AVR: • It is an 8-bit register, i.e. it can address a memory area of 256 bytes maximum. 8051 can only use the internal memory for the stack.
  21. 8 1 Resources of Microcontrollers • Unlike HC11 and AVRwhere SP is initialized with an address at the end of RAM, and decrements with each byte pushed on to the stack, the SP of 8051 increments when data is added to the stack. • For HC11 and AVR, SP points to the first free byte of the stack area. The SP of 8051 indicates the last occupied location of the stack. At RESET, SP is automatically initialized with 07h, hence the first byte pushed to the stack will occupy the location with the address 08h. The Processor Status Word (PSW) is similar to CCR of HC11 or SREG of AVR, and has the following structure: PSW 76543210 CY AC F0 RS1 RS0 OV – P RESET00000000 The bits CY, AC and OV have similar functions to the bits C, H, and V of HC11 and AVR. [RS1:RS0] – Register bank select bits P – Parity bit. P = 1 if the accumulator contains an odd number of 1s, and P = 0 if the accumulator contains an even number of 1s. Thus the number of 1s in the accumulator plus P is always even. The bits PSW1 and PSW5 (F0) are uncommitted and may be used as general-purpose status flags. 1.5 The Peripheral Interfaces Microcontrollers are designed to be embedded in larger systems, and therefore they must be able to interact with the outside world. This interaction is possible by means of the peripheral interfaces. The general structure of a peripheral interface is shown in Fig. 1.6. Depending on the complexity of the specific circuits to be controlled by the program, any peripheral interface contains one or more control and status registers, and one or more data registers. These registers are normally located in the address space of the data memory, and are accessed as RAM locations. Interrupt I/O lines Interface specific circuits request Control Status Data register register register Internal bus Fig. 1.6. Typical structure of a peripheral interface
  22. 1.6 The Interrupt System 9 The most common peripheral interfaces, present in almost all the usual micro- controllers, are: • The I/O (Input/Output) ports. • The asynchronous serial interface (SCI, UART) • The synchronous serial interface (SPI) • Several types of timers • The analog to digital (A/D) converters The following chapters contain detailed descriptions of each of the above peripheral interfaces. Most of the peripheral interfaces have a common feature, which is the capability to generate interrupt requests to the CPU, when some specific events occur. This feature is analyzed in the next paragraph. 1.6 The Interrupt System 1.6.1 General Description of the Interrupt System Most of the events related to the peripheral interfaces, like the change of status of an input line, or reception of a character on the serial communication line, are asynchronous to the program running on the CPU. There are two possible ways to inform the CPU about these events: • One solution is to write the program so that it periodically tests the status of some flags associated with the external events. This technique is called polling. • The other solution is to interrupt the main program and execute a special subrou- tine when the external event occurs. An interrupt is a mechanism that allows an external event to temporarily put on hold the normal execution of the program, forcing the execution of a specific subroutine. Once the interrupt service subroutine completes, the main program continues from the point where it was interrupted. At the CPU level, this mechanism involves the following steps: 1. The identification of the interrupt source. This is automatically done by hardware. 2. Saving the current value of the PC register, thus providing a means to return from the interrupt service routine. The contents of PC are saved to the stack, and the operation is also done by hardware. 3. Then, the PC is loaded either with, or from, the address of a reserved memory area, called the interrupt vector. For each possible interrupt, a unique vector is assigned. The interrupt vectors are hardwired and cannot be modified by the user. 4. At the address of the interrupt vector, the program must contain either the address of the interrupt service routine (HC11 uses this technique) or an instruction for an unconditional jump to this routine (AVR and 8051 work this way). 5. The next step is the execution of the Interrupt Service Routine (ISR). This is a program sequence similar to a subroutine, but ending with a special instruction
  23. 10 1 Resources of Microcontrollers called Return from Interrupt (RTI, RETI). To make sure that the main program is continued exactly from the status it had in the moment when the interrupt occurred, it is crucial that all the CPU registers used by the interrupt service routine are saved at the beginning of the ISR, and restored before returning to the main program. Some microcontrollers, like the HC11 family, are provided with a hardware mechanism to save the whole CPU status, upon reception of an interrupt request. The status is restored by the instruction RTI (Return from Interrupt) before the actual return to the main program. In all other cases, it is the user’s responsibility to save and restore the CPU status in the interrupt service routine. 6. The final step in handling an interrupt is the actual return to the main program. This is done by executing a RTI (RETI) instruction as mentioned before. When this instruction is encountered, the contents of PC, saved in step 2, are retrieved from the stack and restored, which is equivalent to a jump to the point where the program was interrupted. The process of returning from an ISR is similar to returning from a regular subroutine, but there is an important difference: the interrupt service routines cannot be interrupted, and therefore once an interrupt has been acknowledged, further interrupts are automatically disabled. They are re-enabled by the RTI (RETI) instruction. All interrupts occurring during the execution of an ISR are queued and will be handled one by one, once the ISR is serviced. Important note. The stack is essential for the interrupt system. Both the PC and the CPU status are saved in the stack when handling interrupts. Therefore, the SP must be initialized by software before enabling the interrupts. The interrupt service routine must save the CPU status and restore it before returning to the main program. If two or more interrupt requests occur simultaneously, they are serviced in a predetermined order according to a hardwired priority. Refer to the data sheet for each microcontroller for details. The software control over the interrupt system is exerted either globally, by en- abling/disabling all the interrupts by means of specific instructions, or individually, by setting or clearing some control bits, called interrupt masks, associated with each interrupt. In other words, the process of generating an interrupt request is double conditioned, as shown in Fig. 1.7. GLOBAL INTERRUPT MASK LOCAL INTERRUPT MASK INTERRUPT INTERRUPT FLAG REQUEST Fig. 1.7. Double conditioning of interrupt requests
  24. 1.6 The Interrupt System 11 The INTERRUPT FLAG is the actual interrupt source, and, usually, is a flip-flop set by the external event. This bit is, in most cases, accessible for the program as a distinct bit in the status register of the peripheral interface. The LOCAL INTERRUPT MASKS are control bits, located in the control reg- isters of the interface. When set to 1 by software, the interrupts from that specific interface are enabled. The GLOBAL INTERRUPT MASK is a bit located in the CPU status register (CCR, SREG, PSW) that enables or disables all interrupts. In some cases, it is required that the CPU is informed immediately about certain important internal or external events, regardless of the status of the global interrupt mask. The solution to this problem is the non-maskable interrupt, which is uncon- ditionally transmitted to the CPU. A special case of non-maskable interrupt can be considered the RESET. Basically, the behavior of the MCU at RESET is entirely similar to the process of identification and execution of a non-maskable interrupt. 1.6.2 Distinctive Features of the Interrupt System of HC11 The most important feature of the interrupt system of HC11 is that the CPU status is automatically saved by hardware, right after the PC is saved. This feature simplifies the programmer’s work, but it wastes time saving and restoring all CPU registers. In most cases, the interrupt service routine does not use all the CPU registers, but needs to be executed as fast as possible. The global control of the interrupt system is performed by means of the I bit in the CCR register. When I = 1, all maskable interrupts are disabled. When I = 0, the interrupts coming from a specific peripheral interface are enabled if the local mask associated with that interface is set to 1. The I bit can be controlled by means of the instructions SEI (Set Interrupt Mask) equivalent to Disable Interrupts, and CLI (Clear Interrupt Mask), equivalent to Enable Interrupts. Besides the maskable interrupts, HC11 has three non-maskable interrupts, without counting the three possible RESET conditions (activation of the external RESET line, clock monitor fail reset, and watchdog reset). These are: XIRQ – External non-maskable interrupt, ILLOP – Illegal opcode trap, and SWI – software interrupt. The XIRQ interrupt is generated upon detection of a logic level LOW on the XIRQ input line, if the X bit in CCR is clear. The X bit acts similarly to I, but it only affects the XIRQ interrupt, and it is not affected by the SEI and CLI instructions. The only way the user can alter the status of this bit is by the TAP (Transfer A to CCR) instruction. The illegal opcode trap is an internal interrupt generated when an unknown opcode is fetched and decoded into the CPU. A software interrupt is generated when the instruction SWI is decoded. This is useful for defining breakpoints in a program for debug purposes. The priority of the interrupts is hardwired. However, it is possible to define one of the interrupts as the highest priority non-maskable interrupt. For this purpose, the bits [PSEL3–PSEL0] (Priority Select bits) in register HPRIO (Highest Priority Interrupt Register) code the interrupt with the highest priority.
  25. 12 1 Resources of Microcontrollers The vector area for HC11 is located at the end of the address space between the addresses $FFC0–$FFFF. See the data sheets for the list of exact addresses assigned to each interrupt vector. 1.6.3 Distinctive Features of the Interrupt System of AVR There are a few differences between the interrupt system of AT90S8535 and that of HC11. They are listed below: • The interrupt vector does not contain the address of the interrupt service routine, but a jump instruction to that routine. • The vector area is located at the beginning of the program memory address space, between the addresses $0000 and $0010. • There are no non-maskable interrupts besides RESET. • The I bit in SREG acts differently, compared to HC11: when I = 1, the interrupts are enabled. • There is no equivalent to the HPRIO register, and no other means to modify the hardwired relative priority of interrupts. 1.6.4 Distinctive Features of the Interrupt System of 8051 8051 has only five possible interrupt sources, compared to 16 for AVR, and 18 for HC11. The vectors are placed at the beginning of the program memory address space and must be initialized by the software to contain a jump to the interrupt service routine. The interrupts are enabled and disabled according to the same principles described for HC11 and AVR. The difference is that all the control bits associated with the interrupt system are placed in a Special Function Register (SFR) called IE (Interrupt Enable register) located at the address A8h. This register contains the global interrupt control bit, called in this case EA (Enable All interrupts), and bits to enable each individual interrupt. One interesting distinctive feature of the interrupt system of 8051 is the possi- bility to choose between two priority levels (low and high) for each interrupt. To this purpose, a special register called IP (Interrupt Priority register) contains a bit associated with each interrupt. When the priority bit is 0, the associated interrupt has a low priority level, and when the priority bit is 1, the interrupt has high priority. Unlike HC11 and AVR, for 8051 a high-priority interrupt can interrupt a low-priority interrupt service routine. 8051 does not save the CPU status automatically, therefore the interrupt service routine must save and restore the registers used, including PSW. 1.7 Expanding the Resaurces of Microcontrollers In many cases it is possible that the internal resources of a microcontroller are insufficient for certain applications. A typical example is when the number of variables
  26. 1.7 Expanding the Resaurces of Microcontrollers 13 used to store data exceeds the capacity of the internal RAM memory. The obvious solution to these situations is to add external components by creating an expanded microcontroller structure. The disadvantage of this solution is that a significant number of the available I/O lines are used to create the external bus for accessing the new resources, and are no longer available for normal I/O operations. Note that not all microcontrollers can operate with an external bus. The following paragraphs describe how to create and use expanded microcontroller structures. 1.7.1 HC11 Operating with External Bus The HC11 microcontrollers have two pins, called MODA and MODB, which control the operating mode. At RESET the status of these pins is read and, according to the result, the microcontroller selects one of the operating modes listed in Table 1.1. As shown in Table 1.1, there are four possible operating modes, among which two are special and the other two are normal. In the special bootstrap mode, a small ROM memory area becomes visible in the memory map. This ROM contains a short program, called a bootloader, which is executed after RESET, allowing the user to load and run a program in the internal RAM. This is useful, for example, to program the internal ROM memory. See App. A.5 for details on how to do this. The special test operating mode is destined for factory testing, and will not be discussed in this book. In the expanded operating mode, some of the MCU I/O lines are used to implement the external bus. In some cases, to reduce the number of I/O lines used for this purpose, the external data bus is multiplexed with the lower byte of the address bus. Demultiplexing requires an external latch, and a signal AS (Address Strobe), generated by the MCU, as shown in Fig. 1.8. Besides AS, the MCU generates the signal R/W\ (Read/Write) to specify the direction of the transfer on the data bus. A detailed example of using HC11 in expanded mode is presented in App. A.4. From the programmer’s point of view, when using HC11 in expanded operating mode, the following details must be considered: • All the MCU resources, except the I/O lines used to implement the external bus, are still available, and have the same addresses. • The internal ROM can be disabled by clearing the ROMON bit in the CONFIG register. Table 1.1. Selection of the operating mode of HC11 MODB MODA Operating mode 0 0 Special bootstrap 0 1 Special test 1 0 Single chip 1 1 Expanded
  27. 14 1 Resources of Microcontrollers DATA0-DATA7 GND ADR0-ADR7 MULTIPLEXED BUS MULTIPLEXED AS 74LS373 Fig. 1.8. Demultiplexing the external bus 1.7.2 AT90S8515 Operating with External Bus From the two distinct buses of the AVR microcontrollers, only the bus used for the data memory can be, in some cases, expanded to connect external RAM, or RAM – like external devices. AT90S8515 uses the lines of port A to multiplex the data bus with the lower order address bus, and port C for the high order address bus. The signal that strobes the address into the external latch is called ALE (Address Latch Enable). The direction of the transfer is indicated by two signals RD\ (Read) and WR\ (Write) – both active LOW. The circuit for demultiplexing the bus is identical to the one used by HC11, shown in Fig. 1.8. The external bus is activated by software, writing 1 to the SRE bit (Static RAM Enable) in the register MCUCR (MCU Control Register). When using slower external memory, there is the possibility of including a WAIT cycle to each access to the external RAM. Writing 1 to the SRW (Static RAM Wait) bit of MCUCR enables this feature. Appendix A.8 shows an example on how to use AT90S8515 with an external bus. 1.7.3 8051 Operating with External Bus The external bus of 8051 is also multiplexed. Port P0 is used for the data bus and the low-order address bus, and port P2 implements the high-order address bus. The strobe signal for demultiplexing the bus is called ALE (Address latch Enable). What is specific for 8051 is the capability to access on the same physical bus two pages of external memory: one for program memory, and the other for data memory. The two types of access are distinguished by means of a special signal, called PSEN\ (Program Store Enable), generated by the MCU, active LOW. When PSEN\ is active, the external logic must select an external ROM memory in order to provide program code to the MCU through the data bus. The access to the external RAM is controlled at the hardware level by the signals RD\ (Read) and WR\ (Write), generated by the microcontroller. An additional signal, called EA\ (External Access), active LOW, disables the internal ROM, and redirects all the accesses to the internal
  28. 1.8 Exercises 15 program memory (in the address range 0000h–0FFFh) to the external bus. Any access to program memory at addresses higher that 1000h are directed to the external bus regardless of the status of the EA\ input. At the software level, accessing the external RAM is done by means of the special instruction MOVX (Move to or from external RAM). Chapter 11 and App. A.12 contain detailed examples of using 8051 with an external bus. 1.8 Exercises SX 1.1 Write a fragment of program to access a constant stored in the program memory of a MCU with the Von Neumann architecture (HC11). Solution Like all Von Neumann computers, HC11 uses a single bus to connect all the resources to the CPU, and has a single address space. Therefore, there is no difference between the ways it accesses constants located in the program memory or variables stored in RAM. The following code fragment does the job: LDAA ROMTAB ROMTAB DB $55 ;This defines $55 as ;a constant located ;in the program memory area After the execution of the instruction LDAA ROMTAB, the contents of the accumulator A are identical to the contents of the memory location having the address ROMTAB ($55 in this case). The following example uses the X register as a pointer to a table of constants, ROMTAB. After the execution of this code, A contains $55, B equals $AA, and X contains the address ROMTAB. LDX #ROMTAB ;set X to point to ROMTAB LDAA 0,X ;read one constant into A LDAB 1,X ;read another constant into B ROMTAB DB $55 ;This defines $55 as a ;constant located in the ;program memory area DB $AA
  29. 16 1 Resources of Microcontrollers SX 1.2 Write a code fragment to access a constant located in the program memory of a microcontroller having the Harvard architecture (AT90S8515 AVR) Solution The AVR microcontrollers use the special instruction LPM to access constants stored in the program memory. LPM copies to R0 the contents of the program memory location with the address specified by the Z register. The problem is that AVR micro- controllers have the program memory organized in 16-bit words and the assembler assigns a word address to any label found in the code section. LPM interprets the contents of the register Z in the following way: the most significant 15 bits of Z represent the address of the 16-bit word, and the least significant bit is the address of the byte within the 16-bit word: LSB(Z) = 0 indicates the least significant byte, and when LSB(Z) = 1 the most significant byte is addressed. LDI ZH,high(ROMTAB<<1) LDI ZL,low(ROMTAB<<1) LPM ;read first byte MOV R1,R0 ;save $34 to R1 ADIW ZL,1 ;increment Z LPM ;read second byte MOV R2,R0 ;save $12 to R2 ROMTAB DW $1234 In the above example, the expression (ROMTAB<<1) means ROMTAB shifted one position to the left, and high(ROMTAB<<1) designates the most significant byte of the 16-bit value (ROMTAB<<1). The first LPM reads in R0 the lower byte of the constant located at the address ROMTAB ($34) and, after incrementing the address, (ADIW ZL,1) the second LPM reads the most significant byte of the constant ($12). SX 1.3 Write a code fragment to access a constant stored in the program memory of an 8051 microcontroller. Solution 8051 uses a special instruction to read ROM constants. This is MOVC (Move Code) and has the following syntax: MOVC A,@A+DPTR
  30. 1.8 Exercises 17 The effect of this instruction is that the accumulator A is loaded with the contents of the program memory location having the address obtained by adding the 16-bit integer in DPTR with the unsigned byte in A. CLR A ;clear accumulator A MOV DPTR,#ROMTAB ;load DPTR with the address ;ROMTAB MOVC A,@A+DPTR ;get constant in A ROMTAB: DB 55h ;define the constant here SX 1.4 Provide an example of interrupt vector initialization for HC11. Solution The HC11 interrupt vector is a 2-byte memory space, which must be initialized with the starting address of the interrupt service routine. For example, the interrupt vector associated with RESET (remember RESET is treated as a non-maskable interrupt) is located at the addresses $FFFE–$FFFF. At RESET, the MCU reads the two bytes from these addresses ($FFFE contains the most significant byte) and loads the resulting 16-bit value into PC. MAIN ;Program entry point at ;RESET ORG $FFFE ;store the value of the ;label MAIN at $FFFE-$FFFF DW MAIN SX 1.5 Provide an example of interrupt vector initialization for AVR. Solution The vector area of the AVR microcontrollers start at the address $0000 in the address space of the program memory. Each interrupt vector occupies a 16-bit word. Unlike HC11, the AVR simply loads the hardwired value of the vector into the PC when an interrupt is acknowledged. Initializing the vector consists in placing in the address of the vector an instruction of an unconditional jump to the interrupt service routine. For
  31. 18 1 Resources of Microcontrollers example, the interrupt vector associated with the analog comparator has the address $000C. The initialization of this vector is shown below: .ORG $000C RJMP ANA_COMP ;unconditional jump to the ;interrupt handler ANA_COMP: RETI
  32. 2 Using the Digital I/O Lines 2.1 In this Chapter This chapter contains an overview of the parallel I/O subsystem of the HC11, AVR, and 8051 microcontrollers, from a hardware and software perspective. 2.2 Overview of the Parallel I/O System The digital I/O lines are the simplest and most common way microcontrollers interact with the outside world. Figure 2.1 shows how digital input and output lines are connected to the internal bus of the MCU. In case of an input line, the status of the MCU pin is transferred on the internal bus to the CPU by activating the internal signal RP (Read Port), generated during the execution of the instruction used to read the port. An output line is associated with an internal latch, which can be written from the internal bus and the driver connected to the physical pin. In practice, things are a bit more complicated. For economic and technological reasons, it is more convenient to assign two or more functions to each pin than to double the number of pins of the capsule. This is the reason why all microcontrollers extensively use bi-directional input/output lines. The simplest way to obtain a bi- directional line is to use an open drain driver for the output line. When the output Internal bus RP Pin D Q Pin Internal bus WP CLK Fig. 2.1. The principle of accessing the input and output lines
  33. 20 2 Using the Digital I/O Lines VCC Internal bus PIN D Q WP C Q RP Fig. 2.2. Bi-directional I/O line with open drain output driver transistor is blocked, an external device can control the line. Figure 2.2 shows the logic diagram of a bi-directional I/O line implemented according to this principle. When the software writes 1 to the latch associated with the output line, the output transistor is blocked, and the line is turned into an input line. This solution is used by the 8051 microcontrollers. Another way to do this is to associate to each bi-directional I/O line an additional latch, called a direction latch, which controls a tri-state output driver. When the direction latch is set to 1 by software, the I/O line is configured as an output line. A simplified logic diagram of an I/O line implemented according to this principle is shown in Fig. 2.3. This method of controlling the direction of the I/O lines is characteristic of the microcontrollers belonging to the HC11 and AVR families. Usually, the I/O lines are grouped into 8-bit ports, which have individual addresses in the memory map. Similarly, the direction control bits are grouped into 8-bit registers, called Data Direction Registers (DDR), associated with each I/O port. Note that the I/O port, along with the associated data direction register, form a structure similar to the general structure of the I/O peripheral interface, shown in Fig. 1.6, where the data register is the port itself, and the control register is the data direction register. Often, the I/O lines have alternate functions in connection with some of the microcontroller’s subsystems. For example, the asynchronous serial interface of the RP PORTx D Q PIN WP C Q D Q DDRx WDDR C Q Internal bus Fig. 2.3. Bi-directional I/O line with direction control
  34. 2.3 Electrical Characteristics of the I/O Lines 21 HC11 uses the lines of port D, and the timer subsystem can use the lines of port A. Normally, the external pins are automatically configured for the alternate function when the respective subsystem is enabled by software, overriding the settings in the data direction register, but this is not an absolute rule. Refer to the data sheet of each microcontroller for details on how a certain peripheral interface shares the MCU pins with the I/O ports. 2.3 Electrical Characteristics of the I/O Lines One simple rule about interfacing a microcontroller is that any output line can safely drive one standard TTL load, and the voltage on any input may swing between the potential of GND and Vdd. In some particular cases, certain output lines can drive up to 20 mA each, but even in these cases, care must be taken that the total power dissipation does not exceed the limit specified by the manufacturer. If the load current or voltage requirements are higher than the capabilities of the microcontroller, the solution is to use adequate buffers between the control circuit and the load. Figure 2.4 shows a possible way to connect a relay to an output line of the 68HC11F1 microcontroller. The relay is driven by the CMOS circuit 40107, able to drain a current up to 100 mA. Note the presence of the pull-down resistor R1, which connects the MCU output to the ground. Its purpose is to maintain the line at the stable potential of ground during RESET. This is required because, at RESET, all the I/O lines of the microcontroller are automatically configured as input lines. In the time interval between RESET and the moment when the I/O line is configured as output, the potential at the input of the 40107 is undetermined, and thus the relay can be unintentionally activated. The value of the pull-down resistor is determined by the fact that it loads the MCU output line, which can supply a maximum current of 8–1 mA. A value of 10 K for this resistor loads the output line with 0.5 mA and provides a safe pull-down for the input of 40107. VCC 7 3 K1 5 1 40107 2 3 1 R1 68HC11 GND Fig. 2.4. Connecting a relay to an output line of a microcontroller
  35. 22 2 Using the Digital I/O Lines Output IC1 Q1 Input R1 2k7 R2 7k2 Q2 R3 3k ULN2803 GND GND Fig. 2.5. ULN 2803 typical Darlington transistor interface for output lines When higher current values are required, Darlington transistors are recommended to connect the load. Figure 2.5 shows the schematic of a Darlington driver, as im- plemented in the circuit ULN2803. This contains an array of eight such Darlington drivers, each being able to sink 500 mA current and to stand 50 V VCE voltage. As far as the input lines are concerned, the most common way of using them is to read the status of contacts (push buttons, relays, etc.). The interface circuits must provide precise logic levels for each possible status of the contact, and to eliminate, as much as possible, the mechanical vibrations of the contact. A typical interface circuit for digital input lines is presented in Fig. 2.6. R1 is a pull-up resistor, intended to maintain a stable logic level high, when the contact is open. Typical values are in the range 4.7 K–10 K. The capacitor C1, and the Schmitt trigger 40106 are destined to eliminate the effect of the vibrations of the contact, and to create clean edges for the electrical signal applied to the MCU port. Often, it is required that the MCU ground be separated from the ground of the input circuits. In this case, it is recommended that the input lines are optically isolated, using circuits similar to that presented in Fig. 2.7. In this circuit, the resistor R1 limits the current through the LED of the optocoupler OK1. When K1 is closed, the transistor of the optocoupler saturates, providing a logic level zero at the input line of the microcontroller. The role of R3 is to drain the charge accumulated in the parasite capacitance of the junction BE of the transistor, thus improving the rising edge of the signal in the collector. Typical values for R3 are in the range 330 K–470 K. VCC1 VCC2 R1 R2 OK1 VCC MCU pin 5 1 K1 40106D R1 MCU pin 2 1 Input line 4 2 C1 K1 6 4N33 R3 GND GND GND1 GND1 GND2 Fig. 2.6. Typical input circuit for reading relay contacts, push buttons, etc. Fig. 2.7. Optically isolated input line
  36. 2.4 Controlling the I/O Lines by Software 23 2.4 Controlling the I/O Lines by Software The HC11 microcontrollers treat the I/O ports and the associated direction registers as memory locations. The software initialization of I/O lines consists in writing to the data direction register a byte having 1 in the positions corresponding to the output lines, like in this example: INIT_PORTD LDAA #$30 ;configure PORTD, bit 4,5 as STAA DDRD ;output For HC11, the software can read a port configured as output. In this situation, the last value written to the port is read. Data written to an input port is not visible to the MCU pins until the port is reconfigured as an output port. The 8051 microcontrollers have two major features, as far as the I/O ports are concerned: there are no direction registers, and the ports are bit-addressable. All output pins of 8051 have open drain drivers, as shown in Fig. 2.2, and writing a 1 to the port configures the corresponding line as input. Special instructions for bit manipulation allow code sequences like this: MOV C,P1.2 ;Move P1 bit2 to carry MOV P1.3,C ;move carry bit to P1 bit 3 CLR P2.1 ;clear P2 bit 1 SETB P1.0 ;set bit 0 in P1 JB P3.3,LABEL ;Jump to LABEL if P3 bit 3 is set The I/O subsystem of the AVR microcontrollers have some interesting distinctive features (refer to Fig. 2.8). First, note the presence of two data registers, having distinct addresses, associated with each port: one, called PINx, is used when the port is configured as input, and the other, called PORTx, is used when the port is configured as output. VCC Pull-up READPIN READPORT D Q PIN WP C Q D Q DDR WDDR C Q Internal bus Fig. 2.8. Distinctive Features of the I/O lines of the AVR
  37. 24 2 Using the Digital I/O Lines Writing to PORTx when DDRx = 0 (i.e. when the port is configured as input) connects internal pull-up resistors to the input lines corresponding to the bits in PORTx set to 1. The actual status of the input lines is obtained by reading from the address PINx. Reading from the address PORTx, when the port is configured as output, returns the last value written to the port. Special instructions have been provided to allow software access to the I/O ports or to the individual bits thereof. These are: IN Rd,ioport ;read from the address ioport to ;register Rd OUT ioport,Rs ;write data from Rs to ioport SBI ioport,bit ;set specified bit to ioport CBI ioport,bit ;clear specified bit to ioport The following program fragment illustrates aspects of the configuration and access to PORTB: LDI R16, $F0 ;configure upper nibble of PORTB ;as output OUT DDRB,R16 LDI R16,$0F OUT PORTB,R16 ;enable internal pull-ups on ;lower nibble and write 0 in the ;upper nibble IN R0,PINB ;read the input lines 2.5 Exercises SX 2.1 Assuming that the peripheral interfaces that share the lines of PORTD of HC11 are disabled, specify the content of accumulator A after the execution of the following code fragment: LDAA #$38 STAA DDRD LDAA #$30 STAA PORTD LDAA PORTD
  38. 2.5 Exercises 25 Solution Bits 7 and 6 of PORTD of HC11 are not implemented, and always read 0. By writing $38 = 00111000b to DDRD, bits 5, 4, 3 of PORTD are configured as output lines. Only these three bits are affected by subsequent write operations to PORTD. Read operations from an output port return the last value written to the port. For this reason, the content of A after the final read from PORTD in the above example is 00110xxxb. The least significant three bits are input lines, and their status is determined by the logic levels on the external pins of the MCU. SX 2.2 Write a code fragment to configure the upper nibble of PORTC of AT90S8535 as output, and the lower nibble as input, with the internal pull-up resistors enabled, then read the values of PINC0-3 and write them to PORTC4-7. Solution LDI R16,$F0 ;configure port OUT DDRC,R16 LDI R16,$0F ;enable pull-ups OUT PORTC,R16 IN R16,PINC ;read input lines SWAP R16 ;swap nibbles SBR R16,$0F ;keep pull-ups active OUT PORTC,R16 ;write to port SX 2.3 Write a code fragment that configures the line P2.0 of a 8051 as input, then reads the status of this line, and writes the value read to P2.7. Solution SETB P2.0 ;P2.0 configured as input MOV C,P2.0 ;read input line to carry MOV P2.7,C ;write carry to the output line
  39. osdrteeapei i.31 hr w hf eitr r once nsuch in connected are registers shift two where register. 3.1, shift the Fig. is in device communication example handled serial simplest is the The data Consider bit. that by is bit system e. communication i. series, serial in a of feature distinctive main The Communication Asynchronous vs. Synchronous 3.2 creating of principles the and well networks. interfaces, as microcontroller RS422/485 simple 8051, and RS232 and the AVR, of HC11, overview an of of as description interface the communication contains serial It communication. asynchronous serial the to introduction an is chapter This Chapter this In 3.1 Interface Serial Asynchronous the Using 3 seFg n rnmte ln ihdt ntecmuiainln.Such line. communication communication the the time to on sent of called is data moments is clock line, with transmission precise the along at where system, level, transmitted communication transmitter a and the 3.2.) at Fig. generated (see be must RSTR and the called first, the the of called content the that way a oeta,i hscs,tesitcokCK n h oto inl SH/LD signals control the and CLK, clock shift the case, this in that, Note receiver i.3.1. Fig. ycrnu communication synchronous . SH/LD\ RSTR CLK GND D7 D4 D6 D5 D0 D3 D2 D1 xml fsnhoossra omncto circuit communication serial synchronous of Example IC1 10 11 SER 9 12 A QH 13 B 14 C 3 D E 4 Serial data 5 F 6 G H 2 15 CLK GND 1 INH SH\LD/ . 74HC165 transmitter IC2 4 STR 1 5 Q1 2 6 Q2 D 3 7 Q3 CLK 15 Q4 OE 14 Q5 13 Q6 VCC 12 second, the to transferred is , 11 Q7 Q8 RD0 RD1 RD2 RD3 RD4 RD5 RD6 RD7 4094N \
  40. 28 3 Using the Asynchronous Serial Interface SH/LD\ CLK RSTR Fig. 3.2. Waveforms of the control signals for the circuit presented in Fig. 3.1 The problem becomes more complicated when it is not possible to send the serial clock over the communication line. In this situation, the receiver must generate its own clock, RxCLK, to shift data into the Rx shift register. This type of serial communication, where the serial clock is not transmitted on the communication line, is called asynchronous communication. The generic block diagram of an asynchronous communication system is shown in Fig. 3.3. To make this possible, the first requirement is that the transmitter and the receiver clock have exactly the same frequency. A limited number of possible frequencies have been standardized for asynchronous communication. These are: 110, 300, 600, 1200, 2400, 4800, 9600, 19 200, 57 600, 115 200 Hz. Since the frequency of the transmission clock is directly related to the commu- nication speed, so that with each clock pulse a bit of information is transmitted, the communication speed is measured in bits per second or baud. The period of the transmission clock is called the bit time Tb. The second requirement is to mark somehow the beginning of the transmission of a sequence of bits. For this purpose, a special synchronization bit, called the start bit, has been inserted. This has the polarity opposed to the idle line status and its duration equals one TxCLK period. The moment when the transmission ends is known, because the number of bits in each packet is known. In most cases, data is sent in 8-bit packets. To make sure the communication line returns to its idle status after each data packet is transmitted, an Data Data Tx Shift register Serial Rx Shift register line TxCLK RxCLK Transmiter Receiver Fig. 3.3. Block diagram of an asynchronous communication system Start 1 0001100Stop Tb/2 Tb Tb Tb Tb Tb Tb Tb Tb Tb Fig. 3.4. Sampling data line in an asynchronous serial communication
  41. 3.3 Error Detection in Asynchronous Communication 29 additional stop bit is transmitted. This always has the status of the idle line. Figure 3.4. shows how the data line is sampled at the receiver. The falling edge of the data line, corresponding to the start bit, starts the reception process. The data line is sampled after half of the bit time interval to check for a valid start bit, and then at intervals equal to Tb. The values of the data line at these moments are shifted into the receiver data shift register Rx. Important notes. The first bit transmitted in an asynchronous serial communi- cation is the least significant bit (LSB). The idle line status is HIGH. The start bit always has the opposite polarity of the idle line, i. e. it is always 0. The stop bit always has the polarity of the idle line, i. e. it is always 1. 3.3 Error Detection in Asynchronous Communication One serious problem when handling asynchronous serial communication is the vul- nerability to electromagnetic interference. Several means have been provided to de- tect communication errors, and the status register of an asynchronous serial interface normally contains special status bits to indicate these errors. If, for instance, when sampling the data line at the moment T0 + Tb/2 (refer to Fig. 3.4), a value of 1 is obtained, that means the falling edge detected at the moment T0 was not a valid start bit, but a spike due to electromagnetic noise. This type of error is called noise error. Similarly, if the data line status at the moment T1 = T0 + Tb/2 + 9 ì Tbis not HIGH, this means that the expected stop bit is invalid, indicating that the byte received is in error. This type of error is called framing error. Obviously, these two control methods are insufficient to detect all possible errors. Another method to verify the integrity of data is parity control. For this purpose, a special bit, called the parity bit, is transmitted just before the stop bit. This is either the most significant bit of each byte, or an additional ninth bit attached to each byte. The values of the parity bits are automatically set so that the total number of 1s contained in the byte, plus the parity bit, is always an ODD or EVEN number, at the user’s choice. Both the transmitter and receiver must calculate the parity according to the same rule (ODD or EVEN). Upon reception of each byte, the parity is calculated, and, if the parity does not match the rule, the error is reported. Parity control still cannot detect all errors, but, at the hardware level, the methods described above are all that can be done for error detection. For better error detection, software techniques must be used. Basically, software detection of communication errors relies on the following principles:
  42. 30 3 Using the Asynchronous Serial Interface • The communication is based on data packets, having a determined structure. • Each data packet contains a special field reserved for a sophisticated checksum. The transmitter computes the checksum for each packet and inserts it into the reserved field of the packet. • The receiver recalculates the checksum of the packet and compares it with the value calculated by the transmitter and sent along with the packet. If the two values don’t match the packet is rejected, and the transmitter is requested to repeat the transmission of the packet. This method is called Cyclic Redundancy Check Control (CRC). The algorithms used to compute the checksums are so complex that the probability that a packet with errors still has a correct checksum is extremely low. 3.4 The General Structure of the Asynchronous Serial Communication Interface The general block diagram of an asynchronous serial interface is presented in Fig. 3.5. This circuit is called a Universal Asynchronous Receiver Transmitter (UART). There are numerous stand-alone integrated circuits with this function, but most microcon- trollers include a simplified version of UART, with the generic name Serial Commu- nication Interface (SCI). This chapter contains details on the implementation of the SCI of HC11, AVR and 8051 microcontrollers. Even though there are differences in what concerns the names of the registers associated with the interface, or the names and particular functions of the control and status bits, the general structure of the interface is basically the same in all microcontrollers. CLK BAUD rate generator TxDTx shift register Rx shift register RxD Control logic Control Tx Data Rx Data Status Internal bus Fig. 3.5. General block diagram of the asynchronous serial communication interface 3.5 The Serial Communication Interface of 68HC11F1 SCDR – SCI Data Register The transmitter’s and receiver’s data registers have the same address and the same name: Serial Communication Data Register (SCDR). Physically, they are distinct registers, but the write operations to SCDR are directed to the transmitter’s data
  43. 3.5 The Serial Communication Interface of 68HC11F1 31 register, while the read operations from SCDR return the content of the receiver’s data register. BAUD – Baud Rate Generator Control Register To select the communication speed, a special register, called BAUD, has been pro- vided. This controls how the system clock E is divided in the baud rate generator block, before it is applied to the control logic that actually generates the clock for the serial shift registers. The system clock is first applied to a programmable counter, called a prescaler. The prescaler output is then applied to a second programmable counter. After the two division stages the frequency of the resulting clock is 16 times the actual baud rate. The BAUD register has the following structure: BAUD 7654 3 210 TCLR – SCP1 SCP0 RCKB SCR2 SCR1 SCR0 RESET0000 0 000 • TCLR – Clear Baud Rate Counters – and RCKB – SCI Baud Rate Clock Check, are only used in special test operating mode. • SCP[1:0] – SCI Baud Rate Prescaller Selects. These two bits control the prescaler division rate, as defined in Table 3.1. • SCR[2:0] – SCI Baud Rate Selects. These bits control the second stage pro- grammable counter of the baud generator, as shown in Table 3.2 Table 3.1. HC11 prescaler control bits SCP1 SCP0 Prescaller divide internal clock by: 00 1 01 3 10 4 11 13 Table 3.2. HC11 baud rate select bits SCR2 SCR1 SCR0 Prescaller output is divided by: 000 1 001 2 010 4 011 8 100 16 101 32 110 64 1 1 1 128
  44. 32 3 Using the Asynchronous Serial Interface Example Knowing that the oscillator frequency is 8 MHz, and that the output fre- quency of the baud generator must be 16 times the actual baud rate, determine the value to write in the BAUD register in order to obtain 9600 baud communication speed. Solution The input clock for the prescaler is the system clock E. fE = fOSC/4 = 2MHz= 2 000 000 Hz The output clock must have the frequency: f1 = 9600 ì 16 = 153 600 Hz This gives the global division rate: 2 000 000/153 600 = 13. Choose the prescaler to divide by 13 (SCP1:SCP0 = 1:1), and the secondary counter to divide by 1 (SCR2:SCR1:SCR0 = 0:0:0). The resulting value for the BAUD register is 00110000b = 30H. Note that for a given oscillator frequency, not all the possible baud rates can be obtained by programming the BAUD register. With an 8-MHz oscillator clock it is impossible to obtain the baud rate of 19 200 bps, because the resulting global division rate is 6.5 (obviously, the divi- sion constant must be as close as possible to an integer value). The solution in this situation is to choose a different oscillator frequency. If, for example, the oscillator frequency is 7.3728 MHz, the global division rate required for 19 200 baud is 6, which can be easily obtained by choosing the prescaler to divide by 3, and the secondary counter to divide by 2. SCSR – SCI Status Register SCSR 7 6 543210 TDRE TC RDRF IDLE OR NF FE – RESET0 0 000000 • TDRE – Transmitter Data Register Empty This bit is automatically set when the transmitter’s data register is available for a write operation. 0 = SCDR busy 1 = SCDR ready for a new operation • TC – Transmit Complete flag The meaning of this bit is very similar to TDRE. The difference is that TC refers to any activity of the transmitter, including sending of break sequences on the serial line. 0 = Transmitter busy 1 = Transmitter ready
  45. 3.5 The Serial Communication Interface of 68HC11F1 33 • RDRF – Receive Data Register Full Flag 0 = SCDR empty 1 = SCDR full This flag indicates that a character has been received in SCDR and it is ready to be handled by software. RDRF is cleared by reading SCSR followed by a read of SCDR. • IDLE – Rx Idle Line Detected Flag 0 = RxD line is active 1 = RxD line is idle IDLE describes the status of the RxD line. It is set to 1 when RxD stays high for at least one character time. IDLE is cleared by reading SCSR then reading SCDR. Once cleared, it is not set again until the line becomes active, and then idles again. • OR – Overrun Error Flag 0 = No overrun 1 = Overrun detected This is an error flag. An overrun error occurs when all the bits of a new character are received, and the previous character has not been handled by the software (RDRF = 1). • NF – Noise Error Flag One of the situations when this error flag is set has been described in Sect. 3.3. In fact, the reception data line is sampled several times during each Tb interval. NF is set when the samples corresponding to the same interval Tb have different values. 0 = character received without noise 1 = noise detected for the last character received • FE – Framing Error FE is set when a logic zero is detected in the position of the stop bit. 0 = Stop bit detected in the right position 1 = Zero detected instead of a stop bit All error bits are cleared by reading SCSR followed by a read from SCDR. SCCR1 – Serial Communications Control Register 1 This is the first of the two control registers of the interface. Only four bits are implemented in this register as follows: SCCR1 7654 3 210 R8 T8 – M WAKE – – – RESET1100 0 000
  46. 34 3 Using the Asynchronous Serial Interface The bits R8, T8, and M control the number of bits of the character transmitted/received over the interface. If the MODE bit M = 0, 8-bit characters are transmitted along with the corresponding start and stop bits. If M = 1, 9 data bits are transmitted for each character. The least significant 8 bits are placed in SCDR, and the most significant bit is T8 in case of a transmission operation and R8 in case of reception. The control bit WAKE is related to an operating mode of the interface, which is specific to HC11, and will not be discussed in this book. SCCR2 – Serial Communications Control Register 2 This register contains the main control bits of the interface SCCR2 76543210 TIE TCIE RIE ILIE TE RE RWU SBK RESET11000000 The most important control bits in this register are TE (Transmitter Enable) and RE (Receiver Enable). When TE = 1, the whole transmitter subsystem is enabled. Similarly RE = 1 enables the receiver subsystem. These bits are cleared at RESET, therefore they must be set by software in the SCI initialization sequence. The most significant four bits of this register, TIE, TCIE, RIE, ILIE, are local interrupt masks for SCI-related interrupts. • TIE – Transmitter interrupt enable 0 = TDRE interrupts disabled 1 = An interrupt request is generated when TDRE = 1. • TCIE – Transmit Complete Interrupt Enable 0 = TC interrupts disabled 1 = SCI interrupt requested when TC status flag is set • RIE – Receiver Interrupt Enable 0 = RDRF and OR interrupts disabled 1 = SCI interrupt requested when RDRF (receiver data register full) flag or the OR (overrun error) bit in SCSR is set • ILIE – Idle-Line Interrupt Enable 0 = IDLE interrupts disabled 1 = SCI interrupt requested when IDLE status flag is set This bit is used in connection with the wake-up operating mode. • RWU – Receiver Wakeup Control 0 = Normal SCI receiver 1 = Wakeup enabled and receiver interrupts inhibited
  47. 3.6 The Asynchronous Serial Communication Interface of AVR Microcontrollers 35 • SBK – Send Break 0 = Break generator off 1 = Break codes generated Writing 1 to this bit of SCCR2 causes a break character to be generated, i. e. the TxD line is pulled to zero for at least one character time. 3.6 The Asynchronous Serial Communication Interface of AVR Microcontrollers The information in this paragraph refers to the microcontroller Atmel AT90S8535. Other members of the AVR family may have different structures of the asynchronous serial interfaces. See the data sheet for each specific microcontroller, for other models. The data registers of the transmitter and receiver share the same address, just like in case of the HC11 microcontrollers. The two physical registers are accessible for the software as a single register, called UDR (UART Data Register). UDR is entirely similar to SCDR of HC11. The equivalent of the BAUD register of HC11 is called UBRR (UART Baud Rate Register), for the AVR. The difference is that it is easier to use and much more flexible than the HC11 register. The clock frequency of the output signal of the baud rate generator is 16 times the actual baud rate, and is determined using the following formula: 16 ì BaudRate = Fosc/(UBRR + 1) (3.1) where UBRR is the contents of UBRR, as written by software. The status register of the interface is called the USR (UART Status Register) and has the following structure: USR 76 5 43210 RXC TXC UDRE FE OR – – – RESET00 1 00000 Here is the description of the status bits in USR: • RXC – Reception Complete. This bit has a similar function to RDRF of the HC11. It is automatically set by hardware when a character is available in UDR. It is cleared by reading UDR, or when the associated interrupt is executed. • TXC – Transmission Complete. This bit is set by hardware when the transmission of a character completes. It has a similar function to the TC flag of HC11. TXC is automatically cleared when the associated interrupt is executed or by writing 1 to the corresponding position of USR. This is the only Read/Write bit of USR. All other bits are Read Only. • UDRE – USART Data Register Empty. This is the equivalent of the TDRE status bit of HC11, and indicates that the transmitter is ready to accept a new character.
  48. 36 3 Using the Asynchronous Serial Interface • OR – Overrun, and FE – Framing Error, have exactly the same meaning as in HC11 SCSR. Unlike HC11, these bits are cleared only when a new character has been received and read correctly. The control register of the interface UCR (UART Control Register) has the following structure: UCR 76543210 RXCIE TXCIE UDRIE RXEN TXEN CHR9 RXB8 TXB8 RESET 0 0 0 0 0 0 0 0 • RXCIE, TXCIE, and UDRIE are local interrupt masks associated with the flags RXC, TXC, and UDRE, respectively. When a mask is set to 1 by software, the associated flag generates an interrupt when set to 1. • TXE and RXE have identical functions with TE and RE of HC11. When TXE = 1 the transmitter is enabled, and RXE = 1 enables the receiver. • CHR9 – this bit is similar to M from HC11. CHR9 = 1 indicates 9-bit transmis- sion. In this case, RX8 and TX8 are the most significant bits of the transmit- ted/received characters. 3.7 The Asynchronous Serial Interface of 8051 The 8051 serial communication interface is less typical than those presented in the previous paragraphs. The first significant difference is that the baud rate generator is missing. It is replaced by one of the system timers. The interface data register is called SBUF, and it is similar to the data register of HC11 and AVR. The control register of the interface, SCON, also contains several status bits. It has the following structure: SCON 7 6543210 FE/SM0 SM1 SM2 REN TB8 RB8 TI RI RESET0 0000000 The bits SM[0:1] (Serial communication Mode control) select one of the four possible operating modes for the serial interface, as shown in Table 3.3. Table 3.3. 8051 serial communication mode select bits SM0 SM1 MODE Description Baud rate 0 0 0 Shift register fosc/12 0 1 1 8-bit UART Variable (set by timer) 1 0 2 9-bit UART fosc/32 or fosc/64 1 1 3 9-bit UART Variable (set by timer)
  49. 3.8 Programming the Asynchronous Serial Interface 37 In the operating mode 0, the interface acts like a serial shift register. The serial shift clock has a fixed frequency, equal to fosc/12. Eight data bits are transmitted, starting with the least significant bit (LSB). In mode 1, 10 bits are shifted from (to) SBUF: one start bit, eight data bits (LSB first) and one stop bit. The communication speed is variable and programmable using the system timer. In operating modes 2 and 3, nine data bits are sent, packed by a start bit and a stop bit. The communication speed is fixed in mode 3 and variable in mode 3. Modes 2 and 3 are designed for multiprocessor communication. This operating mode is specific for 8051, and will not be discussed in this book. For normal operating modes 0, 1, the SM2 bit must be cleared. The most significant bit of SCON, FE/SM0, has a dual function. The selection between the two functions is made by the bit SMOD0, in the register PCON (Power Control Register). If SMOD0 = 1, then bit 7 (SCON) = FE, and if SMOD0 = 0, then bit 7 (SCON) = SM0. FE (Framing Error) is set if a zero is detected in the position of the stop bit while receiving a character, and cleared by writing zero to the corresponding position of SCON. The control bit REN (Receiver Enable) is used to enable (REN = 1) or disable (REN = 0) the receiver. There is no similar bit to enable/disable the transmitter. TB8 – RB8 contain the ninth data bit (the most significant bit, MSB) in operating modes 2 and 3. TI (Transmit Interrupt flag) is set by hardware at the end of the transmission of a character. If the interrupt associated with the serial interface is enabled, the condition TI = 1 generates an interrupt. TI must be cleared by software by writing zero to this position of SCON. RI (Receive Interrupt flag) is hardware set when a character has been received and is available in SBUF. If the local interrupt mask is set to 1, an interrupt is generated. RI must be cleared by writing zero to this position of SCON. If the interrupts are disabled, TI and RI can be polled by software. As described in Chap. 1, the interrupt system of 8051 is controlled by the IE reg- ister. For the serial communication interface, one single bit, called ES, is reserved in this register. Therefore it is not possible to enable/disable the receiver and transmitter interrupts separately. To get the full picture on the serial communication of 8051, refer to Chap. 6 for an example on how to use the system timer as a baud rate generator. 3.8 Programming the Asynchronous Serial Interface When programming any peripheral interface there are two major aspects to con- sider: the initialization of the interface, and the actual data handling. Normally, the initialization sequence is executed only once, after RESET. Data handling can be performed either by periodically testing the status bits of the interface (polling), or by enabling the interrupts associated with the interface. This paragraph contains several examples of initialization sequences and serial communication data handling for HC11 and AVR.
  50. 38 3 Using the Asynchronous Serial Interface 3.8.1 Programming the SCI of HC11 The initialization sequence must do the following: • Enable the transmitter and the receiver. • Select the communication speed, by writing an appropriate value to the BAUD register. • Enable interrupts, if this is required. Here is an example on how to initialize the SCI of 68HC11F1 for 9600 baud, no interrupts. In this example it is assumed that the oscillator frequency is 8 MHz. INIT_SCI LDAA #$30 ;see paragraph 3.5. STAA BAUD ;9600 baud CLR SCCR1 ;clear M for 8 bit ;communication LDAA #$0C ;TE=1, RE=1 STAA SCCR2 ;no interrupts And the reception and transmission routines may look like this: SCI_REC LDAA SCSR ;read status register ANDA #$20 ;isolate RDRF bit BEQ SCI_REC ;wait until RDRF is set LDAA SCDR ;get received character STAA SOMEWHERE ;and save it RTS SCI_SEND TAB ;save character to B SSLOOP LDAA SCSR ;read status register ANDA #$80 ;isolate TDRE BEQ SSLOOP ;wait until transmitter ;ready STAB SCDR ;send character RTS ;and return This way of writing the SCI_REC routine is a very bad idea. It is always recom- mended be avoided wait loops, that when the duration of the loop is unknown. In the above example, the processor spends most of the time waiting for a character from the SCI. A much better solution would be to write the reception routine like this: SCI_REC2 LDAA SCSR ;read status register ANDA #$20 ;isolate RDRF bit BEQ FRET ;failure return LDAA SCDR ;get received character STAA SOMEWHERE ;and save it SEC ;Set Carry to inform RTS ;the main program FRET CLC ;Clear carry RTS
  51. 3.8 Programming the Asynchronous Serial Interface 39 This time, the processor doesn’t wait indefinitely for a character. It tests from the beginning whether a character is available in SCDR, by checking the RDRF flag. If a character has been received, this is read and saved in a variable, and the carry flag is set to inform the main program about the event. If no character has been received, the carry bit is cleared. Such a reception routine must be called periodically in a program loop, but it has the advantage that the CPU does not hang up until a character is received. An even better solution would be to use SCI reception interrupts to handle the reception of characters. For this purpose, the initialization routine must be modified to enable the interrupts generated by RDRF. INIT_SCI LDAA #$30 ;see paragraph 3.5 STAA BAUD ;9600 baud CLR SCCR1 ;clear M for 8 bit ;communication LDAA SCSR ;clear flags if any LDAA SCDR CLR QSCI CLR QSCIERR LDAA #$2C ;RIE=1, TE=1, RE=1 STAA SCCR2 ;enable receiver ;interrupts The control word written into SCCR2 contains the RIE bit set to 1, thus enabling the reception interrupts. Note that, before enabling the interrupts, SCSR and SCDR are read in this sequence in order to clear any flag that might generate a false interrupt. QSCI and QSCIERR are two variables indicating that a character has been received, or that a communication error has been detected. The interrupt service routine looks like this: SCI_ISR LDAA SCSR ANDA #$0E ;Isolate all error flags BNE SCIERR ;if error, inform the ;main program LDAA SCDR ;get character STAA SCIRB ;save it in a buffer INC QSCI ;true QSCI RTI ;return from interrupt SCIERR LDAA SCDR ;read SCDR to clear flags STAA SCIRB INC QSCI ;true QSCI INC QSCIERR ;true error flag RTI Note that when a reception error occurs, it is important to read the character received to make sure that the flag that has generated the interrupt is cleared. It is seldom required to analyze what error occurred, because in most cases, the only thing to do is to ask for the character to be retransmitted.
  52. 40 3 Using the Asynchronous Serial Interface Important note. The SCI of HC11 uses two lines of PORTD to implement the transmission and reception lines TxD, RxD. By enabling the SCI transmitter and receiver, the TxD line is automatically configured as an output line, and RxD is configured as an input line, regardless of the contents of DDRD. 3.8.2 Programming the UART of AT90S8535 Here is an example of initializing the UART of AT90S8535 for 19 200 baud, 8 bits per character, no interrupts: .EQU K19200=25 ;xtal=8MHz ;BaudRate=19200 Init_Uart: Ldi R16,K19200 ; set baud rate Out UBRR,R16 Ldi R16,$18 ;RXEN=1, TXEN=1 Out UCR,R16 Ret To enable reception interrupts, the control word written to UCR must be modified so that the bit RXCIE = 1 (Reception Complete Interrupt Enable). .EQU K19200=25 ;xtal=8MHz ;BaudRate=19200 Init_Uart: Ldi R16,K19200 ; set baud rate Out UBRR,R16 Ldi R16,$98 ;RXEN=1, TXEN=1 Out UCR,R16 ;RXCIE=1 Ret Unlike HC11, AVR microcontrollers clear the interrupt flag automatically by hardware, when the interrupt is executed. The CPU status is NOT saved and restored automatically, and therefore the CPU registers used by the interrupt routine must be saved to the stack by software. Here is an example of a simple interrupt service routine for AVR: Uart_ISR: Push R16 ;save CPU status In R16,SREG Push R16 In R16,UDR ;get character Sts RECBUF,R16 ;save it Ldi R16,$FF Sts QUART,R16 ;true QUART Pop R16 ;restore status
  53. 3.8 Programming the Asynchronous Serial Interface 41 Out SREG,R16 Pop R16 Reti ;return to main QUART is a software flag that, when true, informs the main program that a character is available. RECBUF is a one-character buffer to store the character received from the UART. 3.8.3 Programming the UART of 8051 The 8051 asynchronous serial interface does not include a dedicated baud rate gen- erator. It uses the internal timer to generate the serial clock. Refer to Chap. 6 to understand how the timer is used in the following initialization routine. The control word written to SCON selects the operating mode 1 for the serial interface, and sets the bit REN = 1 to enable the receiver subsystem. INIT_UART: MOV SCON,#50H ;UART mode 1, REN=1 MOV PCON,#80H ;SMOD=1 MOV TMOD,#20H ;C/T=0, M1=1, M0=0 MOV TH1,#0FAH ;auto reload value MOV TCON,#40H ;TR1=1 start counting RET Serial interface interrupts can be enabled by setting the bit ES in the register IE. Below is an example of serial reception and transmission routines, which use RI and TI polling rather than interrupts: GETCHR: CLR C JB RI,GETCHR1 ;if character received RET GETCHR1: MOV A,SBUF ;get it CLR RI ;always clear flag! SETB C ;inform main program RET SENDCHR: CLR C JB TI,SENDCHR1 ;check if transmitter ;ready RET SENDCHR1: CLR TI MOV SBUF,A ;start sending SETB C ;set carry to inform main ;program RET
  54. 42 3 Using the Asynchronous Serial Interface 3.9 Hardware Interfaces for Serial Communication The asynchronous serial interface has been created to allow connection between digital devices over relatively long distances. The problem is that, as the distance in- creases, the effect of parasite capacitance and inductance of the cables becomes more important, and the electromagnetic interference grows stronger. As a consequence, the signals transmitted in this way are distorted and attenuated to such an extent that the information carried by the signals cannot be extracted at the receiver. To overcome the perturbing effect of long connection cables, several methods of processing the electrical signals have been developed. Before transmission, the signals are transformed by special interfaces, in order to increase their overall immunity to perturbations. This section describes three such interfaces. 3.9.1 The RS232 Interface RS is an abbreviation for Recommended Standard. The recommendation comes from the Electronics Industry Association (EIA), which proposed in 1969 the RS232 standard, aiming to bring order in the multitude of technical solutions to the problems of serial communication. The main characteristic of RS232 is that the signals are carried as single voltages, referred to a common ground. The voltage levels associated with the logic levels 0 and 1 are as follows: For logic 0, the voltage on the communication line must be in the range +6Vto +15 V. For logic 1, the voltage must be in the range −6Vto−15 V. In practice, the transmission devices generate ±12 V. The receiving devices accept as logic 0 any signal ranging from +3Vto+15 V, and as logic 1 any signal with the amplitude in the range −3Vto−15 V. A number of special RS232 interface circuits have been developed. One very popular circuit with this function is MAX232, from Maxim Semiconductors. This contains two RS232 transmitters and two RS232 receivers in the same package. The major advantage of this circuit is that it uses an internal oscillator and four external capacitors to generate the ±12 V power supply sources, starting from a single +5V C1 VCC C4 22u C1+ 1 2 V+ 22u C1- 3 6 V- C2 4 C3 22u C2+ 22u GND C2- 5 11 TxD Tx 232 14 T1OUT T1IN 7 10 Rx 232 T2OUT T2IN RxD 13 R1IN R1OUT 12 8 R2IN R2OUT 9 MAX232 Fig. 3.6. A typical RS232 interface circuit MAX232