EMBEDDED SYSTEMS AN INTRODUCTION USING THE RENESAS RX62N MICROCONTROLLER
James M. Conrad University of North Carolina at Charlotte
Alexander G. Dean North Carolina State University Micrim Press 1290 Weston Road, Suite 306 Weston, FL 33326 USA www.micrium.com
Designations used by companies to distinguish their products are often claimed as trademarks. In all instances where Micri m Press is aware of a trademark claim, the product name appears in initial capital letters, in all capital letters, or in accordance with the vendor’s capitalization preference. Readers should contact the appropriate companies for more complete information on trademarks and trademark registrations. All trademarks and registered trademarks in this book are the property of their respective holders.
Copyright © 2011 by James M. Conrad and Alexander G. Dean except where noted otherwise. Published by Micrim Press. All rights reserved. Printed in the United States of America. No part of this publication may be reproduced or dis- tributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher; with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication.
The programs and code examples in this book are presented for instructional value. The programs and examples have been carefully tested, but are not guaranteed to any particular purpose. The publisher and content contributors do not offer any warranties and does not guarantee the accuracy, adequacy, or completeness of any information herein and is not responsible for any errors or omissions. The publisher and content contributors assume no liability for damages resulting from the use of the information in this book or for any infringement of the intellectual property rights of third parties that would result from the use of this information.
Library of Congress subject headings:
1. Embedded computer systems 2. Real- time data processing 3. Computer software—Development
For bulk orders, please contact Micrium Press at: ϩ1 954 217 2036
ISBN: 978-1-935772-99-6 NOTICE 1. All information included in this document is current as of the date this document is issued. Such information, however, is subject to change without any prior notice. Before purchasing or using any Renesas Electronics products listed herein, please confirm the latest product information with a Renesas Electronics sales office. Also, please pay regular and careful attention to additional and different information to be disclosed by Renesas Electronics such as that disclosed through our website. 2. Renesas Electronics does not assume any liability for infringement of patents, copyrights, or other intellectual property rights of third parties by or aris- ing from the use of Renesas Electronics products or technical information described in this document. No license, express, implied or otherwise, is granted hereby under any patents, copyrights, or other intellectual property rights of Renesas Electronics or others. 3. You should not alter, modify, copy, or otherwise misappropriate any Renesas Electronics product, whether in whole or in part. 4. Descriptions of circuits, software and other related information in this document are provided only to illustrate the operation of semiconductor products and application examples. You are fully responsible for the incorporation of these circuits, software, and information in the design of your equipment. Renesas Electronics assumes no responsibility for any losses incurred by you or third parties arising from the use of these circuits, software, or information. 5. When exporting the products or technology described in this document, you should comply with the applicable export control laws and regulations and follow the procedures required by such laws and regulations. You should not use Renesas Electronics products or the technology described in this doc- ument for any purpose relating to military applications or use by the military, including but not limited to the development of weapons of mass de- struction. Renesas Electronics products and technology may not be used for or incorporated into any products or systems whose manufacture, use, or sale is prohibited under any applicable domestic or foreign laws or regulations. 6. Renesas Electronics has used reasonable care in preparing the information included in this document, but Renesas Electronics does not warrant that such information is error free. Renesas Electronics assumes no liability whatsoever for any damages incurred by you resulting from errors in or omis- sions from the information included herein. 7. Renesas Electronics products are classified according to the following three quality grades: “Standard”, “High Quality”, and “Specific”. The recom- mended applications for each Renesas Electronics product depends on the product's quality grade, as indicated below. You must check the quality grade of each Renesas Electronics product before using it in a particular application. You may not use any Renesas Electronics product for any application categorized as “Specific” without the prior written consent of Renesas Electronics. Further, you may not use any Renesas Electronics product for any application for which it is not intended without the prior written consent of Renesas Electronics. Renesas Electronics shall not be in any way liable for any damages or losses incurred by you or third parties arising from the use of any Renesas Electronics product for an application categorized as “Spe- cific” or for which the product is not intended where you have failed to obtain the prior written consent of Renesas Electronics. The quality grade of each Renesas Electronics product is “Standard” unless otherwise expressly specified in a Renesas Electronics data sheets or data books, etc. “Standard”: Computers; office equipment; communications equipment; test and measurement equipment; audio and visual equipment; home electronic appliances; machine tools; personal electronic equipment; and industrial robots. “High Quality”: Transportation equipment (automobiles, trains, ships, etc.); traffic control systems; anti-disaster systems; anti-crime systems; safety equipment; and medical equipment not specifically designed for life support. “Specific”: Aircraft; aerospace equipment; submersible repeaters; nuclear reactor control systems; medical equipment or systems for life support (e.g. artificial life support devices or systems), surgical implantations, or healthcare intervention (e.g. excision, etc.), and any other applications or purposes that pose a direct threat to human life. 8. You should use the Renesas Electronics products described in this document within the range specified by Renesas Electronics, especially with respect to the maximum rating, operating supply voltage range, movement power voltage range, heat radiation characteristics, installation and other product characteristics. Renesas Electronics shall have no liability for malfunctions or damages arising out of the use of Renesas Electronics products beyond such specified ranges. 9. Although Renesas Electronics endeavors to improve the quality and reliability of its products, semiconductor products have specific characteristics such as the occurrence of failure at a certain rate and malfunctions under certain use conditions. Further, Renesas Electronics products are not subject to radiation resistance design. Please be sure to implement safety measures to guard them against the possibility of physical injury, and injury or dam- age caused by fire in the event of the failure of a Renesas Electronics product, such as safety design for hardware and software including but not lim- ited to redundancy, fire control and malfunction prevention, appropriate treatment for aging degradation or any other appropriate measures. Because the evaluation of microcomputer software alone is very difficult, please evaluate the safety of the final products or system manufactured by you. 10. Please contact a Renesas Electronics sales office for details as to environmental matters such as the environmental compatibility of each Renesas Elec- tronics product. Please use Renesas Electronics products in compliance with all applicable laws and regulations that regulate the inclusion or use of controlled substances, including without limitation, the EU RoHS Directive. Renesas Electronics assumes no liability for damages or losses occurring as a result of your noncompliance with applicable laws and regulations. 11. This document may not be reproduced or duplicated, in any form, in whole or in part, without prior written consent of Renesas Electronics. 12. Please contact a Renesas Electronics sales office if you have any questions regarding the information contained in this document or Renesas Electron- ics products, or if you have any other inquiries. (Note 1) “Renesas Electronics” as used in this document means Renesas Electronics Corporation and also includes its majority-owned subsidiaries. (Note 2) “Renesas Electronics product(s)” means any product developed or manufactured by or for Renesas Electronics.
Preface
This book is the results of a long relationship the authors have enjoyed with Renesas Electronics America, Inc. (and one of its predecessors, Mitsubishi Electronics). We origi- nally worked with this company because of their commitment to providing a low-cost eval- uation board and free development software that students could purchase and use in classes and senior design projects. Over the years the boards have remained as affordable (and popular) as ever, and the software development tools available have added more function- ality while still remaining available for free to our students. We have been teaching embedded systems courses for over twelve years (and working in the field even longer). We had not been able to find a book suitable for using in an un- dergraduate course that would lend itself to the theoretical and applied nature of embedded systems design. Renesas had been asking us to create a book for several years, and the in- troduction of the new RX62N microcontroller offered a wonderful opportunity to work with this powerful device and integrate it into our classes. This book also has a radical feature not seen in many books currently on the market (if any). It is freely available for download and is also provided with the Renesas RX62N evaluation board. It is also available for purchase in hardcopy form for a modest price. This book can be used on its own for an Introduction to Embedded Systems class or an Introduction to Microprocessors/Microcontrollers. It can also be used as a supplement in many different types of classes. This book would not have been possible had it not been for the assistance of numerous people. Several students and educators contributed to some of the chapters, including: Adam Harris (1, 2), Suganya Jebasingh (2, 6), Vikram Gill (3,4), Archana Subramanian (4), Onkar Raut (5, 7), Steven Erdmanczyk (8,9), Sunil Gurram (8,11), Aswin Ramakrishnan (11), Vivek Srikantan (12), and Paul Mohan Das (12). Stephanie Conrad heavily edited versions of the chapters. Michael McLain helped create the solutions for the homework assignments. Thanks go to the compositor, Linda Foegen, and especially to June Hay-Harris, Rob Dautel, and Todd DeBoer of Renesas for their help in getting this book produced and published (and for their patience!). Many, many thanks go to the reviewers who offered valuable sugges- tions to make this book better, especially Jerry Zacharias, Mitch Ferguson, Mike Wilkinson, and students from my UNC Charlotte Embedded Systems course. Jim Conrad: I would like to personally thank my parents, the Conrads, and my in-laws, the Warrens, for their continued assistance and guidance through the years while I worked on this and other books. Also, I would especially like to thank my children, Jay, Mary Beth, and Caroline, and my wife Stephanie, for their understanding when I needed to spend more time on the book than I spent with them.
v vi PREFACE
Alex Dean: I would like to thank Bill Trosky and Phil Koopman for opening the doors into so many embedded systems through in-depth design reviews. I would like to thank my students in my NCSU embedded systems courses for bringing their imagination, excite- ment, and persistence to class projects. I would also like to thank my wife Sonya for shar- ing her passion of seeking out and seizing opportunities, and our daughters Katherine and Jacqueline for making me smile every time I leave work to head home.
James M. Conrad and Alexander G. Dean September 2011 Foreword
The world of MCU-based embedded designs can be divided into those that take advantage of existing code and MCUs, and those that require leading edge MCU architectures and implementations. Dr. Conrad, with assistance from Dr. Dean, spent more than a year inter- nalizing the inner workings and surrounding ecosystem of the newly-developed RX archi- tecture, and have generated a book showcasing the RX line which has a level of peripheral integration that has not been seen before. Indeed, by taking the best DNA of both CISC and RISC architectures, and combining them into a new breed of MCU, the RX line enables design approaches that were previously spread across the CISC and RISC camps and inac- cessible in one device line. The authors leverage the capabilities of the RX and demonstrate their own expert grasp of all the dynamics that differentiate successful end solutions from those of the “me-too” variety. They recognize that successful embedded systems require more than just good hardware and software engineering. Jim and Alex have masterfully applied RX capabilities to real world challenges using examples, applications, and approaches that will surely em- power individuals and teams of designers. Readers aspire to find books that have the right balance between depth and breadth. Where there is too much detail, the relevance can be obscured; while a broad brush ap- proach may trivialize the essence of key topics. This is especially true of books relating to embedded designs that must achieve a utilitarian purpose. Here, Jim and Alex skillfully navigate from topic to topic, knowing exactly when to throttle for maximum utility. Whether you are a university student preparing for the real world, a design engineer looking for leading edge approaches to time-critical processes, or a manager attempting to further your risk management techniques, you will find their approach to embedded sys- tems to be stimulating and compelling.
Ali Sebt Renesas September 8, 2011
vii
Contents
Preface iii Foreword v
CHAPTER ONE Introduction to Embedded Systems 1
1.1 Learning Objectives 1 1.2 Concepts 1 1.2.1 Economics and Microcontrollers 1 1.2.2 Embedded Networks 2 1.3 Typical Benefits of Embedded Systems 2 1.3.1 Greater Performance and Efficiency 3 1.3.2 Lower Costs 3 1.3.3 More Features 4 1.3.4 Better Dependability 4 1.4 Embedded System Functions 4 1.5 Attributes of Embedded Systems 5 1.6 Constraints on Embedded Systems 6 1.7 Designing and Manufacturing Embedded Systems 6 1.8 An Example of an Embedded System: The EIN GreenEval Zigbee Module 7 1.9 Summary of Book Contents 8 1.10 Recap 9 1.11 References 9
CHAPTER TWO Concepts of Microcontrollers 11
2.1 Learning Objectives 11
ix x CONTENTS
2.2 Interfacing with Digital Signals 11 2.2.1 General Purpose Digital I/O 11 Data Direction Register (DDR) 12 Data Register (DR) 13 Port Register (PORT) 14 Check State of Switch1 (Port 4 bit 0) and Turn On LED1 (Port D bit 0) 15 Input Buffer Control Register (ICR) 15 Open Drain Control Register (ODR) 15 Pull-Up MOS Control Register (PCR) 16 2.2.2 Example 1: Reading Switches to Control LEDs 16 Using LEDs as Outputs 16 Using Switches as Inputs 17 2.2.3 Driving Motors and Coils 20 2.2.4 Scanning Matrix Keypads 22 2.3 Interfacing with Analog Signals 24 2.3.1 Analog to Digital Converters 24 2.3.2 Analog Comparator 25 2.3.3 Digital to Analog Conversion 26 Resistor Networks 26 Binary Weighted DACs 26 R- 2R DAC 27 Pulse Width Modulation 28 2.4 Infrastructure: Power, Clock, and Reset 28 2.4.1 Power Supply 28 2.4.2 Clock Signal Generation 30 2.4.3 Reset Circuit 31 2.5 Recap 32 2.6 References 32 2.7 Exercises 32 CONTENTS xi
CHAPTER THREE Organization and Architecture of the Renesas RX62N Microcontroller Board 35
3.1 Learning Objectives 35 3.2 Basic Concepts 35 3.2.1 Introduction to Computer Organization & Architecture 35 3.2.2 Architecture of the Renesas RX62N 38 CPU 42 Register Set 42 3.2.3 Data Types 52 3.2.4 Endianness 55 3.2.5 Data Arrangement 56 3.2.6 Bus Specification 57 Description of Buses 58 Bus Error Monitoring Section 63 Types of Bus Error 63 3.3 Basic Examples 64 3.4 Advanced Concepts 65 3.4.1 Pipelining 65 Pipeline Basic Operation 67 3.4.2 Operating Modes 71 3.4.3 Memory Organization 75 Byte Addressing vs. Word Addressing 75 3.4.4 Memory Map 76 3.4.5 I/O Registers 76 3.5 Advanced Examples 79 3.6 References 81 3.7 Exercises 82 xii CONTENTS
CHAPTER FOUR Software Development Tools 85
4.1 Learning Objectives 85 4.2 Basic Concepts 85 4.2.1 Compilation Mechanism 85 4.2.2 Compilers for Embedded Systems 87 4.2.3 RX Compiler Package 87 Features of RX Family C/Cϩϩ Compiler 88 4.2.4 Debugging Tools 89 4.2.5 Introduction to HEW 89 Creating or Opening a Project in HEW- IDE 90 Windows in HEW 92 Concept of Configuration and Session 93 Configuration 94 Session 94 4.2.6 Concepts of Header Files 94 Header Files Used in RX Family C/Cϩϩ Compiler 95 Header Files Associated with RX62N 95 4.3 Basic Examples 96 4.4 Advanced Concepts 106 4.4.1 Advanced Debugging Concepts 106 4.4.2 The J- Link Debugger 117 Features 118 4.4.3 Description of the Header Files Used in the RX Family 118 4.5 Advanced Examples 130 Window Configuration 130 Changing the Register Display Radix 131 Setting the Layout 131 Choosing a Register to be Displayed 133 Modifying the Register Contents 133 Setting the Flag Value 134 CONTENTS xiii
Screenshot 134 Saving Register Contents 135 4.6 References 136 4.7 Exercises 137
CHAPTER FIVE Software Engineering for Embedded Systems 141
5.1 Learning Objectives 141 5.2 Introduction 141 5.2.1 Risk Reduction 141 5.3 Software Development Stages 142 5.3.1 Development Lifecycle Overview 142 5.3.2 Requirements 145 5.3.3 Design Before Coding 146 5.3.4 Peer Reviews of Design Artifacts 147 5.3.5 System Architecture and Design Approach 147 Time-Critical Processing 148 Safety-Critical Processing 149 5.3.6 Detailed Design 149 5.3.7 Implementation 151 5.3.8 Software Testing 152 Do We Know How the System is Built? 153 How Many Modules Do We Test at a Time? 153 How Do We Keep from Breaking Old Bug Fixes? 154 5.4 Software Development Lifecycle Models 155 5.4.1 Waterfall Process 155 5.4.2 Iterative Process 156 5.4.3 Spiral Process 156 5.4.4 Agile Development Methods 157 5.4.5 Prototyping 158 xiv CONTENTS
5.5 Recap 158 5.6 References 158 5.7 Exercises 159
CHAPTER SIX Converting Between the Analog and Digital Domains 161
6.1 Learning Objectives 161 6.2 Basic Concepts 161 6.2.1 Analog to Digital Conversion by Successive Approximation 163 6.2.2 Conversion Speed 165 6.2.3 Transfer Function Calculation 165 6.3 Basic Examples 167 6.3.1 Conversion Speed 167 6.3.2 Digital Value for a Given Analog Value 167 6.3.3 Step Size 168 6.4 Advanced Concepts 168 6.4.1 12-Bit A/D Converter 168 Registers 170 A/D Data Registers n (ADDRn) (n ϭ A to H) 170 A/D Control Register (ADCSR) 170 A/D Channel Select Register (ADANS) 171 A/D- Converted Value Addition Mode Select Register (ADADS) 171 A/D- Converted Value Addition Count Select Register (ADADC) 172 A/D Control Extended Register (ADCER) 173 A/D Start Trigger Select Register (ADSTRGR) 173 Operation 175 Single-Cycle Scan Mode 175 Continuous Scan Mode 178 6.4.2 10-Bit A/D Converter 178 Registers 178 A/D Data Register (ADDRn) (n ϭ A to D) 178 CONTENTS xv
A/D Control/Status Register (ADCSR) 178 A/D Control Register (ADCR) 180 A/D Data Placement Register (ADDPR) 181 A/D Self- Diagnostic Register (ADDIAGR) 181 Operation 182 6.4.3 D/A Converter 183 D/A Registers 183 D/A Data Register (DADRm) (m ϭ 0, 1) 184 D/A Control Register (DACR) 184 D/A Data Placement Register (DADPR) 184 Operation 184 6.5 Advanced Examples 186 6.5.1 12-Bit ADC 186 Output 188 6.5.2 10-Bit ADC 188 Output 190 6.5.3 DAC 190 6.6 Recap 191 6.7 References 192 6.8 Exercises 192
CHAPTER SEVEN Serial Communications 193
7.1 Learning Objectives 193 7.2 Basic Concepts of Serial Communications 193 Terminologies 194 7.2.1 Introduction to the RX62N Serial Communication Interfacing 196 7.2.2 Universal Asynchronous Receiver and Transmitter 198 Registers Related to the SCI in UART Mode 200 Serial Mode Register (SCIX.SMR) 201 Serial Control Register (SCIx.SCR) 202 xvi CONTENTS
Serial Status Register (SCIx.SSR) 203 Bit Rate Register (SCIx.BRR) 204 Transmit Data Register (SCIx.TDR) 205 Receive Data Register (SCIx.RDR) 205 Variations to the UART 205 7.2.3 Renesas Serial Peripheral Interface 205 General Working of SPI Modules 207 Configurations of the Renesas SPI 208 Registers Related to the Renesas Serial Peripheral Interface 208 Configuring the RSPI to Function in Single Master Single Slave Mode 220 7.2.4 Renesas Inter Integrated Circuit Bus 221 I2C Bus Protocol 221 I2C Communication Modes 222 Registers Related to the RIIC Interface 224 7.3 Basic Examples 236 7.3.1 Basic Transmission/Receiving of Serial Data via UART 236 Explanation of Initialization Code 239 Explanation of Transmission Code 240 Explanation of Reception Code 241 Explanation of Main Program 241 7.3.2 Basic Transmission of Data Using Serial Peripheral Interface Bus 242 Explanation of Initialization Code 244 Transmission Code 246 Explanation of Transmission Code 246 Main Code 247 Explanation of Main Code 247 7.3.3 Basic Transmission and Reception of Data Using the Renesas I2C Bus 248 7.4 Advanced Concepts 262 7.4.1 Applying FIFO Data Structures for Transmission and Reception Using the UART Serial Communications Interface 262 7.4.2 Multiprocessor Communication Using the Renesas Serial Peripheral Interface 264 Master Algorithm 266 Slave Algorithm 267 CONTENTS xvii
7.4.3 Transfer of Data Between Peripherals Connected on the I2C Bus Using FIFOs 268 7.5 Advanced Examples 276 7.5.1 FIFO Data Structures for Transmission and Reception Using the UART Serial Communications Interface 276 Setting Up Interrupt Service Routines 276 Main Program 279 7.5.2 Multiprocessor Communication Using Queues and the Renesas Serial Peripheral Interface 280 Setting Up Interrupt Service Routines 280 Setting Up Function Definitions for Operating on the Queues 281 Setting Up All the Function Details Related to the Functioning of the UART and FIFO Queues 282 Main Program 285 7.5.3 Transfer of data between peripherals connected on the I2C bus using FIFOs 286 7.6 Recap 297 7.7 References 299 7.8 Exercises 299
CHAPTER EIGHT Event Counters, Timers, and the Real Time Clock 301
8.1 Learning Objectives 301 8.2 Basic Concepts 301 8.2.1 Timer and Event Counter 301 Timer 301 Event Counter 302 8.2.2 Cascading Timers 310 8.2.3 Pulse Output Operation 311 8.3 Real Time Clock 313 8.3.1 RTC Registers 314 8.3.2 Setting the RTC 321 8.3.3 Reading the RTC 322 xviii CONTENTS
8.4 Basic Examples 323 8.4.1 Setting Up Cascaded Timers 323 8.4.2 Setting Up a Timer for Pulse Output 327 8.4.3 Setting and Reading from the Real Time Clock 328 8.5 Advanced Concepts 333 8.5.1 Using a Cascaded Timer with 16-Bit Timer Constant Registers 333 8.5.2 Calculating and Programming Pulse Frequency and Duty Cycle in Pulse Output Mode, and Controlling a Servo Motor 334 8.5.3 Using the Real Time Clock’s Alarm and Periodic Interrupts 336 8.6 Advanced Examples 337 8.6.1 Using a Cascaded Timer with 16-Bit Timer Constant Registers 337 8.6.2 Setting Up Pulse Output Mode to Control a Servo Motor 340 8.6.3 Using the Real Time Clock’s Alarm and Periodic Interrupts 343 8.7 Recap 347 8.8 References 347 8.9 Exercises 347
CHAPTER NINE Using Interrupts with Peripherals 349
9.1 Learning Objectives 349 9.2 Basic Concepts 349 9.2.1 Using Interrupts for Tasks versus Other Methods 349 9.3 Interrupts 350 Interrupt Request Register n (IRn) (n ϭ interrupt vector number) 351 IR Flag (Interrupt Status Flag) 354 Interrupt Priority Register m (IPRm) (m ϭ 00 to 8Fh) 355 Fast Interrupt Register (FIR) 356 Software Interrupt Activation Register (SWINTR) 356 IRQ Control Register i (IRQCRi) (i ϭ 0 to 15) 357 Non- Maskable Interrupt Enable Register (NMIER) 357 Non- Maskable Interrupt Status Register (NMISR) 358 CONTENTS xix
Non- Maskable Interrupt Clear Register (NMICLR) 359 NMI Pin Interrupt Control Register (NMICR) 360 9.3.1 Interrupt Vector Table 360 9.3.2 Interrupt Operation 360 Edge Detection 361 Level Detection 362 9.3.3 Setting Up an Interrupt for a Peripheral 363 Setting Up an Interrupt 363 Registers Set in the ICU for an Interrupt 365 9.3.4 How an Interrupt Operates 369 9.4 Basic Examples 370 9.4.1 Polling a Switch for Input versus Using an Interrupt 370 9.4.2 Setting up the ADC with an Interrupt 373 9.5 Advanced Concepts 377 9.5.1 Minimizing the Amount of Code in Interrupts 377 9.5.2 Brief Introduction to State Machines 378 9.5.3 State Machines and Using Them with Interrupts 379 9.6 Advanced Examples 380 9.6.1 Using an ADC Interrupt with Flags to Process Data 380 9.6.2 A Simple State Machine Controlled by Interrupts 383 9.7 Recap 389 9.8 References 389 9.9 Exercises 389
CHAPTER TEN Floating Point Unit and Operations 391
10.1 Learning Objectives 391 10.2 Basic Concepts 391 10.2.1 Floating Point Basics 391 Floating Point Representation 391 IEEE 754 Floating Point Standard 392 xx CONTENTS
The IEEE 754 Floating Point Standard 393 Single Precision (32 bits) 393 Double Precision (64 bits) 395 10.2.2 Pipelining Basics 397 Instruction Fetch 397 Instruction Decode 398 Execution 398 Memory Access 398 Write- Back 398 10.2.3 Floating Point in RX62N 398 Floating Point Unit 399 Floating Point Registers 399 Floating Point Instructions 401 FADD 401 FSUB 401 FCMP 403 Floating Point Exceptions 403 Overflow 403 Underflow 404 Inexact 404 Divide- By- Zero 404 Invalid Operation 404 10.3 Basic Examples 404 10.3.1 Operations Explaining Floating Point Exceptions 404 10.4 Advanced Concepts of RX62N Floating Point Unit 408 10.4.1 FPSW in Detail 408 Rounding- Modes 409 Cause Flags 409 Exception Flags 410 Exception Handling Enable Bits 410 Denormalized Number Bit 410 Floating Point Error Summary Flag 411 Reserved Bits 411 CONTENTS xxi
10.4.2 Floating Point Exception Handling Procedure 411 Acceptance of the Exception 411 Hardware Pre- Processing 412 Processing of User- Written Program Code 412 Hardware Post- Processing 414 10.5 Advanced Examples 414 10.5.1 Fixed- Point and Floating- Point Operation Time Calculation 414 Int 417 Float 417 Double 417 10.5.2 Matrix Multiplication Time Calculation 418 Int 422 Float 422 Double 422 10.6 Recap 422 10.7 References 423 10.8 Exercises 423
CHAPTER ELEVEN Watchdog Timer and Brown- Out Detector 425
11.1 Learning Objectives 425 11.2 Basic Concepts of Watchdog Timer 425 11.2.1 Watchdog Timer (WDT) 426 11.2.2 Register Descriptions 426 Timer Counter Register (TCNT) 428 Explanation of the Code 428 Timer Control/Status Register (TCSR) 428 Bit Description of TCSR 429 Explanation of the Code 431 Reset Control/Status Register (RSTCSR) 431 xxii CONTENTS
Bit Description of RSTCSR 431 Explanation of the Code 432 11.2.3 Operation of WDT 432 11.3 Basic Code Examples 434 11.3.1 Example 1: Setting Up Watchdog Timer Mode 434 Explanation of the Code 434 11.3.2 Example 2: Application of a Watchdog Timer 434 Explanation of the Code 435 11.4 Advanced Concepts of the Watchdog Timer 436 11.4.1 Interval Timer Mode 436 11.4.2 Inde pen dent Watchdog Timer (IWDT) 436 Bit Description for IWDTCR 438 Bit Description of IWDTSR 441 Operation of Inde pen dent Watchdog Timer 441 11.5 Complex Examples 443 11.5.1 Example 1: Interval Timer Mode of a Watchdog Timer 443 Explanation of the Code 443 11.5.2 Example 2: Setting Up of IWDT 444 Explanation of the Code 444 11.6 Brownout Condition 444 11.6.1 How Brownout Occurs 444 11.6.2 Automatically Detecting a Brownout Condition 444 11.7 Recap 445 11.8 References 445 11.9 Exercises 445
CHAPTER TWELVE Designing Responsive andReal- Time Systems 447
12.1 Learning Objectives 447 12.2 Motivation 447 12.3 Scheduling Fundamentals 449 CONTENTS xxiii
12.3.1 Task Ordering 449 12.3.2 Task Preemption 451 12.3.3 Fairness and Prioritization 452 12.3.4 Response Time and Preemption 453 12.3.5 Stack Memory Requirements 454 12.3.6 Interrupts 455 12.4 Task Management 456 12.4.1 Task States 456 12.4.2 Transitions between States 457 12.4.3 Context Switching for Preemptive Systems 458 12.5 Sharing Data Safely 460 12.5.1 Data Shared Objects 460 12.5.2 Function Reentrancy 461 12.5.3 High- Level Languages and Atomicity 462 12.5.4 Shared-Data Solutions and Protection 464 Disable Interrupts 464 Use a Lock 465 RTOS- Provided Semaphore 466 RTOS- Provided Messages 467 Disable Task Switching 467 12.6 Nonpreemptive Dynamic Scheduler 467 12.6.1 Concepts 467 12.6.2 Implementation 470 Task Table 470 Managing Tasks 471 Tick Timer Configuration and ISR 473 Scheduler 474 12.6.3 Example Application using RTC Scheduler 474 12.7 References 475 12.8 Exercises 476
Appendix A 479 Index 487
Chapter One
Introduction to Embedded Systems
1.1 LEARNING OBJECTIVES
In this chapter the reader will learn:
Ⅲ What an embedded system is Ⅲ Why to embed a computer Ⅲ What functions and attributes embedded systems need to provide Ⅲ What constraints embedded systems have
1.2 CONCEPTS
An embedded system is an application- specific computer system which is built into a larger system or device. Using a computer system rather than other control methods (such as non- programmable logic circuits, electro- mechanical controls, and hydraulic control) offers many benefits such as sophisticated control, precise timing, low unit cost, low de- velopment cost, high flexibility, small size, and low weight. These basic characteristics can be used to improve the overall system or device in various ways:
Ⅲ Improved per for mance Ⅲ More functions and features Ⅲ Reduced cost Ⅲ Increased dependability
Because of these benefits, billions of microcontrollers are sold each year to create embed- ded systems for a wide range of products.
1.2.1 Economics and Microcontrollers
Microcontrollers are remarkably inexpensive yet offer tremendous per for mance. The mi- croprocessor for a personal computer may cost $100 or more, while microcontrollers typi- cally cost far less, starting at under $0.25. Why is this so?
1 2 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
Microcontrollers provide extremely inexpensive processing because they can leverage economies of scale. MCUs are programmable in software, so a chipmaker can design a single type of MCU which will satisfy the needs of many customers (when combined with their application- specific software). This reduces the per- chip cost by amortizing the de- sign costs over many millions of units. The cost of an integrated circuit (such as a microcontroller or a microprocessor) depends on two factors: non- recurring engineering (NRE) cost and recurring cost. The NRE cost includes paying engineers to design the integrated circuit (IC) and verify through simulation and prototyping that it will work properly. The recurring cost is in- curred by making each additional IC, and includes raw materials, processing, testing, and packaging. The IC’s area is the major factor determining this recurring cost. The smaller the IC, the more will fit onto a silicon wafer and the lower the recurring cost. Microcontrollers are much smaller than microprocessors for personal computers, so they will cost less (given the same number of ICs sold). The NRE cost must be divided across each IC sold. As the number of ICs sold rises, the NRE adder falls, and so each IC’s price falls as well. Low- volume chips are more expensive than high- volume chips.
1.2.2 Embedded Networks
Some embedded systems consist of multiple embedded computers communicating across an embedded network, and offer further benefits. Each computer on the network uses a communication protocol to share the same set of wires to communicate, rather than dedicating one set for each possible communication route. Several advantages come from having fewer wires:
Ⅲ Lower parts cost, as fewer wires are needed Ⅲ Lower labor costs, as it is faster to assemble Ⅲ Greater reliability, as it has fewer connections to fail
Other advantages come from allowing separate nodes to share information. New features may be possible, or the system efficiency may be improved through better coordination of activities among different nodes.
1.3 TYPICAL BENEFITS OF EMBEDDED SYSTEMS
As an example, let’s examine how embedded systems have affected automobiles. A typical modern car has dozens of microcontrollers embedded within it. Let’s see why. CHAPTER 1 / INTRODUCTION TO EMBEDDED SYSTEMS 3
1.3.1 Greater Performance and Efficiency
Computer control of automobile engines lowers pollution and increases fuel efficiency, re- ducing operating costs. Burning gasoline with air in spark ignition engines is a tricky business if we want to max- imize efficiency, yet minimize pollution. The main factor affecting emissions is the ratio of air mass to fuel mass. The ideal ratio is 14.7 to 1, and the catalytic converter is designed to op- erate most efficiently at this ratio. If there is too little air (a rich mix), then excessive carbon monoxide (CO) and hydrocarbons (HC) will be produced. If there is too much air (a lean mix), then large amounts of oxides of nitrogen (called NOx) will be created. So we would like for each fuel injector to add just the right amount of fuel. This depends on the mass of the air inside the cylinder, which depends on factors such as air temperature and air pressure. These in turn depend on altitude and weather, as well as whether the engine is warmed up or not. Another factor is the timing of the sparkplug firing. If it fires early, then there is more time for combustion within the cylinder before the exhaust valve opens. This raises the av- erage temperature within the cylinder and changes the combustion process, affecting CO, HC, and NOx concentrations. It would be quite impractical to design a mechanical control system to consider all of these factors and squirt the fuel injectors at just the right instant for the right amount of time. Thankfully, an inexpensive microcontroller is quite effective at these kinds of calcu- lations and control.
1.3.2 Lower Costs
There are various ways in which an embedded system can reduce the costs associated with a device.
Ⅲ Component costs: Embedded software can compensate for poor signal quality, al- lowing the use of less- expensive components. For example, a low- cost pressure sensor may be very temperature- de pen dent. If ambient temperature information is already available, then it is a simple matter to compensate for the temperature- induced error. Ⅲ Manufacturing costs: Many vehicles use the Control Area Network (CAN) pro- tocol to communicate across an in- car network. The embedded network reduces assembly and parts costs because of the simpler wiring harness. Ⅲ Operating costs: As mentioned above, an embedded system enables automobile engines to operate more efficiently, reducing the amount of gasoline needed and hence lowering operating costs. Ⅲ Maintenance costs: Some vehicles predict oil life by monitoring engine use his- tory, notifying the driver when an oil change is needed. 4 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
1.3.3 More Features
An MCU running application- specific software offers tremendous opportunities for fea- tures and customization. These features can make your company’s products stand out from the competition.
Ⅲ Cruise control keeps the car running at the same speed regardless of hills, wind, and other external factors. Ⅲ Smart airbags reduce injuries by adjusting inflation speed based on passenger weight. Ⅲ Power seats move to each driver’s preferred position automatically, based on whose keyless entry fob was used to open the car. Ⅲ Headlights and interior lights shut off automatically after a time delay if the car is not running and prevents the lights from draining the battery.
1.3.4 Better Dependability
Embedded systems and networks offer many opportunities to improve dependability.
Ⅲ An engine controller (and other controllers) can provide various “limp- home modes” to keep the car running even if one or more sensors or other devices fail. Ⅲ A warning of an impending failure can be provided. Ⅲ Diagnostic information can be provided to the driver or ser vice personnel, saving valuable trouble- shooting time.
1.4 EMBEDDED SYSTEM FUNCTIONS
There are several common functions which embedded systems typically provide.
Ⅲ Control systems monitor a process and adjust an output variable to keep the process running at the desired set point. For example, a cruise control system may increase the throttle setting if the car’s speed is lower than the desired speed, and reduce it if the car is too fast. Ⅲ There is often sequencing among multiple states. For example, a car engine goes through multiple states or control modes when started. During Crank and Start, the fuel/air mix is lean and depends on the engine coolant temperature. Once the engine has started, the controller switches to the Warm- Up mode, in order to raise the engine and exhaust system temperatures to their ideal levels. Here the fuel/air CHAPTER 1 / INTRODUCTION TO EMBEDDED SYSTEMS 5
mixture and ignition timing are adjusted, again based in part on the engine coolant temperature. When the engine has warmed up it can switch into Idle mode. In this mode the controller seeks to minimize the engine’s speed, yet still run smoothly and efficiently despite changes in loads due to air conditioning, power steering, and the electrical system. Ⅲ Signal processing modifies input signals to eliminate noise, emphasize signal components of interest, and compensate for other factors. For example, a hands- free speakerphone interface may use multiple microphones, beam- forming, and active noise cancellation to filter out low- frequency road noise. Other sensors may have spark- plug noise filtered out. Ⅲ Communications and networking enable different devices on the same network to exchange information. For example, the engine controller may need to send a message indicating speed. To do this, the speed value must be formatted according to the communication protocol and then loaded into the network interface periph- eral for transmission.
1.5 ATTRIBUTES OF EMBEDDED SYSTEMS
Embedded systems are designed so that the resulting device behaves in certain desirable ways.
Ⅲ Embedded systems need to respond to events which occur in the environment, whether a user presses a button or a motor overheats. A system which is not suffi- ciently responsive is not likely to be a successful product. For example, when we press a channel select button for the radio, we would like for it to respond within some reasonable time. Ⅲ For real-time systems, the timing of the responses is critical because late answers are wrong answers. Igniting the fuel in a cylinder is time- critical because bad tim- ing can damage or destroy engine components (to say nothing of reducing power, or the efficiency and pollution concerns mentioned previously). Ⅲ Embedded systems typically require sophisticated fault handling and diagnos- tics to enable safe and reliable operation. Often the fault handling code is larger and more complex than the normal operation code. It is easy to design for the “everything goes right and works fine” case. It is far more difficult to determine methods to handle the exceptional cases. What is likely to fail? Which failures can lead to dangerous conditions? How should the system handle failures? How will you test that the system handles the failures correctly? Ⅲ Embedded systems may be expected to operate indepen dently for years with- out operator attention such as adjustment or resetting. The system is expected to 6 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
operate robustly and always work. Given that it is very difficult and expensive to write perfect, bug- free software, developers build in mechanisms to detect faulty behavior and respond, perhaps by restarting the system.
1.6 CONSTRAINTS ON EMBEDDED SYSTEMS
Embedded systems often have constraints which limit the designer’s options, and can lead to creative and elegant solutions. These constraints are typically different from those for general- purpose computers.
Ⅲ Cost is a common constraint. Many applications which use embedded systems are sold in very competitive markets, in which price is a major factor. Often a manu- facturer will hire subcontractors to design and build individual sub- systems. This allows the manufacturer to pit potential subcontractors against each other, keeping prices down. Ⅲ There may be size and weight limits for portable and mobile applications. An em- bedded system for an automotive remote keyless entry transmitter must fit into a small fob on a key ring which fits easily into a pocket. Similarly, the receiver must not be too heavy. A heavier car will have worse acceleration, braking, cornering, and fuel efficiency. Aircraft and spacecraft are especially sensitive to weight since a heavier craft requires more fuel to achieve the same range. Ⅲ There may be limited power or energy available. For example, a battery has a lim- ited amount of energy, while a solar cell generates a limited amount of power. High temperatures may limit the amount of cooling available, which will limit the power which can be used. Ⅲ The environment may be harsh. Automotive electronics under the hood of a car need to operate across a wide range of temperatures (Ϫ40°C to 125°C, or Ϫ40°F to 193°F), while withstanding vibrations, physical impact, and corroding salt spray. Spark plugs generate broadband radio frequency energy which can interfere with electronics.
1.7 DESIGNING AND MANUFACTURING EMBEDDED SYSTEMS
Embedded systems are designed with a central microcontroller and other supporting elec- tronic components mounted on a printed circuit board (PCB). PCBs provide the means to connect these integrated circuits to each other to make an operational system. The PCB pro- vides structural support and the wiring of the circuit. The individual wires on the PCB are called traces and are made from a flat copper foil. While many circuit designs may use the same standard components, the PCB is often a custom component for a given design. Designing a PCB requires a completed schematic for the circuit. This schematic is sometimes different than the schematic seen in textbooks. It often contains extra informa- CHAPTER 1 / INTRODUCTION TO EMBEDDED SYSTEMS 7
Figure 1.1 EIN GreenEval Zigbee Module.
tion about the components and construction of the board. For example, a textbook schematic may only show a battery for the power supply, while the production schematic would show the battery case, the number of cells, the rating of the battery, and the manu- facturers of the components. From the schematic, a designer will use their computer- aided design tools to identify the size of the PCB, and then place the electronic components on their board drawing. The designer will also place the wiring between the components on the PCB. The physical PCB is manufactured from a fiberglass- resin material that is lightweight and inexpensive. A manufacturer will add copper wiring traces to the surfaces of the board and the appropriate insulation and white silk screening. The final manufacturing steps are applying solder, placing the components, and heating/cooling the solder. Figure 1.1 shows an example of a finished board. The completed boards are electrically tested for functionality. Any board failing the test is inspected in more detail to find the problems. These boards are repaired to increase the passing rate acceptable to the manufacturer. The boards are wrapped in anti- static ma- terials and shipped to the next location for the next stage of production, or immediately in- stalled in a mechanical enclosure (like the mechanical shell of a mobile phone).
1.8 AN EXAMPLE OF AN EMBEDDED SYSTEM: THE EIN GREENEVAL ZIGBEE MODULE
The EIN GreenEval Zigbee (Envisionnovation, http://www.eininc.net/products.html) mod- ule is one example of a Renesas MCU- based embedded system. This device has thirty- four digital I/O lines that are controlled by a Zigbee radio. 8 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
Figure 1.1 shows the main board of the EIN GreenEval Zigbee Module. As seen in this example, taking off the shielding provides a good look at the internal circuitry. Six of the main components are visible. Starting from left to right; the large cylindrical device hang- ing off the left edge of the board is an antenna for the 2.4 GHz radio. The chip labeled 5PE20V (http://www.micron.com//get-document/?documentId= 5965&file=M25PE20_10.pdf) (the small 8-pin chip at the top left of the image) is a page- erasable serial FLASH chip. This chip communicates with the Renesas MCU through the SPI bus. This chip is also used to hold more data than the MCU. Since the MCU can only handle 8 k of data, it is quickly filled. This extra FLASH chip can hold an additional 2 Mbits. The square chip on the lower left is a Skyworks 2.4 GHz Front- End Module (FEM) (SKYWORKS Solutions, Inc., http://www.skyworksinc.com/Product.aspx?ProductIDϭ752), which simply boosts radio signals sent from the MCU. It is controlled by three output pins of the MCU. One pin controls putting the FEM to sleep to save power, another pin selects whether the FEM will send or receive data, and the last pin actually transmits and receives data to and from the FEM. The large chip in the center is a Renesas R5FF36B3 from the M16C family of chips with 256 K ϩ 24 K of ROM, 20 k RAM, and 8 k of data (Renesas Electronics America, Inc., RENESAS MCU: M16C Family/M16C/60 SERIES, http://am.renesas.com/products/ mpumcu/m16c/m16c60/m16c6b/m16c6b_root.jsp). Thirty-four I/O pins are used to inter- face with external pins on the module. This processor is running at 4 MHz (controlled by the small metal chip which is actually a temperature compensated crystal oscillator). This chip has an RF radio built in. The pins at the far right are a programming and interface header. They are used to com- municate with and program the Renesas MCU.
1.9 SUMMARY OF BOOK CONTENTS
This book is structured as follows:
Ⅲ Chapters 2 and 3 present basic microcontroller concepts and the specifics of the RX62N. Ⅲ Chapters 4 and 5 show how software is built. At the low level they show how pro- grams are compiled and downloaded. At the high level they show software engi- neering concepts and practices. Ⅲ Chapters 6 through 8 present how to use peripherals to interface with the environ- ment and simplify programs. Ⅲ Chapter 9 presents how to use interrupts to improve response times and program structure. CHAPTER 1 / INTRODUCTION TO EMBEDDED SYSTEMS 9
Ⅲ Chapter 10 presents how to use the floating- point math support in the RX62N. Ⅲ Chapter 11 presents how to increase system robustness using the watchdog timer and voltage brownout detector. Ⅲ Chapter 12 presents how to structure multi- threaded software so the resulting sys- tem is predictably responsive.
1.10 RECAP
An embedded system is an application- specific computer system which is built into a larger system or device. Using a computer system enables improved perfor mance, more functions and features, lower cost, and greater dependability. With embedded computer systems, manufacturers can add sophisticated control and monitoring to devices and other systems, while leveraging the low- cost microcontrollers running custom software.
1.11 REFERENCES
Envisionnovation. EININC Products. Ontario: Envisionnovation, 2010. Web. Accessed at http://www.eininc. net/products.html Numonyx MP25PE20 datasheet http://www.micron.com//get-document/?documentId=5965&file=M25PE20_ 10.pdf RENESAS MCU: M16C Family/M16C/60 SERIES. Renesas Electronics America, Inc., 2010. Web. Accessed at http://am.renesas.com/products/mpumcu/m16c/m16c60/m16c6b/m16c6b_root.jsp SKYWORKS Solutions, Inc. SKYWORKS Products: SKY65352–11. Woburn, MA: SKYWORKS Solutions, Inc., 2009. Web. Accessed at http://www.skyworksinc.com/Product.aspx?ProductIDϭ752
Chapter Two
Concepts of Microcontrollers
2.1 LEARNING OBJECTIVES
Embedded systems consist of computers embedded in larger systems. Additional circuitry such as power supplies, clock generators, and reset circuits, is required for the computer to work. Transducers (devices that convert one type of energy into another) are also used to connect microcontrollers to the outside world. There are two classes of transducers: inputs and outputs. Inputs are also known as “sensors” and contain such things as switches, key- pads, and buttons. Output transducers include devices such as LEDs, motors, and coils. In this chapter the reader will learn general information about:
Ⅲ Connecting LEDs Ⅲ Connecting motors and coils Ⅲ Connecting switches and buttons Ⅲ Connecting keypads Ⅲ Analog to digital conversion Ⅲ Digital to analog conversion Ⅲ Power supplies for embedded systems Ⅲ Clock generation options Ⅲ Reset circuitry
2.2 INTERFACING WITH DIGITAL SIGNALS
2.2.1 General Purpose Digital I/O
Embedded systems consist of computers embedded in larger systems. The processor needs to sense the state of the larger system and environment, and control output devices. The most basic way to do this is through one or more discrete signals, each of which which can be in one of two states (on or off). General purpose digital I/O ports are the hardware which can be used to read from or write to the system outside the microcontroller.
11 12 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
The RX62N has eleven I/O ports (Port 0 to 5, A to E). Each port has eight pins, and on most ports all eight pins can be selected as inputs or outputs. However, on some ports some pins are reserved. The reserved pins cannot be configured as I/O pins. Each port has a Data Direction Register (DDR), Data Register (DR), Port Register (PORT), and Input Buffer Control Register (ICR). The pins of a port may serve several purposes; for example, Port 4 pin 0 can be used as a general purpose I/O pin, as an A/D converter input, or as an interrupt input. Depending on the purposes these pins serve, they might have extra regis- ters. Ports A through E have an extra register called the Pull- up MOS Control Register (PCR), and Ports 0 to 3 (P30 to P34) and C have Open Drain Control Register (ODR). All of these registers are 8 bits long. Certain other registers called Port Function Registers are also present. These registers are associated with special features of the RX62N board such as USB, CAN, etc.
Data Direction Register (DDR) This register, as the name suggests, is used to set the data direction (input or output) of a pin. DDR is a read/write register. Each bit of the Data Direction Register represents a pin.
b7 b6 b5 b4 b3 b2 b1 b0
Value after reset: 0 0 0 0 0 0 0 0
Figure 2.1 Data Direction Register. Source: Kuphaldt, T. R. “Successive Approximation ADC,” in All about Circuits, page 765.
The ‘iodefine_RX62N.h’ file has C code constructs that make it easy to access each port with C code. Each port is defined as a structure and each register of the port is defined as a union of variables within that structure. An example of how the DDR is defined inside a port structure follows:
1. struct st_port4 { 2. union { 3. unsigned char BYTE; 4. struct { 5. unsigned char B7:1; 6. unsigned char B6:1; 7. unsigned char B5:1; 8. unsigned char B4:1; CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 13
9. unsigned char B3:1; 10. unsigned char B2:1; 11. unsigned char B1:1; 12. unsigned char B0:1; 13. } BIT; 14. } DDR; 15. }
Line 1 shows that port0 has been defined as a structure. Lines 2 to 14 suggest that Data Direction Register (DDR) has been defined as a union with the variable BYTE and a struc- ture called BIT. This organization helps in easy access of the bits of the DDR. Unsigned char Bn:1(n 0 to 7) indicates that the character variable is assigned one bit. To select a particular pin as the input pin, the corresponding bit of the DDR has to be set to ‘0’; and to select a pin as output, the corresponding bit of the DDR has to be set to ‘1.’ The general syntax to set a bit of the DDR is PORTx.DDR.BIT.Bn (x 0 to 5, A to E; and n 0 to 7) since ports are defined as structures and accessing structure members is done so this way. To configure multiple pins at the same time, the char variable BYTE can be used. All pins are configured as inputs at reset, by default.
EXAMPLE 1
Set Switch 1 (Port 4 bit 0) as Input PORT4.DDR.BIT.B1 =0;
When a pin is selected as an input from a peripheral, the Input Buffer Control Register (ICR) has to be enabled. The ICR will be explained a little later. Selecting a pin as an output involves setting the Data Register (DR) and the Data Direction Register (DDR).
Data Register (DR) The Data Register is used to store data for pins that have been configured as output pins. This register is similar to the DDR in that each bit of the register represents a pin and certain bits of certain ports are reserved. 14 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
b7 b6 b5 b4 b3 b2 b1 b0
Value after reset: 0 0 0 0 0 0 0 0 Figure 2.2 Data Register.
The Data Register (DR) is also defined as a union of variables inside the port structure, in the ‘iodefine_RX62N.h’ file. It is presented just like the DDR. Unsigned char: 1 is used to represent reserved pins. The syntax to access the bits of the Data Register (DR) is PORTx.DR.BIT.Bn (x 0 to 5, A to E; and n 0 to 7). To select a pin as an output pin, first set the Data Register (DR) to a known value, preferably 0, so that changes in the output can be easily observed. The char variable BYTE can be used to set multiple pins as output at the same time.
EXAMPLE 2
Set LED1 (Port D bit 0) as Output 1. PORTD.DDR.BIT.B0 = 1; 2. PORTD.DR.BIT.B0 = 0;
Line 1 sets LED1 as an output and line 2 switches on the LED.
Sets LEDs 1, 2, and 3 (Port D bit 0, 1, and 2) as Outputs 1. PORTD.DDR.BYTE = 0x07; 2. PORTD.DR.BYTE = 0xF8;
Line 1 sets LED1, 2, and 3 as outputs and line 2 switches on the LEDs.
Port Register (PORT) Port register is also defined as a union of variables inside the port structure in the ‘iodefine_RX62N.h’ file. PORTx.PORT.BIT.Bn (x 0 to 5, A to E; and n 0 to 7) is used to read the state of a pin and the state is stored in the Port Register regardless of the value in the Input Buffer Control Register (ICR). This register also has some reserved bits. These bits are read as 1 and cannot be modified. CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 15
b7 b6 b5 b4 b3 b2 b1 b0
Value after reset: x x x x x x x x Figure 2.3 Port Register.
Check State of Switch1 (Port 4 bit 0) and Turn On LED1 (Port D bit 0) 1. if(PORT4.PORT.BIT.B0 == 1){ 2. PORTD.DR.BIT.B0 = 1; 3. }
Input Buffer Control Register (ICR) This register is used to buffer the input values for pins that have been configured as input from peripheral modules.
b7 b6 b5 b4 b3 b2 b1 b0
Value after reset: 0 0 0 0 0 0 0 0 Figure 2.4 Input Buffer Control Register.
Before configuring a pin as an input from a peripheral, the ICR must be enabled. To enable the ICR set PORTx.ICR.BIT.Bn (x 0 to 5, A to E; and n 0 to 7) to 1. If a pin has to be configured as an output pin, set PORTx.ICR.BIT.Bn (x 0 to 5, A to E; and n 0 to 7) to 0. Setting ICR to 0 disables the ICR. While setting the ICR, make sure that the correspon- ding pin is not in use. For example, when setting IRQi (i 0 to 15) as input, first disable the interrupts, next enable ICR and then enable interrupts. It is necessary to follow the above steps to avoid unintended operations from taking place.
Open Drain Control Register (ODR) Most output pins function as CMOS but some output pins can operate as CMOS or NMOS open- drain pins. Since NMOS circuits are faster compared to the CMOS circuits, which consist of the slower p- channel transistors, using NMOS open- drain pins as outputs would be similar to a wired- OR connection. All of the pins of port 0, 1, 2, C and pins 0 to 4 of port 3 are capable of functioning as NMOS open- drain output pins. Setting PORTx.ODR.BIT.Bn (x 0 to 5, A to E; and n 0 to 7) to 1, selects the pin as an NMOS open- drain pin. 16 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
Pull-Up MOS Control Register (PCR) Some devices have limited signal swing. When such a device is interfaced with the RX62N board, the signal from the device has to be pulled up so that it is in the valid voltage range of the board (this is not the typical usage, the typical usage is the external de- vice is only capable of pulling down; or there is nothing attached and you do not want the port to float). To simplify this kind of interfacing, pull- up MOS circuitry is available for ports A to E. To enable pull- up MOS for a particular pin of a port, set PORTx.PCR.BIT.Bn (x 0 to 5, A to E; and n 0 to 7) to 1. To disable pull- up MOS, set PORTx.PCR.BIT.Bn (x 0 to 5, A to E; and n 0 to 7) to 0. The PCR is automatically disabled for pins configured as outputs. To enable or disable pull- up MOS for multiple pins use PORTx.PCR.BYTE command. The value of the PCR after reset is 0x00.
2.2.2 Example 1: Reading Switches to Control LEDs
Using LEDs as Outputs LEDs require a current- limiting resistor so that they do not draw too much current from the I/O pin to which they are connected. Most microcontrollers can sink more current than they can supply, so generally LEDs are connected with the cathode to the microcontroller pin, and a current- limiting resistor between the anode and supply voltage. Formula 2.1 shows how to calculate the value of the current limiting resistor. Figure 2.5 shows the two ways of connecting LEDs to a microprocessor.
R (VOutput VLED)/ILED Formula 2.1
R5F211A1DD 5 VSS/AVSS LED2 R2 18 P1_0/AN9/KI01/CMP0_0
17 GND P1_1/AN8/KI0/CMP0_0 15 P1_2/AN10/K12/CMP0_2 14 P1_3/ANN11/KI3/TZOUT 13 P1_4/TXD0 12 P1_5/RXD0/CNTR01/INI11 11 P1_6/CLK0/SSIO1 10 P1_7/CNTR00/INI10 19 P3_3/TCIN/INI3/SSI00/CMP1_0
Figure 2.5A The microprocessor is sourcing current to an LED. Turning on this LED requires a logical HIGH signal on the output pin. If the LED is attached to Port D, Pin 0, and that pin is set to an output; then the code needed to turn the LED on would be: PORTD.DR.BIT.B0 = 1; CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 17
R5F211A1DD 5 VSS/AVSS R2 18 P1_0/AN9/KI01/CMP0_0
17 VCC P1_1/AN8/KI0/CMP0_0 15 LED1 P1_2/AN10/K12/CMP0_2 14 P1_3/ANN11/KI3/TZOUT 13 P1_4/TXD0 12 P1_5/RXD0/CNTR01/INI11 11 P1_6/CLK0/SSIO1 10 P1_7/CNTR00/INI10 19 P3_3/TCIN/INI3/SSI00/CMP1_0
Figure 2.5B The microprocessor is sinking current from the LED. Turning on the LED requires a logical LOW on the output pin. If the LED is attached to Port D, Pin 0, and that pin is set to an output; then the code needed to turn the LED on would be: PORTD.DR.BIT.B0 =0;
Using Switches as Inputs A simple interfacing design can include using a pull- up resistor on a pin that is also con- nected to ground through a button or switch. The resistor will pull the voltage on that pin to logic HIGH until the button connects to ground. When the button is pressed, the voltage at that pin will drop to zero (logic LOW). Figure 2.6 shows a schematic of this approach. If the switch in Figure 2.6 is connected to Port D pin 0, the code to check this switch would be:
1. if(PORTD.PORT.BIT.B0 == 0){ 2. //Conditional code goes here 3. }
VCC
R5F211A1DD
5 R19 VSS/AVSS 18 P1_0/AN9/KI01/CMP0_0 17
P1_1/AN8/KI0/CMP0_0 2 15 P1_2/AN10/K12/CMP0_2 14 P1_3/ANN11/KI3/TZOUT 1 13 S1 P1_4/TXD0 12 P1_5/RXD0/CNTR01/INI11 11 P1_6/CLK0/SSIO1 10 P1_7/CNTR00/INI10 19 GND P3_3/TCIN/INI3/SSI00/CMP1_0 20 P3_4/SCS/SCA/CMP1_1
Figure 2.6 Basic button connection to a microprocessor input pin. 18 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
Contact bounce is a worry with any mechanical switch. When the switch is closed, the mechanical properties of the metals in the switch cause the contacts to literally bounce off of one another. This can cause false signals to be read as inputs. Your design should take this into account with either a hardware or software debouncing solution. Hard- ware debouncing circuits often require digital logic as well as some resistors and ca- pacitors. Hardware debouncing circuits are very useful for interrupt pins. Software de- bouncing is accomplished by setting up a timer to check the state of the switch at a set interval, such as every 1 ms. If the value of the input has been the same for the duration of the timer (1 ms in this case) the input can be considered valid. This method helps to ignore false input values. To better understand configuring I/O pins let us look at an example. The RX62N board has three push buttons and twelve LEDs (six red and six green). Switches and LEDs are simple I/Os and in the following program we will see how to set up switches as inputs and LEDs as outputs. According to this program, when switch1 is pressed, green LEDs will glow, when switch2 is pressed, red LEDs will glow, and when switch3 is pressed, all the LEDs will glow.
1. #include “iodefine_RX62N.h” 2. #ifdef YRD_RX62N 3. #define LED1 PORTD.DR.BIT.B0 4. #define LED2 PORTD.DR.BIT.B1 5. #define LED3 PORTD.DR.BIT.B2 6. #define LED4 PORTD.DR.BIT.B3 7. #define LED5 PORTD.DR.BIT.B4 8. #define LED6 PORTD.DR.BIT.B5 9. #define LED7 PORTD.DR.BIT.B6 10. #define LED8 PORTD.DR.BIT.B7 11. #define LED9 PORTE.DR.BIT.B0 12. #define LED10 PORTE.DR.BIT.B1 13. #define LED11 PORTE.DR.BIT.B2 14. #define LED12 PORTE.DR.BIT.B3 15. #define LED1_DDR PORTD.DDR.BIT.B0 16. #define LED2_DDR PORTD.DDR.BIT.B1 17. #define LED3_DDR PORTD.DDR.BIT.B2 18. #define LED4_DDR PORTD.DDR.BIT.B3 19. #define LED5_DDR PORTD.DDR.BIT.B4 20. #define LED6_DDR PORTD.DDR.BIT.B5 21. #define LED7_DDR PORTD.DDR.BIT.B6 22. #define LED8_DDR PORTD.DDR.BIT.B7 23. #define LED9_DDR PORTE.DDR.BIT.B0 24. #define LED10_DDR PORTE.DDR.BIT.B1 CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 19
25. #define LED11_DDR PORTE.DDR.BIT.B2 26. #define LED12_DDR PORTE.DDR.BIT.B3 27. #define LED_ON 1 28. #define LED_OFF 0 29. #define ALL_LEDS_ON {LED1 = LED2 = LED3 = LED4 = LED5 = LED6 = LED7 = LED8 = LED9 = LED10 = LED11 = LED12 = LED_ON;} 30. #define ALL_LEDS_OFF {LED1 = LED2 = LED3 = LED4 = LED5 = LED6 = LED7 = LED8 = LED9 = LED10 = LED11 = LED12 = LED_OFF;} 31. #define ENABLE_LEDS {LED1_DDR = LED2_DDR = LED3_DDR = LED4_DDR = LED5_DDR = LED6_DDR = LED7_DDR = LED8_DDR = LED9_DDR = LED10_DDR = LED11_DDR = LED12_DDR = 1;} 32. #endif 33. #define SW1 PORT4.PORT.BIT.B0 34. #define SW2 PORT4.PORT.BIT.B1 35. #define SW3 PORT4.PORT.BIT.B2 36. #define ENABLE_SWITCHES {PORT4.DDR.BIT.B0 = PORT4.DDR.BIT.B1 = PORT4.DDR.BIT.B2 = 0;} 37. void main(void){ 38. ENABLE_LEDS; 39. ENABLE_SWITCHES; 40. while(1){ 41. if(SW1 == 0){ 42. LED12 = LED11 = LED10 = LED6 = LED5 = LED4 = LED_ON; 43. } else if(SW2 == 0){ 44. LED9 = LED8 = LED7 = LED3 = LED2 = LED1 = LED_ON; 45. } else if(SW3 == 0){ 46. ALL_LEDS_ON; 47. } else { 48. ALL_LEDS_OFF; 49. } 50. } 51. }
In line 1, the file ‘iodefine_RX62N.h’ has been included. It is a custom header file created by Renesas for easy access and manipulation of data. The RX62N board has two sets of LEDs: RSK_RX62N LEDs which are used to indicate basic functions like power on, and YRD RX62N LEDs which are used to simulate a motor. This program uses the YRD RX62N LEDs to demonstrate the use of digital I/O pins. Line 2 and line 32 are used to indicate that the statements between them should be executed only for YRD RX62N LEDs. All pins of Port D and pins 0 to 3 of Port E are the LED pins. The three switches are at Port 4 bits 0 to 2. 20 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
In main, first the LEDs have been enabled (line 38). ENABLE_LEDS is a macro de- fined earlier in the program (line 31) to set the Data Direction Register (DDR) of the LEDs to 1; i.e., set up the LED pins as output pins. Next, the switches have been enabled (line 39). ENABLE_SWITCHES is another macro defined earlier (line 36) to set the Data Direction Register (DDR) of the switches to 0; i.e., set up the switch pins as output pins. The next part of the program is an important part of many embedded systems—the while (1) loop (line 40). This loop makes the microcontroller execute all the statements within the loop repeatedly until the microcontroller is stopped by an external force (e.g., power off). In this program, the conditions for LED operation are given within the while (1) loop using if- else statements (lines 41 to 47). Even though use of the switch statement will result in much better code, the if- else statement has been used for easy understanding.
Ⅲ If switch 1 is pressed (state of switch 1 is low), all the green LEDs are turned on (line 42). The state of the switch is checked using the macro defined in line 33 us- ing the PORT register. From the schematic of the board it can be seen that green LEDs are LED 12, 11, 10, 6, 5, and 4. They are turned on by setting the Data Register (DR) of the LED pins to 1 (active high) which has been defined using the macro LED_ON in line 27. Ⅲ If switch 2 is pressed (state of switch 2 is low), all the red LEDs are turned on (line 44). The state of the switch is checked using the macro defined in line 34 us- ing the PORT register. From the schematic of the board it can be seen that red LEDs are LED 9, 8, 7, 3, 2, and 1. They are turned on by setting the Data Register (DR) of the LED pins to 1 (active high) which has been defined using the macro LED_ON. Ⅲ If switch 3 is pressed (state of switch 3 is low), all the LEDs are turned on (line 46) using the macro LED_ON. Ⅲ If none of the switches are pressed (line 47) all the LEDs are turned off using the macro LED_OFF (line 48).
2.2.3 Driving Motors and Coils
Input/Output (I/O) pins on a microcontroller have specific limits to the amount of current each pin can sink or source. These limits are found in the datasheet. Voltage levels can also be different between sensors and the microcontroller. Both of these constraints must be taken into account when designing interfaces for the actuator. Because of their large coils, motors draw a lot of current. For Direct Current (DC) mo- tors, simple transistor drivers or H- bridges (shown in Figure 2.7) can be used to interface them with a microcontroller. If the left input of the circuit in Figure 2.7 is connected to CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 21
Port D pin 0 and the right input of this circuit is connected to Port D pin 1, the code to turn the motor one direction would be:
1. PORTD.DDR.BYTE = 0x03; //Sets pins 0 and 1 on Port D as outputs 2. PORTD.DR.BYTE = 0x02; //Sets one pin as HIGH and the other as LOW
Stepper motors can use transistors or stepper motor driver ICs. Some ICs such as the L293 or the 754410 are specifically designed to drive the DC motors and interface directly with a microcontroller. Servos are gearboxes that have motor control circuitry built in. These devices can often connect their control pins directly to a microprocessor as their in- ternal circuitry handles driving the motor itself. Other large coils such as relay coils should be treated similarly to motors. Figure 2.8 shows a basic coil driving circuit. Code to drive the coil is the same as it is to drive an LED.
Vout
Q2 Q4 R17 2N3906 2N3906 R18
MOTOR
Q1 Q3 2N3904 2N3904
GND
Figure 2.7 H- bridge motor driver. Two if the microprocessor’s outputs are connected to the resistors. Note: Both inputs should not be the same value for the motor to turn. 22 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
Vout
R5F211A1DD R20 5 VSS/AVSS L1 2 18
P1_0/AN9/KI01/CMP0_0 D1 1N4004 17 P1_1/AN8/KI0/CMP0_0 15 P1_2/AN10/K12/CMP0_2 14 T2 P1_3/ANN11/KI3/TZOUT 1 13 2N3904 P1_4/TXD0 12 P1_5/RXD0/CNTR01/INI11 11 P1_6/CLK0/SSIO1 R16 10 P1_7/CNTR00/INI10 19 P3_3/TCIN/INI3/SSI00/CMP1_0 20 P3_4/SCS/SCA/CMP1_1 1 P3_5/SSCK/SCL/CMP1_2 2 GND P3_7/CNIR0/SSO/IXD1
Figure 2.8 A simple coil driver.
There are other methods of controlling large loads with a microprocessor, such as using re- lays or triacs. The overall concept with all load driving circuits is to keep the source and sink currents of the microprocessor within the manufacturer’s recommendations. Some sensors may require different voltages than what the microprocessor requires. Care should be taken when interfacing these sensors. If the microprocessor runs at 5 V and the sensor runs at 1.8 V, the microprocessor will not be able to read a HIGH logic signal on the sensor output. Circuits for interfacing with higher voltage sensors can be designed us- ing transistors or by using level converter ICs, which convert the signals between the mi- crocontroller and the sensor either uni- directionally or bi- directionally (in case the micro- processor needs to communicate to the sensor.) The use of a flyback diode is very important when interfacing inductive loads, to safely dissipate the voltage spike when the voltage to the load is removed.
2.2.4 Scanning Matrix Keypads
Keypads work as a matrix of buttons. For instance, Figure 2.9 shows an example keypad matrix. The top three output pins are used as the columns of the matrix. The three pins con- nected as the rows of the matrix are all input pins. A button is placed in the circuit at each intersection of a column and row. One at a time, the output pins turn on and each of the in- put pins is read. If an input is detected, the microprocessor can determine which button on the keypad had been pressed. For example, if the microprocessor noted an input on the CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 23 middle row pin at the time in which the middle output was logic HIGH, then the center button must have been pressed. If the columns in Figure 2.9 are connected to Port D bits 0, 1, and 2 respectively, and the rows are connected to Port E bits 0, 1, and 2 respectively; code to read the keypad values of the first column would be:
1. PORTD.DR.BIT.B0 = 1; //Set the output of the first column to 1 2. PORTD.DR.BIT.B1 = 0; //Set the output of the second column to 0 3. PORTD.DR.BIT.B2 = 0; //Set the output of the third column to 0 4. 5. if(PORTE.PORT.BIT.B0 == 0){ 6. //Conditional code for Row 0 7. } 8. 9. if(PORTE.PORT.BIT.B0 == 0){ 10. //Conditional code for Row 1 11. } 12. 13. if(PORTE.PORT.BIT.B0 == 0){ 14. //Conditional code for Row 2 15. }
R5F211A1DD 5 VSS/AVSS 18 P1_0/AN9/KI01/CMP0_0 17 P1_1/AN8/KI0/CMP0_0 15 P1_2/AN10/K12/CMP0_2 14 P1_3/ANN11/KI3/TZOUT 13 P1_4/TXD0 1 2 1 2 1 2 12 P1_5/RXD0/CNTR01/INI11 S2 S7 S8 11 P1_6/CLK0/SSIO1 10 P1_7/CNTR00/INI10 19 P3_3/TCIN/INI3/SSI00/CMP1_0 1 2 1 2 1 2 20 P3_4/SCS/SCA/CMP1_1 1 S3 S6 S9 P3_5/SSCK/SCL/CMP1_2 2 P3_7/CNIR0/SSO/IXD1 P4_2/VREF 16 1 2 1 2 1 2 P4_5/INI0/HXD1 9 P4_6/XIN 6 S4 S5 S10 P4_7/XOUT 4
MODE 8
Figure 2.9 Keypad button matrix. 24 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
2.3 INTERFACING WITH ANALOG SIGNALS
The world is not digital; it is analog. Microphones, thermometers, speakers, light sensors, and even video cameras are all analog sensors. As a result, the signals from these sensors must be converted to digital values so that the microcontrollers can process them.
2.3.1 Analog to Digital Converters
To read the value of an analog sensor, Analog to Digital Converters (also referred to as ADC, A/D, A- to- D, and A2D) are used. This circuit produces a multi- bit binary number based on a voltage scale. The number of bits in the multi- bit binary number helps determine the resolution or precision of the reading; 8-bit, 10-bit, and 12-bit converters are commonly used. ADCs also require a reference voltage. This is a stable voltage to which the current reading will be com- pared to produce the binary output. The analog reference voltage is scaled by the resolution. Most ADCs use linear scales, so converting the values is straightforward. Figure 2.10 shows the transfer function which is used to convert an analog voltage (measured on the horizontal axis) to its digital output code representation (on the vertical axis). Each step on the transfer function represents one least- significant bit. Figure2.11 shows an example input analog volt- age which is sampled over time.
The resolution of the conversion is determined by Formula 2.2.
Nbits Resolution VLSB Vref /2 Formula 2.2
“3.0V” 11 1 LSB “2.0V” 10
“1.0V” 01 Output Code
“0.0V” 00 1.0V 2.0V 3.0V 4.0V
Input Voltage
Figure 2.10 2-bit ADC conversion chart. The stair step line shows the ADC’s output code. CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 25 Digital Value
Time
Figure 2.11 ADC readings over time.
If Vref 5 V, and there is an 8-bit resolution, the volts per ADC raw value step 5 V/256 0.01953 V/step. To determine the value of the conversion, Formula 2.3 can be used:
Nbits ADC output code int (((2 1) * (Vin /Vref) 1/2 Formula 2.3
For example:
Vref 5 V, Vin 2.26295 V, with a 10-bit resolution; int ((1023 * (2.26295 V/5 V)) 1/2) 463 ADC raw value steps.
Once the raw ADC value is known, the application software should reverse the formula to calculate the actual voltage on that pin. Since the datasheet for most sensors provides a for- mula for converting the voltage to the unit the sensor is measuring (be it degrees Celsius, distance in centimeters, pressure in kilopascals, etc.), this formula can be inserted into the firmware to make sense of the data. More advanced sensors use a communication protocol such as RS- 232, RS- 485, I2C, and SPI. These sensors generally take an analog value, convert it to digital, and then send it to the microcontroller for processing using a communication protocol. These protocols sometimes allow for multiple sensors to be connected to the same pins of the microcontroller.
2.3.2 Analog Comparator
Some microcontrollers may contain one or more comparator circuits. This circuit can be thought of as a simple 1-bit analog to digital converter. It compares an analog voltage input with an analog reference voltage, and then determines which is larger. 26 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
2.3.3 Digital to Analog Conversion
Just as we must convert analog signals to digital to process them, sometimes there is a need to convert digital signals to analog. In systems that control audio, speed, or even light lev- els; digital output from a microprocessor must be converted into an analog signal. There are several different methods for converting digital signals to analog.
Resistor Networks Resistor networks allow a very simple solution for converting digital signals to analog. There are many methods of using resistor networks for DACs, but two designs are pre- dominantly used.
Binary Weighted DACs Resistor networks are another simple method for DAC conversion. Several different methods are available for using resistor networks, and again it is up to the designer to
R5F211A1DD 5 VSS/AVSS 18 P1_0/AN9/KI01/CMP0_0 17 P1_1/AN8/KI0/CMP0_0 R4 15 P1_2/AN10/K12/CMP0_2 14 P1_3/ANN11/KI3/TZOUT 13 P1_4/TXD0 R5 12
P1_5/RXD0/CNTR01/INI11 Vout 11 P1_6/CLK0/SSIO1 10 P1_7/CNTR00/INI10 R6 19 P3_3/TCIN/INI3/SSI00/CMP1_0 20 P3_4/SCA/SCD/CMP1_1 R7 1 P3_5/SSCK/SCL/CMP1_2 2 P3_7/CNIR0/SSO/IXD1 P4_2/VREF 16 P4_5/INI0/HXD1 9 P4_6/XIN 6 P4_7/XOUT 4
MODE 8 RESET 3 VCC/AVCC 7 IC5
Figure 2.12 4-bit binary weighted network DAC design. Source: Kester, W. A., and Analog Devices, Inc., Data Conversion Handbook, 2005, page 153–159. CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 27 decide which method is best for a particular design. Voltage- Mode Binary Weighted DACs are commonly used with microcontroller circuits. In this design, resistors are connected together on one end (the analog output), and the other ends are connected di- rectly to the pins of a microcontroller port. The values of the resistors are based on bi- nary bit place- values (R, 2R, 4R, 8R, etc.; with R being the least significant bit or LSB). When the pins of the microcontroller are set to HIGH, then the sum voltage of the ana- log output are related to the value on that port. Figure 2.12 shows an example of a 4-bit Binary Weighted DAC.
R- 2R DAC Another method of using resistor networks to design a DAC is called the R- 2R or R/2-R Net- work. It consists of resistors of only two values. One value is twice the value of the other. For instance, if the R resistors are one kilo- ohm, then the 2R resistors must equaltwo kilo- ohms. Figure 2.13 shows an example R- 2R network (Kuphaldt, T. R., “The R2-R,”).
R5F211A1DD GND 5 VSS/AVSS
18 R15 P1_0/AN9/KI01/CMP0_0 17 P1_1/AN8/KI0/CMP0_0 R8 15
P1_2/AN10/K12/CMP0_2 R9 14 P1_3/ANN11/KI3/TZOUT 13 P1_4/TXD0 R10 12 P1_5/RXD0/CNTR01/INI11 11 R11 P1_6/CLK0/SSIO1 10 P1_7/CNTR00/INI10 R12
19 R13 P3_3/TCIN/INI3/SSI00/CMP1_0
20 Vout P3_4/SCS/SCD/CMP1_1 R14 1 P3_5/SSCK/SCL/CMP1_2 2 P3_7/CNIR0/SSO/IXD1 P4_2/VREF 16 P4_5/INI0/HXD1 9 P4_6/XIN 6 P4_7/XOUT 4
MODE 8 RESET 3 VCC/AVCC 7 IC6 Figure 2.13 R- 2R network. R9, R11, and R13 are considered “R” resistors and all 1kohm while R8, R10, R12, R14, and R15 are considered “2R” and all 2kohm. Source: “The R2-R,” in Kuphaldt, T. R., All about Circuits, http://www.allaboutcircuits.com/vol_4/chpt_13/2.html 28 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
Figure 2.14 An example PWM signal. If this were controlling an active- high LED, the LED would be brighter during the first half of the graph, and dimmer over the second half.
As with the binary weighted DAC, the output voltage corresponds to the binary value on the port. The following example is valid for both R- 2R as well as Binary Weighted DACs: If the Vref is 5 V and there is a 4-bit binary value 1001 (decimal number 9) on the mi- crocontroller pins, we would expect the output voltage to be:
N Vout (Vref /(2 )) * (binary value of microcontroller output) Formula 2.4
For example: (5 V / 16 bits) * (9) 2.8125 V.
Pulse Width Modulation A common method for controlling the speed of a simple DC motor or the brightness of an LED is Pulse Width Modulation. Pulse Width Modulation works as a DAC by changing the duty cycle of an oscillating digital output as shown in Figure 2.14. In the case of an LED, the more time the duty cycle is HIGH, the brighter the LED. This method works in cases where the oscillating frequency is so fast that the resulting output seems smooth. The LED is actually turning on and off several times per second; however, the human eye can- not detect the inde pen dent flashes of the LED due to their speed. Motor speed can be con- trolled this way because the inertia of the spinning armature carries the motor forward through the moments when no power is applied.
2.4 INFRASTRUCTURE: POWER, CLOCK, AND RESET
2.4.1 Power Supply
When designing the power supply for an embedded system, the designer must determine how to power peripherals and whether or not they will use a separate supply. This decision will affect the overall design requirements of the power supply. This chapter only ad- dresses the power supply for the microprocessor itself. CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 29
Voltage and current ratings for the microprocessor can be found in the manufacturer’s datasheet for the chip, often under the title of Recommended Operating Conditions or Electrical Characteristics. Another section in the datasheet also shows Absolute Maximum Ratings, which should be considered but not confused with the recommended values. To be assured that the chip will operate as expected, a system should never be designed to operate too close to the absolute maximum or minimum power ratings. Fluc- tuations in the power supply may cause the values to go over the absolute maximum ratings of the chip, which can damage the microprocessor. The power supply should be designed with a safety factor to account for these fluctuations, hence the recommended values. Once the requirements are determined, the source of the power must be determined. Whether the design plugs into the wall or if it uses batteries will determine the type of power supply circuit. If the design uses mains power, then a standard design method for a power supply cir- cuit can be used. This design will require a transformer to drop the voltage to an acceptable range for a voltage regulator chip. Capacitors will be required to smooth out any ripple or noise. If batteries are to be used, then the type of battery (NiCad, NiMH, LiPo, etc.) must be selected based on the current rating each battery type can supply, and whether the design will need to be rechargeable. The length of time a battery will last can be calculated based on the capacity of the bat- tery and the amount of current the circuit uses using Formula 2.5.
Battery Life (hours) Capacity (amp- hours) / current (amps) Formula 2.5
An 800 mAh battery will power a device that draws 200 mA for;
800 mAh / 200 mA 4 hours
Putting batteries in parallel adds their current capacities. Putting them in series adds their voltages. For two batteries with each 1.5 V and 2000 mAh:
Series: 1.5 V 1.5 V 3.0 V at 2000 mAh Parallel: 2000 mAh 2000 mAh 1.5 V at 4000 mAh
If the batteries need to be recharged, then a battery charging circuit as well as battery level monitor will also need to be designed. Regardless of which batteries are chosen, a voltage regulator of some type is generally required. The use of linear or switch- mode voltage regulator integrated circuits (ICs) is a standard practice. 30 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
2.4.2 Clock Signal Generation
Microprocessors are synchronous circuits that require a clock to work. This clock allows data to be pushed through the stages of the instruction pipeline and helps the microproces- sor coordinate tasks. When selecting a clock generator, the microcontroller datasheet must be used. This datasheet gives the values of the different clocks that a particular micro- processor can accept. There are two major types of clock signal generators: those that work on purely electrical principles, and those that work on mechanical vibration (resonance of a quartz element). The signal generators for the electrical driven clock can be simple resistor- capacitor (RC) or inductor- capacitor (LC) circuits. Generally, these clocks aren’t very accurate on their own, and their design can become quite complicated when precision is required. Many microprocessors offer signal generators with an internal clock that consists of an RC circuit inside the chip, which can be configured. These clocks should not be used when precision is required. Figure 2.15 shows the connection of an RC oscillator to the clock input of a microprocessor.
19 VCC P3_3/TCIN/INI3/SSI00/CMP1_0 20 P3_4/SCS/SCA/CMP1_1 1 P3_5/SSCK/SCL/CMP1_2 2 P3_7/CNIR0/SSO/IXD1 P4_2/VREF 16 P4_5/INI0/HXD1 9
P4_6/XIN 6 R3 P4_7/XOUT 4 C1 MODE 8 RESET 3 VCC/AVCC 7 U3
GND Figure 2.15 RC clock generator.
Clock signal generators that are mechanically driven use a quartz crystal to produce a steady signal. These oscillators rely on the piezoelectric effect of the crystal. This method of clocking is accurate (around 30 parts per million or about 0.003% error), cheap, and widely available. Generally, two small load capacitors are required between each lead of the crystal and ground. The values of these capacitors are based on the crystal characteris- tics and are listed in the crystal’s datasheet. CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 31
19 P3_3/TCIN/INI3/SSI00/CMP1_0 20 P3_4/SCS/SCA/CMP1_1 1 P3_5/SSCK/SCL/CMP1_2 2 P3_7/CNIR0/SSO/IXD1
P4_2/VREF 16 C3
P4_5/INI0/HXD1 9 GND
P4_6/XIN 6 Y1 P4_7/XOUT 4
MODE 8
RESET 3 C2
VCC/AVCC 7 GND U4 Figure 2.16 Connection of a crystal clock generator chip.
Ceramic resonators are growing in popularity for use as a clock generator. The res- onators use a piezoelectric ceramic element that is not as accurate as quartz, yet more ac- curate than RC circuits. They also contain the appropriate load capacitors built in so they do not require any additional components to work. External clock generator integrated circuit chips can also be used. These clocks use a quartz or RC circuit as a resonant oscillator, but also contain an amplifier. The frequency can be changed by reprogramming the clock generator. The duty cycle is also selectable for use in cases where a 50 percent duty cycle cannot be used. These circuits are usually more expensive when compared to other oscillators.
2.4.3 Reset Circuit
Resetting a microprocessor starts the processor off in a predictable state. When a reset is detected, the microprocessor loads predefined values into the system control registers. These registers are useful in case of a catastrophic event, such as if the power supply were to drop below a certain threshold. All microprocessors designate a pin that is solely used for resetting the chip. A reset circuit controls this pin to assure a reset is valid if it is used. The requirements of a reset circuit is specific to the microprocessor being used and can be found in the manufacturer’s datasheet. Some microcontrollers contain reset logic inter- nally; however, the manufacturer’s datasheet should be consulted to make sure it meets the specifications for your application. Alternatively, reset controller chips can be used which contain all the parts necessary for the circuit. Even though they are generally more expen- sive in some cases, such as low- volume productions, it may be best to use reset controller chips. 32 EMBEDDED SYSTEMS USING THE RENESAS RX62N MICROCONTROLLER
2.5 RECAP
It should now be easier to understand how the embedded systems you encounter in your everyday life actually operate and communicate with the outside world. It should also be easier to break some of these systems down into their component parts, given the knowl- edge of sensor and actuator interfacing presented in this chapter.
2.6 REFERENCES
Kester, W. A., and Analog Devices, Inc. Data Conversion Handbook. Lawrence, KS: Newnes, 2005: pp. 153–159. Print. Kuphaldt, T. R. “Successive Approximation ADC,” in All about Circuits. Electronic publication. Accessed at http://www.allaboutcircuits.com/vol_4/chpt_13/6.html “The R2-R,” in Kuphaldt, T. R., All about Circuits. Electronic publication. Accessed at http://www. allaboutcircuits.com/vol_4/chpt_13/2.html
2.7 EXERCISES
1. Name ten devices that use an embedded system. 2. Write the C code to set port 4, bits 0 through 3 to be input pins, and port 4, bits 4 through 7 to be output pins. 3. Write the C code to read the data on port 4, bits 0 through 3 and write the read data to port 4, bits 4 through 7. 4. How long will a 2500 mAh battery last if the circuit using it runs at 600 mA? 5. You have a wireless sensor node whose current drain is 50 mA for one minute every one hour and 0.001 mA the rest of the time. I am using a single 5000 mAh cell as the power supply for this device. How long will my device run in hours, days, and years? 6. What are the different kinds of clock generators? Define their base technologies. 7. What resistor value should be used to connect an LED with a forward voltage of 3.1 volts and a forward current of 20 mA to the input pin of a microcontroller that outputs 5 volts? 8. Is it generally safe to connect a coil or motor directly to a microcontroller I/O pin? Why or why not? 9. Is it generally safe to connect a servo control input directly to a microcontroller I/O pin? Why or why not? CHAPTER 2 / CONCEPTS OF MICROCONTROLLERS 33
10. How many volts per ADC step are in a system with an ADC resolution of 10-bits, and a reference voltage of 3.3 V? 11. How many volts per ADC step are in a system with an ADC resolution of 12-bits, and a reference of 5 V? 12. An analog input has a voltage of 1.37860. What value will the ADC return if it has an 8-bit resolution and a reference of 4.25 volts? 13. An analog input has a voltage of 7.61245. What value will the ADC return if it has a 12-bit resolution and a reference of 10 volts? 14. Using a binary- weighted DAC, using 8 bits and a reference of 4.35 volts, what is the voltage of the output if the 8-bit value is 01011010?
Chapter Three
Organization and Architecture of the Renesas RX62N Microcontroller Board
3.1 LEARNING OBJECTIVES
In this chapter the reader will learn about: