Embedded Systems: : Design, Programming and Applications [1 ed.] 9781783320462, 9781842657829

EMBEDDED SYSTEMS discusses the architecture, its basic hardware and software elements, programming models and software e

367 80 3MB

English Pages 396 Year 2014

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Embedded Systems: : Design, Programming and Applications [1 ed.]
 9781783320462, 9781842657829

Citation preview

Amar K. Ganguly

a Alpha Science International Ltd. Oxford, U.K.

Embedded Systems: Design, Programming and Applications 402 pgs. | 129 figs. | 43 tbls.

Amar K. Ganguly Department of Electronics and Communication Engineering Asansol Engineering College Asansol Copyright © 2014 ALPHA SCIENCE INTERNATIONAL LTD. 7200 The Quorum, Oxford Business Park North Garsington Road, Oxford OX4 2JZ, U.K.

www.alphasci.com All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without prior written permission of the publisher. ISBN 978-1-84265-782-9 E-ISBN 978-1-78332-046-2 Printed in India

In loving memory of my wife Mrs. Rina Ganguly

Acknowledgements

I would like to express our deep gratitude to Dr. B. K. Dey, Principal; Registrar; Advisor; Mr. T. K. Ghosh, Director; Mr. T. Singh, Director; Dr. M. G. Tiary, HOD, ECE Department; Asansol Engineering college for their constant encouragement and strong support in writing this book. I am deeply indebted to Professor Alok K. Das and Professor P. Banerjee, Electronics and Telecommunication Engineering Department, Jadavpur University; Prof. Anish Dev, Applied Physics Department, Calcutta University; Dr. S. Kundu, HOD, CSE Department, West Bengal University of Technology; for their constructive suggestions directly or indirectly to improve the book. I am also grateful to Prof. A. K. Aditya, Director NSHM, Durgapur and Dr. Krishnendu Chakraborty, Principal, Kalyani Govt. Engineering College; Mr. Subhashish Maitra, Kalyani Govt. Engineering College; for many constructive suggestions for improving the book. I wish to thank post graduate students of Asansol Engineering College for finding solutions of problems related to the subject included in this book. We also wish to thank Mr. Manik Bhoumik, Asst. Professor, NIT Agartala and Aparna Bhoumik for their encouragement and strong support in writing this book. I am deeply indebted to my wife Mrs. R. Ganguly and my daughter Suparna Bhattacharya for their constant encouragement in writing this book. I am indebted to Mr. Bidyut Patra, Head Librarian, Asansol Engineering College for issuing valuable books and journals related to the subject content of this book. I am grateful to the reviewers of this book for providing their valuable time to review this book. I wish to thank Mr. N. K. Mehra, Publisher and Managing Director, Narosa Publishing House Private Limited for constant encouragement and strong support in writing this book. I am very much grateful to him for taking entire responsibility of publication of this book. I obtained valuable comments from outstanding professionals directly involved in teaching this subject and also engaged in research and development works in educational institutions and industries on this subject. I am really grateful to them. I also expressed my deep gratitude to the

viii

Acknowledgements

authors of numerous papers, articles and books which I have referenced. I also thank my friends and my family for inspiring me in writing this book. It is needless to say that without all the above help and support, the writing and publication of this book would not have been possible. Amar K. Ganguly

Preface

Now-a-days embedded systems are used in our daily life. Embedded systems are used in toys, video games, automatic chocolate-vending machines, mobile phones, smart cards, ATM, network systems and so on. Initially, embedded systems were designed using first generation microprocessor like 8085. Using this microprocessor, the embedded systems had limited applications. Embedded computing system design is a useful skill for many types of product. Automobiles, personal digital assistants (PDAs), and even household appliances make extensive use of embedded systems. Now an Embedded system consists of computer hardware with embedded software which is a dedicated system for applications. It is a hardware platform with microprocessor or microcontroller and input/output devices which support required tasks and implement software that perform the required processing. Designers in many fields must be able to identify where microprocessors can be used, design a hardware platform with I/O devices that can support the required tasks, and implement software that perform the required processing. A microprocessor is a single chip CPU. VLSI technology has allowed us to put a complete CPU on a single chip. Scientists realized that a general purpose computer programmed properly could implement the required function, and that the computer on a chip could then be reprogrammed for use in other products as well. Since integrated circuit design was an expensive and time consuming process, the ability to reuse the hardware design by changing the software was a breakthrough. Automobile designers started making use of the microprocessor soon after single chip CPUs became available. Microprocessors and microcontrollers are available in different levels of sophistications. A microcontroller is a true computer on a chip. It is a general purpose microprocessor with inbuilt RAM, ROM, I/O ports, and timers. A microcontroller has a CPU in addition to a fixed amount of RAM, ROM, I/O ports, and a timer all on a single chip. It is used to read data, perform limited calculations on that data, and control the interfaced devices based on those calculations. The microcontroller stores the program in ROM inbuilt in the microcontroller. Therefore, microcontroller is a single chip microprocessor system which consists of CPU, RAM, ROM serial and parallel I/O ports, timers and interrupts. Following additional circuits are added to microcontrollers to perform some special functions. These circuits are analog to digital converters (ADC), Counter

x

Preface

arrays, Watchdog timers (WDT), Pulse Width Modulation (PWM) circuit, Universal Synchronous and Asynchronous Receiver Transmitter (USART) circuit, Phase Locked Loop (PLL) circuit External bus controllers. For this reason, the microcontrollers are suitable processor for embedded systems. Embedded systems contain processing cores that are typically either microcontrollers or digital signal processors (DSP). The key characteristic, however, is being dedicated to handle a particular task. They may require very powerful processors and extensive communication. Since the embedded system is dedicated to specific tasks, design engineers can optimize it to reduce the size and cost of the product and increase the reliability and performance. Physically, embedded systems range from portable devices such as digital watches and MP3 players, to large stationary installations like traffic lights, factory controllers, or the systems controlling nuclear power plants. Complexity varies from low, with a single microcontroller chip, to very high with multiple units, peripherals and networks mounted inside a large chassis or enclosure. This book is about embedded system design and their applications. The organizations of the chapters are described here. The definition of embedded systems, categories of embedded systems, requirement of embedded systems, embedded hardware unit, embedded software units, embedded software and applications of embedded system are described in Chapter 1. In Chapter 2 all most all embedded processors and characteristics of embedded processor are described. Microcontrollers and classification of microcontrollers are also shown in this chapter. Architecture of digital signal processor (DSP) and its application is described here. I have described design process in embedded system, Challenges in embedded system design, formalization of system design, design examples in Chapter 3. An embedded system is characterized by real time and multi-rate operations in which the system works, reacts to events, interrupts and schedules the system’s functioning in real-time. It controls latencies to meet deadlines. In this chapter latencies are describe elaborately. Microprocessor is the main part of a Real-Time Embedded System (RTES). Microprocessor selection process for embedded systems is discussed here. Now-a-days embedded systems are designed on a single silicon chip using VLSI technology. This chip is known as System on Chips (SoC). SoC is designed on a single silicon chip that has all necessary analog and digital circuits, microprocessor and software. The basic components of SoC are also described here. In Chapter 4, interrupt types and how microprocessor responds to these interrupts in variety of applications are described. Interrupt vector table and its initialization and method of writing interrupt service procedure are described here. Programmable interrupt controller (8259A) is also required for interrupt applications. For this reason, block diagram and operation of 8259 for interruption of execution of normal program are also described. The necessary instructions for operation of 8259 are discussed elaborately in this chapter. Programmable timer/counter 8254 is also required for interrupt applications. For this reason, the operation of 8254 for interruption of execution of normal program is described here. The necessary instructions to initialize programmable timer/ counter 8254 for a specified applications is discussed elaborately in this chapter. The available interrupt of microcontroller 8051 also described here.

Preface

xi

Interfacing is a way to communicate and transfer information in either way without ending into deadlocks. It is process of effective communication in real time which involves addressing, arbitration and protocols. In Chapter 5 the interfacing of embedded microprocessor with real world is described. An interfacing circuit consists of decoders and demultiplexers and is designed according to the available control signals and timing plan of bus signals. The circuit connects all the units like processors, memory I/O bus bridge controller and I/O devices through the system buses and I/O buses. I/O bus bridge controller may be a part of the glue interfacing circuit used in the system. It is also used in Programmable Logic Device (PLD), Generic Array Logic (GAL) and FPGA. These logic circuits are also described in this chapter. Data transmission is an important task of embedded system. For this reason, synchronous or asynchronous, serial or parallel data transmission is described in Chapter 6. EIA standard RS-232C and modem are also described here. Universal asynchronous receiver transmitter (UART - 8250) and Universal synchronous asynchronous receiver transmitter (USART-8251) are also described in this chapter. The activities of embedded systems are taken care of by the Real-Time Operating System software stored on the non-volatile memory of the RTES. This software design of embedded system is described in Chapter 7. Program design of embedded system is simplified by program modeling. The models of software design process of embedded system are discussed in this chapter. Software is required for device drivers and device management in an operating system because an embedded system is designed to do multiple functions. For this reason device management software and device driver software are described in this chapter. This chapter also includes different software tools for designing embedded systems. In this chapter, software design methodology is described elaborately. Use of assembly level language, high level language C, object-oriented language C++ and JAVA are also discussed for embedded software design. A process is an instance of a computer program that is being executed. It contains the program code and its current activity. Inter-process communication is described in Chapter 8. Multitasking, multiprogramming processes, threads and tasks are described here. Use of dynamic data exchange, Primary process states and additional process states are discussed in this chapter. Use of a file mapping, mail slot, pipes, remote procedure call, windows sockets for inter-process communication (IPC) are described here. Communication message-based inter-process communication, semaphores, mutex and real-time kernel; IPC using shared memory and queues are described in this chapter. Real-time is a quantitative notion of time. Real-time is measured using a physical (real) clock. In Chapter 9, the real-time operating system is discussed. In this chapter, a basic conceptual understanding of the underlying hardware of a real-time system is described. Types of real-time tasks are described here elaborately. Real-time and embedded computing applications in the first two computing era were restricted to a few specialized applications such as space and defense. Now the use of computer systems based on real-time and embedded technologies has already touched every facet of our life. Real-time and embedded computing applications in the first two computing era were restricted to a few specialized applications such as space and defense. Now the use of computer systems based on real-time and embedded technologies has already touched every facet of our life. In this chapter, applications of real-time systems are discussed. Safety and reliability

xii

Preface

of an embedded system is described here. Real-time tasks and real-time operating system are also discussed here. Embedded system testing services help fulfill customers’ demand for innovative, higherperforming products while addressing safety-critical issues, time-to-market and cost pressures. The value of embedded systems constitutes the software that runs them. Testing and debugging embedded systems is described in Chapter 10. Simulator software also simulates hardware units. A simulator is always independent of a particular targeted system. Simulator is very much useful during the development phase of application software for the system. For this reason, simulator is described in this chapter. Faults in embedded system are discussed here. Finally, dataflow analysis and testing tools are discussed at the end of this chapter. Ninety three references of books journals and websites are included in this book. The readers may take help of these references for further higher studies in embedded systems. This book is a well structured book on embedded system. It has systematic coverage and logical sequence of all topics of embedded system. Maximum effort has been given to provide correct information codes and tools. Readers are requested to point out error to the author, if any in this book. Amar K. Ganguly E-mail: [email protected]

Contents

Acknowledgements Preface

1. Introduction 1.1 1.2 1.3 1.4 1.5

Embedded Systems Categories of Embedded Systems Embedded Processors Embedded Hardware Units Aembedded Software Objective Type Questions Review Questions Choose the Correct Answer

2. Embedded Processors 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8

Introduction Processors Architecture of Intel 80186/80188 Microprocessors Architecture of Pentium Microprocessor Microcontroller Architecture of 8051 Microcontroller Data Communication Digital Signal Processor Review Questions Choose the Correct Answer

vii ix

1.1 1.1 1.2 1.5 1.14 1.20 1.26 1.27 1.27

2.1 2.1 2.2 2.8 2.13 2.14 2.18 2.33 2.40 2.46 2.48

xiv

Contents

3. Embedded System Design 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15

Introduction Components of an Embedded System Advantage of General Purpose Processor (GPP) Embedded System on Chip (SOC) Field Programmable Gate Array (FPGA) Core Embedding a Processor Memory Design Methodology Structure of an Embedded System Software for Embedded System Design Metrics Challenges in Embedded System Design Input Output Devices and Interfaces Advantages and Disadvantages of Embedded System Formalization Review Questions Choose the Correct Answer

4. Interrupt 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9

Introduction Interrupts of Intel 8085 Microprocessor Interrupts of Intel 8086 Microprocessor Interrupts of 8051 Microcontroller Real-Time Clock Programmable Timer/Counter 8254 Interrupt in Embedded Systems IO-APIC Interrupts PCIe* Interrupt Review Questions Choose the Correct Answer

5. Real World Interfacing 5.1 5.2 5.3 5.4 5.5

Introduction Interfacing the Processor with Memory and I/O Devices Interrupts-Driven I/O Bus Arbitration Processor and Memory Organization

3.1 3.1 3.2 3.5 3.5 3.6 3.7 3.9 3.11 3.15 3.15 3.19 3.20 3.21 3.21 3.22 3.23 3.23

4.1 4.1 4.2 4.17 4.23 4.27 4.28 4.33 4.44 4.45 4.45 4.47

5.1 5.1 5.1 5.7 5.8 5.16

Contents

5.7

Case Studies Review Questions Choose the Correct Answer

6. Programmable Communication Interface 6.1 6.2 6.3 6.4

Introduction Serial Data Transmission Serial Data Transmission Methods and Standards Universal Asynchronous Receiver Transmitter (UART 8250) Review Questions Choose the Correct Answer

7. Software Design 7.1 7.2 7.3 7.4 7.5 7.6 7.7 7.8 7.9

Introduction Software Software Tools for Designing Embedded Systems Software Design Methodology Programming Embedded Systems Features of Assembly Language Assembly Level Language for Embedded Controller 8051 High Level Language Programming C Program Elements Review Questions Choose the Correct Answer

8. Interprocess Communication 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 8.10 8.11

Introduction Process States Multiprogramming Child Process Orphan Process Inter Process Communication Windows Supported Interprocess Communication (IPC) Processor Register States Basic Kernel Services IPC using Shared Memory Communication Semaphores Review Questions

xv 5.17 5.18 5.19

6.1 6.1 6.2 6.4 6.10 6.23 6.25

7.1 7.1 7.2 7.3 7.5 7.5 7.12 7.24 7.29 7.30 7.39 7.42

8.1 8.1 8.1 8.4 8.6 8.6 8.7 8.9 8.20 8.22 8.24 8.38 8.41

xvi

Contents

9. Real-Time Operating System 9.1 9.2 9.3 9.4 9.5 9.6 9.7 9.8 9.9 9.10 9.11 9.12

Introduction Real-Time System Characteristics of Real-Time Systems Types of Real-Time Tasks Task Instance, Task Precedence and Response Time Applications of Real-Time Systems Safety and Reliability Types of Real-Time Tasks Real-Time Operating System Mode Structure of Real-Time Operating Systems Designing Advantages of RTOS for Designing Embedded Systems Review Questions

10. Testing and Debugging Embedded Systems 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11 10.12 10.13 10.14 10.15 10.16 10.17 10.18 10.19

Introduction Testing and Debugging Real-Time Systems Hardware Fault Model Software-Hardware Covalidation Fault Model Core Test Wrapper Online Testing Non-Concurrent Testing Concurrent Testing Test Plan Test Programming and Test Pattern Generation Automatic Test Generation ATPG for Hardware-Software Covalidation Embedded Software Testing Interaction Testing Technique between Hardware and Software in Embedded Systems Non-Testing-Based Verification Empirical Study Objects of Analysis Property-Based Oracles Laboratory Tools for Hardware Testing Review Questions

9.1 9.1 9.1 9.4 9.6 9.8 9.8 9.11 9.16 9.17 9.19 9.20 9.26 9.29

10.1 10.1 10.4 10.7 10.9 10.11 10.13 10.14 10.14 10.14 10.14 10.15 10.15 10.16 10.18 10.18 10.23 10.24 10.25 10.26 10.29

Contents

xvii

Appendix I: Hex Code of 8085 Instructions Appendix II: Instruction Set of 8051 Appendix III: Instructions of 8086/8088

A.1 A.4 A.7

References

R.1

Index

I.1

1 1.1

Introduction

EMBEDDED SYSTEMS

An Embedded system consists of computer hardware with embedded software which is a dedicated system for applications. It is a hardware platform with microprocessor or microcontroller and input/ output devices which support required tasks and implement software that perform the required processing. Embedded system includes programmable computer but not itself a general purpose system. It is any device that includes a programmable computer but is not itself intended to be a general purpose computer. Thus, a PC is not itself an embedded computing system, although PCs are often used to build embedded computing systems. Embedded computing system design is a useful skill for many types of product. Automobiles, personal digital assistants (PDAs), and even household appliances make extensive use of microprocessors. Designers, in many fields, must be able to identify where microprocessors can be used and design a hardware platform with I/O devices that can support the required tasks, and implement software that perform the required processing. The utility of computers, in replacing mechanical or human controllers and to support real time operation, was evident from the very beginning of the computer era. A microprocessor is a single chip CPU. VLSI technology has allowed us to put a complete CPU on a single chip. Scientists realized that a general purpose computer programmed properly could implement the required function, and that the computer on a chip could then be reprogrammed for use in other products as well. Since integrated circuit design was an expensive and time consuming process, the ability to reuse the hardware design by changing the software was a breakthrough. Automobile designers started making use of the microprocessor soon after single chip CPUs became available. Microprocessors and microcontrollers are available in different levels of sophistications. 1. Eight bit microprocessor or microcontroller is used in embedded systems for low cost application and includes on board memory and I/O devices. 2. Sixteen bit microprocessor or microcontroller is used for more sophisticated applications. An embedded system consists of three main components embedded into it. These main components are described on next page.

1.2

Embedded Systems: Design, Programming and Applications

1. The hardware components are similar to computer hardware. The hardware components of embedded system are shown in Fig. 1.1. It does not require any secondary memory like hard disc or CD because its software usually embeds in ROM; 2. Main application software is embedded in the system. This software concurrently performs many tasks or processes or threads; 3. A real time operating system (RTOS) is embedded in a embedded system. RTOS supervises execution of application software. Priorities of tasks are also maintained by RTOS.

Fig. 1.1

1.2

Components of embedded system hardware

CATEGORIES OF EMBEDDED SYSTEMS

Embedded systems are classified into three types. 1. Small scale embedded systems: Eight or sixteen bit microcontrollers are used for smallscale embedded systems. This system is simple and may be battery operated. An editor, assembler and cross assemblers are used for embedded software of small scale embedded systems. If C language is used for programs, executable codes are stored in the system memory. Memory capacity of this type of embedded system should be sufficient to store the software. Small-scale embedded system designer must have good knowledge on following topics. (i) Computer architecture and organizations; (ii) Memories; (iii) Memory allocation; (iv) Interfacing memories; (v) ROM burning; (vi) Use of decoders and demultiplexers; (vii) Direct memory access; (viii) Ports;

Introduction

1.3

(ix) Device drivers in assembly; (x) Timers; (xi) Interrupt servicing mechanism; (xii) C program; (xiii) Memory optimization; (xiv) Selection of hardware and microcontroller; (xv) Debugging software. The designer must also have knowledge on the following topics. (i) Data communication; (ii) Software engineering; (iii) Control engineering; (iv) Motors and actuators; (v) Sensors and transducers; (vi) Measurement and instrumentation; (vii) Analog electronic design; (viii) IC design. 2. Medium scale embedded systems: Sixteen or thirty two bit microcontrollers are used for medium scale embedded systems. This system may also employ the readily available single purpose processor for various functions. Hardware and soft ware of this type of embedded system is complex. Suitable programming tools of medium scale embedded systems are object oriented programming, RTOS, simulator, debugger etc. The medium scale embedded system designer must have knowledge on following topics. (i) C, C++, Java programming; (ii) RTOS programming and program modeling skills; (iii) Tasks or threads and their scheduling by RTOS; (iv) Cooperative and preemptive scheduling; (v) Inter processor communication functions; (vi) Use of semaphores, mailbox, queues, sockets and pipes; (vii) Use of shared data and programming the critical section and re-entrant functions; (viii) Handling of interrupt latencies and meeting task deadlines; (ix) Use of physical and virtual device drivers; (x) Access to an RTOS programming tool with Application Programming Interface (API); (xi) Hardware organization and use of APIs. 3. Sophisticated embedded systems: There are many complexities in sophisticated embedded systems. These embedded systems require Intellectual Property (IPs) core, scalable processors, configurable processors and Programmable Logic Arrays (PLA). IP provides a design for implementing Hyper Text Transfer protocol (HTTP) or File Transfer Protocol (FTP) or Bluetooth protocol to transmit file on internet. It is used for bus control. These

1.4

Embedded Systems: Design, Programming and Applications

embedded systems are used for cutting edge applications which require hardware and software co-design. In this system, software implements some of the functions of the hardware resources. The Sophisticated embedded system designer must have knowledge on following topics. (i) Solution of high level complexities of hardware and software; (ii) Hardware units and programming in C, C++ and Java; (iii) RTOS and other programming tools; (iv) Optimum design solution and system integration.

1.2.1

Requirement of Embedded Systems

Embedded computing is in many ways much more demanding than the sort of programs that you may have written for PCs or workstations. Functionality is important in both general purpose computing and embedded computing, but embedded applications must meet many other constraints as well. Embedded computing systems have to provide sophisticated functionality which is described below. (i) Complex algorithms: The operations performed by the microprocessor may be very sophisticated; (ii) User interface: Microprocessors are frequently used to control complex user interfaces that may include multiple menus and many options; (iii) Real time: Many embedded computing systems have to perform in real-time, if the data is not ready by a certain deadline, the system breaks; (iv) Multirate: Many embedded computing systems have several real-time activities going on at the same time. They may simultaneously control some operations that run at slow rates and others run at high rates. Multimedia applications are prime examples of multirate behavior. The audio and video portions of a multimedia stream run at very different rates, but they must remain closely synchronized. Failure to meet the deadline on either the audio or video portions spoils the perception of the entire presentation. Requirements of embedded systems may be functional or non-functional. We must capture the basic functions of the embedded system, but functional description is often not sufficient. Typical non-functional requirements include following properties. (i) Performance; (ii) Cost; (iii) Physical size and weight; (iv) Power consumption. Functional requirements of embedded systems are listed below. (i) Proper hardware; (ii) Minimum power consumption; (iii) Consideration of upgradeable design; (iv) Complex method of testing; (v) Limited observability and controllability;

Introduction

1.5

(vi) Restricted development environment; (vii) Restricted development environment; (viii) Real-time and multi-rate operations.

1.2.2

Constraints

There are three functional constraints in embedded systems. (i) Processor speed; (ii) System memory; (iii) Power dissipation in run, wait for events, wake-up, sleep and stop cycles. There are following constraints with regard to performance, power, size and design and cost.

1.3

EMBEDDED PROCESSORS

A processor is an important element of the embedded system. It is a programmable logic device which can be used as processing unit or computing unit of a computer. It also has decision making capability by executing a program. The physical components of the microprocessor based systems are called hardware. The set of instructions used for the operation of microprocessor is called software. Actually, different logical circuits of microprocessors are operated by binary numbers 0 or 1 which are called bits. The instructions of microprocessor consist of bits arranged in a suitable pattern. If the instructions are formed by bits then the language of the microprocessor is called machine language. Writing a program in machine language is tedious. For this reason, the instructions are abbreviated to write the program in an easy way. These abbreviated instructions are called mnemonics. The language developed by mnemonics is called assembly level language or assembly language. A set of instructions written for the microprocessor to accomplish a task is called program and a group of program is called software. Microprocessor is manufactured by very large-scale integration (VLSI) technology. It is a clock driven semiconductor device. Microprocessor consists of following three building blocks. 1. Register array; 2. Arithmetic and logic Unit (ALU); 3. Control unit (CU). Figure 1.2 Shows block arrangement of basic microprocessor. The different segments of microprocessor are described below. Arithmetic and Logic Unit (ALU):

Arithmetic and logic unit (ALU) is constructed with logic gates and it is used for mathematical computation and logical decision. As for example, it performs addition, subtraction and logical operation using AND, OR, Ex-OR etc. Register Array:

The registers consist of memory elements. Four bit, 8 bit, 16 bit, 32 bit or 64 bit registers are fabricated in microprocessor. Actually, the microprocessors are named according to its register size. If a microprocessor has registers of 4 bit size then it is called four bit microprocessor. Thus, microprocessor having 8 bit registers is known as eight bit microprocessor. The registers of microprocessors store data temporarily during execution of the program.

1.6

Embedded Systems: Design, Programming and Applications

Arithmetic and logic unit

Register array

Control unit

Fig 1.2

Control Unit (CU):

Block arrangement of basic microprocessor

The control unit controls the operation of microprocessor by providing control signal to different segments of microprocessor. Actually control unit controls the timing of operation of different electronic circuits of microprocessor. Evolution of microprocessor started with an innovative approach of logic design and development of integrated circuit (IC) technology. The integrated circuit technology was developed at four scale of integration as described below. 1. Small-Scale Integration (SSI): The integrated circuit designed with less than one hundred components is called Small-Scale Integration or SSI. This technology is used for fabrication of logic gates in a single chip IC; 2. Medium-Scale Integration (MSI): The integrated circuit designed with less than one thousand but more than one hundred gates is called Medium-Scale Integration or MSI. This technology is used for fabrication of hundreds of logic gates in IC; 3. Large-Scale Integration (LSI): The integrated circuit designed with less than ten thousand but more than one thousand logic gates is called large-scale integration or LSI. This technology is used for fabrication of INTEL 4004 microprocessor; 4. Very Large-Scale Integration (VLSI): The integrated circuit designed with more than ten thousand logic gates is called Very Large-Scale Integration or VLSI. This technology is used for fabrication of INTEL 8085 microprocessors and microcontrollers; 5. Super Large-Scale Integration (SLSI): The integrated circuit designed with more than a million logic gates is called Super Large-Scale Integration or SLSI. This technology is used for fabrication of advanced microprocessors. The first microprocessor was developed by INTEL Corporation in 1971 in the brand name of INTEL 4004. It is a 4 bit microprocessor designed with large scale integration (LSI) technology. The number of instruction of INTEL 4004 instruction set was 45. This microprocessor was fabricated by P-MOS technology. The rate of execution of the instructions by this microprocessor is 50 KIPS (Kilo instruction per second). Many other companies also produced 4 bit microprocessors like PPS- 4 by Rockwell international, T 3472 by Toshiba, TMS 1000 by Texas instruments etc. In 1972, INTEL Corporation produced the first 8 bit microprocessor INTEL 8008. This microprocessor can address an expanded memory size of 16 Kilobytes and 48 instructions

1.7

Introduction

can be used by this microprocessor. In 1973, INTEL Corporation produced the first modern 8 bit microprocessor INTEL 8080. This processor is fabricated by NMOS technology. 8080 microprocessor is ten times faster than 8008 microprocessor. Execution rate of this processor is 500 KIPS. Memory capacity of INTEL 8080 is 64 KB which is four times more than that of 8080. In 1975, INTEL produced the improved version of 8 bit microprocessor INTEL 8085. Execution rate of this processor is 769.23 KIPS. This processor has its own internal clock generator and internal system controller. INTEL 8085 can execute 246 instructions. In the mean time, many other companies introduced 8 bit microprocessor as listed in Table 1.1. Table 1.1 Manufacturer

Chip number

Motorola Corporation

MC 6800 and MC 6809

INTEL Corporation

INTEL 8080, INTEL 8085

Fairchild

F8

Zilog

Z80 and Z800

National semiconductor

NSC 800

Rockwell International

PPS-8

The microprocessor is a clock driven semiconductor device consisting of electronic logic circuits manufactured by using either large scale integration (LSI) or a very large scale integration technique. The age of advanced microprocessor started in 1978 when INTEL introduced a 16 bit microprocessor INTEL 8086. It is a sixteen bit processor. Just after one year, INTEL Corporation released 8088 microprocessor. INTEL 8088 is a sixteen bit processor. Both the processors are almost similar in working principle. These processors can address one Megabyte of memory location and execution speed of 8086 microprocessor is 2.5 million instructions per second (MIPs). The high execution speed and high memory addressing capability of 8086 and 8088 made them very much popular to use these microprocessors in microcomputer applications. The speed of execution of 8086 and 8088 is increased by using instruction queue or cache. Actually, 8086 and 8088 microprocessor pre-fetch few instructions and place them in queue before execution. The instructions of microprocessor consist of bits arranged in a suitable pattern. If the instructions are formed by bits then the language of the microprocessor is called machine language. Writing a program in machine language is tedious. For this reason, the instructions are abbreviated to write the program in an easy way. These abbreviated instructions are called mnemonics. The language developed by mnemonics is called assembly level language or assembly language. A set of instructions written for the microprocessor to accomplish a task is called program and a group of program is called software. INTEL 8086 and 8088 microprocessors have many instructions set. The number of instructions of this microprocessor is about 20,000. These instruction sets are large in number and complex in operation. For this reason, these microprocessors are known as complex instruction set computers (CISC). 8086 and 8088 have more internal registers to provide more storage space than that of

1.8

Embedded Systems: Design, Programming and Applications

8085. The 16 bit registers help to write program efficiently. Thus the first member of the advanced microprocessor family is INTEL 8086 and it is used in sophisticated applications. Large number and complexity of instructions of CISC microprocessor causes reduction in computing speed of microprocessors. For this reason, reduced instruction set computer (RISC) microprocessor is developed to increase computing speed of the microprocessor by decreasing execution time of the instruction using hardwired control unit.

1.3.1

Microprocessors

Different types of processors are used in embedded systems. Figure 1.3 shows the use of different types of processor in embedded systems. 80%

60%

40%

20%

00% 4 bit

4 bit

16 bit 32 bit Processors

64 bit

Special

Fig. 1.3 Use of different types of processor

We shall describe here a 16 bit processor. This microprocessor has two functional units. These functional parts are known as 1. Bus Interface unit (BIU). 2. Execution unit (EU). The BIU performs the following functions. 1. BIU transmits address of instruction and data. 2. It fetches instructions from memory. 3. BIU reads data from input/output ports and memory. 4. BIU writes data to input output/ports and memory. 5. BIU performs the function of all data and address transmission through the buses for execution unit. 6. It generates 20 bit address using 16 bit offset address and content of segment registers. Thus combined functioning of BIU and EU of microprocessor executes instructions of the programs. Bus Interface unit may be called as program flow control unit. This unit includes a fetch unit for fetching instructions from memory. Execution unit sends signal to BIU to fetch instruction or data from desired location. It decodes instructions and executes instructions. The EU includes

Introduction

1.9

the Arithmetic and Logic Unit (ALU). It can also execute instructions for a CALL or branch to another program. The processor runs fetch and execute cycle. A microprocessor is available as an IC chip. Following processor chip can be used in embedded systems. (i) General purpose processor: Microprocessor and embedded processor; (ii) Application Specific Instruction Set Processor (ASIP): ASIP includes microcontroller, embedded microcontroller, Digital signal processor and media processor, Network processor, I/O processor or domain specific programmable processor; (iii) Single purpose processor as additional processor: Coprocessor, Java code accelerator and controllers; (iv) Application specific system processor; (v) Multi-core processor or multiprocessor. The embedded system designer should consider the following properties for selection of processor. (i) Maximum bits in the operand; (ii) Instruction set; (iii) Clock frequency; (iv) Processor’s ability to solve complex algorithms. Considering above four factors general purpose processor (GPP) is the most suitable for embedded system processor. The advantages of GPP are stated below. (i) System development is easy because Processing is based on general purpose instruction set; (ii) I/O interfacing designed for GPP can be used for new system; (iii) Compiler facilities are available for embedded software development in high level language; (iv) Tested and debugged processor specific Application Program Interfaces (APIs) are available. Now-a-days microprocessor includes catches, arithmetic unit, pipelining and super scaling unit. Clock frequency of the processor also increased to 4 GHz. As a result, processing of instructions became very fast. The processors used in embedded system are ARM, 80X86 and SPARC family of microprocessors. If the embedded software is located in external memory, microprocessor is used in embedded system as general purpose processor.

1.3.2

Microcontroller

A microcontroller is a true computer on a chip. It is a general purpose microprocessor with inbuilt RAM, ROM, I/O ports, and timers. A microcontroller has a CPU in addition to a fixed amount of RAM, ROM, I/O ports, and a timer all on a single chip. It is used to read data, perform limited calculations on that data, and control the interfaced devices based on those calculations. The microcontroller stores the program in ROM inbuilt in the microcontroller. Therefore, microcontroller is a single chip microprocessor system which consists of CPU, RAM, ROM serial and parallel I/O ports, timers and interrupts.

1.10

Embedded Systems: Design, Programming and Applications

Following additional circuits are added to microcontrollers to perform some special functions. 1. Analog to Digital Converters (ADC): This electronic circuit is added to convert external signals to digital signals; 2. Counter arrays: A few counter circuits are added to microcontroller for pulse generation; 3. Watchdog Timers (WDT): This timer is used to reset the microcontroller if program execution hangs-up; 4. Pulse Width Modulation (PWM) circuit: PWM circuit is used for speed control of DC Motors; 5. Universal Synchronous and Asynchronous Receiver Transmitter (USART) circuit: This circuit is used for serial data transfer; 6. Phase Locked Loop (PLL) circuit: This circuit is used for synchronous communication; 7. External bus controllers: This circuit is used for controlling the bus system to connect static (RAM/ROM) and dynamic (SDRAM) memories. Uses of microcontrollers

Four bit microcontrollers are low cost microcontrollers. These microcontrollers are extensively used in electronic toys. 4 bit microcontrollers are also used in alphanumeric LED/LCD display drivers and portable battery chargers. Eight bit microcontrollers are the most popular microcontroller in use. Eight bits have proven to be suitable word size for controller tasks. One byte data word is adequate for most of the control and monitoring application. This byte size is also suitable for data communication. These microcontrollers are used in various control applications such as speed control of electric motors, position control and process control system. Sixteen bit microcontrollers are used for high speed control systems. These microcontrollers can be programmed using high level language as well as assembly level language. The 16 bit microcontrollers are used in disc drives, modems, printers, scanners, servo control systems etc. Thirty two bit microcontrollers are used for very high speed intelligent control systems. These microcontrollers can be programmed using high level language as well as assembly level language. The 32 bit microcontrollers are used in image processing, disc drives, modems, printers, scanners, servo control systems etc. Block diagram of 8051 microcontroller

In 1980s, Intel Corporation developed the 8051 microcontroller. This microcontroller is available in N-Channel Metal Oxide Semiconductor (NMOS) and Complementary Metal Oxide Semiconductor (CMOS) construction in variety of package types. The 8051 chip is housed in a 40 pin DIP. The block diagram of 8051 microcontroller is shown in Fig. 1.4. The device is low power static design which offers a wide range of operating frequencies down to zero. Provision of idle mode and power-down mode operations are available in 8051. It operates with the power supply voltage range from 2.7 V to 5.5 V. The unique features of 8051 are internal ROM and RAM, I/O ports with

1.11

Introduction

programmable pins, timers/counters and serial data communication circuits. Table 1.2 shows the special features of 8051. The 8051 architecture shows following CPU components and specific features. 1. Arithmetic Logic Unit (ALU) for mathematical calculations and logical decisions; 2. Registers A and B; 3. Sixteen bit program Counter (PC) and data pointer; 4. Eight bit Program Status Word (PSW); 5. Eight bit Stack Pointer (SP); 6. Internal 4 K X 8 ROM; 7. Internal 128 X 8 RAM; 8. Four register banks, each bank containing 8 registers; 9. Eighty bytes of general purpose data memory; 10. Sixteen bytes which can be addressed at the bit level; 11. Four 8 bit I/O ports, each having 8 pins; 12. Three 16 bit timer/counter; 13. Full duplex serial data Receiver/Transmitter; 14. Six control registers viz., TCON, TMOD, SCON, PCON, IP and IE; 15. Three external and two internal interrupt sources; 16. Oscillator and clock circuits; 17. Boolean processor. Figure 1.4 shows the schematic block diagram of microcontroller 8051. It consists of a central processing unit which obtains the clock signal from an external oscillator as shown in figure. It has inbuilt 4K byte ROM and 128 byte RAM. 8051 has interrupt control unit and bus control unit. Two timers are included in this microcontroller chip. Four 8 bit I/O ports and two serial ports are also included in microcontroller 8051. External interrupts

Timer 1

Interrupt control

128 Byte RAM

4 K Byte ROM

Counter inputs

Timer 0

CPU

Bus control

Oscillator

ALE PSEN

Fig. 1.4

RST

Four I/O ports

Serial port

EA P0

P2

P1

P3

T×D

Schematic block diagram of microcontroller 8051

R×D

1.12

Embedded Systems: Design, Programming and Applications

The microprocessor is a single chip VLSI circuit. It is suitable for embedded systems for real time control applications with on chip memory. Microcontrollers are also available in dual core high computational circuits. Microcontroller chip suitable for embedded systems are 8051, 8051 MX, PIC 16F84, 16C76, 16F876 etc. Special features of 8051 microcontrollers

Table 1.2 shows the special features of 8051 microcontroller. Table 1.2

Special features of 8051

Feature

Quantity

ROM

4 K bytes

RAM

128 byte

Timer

2

Input output pins

32

Serial port

1

Interrupt sources

6

Following additional circuits are added to microcontrollers to perform some special functions. 1. Analog to Digital Converters (ADC): This electronic circuit is added to convert external signals to digital signals. 2. Counter arrays: A few counter circuits are added to microcontroller for pulse generation. 3. Watchdog Timers (WDT): This timer is used to reset the microcontroller if program execution hangs-up. 4. Pulse Width Modulation (PWM) circuit: PWM circuit is used for speed control of DC motors. 5. Universal Synchronous and Asynchronous Receiver Transmitter (USART) circuit: This circuit is used for serial data transfer. 6. Phase Locked Loop (PLL) circuit: This circuit is used for synchronous communication. 7. External bus controllers: This circuit is used for controlling the bus system to connect static (RAM/ROM) and dynamic (SDRAM) memories. Difference between microprocessors and microcontroller is shown in Table 1.3. Table 1.3

Difference between microprocessor and microcontroller Microprocessor

Microcontroller

1. Microprocessor consists of ALU, registers, control unit and buses fabricated on a single chip.

1. Microcontroller consists of ALU, registers, control unit, buses, RAM, ROM, timers/counters, I/O ports and interrupts fabricated on a single chip.

2. Microprocessor contains no RAM, ROM, I/O ports on chip.

2. Microcontroller has CPU in addition to a fixed amount of RAM, ROM, timer, interrupts and I/O ports on the same chip. Contd

Introduction

1.13

Contd

3. The microprocessor system is bulkier and expensive 3. Microcontroller system is cheap due to RAM, ROM, due to addition of external RAM, ROM and periphtimer, interrupts and I/O ports are in inbuilt the same eral chips. chip. 4. Microprocessor system requires large circuitry for operation.

4. Microcontroller system does not require large circuitry for operation.

5. Microprocessor has versatility so that the designer 5. In microcontroller system RAM, ROM and I/O ports can use the RAM, ROM and I/O ports as per their are limited. requirement. 6. Microprocessor is not suitable for many applications in which cost and space are critical.

6. Microcontroller is ideal for many applications in which cost and space are critical.

Now-a-days various types of microcontrollers are available for three categories of embedded systems. Figure 1.5(a) shows commonly used microcontrollers in small-scale embedded systems, Fig. 1.5(b) shows commonly used microcontrollers in medium-scale embedded systems and Fig. 1.5(c) shows commonly used microcontrollers in large-scale embedded systems.

Fig. 1.5(a)

Fig. 1.5(b)

Fig. 1.5(c)

1.3.3

Commonly used microcontrollers in small-scale embedded systems

Commonly used microcontrollers in medium-scale embedded systems

Commonly used microcontrollers in large-scale embedded systems

Single Purpose Processors

Following single purpose processors are used in embedded systems;

1.14 (i) (ii) (iii) (iv) (v) (vi) (vii) (viii)

(ix) (x) (xi) (xii)

1.4

Embedded Systems: Design, Programming and Applications

Coprocessor is used in embedded systems for floating point processing; Graphic processor is required for displaying graphics from memory buffer; Pixel coprocessor is used in digital camera for displaying images; Encryption engine is used to encrypt data for secured transmission; Decryption engine is used to decrypt the encrypted data at receiver-end; Discrete Cosine Transformation (DCT) and Discrete Cosine Inverse Transformation (DCIT) are used in embedded system for audio and video signal processing; Protocol stack processor is required to prepare a protocol stack before sending data to a network; Network processor is used to establish network connection for sending and receiving acknowledgement, and data transmission request. It is also used to detect and correct data frame error; Java code accelerator (coprocessor) takes advance action for completion of next object in Java program; CODEC processor encodes and decodes the information; JPEG CODEC processor is used in embedded system for compression and decompression of data; Controller is used in embedded systems to control peripherals, direct memory access or buses.

EMBEDDED HARDWARE UNITS

The embedded system requires following hardware units. Power supply unit: The embedded system requires a power source and optimized power dissipation from the total energy requirement. Embedded system operates in one of the following power ranges. (a) 5.0 volt ± 0.25 volt (b) 3.3 volt ± 0.3 volt (c) 2 volt ± 0.2 volt Some embedded systems do not have their own power supply. These systems either connect external supply or use charge pumps. The charge pump is an electronic circuit which accumulates charge from the bus signals or wireless radiation. Clock:

The electronic circuitry generates the clock pulses to synchronize the operations of microcontroller. Figure 1.6 shows a crystal oscillator circuit which is used to generate the clock pulses. The crystal frequency is the basic clock frequency of the microcontroller. The 8051 operates at 12 MHz frequency. The quartz crystal with the capacitors, as shown in figure, is connected to the microcontroller externally. All other components of oscillator are inbuilt within the 8051 IC. The clock controls system timers and the CPU machine cycle. For this reason a highly stable oscillator is required for embedded systems. Real-time clock:

A real-time clock is a clock that which is started by the system and it does not stop and reset. The count value of real-time clock can be reloaded. Real-time clock is set for ticks using pre-scaling bits and rate set bits in timer control register. Real-time clock generates

1.15

Introduction

XTAL1 pin

Crystal oscillator XTAL2 pin

Fig. 1.6

Quartz crystal circuit for oscillator

regular interval interrupts on its each time out. Therefore, an interrupt service routine is executed on each time out of real-time clock. Real-time clock (RTC) is used in a system to save the current date and time. It is also used in a system to return the control of the system after definite interval of time. Watchdog timer reset:

Reset means that the processor starts the processing of instructions from the starting address. Processor stores the starting address in program counter on a power-up. This reset of program is known as power-up reset. Instructions are fetched from that address following the reset of the processor. The reset and executes on a power-up program can be either a system program that executes from beginning or a system boot-up program or a system initialization program. There are two start-up addresses in certain processor. One address is for power-up reset vector and the other on reset vector after reset or time out signal from watchdog timer. The processor fetches the address bytes for program counter from first power-up reset vector on power-up and fetches the address bytes for program counter from second reset vector on receiving timing out signal from watchdog timer. This reset is known as watchdog timer reset. Reset circuit can be activated by an external reset circuit which is activated on power-up.

Memory: There are various types of memory in a system. The system has internal RAM and ROM for program code bytes and data storage. External memory can be added to the system using suitable circuits. Internal RAM is organized in following three different areas. (a) Register banks; (b) Random access memory (RAM) area; (c) Read only memory (ROM) area. Now-a-days, caches are also available in higher version of embedded processors. A cache is small, fast memory that holds copies of some of the contents of the main memory. Because the cache is fast, it provides higher speed access for the CPU; but since it is small, not all requests can be satisfied by the cache, forcing the system to wait for the slower main memory. Caching makes sense when the CPU is using only a relatively small set of memory locations at any one time; the set of active locations is often called the working set. A cache controller mediates between the CPU and the memory system comprised of the cache and the main memory. The most basic characteristics of a memory is its capacity. Manufacturers usually make several versions of a memory of a given size, each with a different data width. For example, a 4 Mbit memory may be available as a 1M X 4 bit. A single memory access obtains a 4 bit data item, with a maximum of 220 different addresses. Internally, the data are stored in a 2-dimensional array of memory cells. Most memories include an chip enable signal that enables the memory to store data.

1.16

Embedded Systems: Design, Programming and Applications

There are two major categories of random access memory (RAM): Static RAM or SRAM and dynamic RAM or DRAM. SRAM is faster than DRAM and SRAM consumes more power than DRAM. Memory density of DRAM is higher than that of SRAM. DRAM values must be periodically refreshed. The interface to a dynamic RAM is more complex because DRAMs are designed to minimize the number of required pins. There are several varieties of ROM available e.g. electrically erasable programmable ROM (EEPROM) or flash ROM, Programmable ROM PROM etc. Flash memory uses standard system voltage for erasing and programming, allowing it to be programmed inside a typical system. Factory programmed ROM and field-programmable ROM are available for embedded systems. Buses:

The bus consists of a common set of lines to connect multiple devices, hardware units and I/O ports. It is the mechanism by which the CPU communicates with memory and I/O devices. It defines a protocol by which the CPU, memory and devices communicate. A bus may be a serial or parallel bus. One of the major roles of the bus is to provide an interface to memory. A bus communication protocol specifies how signals communicate on the bus. The protocols also specify the ways of arbitration when several devices need to communicate. through the bus and ways of polling bus requirement from each device at an instance. The basic building block of most bus protocols is four cycled handshake. The hand shake ensures that when two devices want to communicate, one is ready to transmit and the other is ready to receive. The handshake uses a pair of wires dedicated to the handshake, enquiry and acknowledge. Extra wires are used for the data transmitted during the handshake. At the end of handshake, both handshaking signals are low, the system has thus returned to its original state for another handshake enable data transfer. Microprocessor buses build on the handshake for communication between the CPU and other system components. The term bus is used in two ways. The most basic use is as a set of related wires, such as address wires or address bus. Clock provides synchronization to the bus components. Some buses provide disconnected transfer. In these buses, the request and response are separate. A first operation requests the transfer. The bus can then be used for other operations. The transfer is completed later, when the data are ready. Some buses use multiplexed address and data. Additional control lines are provided to tell whether the value on the address/data lines is an address or data. These control lines are called control bus. Typically, the address comes first on the combined address/data lines, followed by the data. Some buses use multiplexed address and data. Additional control lines are provided to tell whether the value on the address/data lines is an address or data.

Direct Memory Access (DMA) controller:

Direct memory access (DMA) is a bus operation that allows read/write operation without CPU control. A DMA transfer is controlled by a DMA controller, which requests control of the bus from the CPU. The DMA controller performs read and write operations directly between devices and memory. The DMA controller provides ‘bus request’ signal to CPU. CPU performs the current task and provides ‘bus grant’ signal to DMA controller. A device that can initiate its own bus transfer is known as a bus master. Then data is transferred between memory and I/O device. After the transaction is finished, the DMA controller returns the bus to the control of CPU.

Introduction

1.17

Input/Output (I/O): I/O ports connect the system to the outside world. Each latch and corresponding driver of ports is provided to the corresponding on chip I/O ports. All ports are bidirectional input output ports. The port addresses are stored in the special function register bank. I/O port is used as either input or output port. The I/O pins are used for both address and data. Address Latch Enable (ALE) signal indicates whether I/O port is transmitting address or data. When ALE = 0, it provides data. If ALE = 1, I/O port transmit address. The port registers specify the value to be output on the specific output port and read value from the specified input port. Ports are also used as bit addressable. The I/O port also can be used as serial data communication. Following functions are also done by this I/O port. (a) Serial input data; (b) Serial output data; (c) External interrupt INT0; (d) External interrupt INT1; (e) External timer input T0; (f) External timer input T1; (g) External data memory write strobe WR; (h) External data memory read strobe RD. Analog to Digital Converter (ADC):

The electrical signal, obtained from the output of the transducer, is an analog signal. This analog signal must be converted to digital signal which is suitable for input to microprocessor. For this reason, we require an analog to digital converters (ADC) for microprocessor based systems. The function of ADC is to produce a digital word corresponding to the magnitude of some analog voltage or current. Different types of commonly used A/D converters are mentioned below. (a) Parallel converter A/D converter; (b) Dual slope A/D converter; (c) Successive approximation type A/D converter. The available A/D converter ICs, manufactured by National Semiconductor Corporation are ADC0801, ADC 0802, ADC0803, ADC 0804, ADC0808, ADC 0809 etc. These A/D converters are CMOS 8 bit successive approximation A/D converters that use a differential potentiometric ladder. These converters are designed to allow operation with derivative control bus with tri-state output latches driving the data bus directly. These ADCs do not require any interfacing logic to locate memory or I/O devices. The voltage reference input to these ADCs can be adjusted to encode any smaller analog voltage span to the full 8 bits of resolution. Special features of these ADCs are mentioned below. (a) Compatible with microprocessors; (b) No interfacing logic is needed; (c) Easy interface to all microprocessors through Programmable Peripheral interface; (d) They accept differential analog voltage inputs; (e) Logic inputs and outputs of these ADCs meet both MOS and TTL voltage level;

1.18

Embedded Systems: Design, Programming and Applications

(f) They work with 2.5 volts reference voltage; (g) These ADCs have on chip clock generator; (h) Zero adjustment is not required; (i) Input voltage level range is 0 to 5 volts; (j) Resolution 8 bits; (k) Maximum conversion time is 100 µs. ADC0809 operates with clock signal of frequency range 10 kHz to 1280 kHz. The conversion time of the ADC is inversely proportional to clock frequency. Reference voltage of ADC is supplied from a constant voltage source which is independent of the variation of load. The analog input is applied to the ADC through a sample and hold circuit LF398. Digital to Analog Converter (DAC): The output signal from a processor is a digital signal. This digital signal is to be converted to analog signal for different applications like audio system, measurement of a physical quantity or industrial control systems. For this reason, a digital to analog signal converter is required to be interfaced with processor. Three types of digital to analog converters are available in the market. (a) Current output type: It provides current output corresponding to input digital signal. (b) Voltage output type: It converts the current signal into voltage signal internally and provides voltage output corresponding to input digital signal. (c) Multiplying type: The output of multiplying type DAC represents the product of the input signal and the reference signal. Digital to analog converters (DAC) are available as integrated circuit specially designed to be compatible with microprocessor. These DAC includes a latch on the chip. DAC0800 IC has following special features. (a) Fast settling time (100 nS); (b) Full-scale error = ± 1 LSB; (c) Non-linearity over temperature ± 0.1%; (d) Full-scale current drift = ± 100 ppm/°C; (e) Output compliance = – 10V ± 18V; (f) Power supply range = ± 4.5V to ± 18 V; (g) Complementary current outputs; (h) Compatible to TTL, CMOS, PMOS etc.; (i) Two quadrant wide range multiplying capability; (j) Low power consumption; (k) Low cost. Key board: It is an array of switches. It is an important device for getting user inputs. It includes some internal logic circuit for interfacing to the processor and key-debounching circuits. It has software for the system to receive input from a set of keys of the keyboard. Touch screen may be used for a virtual keyboard. A keyboard may have 104 keys or more The keypad has not more

Introduction

1.19

than 32 keys. Keypad and keyboard may be interfaced serially or parallel with the processor. A T9 keypad is used in mobile set.T9 keypad has 16 keys and four menu keys. Liquid Crystal Diode (LCD) and Light Emitting Diode (LED):

Any system requires a display unit to display the status or message for a line. The system also needs necessary interfacing circuit and software for the output to LCD or LED display.

Modem, pulse dialer and transceivers:

A modem or Pulse dialer and transceivers are used in communication system. These devices require necessary interfacing circuit and software.

Interrupt handler:

Execution of normal program by processor can be interrupted by external signal or instruction written in the program. Microcontrollers also allow interruption of execution of the program. A type code is assigned by microcontroller to every interrupt for identification of interrupts. The interrupt can also be initiated by external devices or by software instructions. When interrupt is initiated, the microprocessor stops execution of the current program and calls a procedure or service routine which services the interrupt. At the end of the interrupt service routine, execution of the main program again starts from the instruction where it stopped before the interrupt. If the execution of a normal program of a microprocessor is interrupted by instruction then the interrupt is known as software interrupt. Therefore, interrupts are enabled by using software. The interrupts are also disabled by software. Actually, when a microcontroller is executing an important program then the interrupts are disabled. Some time it is desirable to inhibit the interruption of the execution of the program. Execution of a program may be interrupted by abnormal internal condition of the microcontroller. This is known as exception. Interruption of execution of the program may also be caused by external events. This is also a type of exception. However, Exceptions includes program faults, traps and abnormal conditions generated by hard wares. All most all applications of microcontrollers involve responding to events quickly to control the events. Interrupts are only means by which real-time program can be written successfully. Interrupt may be generated in chip operation or it can be applied from external source. The interrupt subroutines are stored in a predetermined address. There are five interrupts applicable in 8051. Three interrupts are generated by timer flag 0, timer flag 1 and the serial port interrupt. Two interrupts are initiated by external signal applied to pins INT0 and INT1. The program controls the functions of all interrupts. Programmer can change the content of interrupt enable register (IR), interrupt priority register and timer control register to perform desirable functions. The content of IE and IP special function registers are shown below. There are two ways by which a microcontroller can serve several devices.

Interrupt:

The program associated with interrupt is called Interrupt service routine. Many devices can be served by assigning priority, but not at the same time. In interrupt method the microcontroller can ignore a device request for service.

Polling:

In polling, the microcontroller continuously monitors the status of a given device; when the condition is met, it performs the service. The main disadvantage of polling is that it wastes much of the microcontroller’s time. It is not possible to assign priority and ignore a device for service since polling method checks all devices in a round-robin process. Steps of execution of interrupt are described below. 1. Finishes the instruction it is executing and saves the address of the next instruction on the stack;

1.20

Embedded Systems: Design, Programming and Applications

2. Saves the current status of all the interrupts; 3. Jumps to a fixed location in memory called the interrupt vector table that holds the address of the interrupt service routine; 4. The micro controller gets the address of the ISR from the interrupt vector table, jumps to it and starts to execute it; 5. After executing RETI instruction, the microcontroller returns to the place from where it was interrupted and starts to execute from that address.

1.5

AEMBEDDED SOFTWARE

Most of the registers of 8051 are 8 bit. Widely used registers of 8051 are A (accumulator), B, R0, R1, R2, R3, R4, R5, R6, R7, DPTR, and PC (program counter). DPTR and PC are only 16 bit registers of 8051. The assembly language instructions are described in Appendix I.

1.5.1

Assembling and Running an 8051 Program

Steps to create an executable Assembly language program are described as follows. 1. First we use an editor to type in a program. The editor must be able to produce the ASCII file. For many assemblers, the file name follow the usual DOS conventions, but the source file has the extension .asm. or .src. depending on the assembler being used; 2. The .asm. source file containing the program code created in step 1 is fed to an 8051 assembler. The assembler converts the instruction into machine code. The assembler will produce an object file and a list file having extensions of .obj. and .lst., respectively; 3. Assemblers require a third step called linking. The link program takes one or more object files an produces an absolute object file with extensions of .abs. This abs file used by 8051trainers that have a monitor program; 4. Next the abs file is fed into a program called. OH (object to hex converter) which creates a file with extension .hex. that is ready to burn into ROM. The program counter points to the address of the next instruction to be executed. As the CPU fetches the opcode from the program ROM, the program counter is incremented to point the next instruction. Since the PC is 16 bit register, it can access a total of 64 K bytes of code. At power up or reset the 8051 wakes up at memory address 0000 i.e. the PC has the value of 0000 in it. For this reason the first opcode must be burnt at 0000H of program ROM. Because this is the address where it looks for the first instruction when it is booted. Some family members of 8051 family have only 4 K bytes of on chip ROM. No member of 8051 family can access more than 64 K bytes of opcode since the program counter is 16 bit register. The 8051 microcontroller has only one data type. It is 8 bits, and the size of register is also 8 bits. It is the job of the programmer to break down data larger than 8 bits to be processed by the CPU. DB (define byte): the DB directive is the most widely used data directive in the assembler. It is used to define data of 8 bit.when DB is used to define data, the numbers can be in decimal, binary,

Introduction

1.21

Editor program

Assembler program

Linker program

OH program

Fig. 1.7

Steps of assembling and running an 8051 program

hex or ASCII format. For decimal, .D. is used after the decimal number, but using .B. (binary) and .H. (hexadecimal) for others is required. Regardless of which is used, the assembler will convert the number to hex. To indicate ASCII, simply place it in quotation marks.

Example: ORG 500H; DATA1: DB 28; DATA2: DB 00110101B; DATA3: DB 39H; ORG 510H; DATA4: DB 259; ASCII NUMBERS.

1.5.2

Assembler Directives

ORG (origin): The ORG directive is used to indicate the beginning of the address. The number

that comes after ORG can either in HEX or in decimal. EQU (equate):

This is used to define a constant without occupying a memory location. The EQU directive does not set aside storage for a data item but associates a constant with a data label so that when the label appears in the program, its constant value will be substituted for the label.

Example: COUNT EQU 25 ------------------------. -----------------------MOV R3, #COUNT When executing the instruction .MOV R3, #COUNT. , the register will be loaded with the value 25.

1.22

Embedded Systems: Design, Programming and Applications

Data Types and Directives: Assume that there is a constant used several times in the program body and you need to change the value. Using EQU directive it can be done easily. Otherwise one need to change the value throughout the program body. END Directive:

This indicates to the assembler the end of the source file. The END directive is the last line of an 8051 program. where it looks for the first instruction when it is booted.

8051 Flag Bits and the PSW Register: Like any other microprocessor the 8051 has a flag register to indicate arithmetic conditions such as carry bit. The flag register in the 8051 is called the program status (PSW) register. PSW register (Program Status Word register) is an 8 bit register only 6 bits of which are used by the 8051. Two unused bits are user definable flags. Four of the flags are called conditional flags meaning that they indicate some conditions that resulted after an instruction was executed.

8051 Register Banks There are 128 bytes of RAM inside the 8051microcontroller which are assigned addresses 00 to 7FH. These 128 bytes are divided into three different groups as follows. 1. A total 32 bytes from locations 00 to 1FH are set aside for register banks and the stack; 2. A total of 16 bytes from location 20H to 2FH are set aside for bit addressable read/write memory and instructions; 3. A total of 80 bytes from locations 30H to 7FH are used for read/write storage, or what is normally called scratch pad. These 80 locations of RAM are widely used for the purpose of storing data and parameters by 8051 programmers. As mentioned earlier, a total of 32 bytes of RAM are set aside for the register bank and the stack. These 32 bits are divided into 4 banks of registers in which each bank has 8 register. The major problem in programming 8051 is that, bank1 uses the same RAM space as the stack. We must either not use register bank 1 or we must allocate another area of RAM for the stack.

Stack in the 8051 The stack is a section of RAM used by the CPU to store information temporarily. This address could be data or address. The register used to access the stack is the stack pointer (SP) register. It is only 8 bit wide, which means that it can take values of 00 to FFH. When the 8051 is powered up, the stack pointer contains value 07. This means that RAM location 08 is the first location being used for the stack by the 8051. The storing of a CPU register in the stack is called PUSH, and loading the contents of the stack back into a CPU register is called POP. In the 8051 the stack pointer is pointing to the last used location of the stack. As we push data on to the stack, the stack pointer is incremented by one. To push a register on to the stack we must use their RAM addresses.

Example: The instruction PUSH 1 pushes content of register R1 onto the stack. Popping the contents of the stack back into the register is the opposite process of pushing. With every POP, the top byte of the stack is copied to the register specified by the instruction and the stack pointer is decremented by once.

Introduction

1.5.3

1.23

Assembly Level Language

Assembly level language is suitable for embedded system software. The causes of suitability of high level language is discussed below. 1. High-level languages are converted to code by utility programs named compilers. Because of the general nature of high-level languages, the compliers often produce excess or overhead code; 2. To reduce the size of the program. Assembly language requires no extra overhead code; 3. To write programs for special situations. No standard programs (named drivers) exist. When speed of response is critical, assembly-coded programs execute rapidly because of the exact fit of program code to task requirements; 4. Use of assembly level language in embedded system reduces cost, Reduces code size also reduce the cost of associated ROM; 5. In order to fully understand what is going on “under the hood” of the CPU assembly level language is suitable.

Features of Assembly Language The special features of assembly level language are described below. 1. One instruction appears per line; 2. Labels, which give names to memory locations, start in the first column; 3. Instructions must start in the second column or after to distinguish them from labels; 4. Comments run from some designated comment character to the end of the line.

1.5.4

High Level Language

High level language embedded C, ‘C’ CROSS COMPILER ‘CX51’ and ‘Keil’ are used in embedded system as embedded software. CX51 Compiler:

CX51 is a cross compiler, some aspects of the C programming language and standard libraries are altered or enhanced to address the peculiarities of an embedded target processor. The CX51 compiler provides a number of include files for various 8051derivatives. Each file contains declarations for the SFRs available on that CX51. Optimizing C Compiler, complete implementation of the American National Standards Institute (ANSI) standard is achieved for the C language. CX51 is not a universal C compiler adapted for the 8051 target. It is dedicated to generate extremely fast and compact code for the 8051 microprocessor. CX51 provides the flexibility of programming in C and the code efficiency and speed of assembly language.

Keil:

Keil software contains C cross compiler, Assembler, tiny real-time operating system, and program loader. Keil is used to create embedded applications rapidly for 8051 µcontroller. It supports chips like 8051 microcontrollers, 251 and 166. mVision 2. It simplifies project development for 8051 and other microcontrollers.

1.24

Embedded Systems: Design, Programming and Applications

Advantages of Keil:

Advantages of Keil over other embedded software is mentioned below. 1. Keil supports 8051, 251 and 166 microcontroller family; 2. Keil is optimized for specific architecture of each microcontroller; 3. It generates smallest code and fastest execution speed; 4. Keil provides full control over embedded development by deciding register banks, memory areas, variable types, SFRs; 5. It has full code including ISR which can be written in ‘C’. Object oriented language C, C++, Java, and Visual C++ are also used for software development of embedded system.

1.5.5

Software Design

Program design of embedded system is simplified by program modelling. The models of software design process of embedded system are mentioned below. 1. Object oriented program model; 2. Sequential program model; 3. Synchronous dataflow (SDF) graph or multi-thread graph (MTG) model; 4. Finite state machine for data-path; 5. Universal modelling language (UML).

1.5.6

Device Management Software

Software is required for device drivers and device management in an operating system because an embedded system is designed to do multiple functions. It has to control multiple physical and virtual devices. The physical devices are timers, keyboards, flash memory, display, network cards and ports. The virtual devices are described below. File:

A file is a virtual device which transmits the records to a data sink. It stores the data from the data source. A file is stored in flash memory in the embedded system.

Pipe:

A pipe is used for sending and receiving a stream of bytes from a source to destination,

Socket:

A socket is used for sending and receiving a stream of bytes between client and server software or between source and destination computing system. Ram Disc:

A RAM disc is used for using the RAM in a similar way to files in the disc. A device driver is software for opening, binding or connecting, writing, reading and control action. A device driver accesses a parallel or serial port, keyboard file, pipe, and socket at specific addresses. A device driver controls following three functions.

Initializing:

Initializing is activated by placing appropriate bits in the control register or

control word. Calling ISR:

Calling Interrupt Service Routine (ISR) on interrupt.

Resetting the Status Flag:

Resetting the status flag after an interrupt service.

Introduction

1.25

Device manager software provide codes for detecting the presence of devices. It also initializes the device for testing. The manager includes software for allocating and registering port addresses for various devices. Device manager software ensures one task only at any instant for a device.

1.5.7

Software Tools for Designing Embedded Systems

Following software tools are used for designing the embedded systems. 1. Editor: Editor software is used for writing C codes with the help of key board for entering the program. Using editor software a file is created for addition, deletion, insertion etc; 2. Interpreter: Interpreter translates the program line by line into machine code; 3. Compiler: Compiler creates object file. It includes codes, functions and expression from library routine; 4. Assembler: Assembler translates assembly program into binary opcodes. It creates a binary file. This binary file is an executable file; 5. Cross assembler: The cross assembler assembles the assembly codes used in system development; 6. Simulator: Simulator simulates all functions of an embedded system; 7. Source code: The source code is used for editing, debugging, browsing, disabling and enabling the C++ features; 8. Stethoscope: It is used for tracking the changes in any program variable.It also shows the sequence of multiple processes; 9. Prototype developer: This prototype development tool is needed for the development of system software and hardware; 10. Real Time Operating System (RTOS): An RTOS is a multitasking OS which is needed for functioning in real-time constraints.

1.5.7

Applications of Embedded Systems

The applications of embedded systems are virtually limitless, because every day new products are introduced to the market that utilizes embedded computers in novel ways. In recent years, hardware such as microprocessors, microcontrollers, and FPGA chips have become much cheaper. Many embedded computers even come with extensive libraries, so that writing software becomes a very trivial task indeed. Embedded systems are often required to provide Real-time response. A Real-time system is defined as a system whose correctness depends on the timeliness of its response. Examples of such systems are flight control systems of an aircraft, sensor systems in nuclear reactors and power plants. Now-a-days embedded systems have many applications. A few applications of embedded systems are mentioned below. 1. At present, cricket ball throwing machines are manufactured by some companies of Europe. It is a machine, which is capable to throw cricket ball automatically at different speeds and swings;

1.26

Embedded Systems: Design, Programming and Applications

2. Embedded system is widely used in robotics system for controlling the stepper motor; 3. It is used in washing machine, cooking systems, remote controller of TV, video games, toys and music system; 4. Embedded system is used in point of sales terminals like automatic chocolate vending machine, billing machine, Fax machine, photocopy machine, printer, scanner etc.; 5. It is used in computer as keyboard controller, CD drive controller, HD drive controller, CRT display controller, DRAM controller, DMA CONTROLLER, Printer controller, LAN controller and Disc drive controller; 6. In communication systems, embedded system is used in telephone with memory, mobile communication, pager and computer networking systems; 7. Embedded system is used in CNC machine, closed-loop engine control, dynamic ride control and braking system monitor; 8. Embedded system is used in data acquisition and supervisory control system, multi-display digital panel meter, supervisory control system, industrial process controller, industrial moisture recorder cum controller, digital storage system, spectrum analyzer; 9. In biomedical systems, embedded system is used in ECG, LCD display, and blood cell recorder cum analyzer; 10. In internet appliances, embedded system is used in mail client card to store e-mail and Intelligent Operation, Administration and Maintenance Router (IOAMR); 11. Embedded system is used in bank ATM and credit card transaction; 12. In image processing, embedded system is used for image filtering, pattern recognizing, speech processing, and video processing; 13. Embedded system is used in Aerospace communication, satellite communication and missile control; 14. Embedded interface and networking systems are used in high speed large bandwidth routers, switches and gateways, Storage Area Networks (SAN) and Wide Area Networks (WAN).

Objective Type Questions 1. What do you mean by embedded systems? Describe main components of embedded system. 2. What are the constraints in embedded systems? 3. What do you mean by embedded processor? 4. Describe in brief the functions of additional circuits added to single chip microprocessor to function as microcontroller. 5. What are the special features of 8051 microcontroller? 6. State the differences between microprocessor and microcontroller. 7. Write the names of single purpose processor used in embedded system. 8. Describe different steps to create an executable assembly language program.

Introduction

1.27

Review Questions 1. 2. 3. 4. 5. 6. 7. 8.

Describe the different categories of embedded systems. Describe the requirements of embedded systems. Describe the different segments of microprocessor. Draw the block diagram of 8051 microcontroller and describe the function of each block. Describe different hardware units required for an embedded system. Describe the assembler directives used in embedded software. Explain the causes of suitability of high level language in embedded systems. Write short notes on the following topics. (a) Keil (b) Software design (c) Device management software. (d) Software tools for designing embedded systems (e) Applications of embedded systems.

Choose the Correct Answer 1. An embedded s consists of (a) hardware only (b) software only (c) both hardware and software (d) none of these 2. Embedded systems are generally classified into (a) two types (b) three types (c) four types (d) five types 3. Functional constraints in embedded systems are (a) processor sped (b) system memory (c) power dissipation in run (d) all of these 4. Microprocessors used in embedded systems are (a) four bit microprocessors only (b) eight bit microprocessors only (c) sixteen bit microprocessors only (d) all of these 5. The properties to be considered by embedded system designer are (a) maximum bits in the operand and instruction set (b) instruction set and clock frequency (c) clock frequency and processors ability to solve complex algorithm (d) all of these 6. A microcontroller is a (a) microprocessor (b) a true computer on a chip

1.28

7.

8.

9.

10.

11.

12.

13.

14.

15.

16.

Embedded Systems: Design, Programming and Applications

(c) microprocessor with I/O ports only (d) microprocessor with memory only Number of steps to execute assembly language program is (a) 2 (b) 3 (c) 4 (d) 4 PSW register of 8051 is (a) 4 (b) 8 (c) 16 (d) 32 bit register Number of flag bits in 8051 is (a) 4 (b) 5 (c) 6 (d) 8 Ram capacity of 8051 microcontroller is (a) 64 bytes (b) 128 bytes (c) 256 bytes (d) 512 bytes Stack is a section of (a) ROM (b) RAM (c) EPROM (d) EEPROM CX51 compiler provides (a) flexibility of programming in C (b) code efficiency (c) speed of assembly language (d) all of these Keil software contains (a) C cross compiler (b) assembler (c) tiny RTOS and program controller (d) all of these The models of software design process of embedded system is (a) object oriented program model (b) sequential program model (c) synchronous dataflow (d) universal modelling language (e) all of these Device manager software provides (a) codes for device detection only (b) initialization the device only (c) allocating and registering port addresses only (d) all of these Real-time operating system is a (a) single tasking OS (b) dual tasking OS (c) multitasking OS (d) none of these

2 2.1

Embedded Processors

INTRODUCTION

Embedded technology is now in its prime and the wealth of knowledge available is mind-blowing. However, basic characteristics of an embedded system are very simple as mentioned below. It is a system built to perform its duty, completely or partially independent of human intervention. It is specially designed to perform a few tasks in the most efficient way. It interacts with physical elements in our environment, viz., controlling and driving a motor, sensing temperature, etc. One of the most important factors between an embedded system and a computer is the constraints on system resources. Unlike modern day computers, an embedded system is usually designed to be more compact, energy efficient, and inexpensive. Another factor is that a computer is capable of performing a variety of tasks completely independent of each other. Embedded systems also exhibit single tasking and multitasking capabilities. Embedded systems contain processing cores that are typically either microcontrollers or digital signal processors (DSP). The key characteristic, however, is being dedicated to handle a particular task. They may require very powerful processors and extensive communication. Since the embedded system is dedicated to specific tasks, design engineers can optimize it to reduce the size and cost of the product and increase the reliability and performance. Physically, embedded systems range from portable devices such as digital watches and MP3 players, to large stationary installations like traffic lights, factory controllers, or the systems controlling nuclear power plants. Complexity varies from low, with a single microcontroller chip, to very high with multiple units, peripherals and networks mounted inside a large chassis or enclosure. Effectively programming an embedded system, and implementing it reliably requires the engineer to know many of the details of the system architecture. As people continue to pack more and more transistors onto a single chip, more and more of the stuff that was once “peripheral logic” has been integrated on the same chip as the CPU. A microcontroller includes most or all

2.2

Embedded Systems: Design, Programming and Applications

the electronics needed in an embedded system in a single integrated circuit. Important parts of an embedded processor are mentioned below. 1. CPU; 2. I/O ports; 3. RAM: contains temporary data 4. ROM: contains program and constant data – the firmware. Starting in 1993, many microcontrollers use Flash memory instead of true ROM to hold the firmware, but many engineers still refer to the Flash memory that holds the firmware as “ROM” from force of habit; 5. Timers: we discuss these later at Embedded systems/Programmable controllers; 6. Serial interface: often a USART – we discuss these later at Embedded systems/Serial and parallel IO; 7. EEPROM: contains “permanent” data; 8. Analog-to-digital converter; 9. Digital to analog converter. The earliest microcontrollers contained only the CPU, I/O ports cache RAM and ROM onto the same chip, because such a microcontroller no longer needs “address pins”; etc. We shall describe different types of processors in the following sections.

2.2

PROCESSORS

Evolution of microprocessor started with an innovative approach of logic design. The first microprocessor was developed by INTEL Corporation in 1971 in the brand name of INTEL 4004. It is a 4 bit microprocessor designed with large scale integration (LSI) technology. The number of instruction of INTEL 4004 instruction set was 45. This microprocessor was fabricated by P-MOS technology. The rate of execution of the instructions by this microprocessor is 50 KIPS (Kilo instruction per second). Many other companies also produced 4 bit microprocessors like PPS- 4 by Rockwell international, T 3472 by Toshiba, TMS-1000 by Texas instruments etc. In 1972 INTEL Corporation produced the first 8 bit microprocessor INTEL 8008. This microprocessor can address an expanded memory size of 16 Kilobytes and 48 instructions can be used by this microprocessor. In 1973 INTEL-Corporation produced the first modern 8 bit microprocessor INTEL 8080. This processor is fabricated by NMOS technology. 8080 microprocessor is ten times faster than 8008 microprocessor. Execution rate of this processor is 500 KIPS. Memory capacity of INTEL 8080 is 64 KB which is four times more than that of 8080. In 1975 INTEL produced the improved version of 8 bit microprocessor INTEL 8085. Execution rate of this processor is 769.23 KIPS. This processor has its own internal clock generator and internal system controller. INTEL 8085 can execute 246 instructions. The age of advanced microprocessor started in 1978 when INTEL introduced a 16 bit microprocessor INTEL 8086. It is a sixteen bit processor. Just after one year, INTEL Corporation released 8088. Both the processors are almost similar in working principle. These processors can address one Megabyte of memory location and execution speed of 8086 microprocessor is

Embedded Processors

2.3

2.5 million instructions per second (MIPs). The high execution speed and high memory addressing capability of 8086 and 8088 made them very much popular to use these microprocessors in micro computer applications. The speed of execution of 8086 and 8088 is increased by using instruction queue or cache. Actually, 8086 and 8088 microprocessor pre-fetch few instructions and place them in queue before execution. INTEL 8086 and 8088 microprocessors have many instructions set. The number of instructions of this microprocessor is about 20,000. These instruction sets are large in number and complex in operation. For this reason, these microprocessors are known as complex instruction set computers (CISC). 8086 and 8088 have more internal registers to provide more storage space than that of 8085. The 16 bit registers help to write program efficiently. Thus the first member of the advanced microprocessor family is INTEL 8086 and it is used in sophisticated applications. Large number and complexity of instructions of CISC microprocessor causes reduction in computing speed of microprocessors. For this reason, reduced instruction set computer (RISC) microprocessor is developed to increase computing speed of the microprocessor by decreasing execution time of the instruction using hardwired control unit. RISC microprocessors available in the market are Power PC 601.603, 604 etc., Intel’s PA8000, DEC’s Alpha21064, SUN’s SPARC etc. CISC microprocessors are Intel’s 486, Pentium, Pentium Pro, Pentium II, Celeron, Pentium III, Pentium IV Motorola 68000 etc. Intel Corporation introduced another 16 bit processor 80186 microprocessor which was not at all popular for general purpose computers. It was used for only industrial control. Later on, Intel Corporation produced microprocessor 80286 which possesses higher speed and more memory addressing capability. It is also a 16 bit microprocessor with 24 line address bus. It can provide address for 16 MB memory system. The clock speed of INTEL 80286 microprocessor is also increased to 8 MHz. It requires 250 ns to execute a simple instruction. The execution rate of INTEL 80286 is 4 MIPS. In 1986 INTEL Corporation introduced 32 bit processor 80386. It has 32 bit data bus and 32 bit memory address bus. The memory capacity of this processor is 4 GB (Gigabyte). It is suitable for graphic user interface (GUI) and Computer Aided Design (CAD). INTEL 80386 includes hardware circuitry for memory management and memory assignment. In 1989 INTEL Corporation introduced 80486 microprocessor which incorporates 80386 like microprocessor, 80387 like numeric coprocessor and 8 KB cache memory in the same integrated circuit package. It is faster than its predecessors. The range of clock speed of INTEL 80486 microprocessor is 50 MHz to 66 MHz and instruction execution rate is 50 MIPS. It has expandable 16 KB cache memory. Tripled clock version increases the speed of INTEL 80486 to 120 MHz. This processor has 32 line address bus. In 1993 INTEL Corporation introduced 64 bit Pentium (P5) microprocessor using superscalar technology. The instruction execution rate of this processor is 110 MIPS and clock frequency is 100MHz. Double clocked version of Pentium processor operates at 133 MHz. The cache memory of this processor is increased to 16 KB. It has 64 bit data bus. The memory size of Pentium processor is 4 GB. It is a dual integer processor and executes two instructions simultaneously per

2.4

Embedded Systems: Design, Programming and Applications

clock period. JUMP prediction technology is included in the Pentium processor. It also includes internal floating point coprocessor in the same integrated circuit package. Pentium pro-microprocessor (P6) was also introduced by INTEL Corporation which contains 21 million transistors. It has three integer units and one floating point unit. Basic clock frequency of Pentium pro-microprocessor is 166 MHz. It has 64 bit data bus and 64GB main memory, 16 KB L1 cache and 256 KB L2 cache memory. This processor employs three execution engines so that it can execute three instructions at a time. It can execute 32 bit code efficiently. Pentium promicroprocessor has 36 bit address bus for 64 GB memory system. Now-a-days super scalar technology is used in many microprocessors but these all processors share the same register set. The super scalar processor has multiple pipe lines and executes more than one instruction per clock cycle. This super scalar technology will be used in P7 which includes many microprocessors having their own register sets. One register sets of a microprocessor is linked with the register sets of the other. Actually this technology will operate real parallel processing without using any special program for parallel processing. The central processing unit (CPU) is the most important component in an embedded system. It is a VLSI chip, integrated with memory and other peripherals. Depending on the type of applications the processors are broadly classified into three major categories. 1. General purpose microprocessors; 2. Microcontrollers; 3. Digital signal processors. For more specific applications customized processors can also be designed. Unless the demand is high the design and manufacturing cost of such processors will be high. Therefore, in most of the applications the design is carried out using already available processors in the market. However, the Field Programmable Gate Arrays (FPGA) can be used to implement simple customized processors easily. An FPGA is a type of logic chip that can be programmed. They support thousands of gates which can be connected and disconnected like an EPROM (Erasable Programmable Read Only Memory).

2.2.1

General Purpose Processors

A general purpose processor is designed to solve problems in a large variety of applications as diverse as communications, automotive and industrial embedded systems. In this processor, the manufacturer can invest more for improving the VLSI design with advanced optimized architectural features. The design tools are provided by the manufacturer in such processors. Pentium IV is such a general purpose processor with most advanced architectural features. Microprocessor is manufactured by very large scale integration (VLSI) technology. The microprocessor is a clock driven semiconductor device. It consists of following three building blocks. 1. Register array; 2. Arithmetic and logic Unit (ALU); 3. Control unit (CU).

2.5

Embedded Processors

Figure 2.1 Shows block arrangement of basic microprocessor. The different segments of microprocessor are described below.

Arithmetic and logic unit (ALU)

Register array

Control unit

Fig. 2.1

Block arrangement of basic microprocessor

Arithmetic and Logic Unit (ALU):

Arithmetic and logic unit (ALU) is constructed with logic gates and it is used for mathematical computation and logical decision. As for example, it performs addition, subtraction and logical operation like AND, OR, Ex-OR etc. Register Array:

The registers consist of memory elements. Four bit, 8 bit, 16 bit, 32 bit or 64 bit registers are fabricated in microprocessor. Actually, the microprocessors are named according to its register size. If a microprocessor has registers of 4 bit size then it is called four bit microprocessor. Thus, microprocessor having 8 bit registers is known as eight bit microprocessor. The registers of microprocessors store data temporarily during execution of the program. It has a program counter (PC) to hold the address of the next program instruction to fetch and an Instruction register (IR) to hold the fetched instruction.

Control Unit (CU):

The control unit controls the operation of microprocessor by providing control signal to different segments of microprocessor. Actually control unit controls the timing of operation of different electronic circuits of microprocessor. The control unit consists of circuitry for retrieving program instructions and for moving data to, from, and through the data-path according to those instructions. A general purpose processor consists of a data-path, a control unit tightly linked with the memory as shown in Fig. 2.2. Data line

CPU

Address line Control line

Fig. 2.2 Memory interface

MEMORY

2.6

Embedded Systems: Design, Programming and Applications

The Data-path consists of a circuitry for transforming data and storing temporary data. It contains an arithmetic-logic-unit (ALU) capable of transforming data through operations such as addition, subtraction, logical AND, logical OR, inverting, shifting etc. The data-path also contains registers capable of storing temporary data generated out of ALU or related operations. The internal databus carries data within the data-path while the external data bus carries data to and from the data memory. The size of the data-path indicates the bit-size of the CPU. An 8 bit data path means an 8 bit CPU such as 8085 etc.

2.2.2

Embedded Microprocessor

Embedded microprocessor systems are VLSI chips that are incorporated into products such as cars, fridges, traffic lights, industrial equipment. The number of embedded microprocessor system computers and their economic importance is very important. Embedded microprocessors are essentially microprocessors that are used in electronic devices. Embedded microprocessors are usually designed to perform a certain task and the user seldom has to interact with it. There are following two areas of embedded control applications. 1. Event control or real-time control; 2. Data control. Microcontrollers are used for event control or real-time control. Embedded microprocessors are used for data control. Therefore, embedded controller require following building blocks. 1. Data processing unit; 2. Data formatting unit; 3. I/O control unit; 4. Direct memory access (DMA) control unit; 5. Memory; 6. CPU; 7. Timer unit.

2.2.3

Characteristics of Embedded Microprocessors

Embedded microprocessor does not require any human interaction. As a result, there is no need of human supervisor. The embedded microprocessor relies on the stored programs and data being sent to and from the microprocessor to control its behavior. Embedded microprocessors interact with their environments through an interrupt system. Interrupts are electronic signals sent from external devices that let the processor know that they are done retrieving some data, or converting a signal, or whenever they need to use the processor. The processor then enters its interrupt program and decodes the source of the interrupt to take the correct action. The programs are stored in memory. The embedded microprocessor does not possess a large amounts of available memory for miniaturization of electronics. For this reason, the programs run by embedded microprocessors are usually short. So these small programs can fit onto memory built onto the chip. Embedded processors also use a variety of other devices which are built onto the chip as well. Since embedded processors are usually used to control devices, they sometimes need to accept input from the device

Embedded Processors

2.7

they are controlling. This is done by the analog to digital converter. Analog to digital converter is used to convert the incoming analog signal into data form that the processor can recognize. There is also a digital to analog converter which allows the processor to send signal to the device it is controlling. Embedded microprocessors include many types of timers. One of the most common types of timers is the Programmable Interval Timer (PIT). The PIT counts down from some prefixed value to zero. Once it reaches zero, it sends an interrupt to the processor indicating that it has finished counting. This is useful to restart the device to be controlled. The time processing unit (TPU) is essentially a timer, but more sophisticated in performance. In addition to counting down, the TPU can detect input events and generate output events. The embedded versions of some microprocessors are mentioned below. 1. Embedded ultra low power Intel 486GX processor; 2. Embedded ultra low power Intel 486SX processor; 3. Intel 386CXSA embedded microprocessor; 4. Intel 386CXSB embedded microprocessor; 5. Intel 386EX embedded microprocessor; 6. Intel 386SXSA embedded microprocessor; 7. Intel 80376 high performance 32 bit embedded microprocessor; 8. Rabbit 8 bit embedded microprocessor.

2.2.4

Embedded Microprocessor Systems

The main function of an embedded microprocessor is to monitor and control some real world event. The different steps to design an embedded microprocessor system are shown below. 1. Product requirement definitions; 2. Functionality description; 3. Processor selection; 4. Hardware design; 5. Firmware design; 6. Integration. These steps are not necessarily serial. Still, the steps are preferred for design in Embedded Microprocessor Systems. Building hardware, writing code, and debugging the system are necessary. Design rarely gets the time and attention, it deserves in the real world. But it is hard to know ahead of time where to spend design time to avoid the problems. State transition diagrams in addition to flow charts for design consideration are preferred first. Then state and dataflow diagrams are to be made. Debugging hardware and software is very useful. Understanding this topic is the key to any successful embedded system project. It is important to consider this issue in the design phase, so that debug facilities can easily be added to a system during integration. This is where a designer’s control over the system makes it easy to step through code and trace hardware states. The Intel 80186, 80188 and 80286 are 16 bit microprocessors. These microprocessors are used as embedded controller. Actually, the 80186/80188 family includes four CMOS versions. These

2.8

Embedded Systems: Design, Programming and Applications

versions are compared as embedded controller. Architecture of 80186 and 80188 are described. Interface the 80186/80188 and the 80286 to memory and I/O is described with the help of suitable diagram. Development of Software for these processors is provided in this chapter. The function Software of memory management unit (MMU) of 80286 is stated to show the upgradation of this microprocessor.

2.2.5

Rabbit 8 bit Embedded Microprocessor Series

The Rabbit 3000 is a high-performance embedded microprocessor. It has C-friendly instruction set and fast number-crunching ability. There are many on-chip peripherals and interfacing to both memory and I/O. As a result, requirements of system components are highly reduced. Rabbit 3000 shares a similar architecture and a high degree of compatibility with the Z180, but with key improvements for superior performance and ease of use. Programmers familiar with a Z180-type embedded microprocessor will be completely at ease with the Rabbit 3000. It has 55 MHz clock speed, 6 serial ports, 52 parallel I/O lines, 7 timers, battery back up real-time clock and watchdog timer. The advantages of Rabbit 3000 are written below. 1. Many on-chip peripherals and interfacing to both memory and I/O; 2. Onboard slave port, enabling multi-processor designs; 3. Multiple clock speed options through software, allowing dynamic trading of power versus speed; 4. Highly optimized math libraries, yielding excellent math performance; 5. Three levels of interrupt priority, allowing fast response to real-time events; 6. Remote cold boot for downloading new programs over serial or parallel ports with no pre-existing program; 7. Dynamic C development system supplying royalty-free TCP/IP software stack with source code.

2.3

ARCHITECTURE OF INTEL 80186/80188 MICROPROCESSORS

The 90186 microprocessor is chip is a CMOS integrated circuit. It is a 68 pin IC. This microprocessor consists of following subsystems. 1. A clock generator; 2. A 16 bit ALU; 3. 16 bit general purpose registers; 4. A programmable interrupt controller with a control register; 5. Three 16 bit programmable timers; 6. Two programmable direct memory access (DMA) controller; 7. Chip select unit; 8. Programmable control registers; 9. Bus interface unit; 10. Six byte pre-fetch queue.

2.9

Embedded Processors

The block diagram of Intel 80186 microprocessor is shown in Fig. 2.3. The 80188 is identical to the 80186 microprocessor except following differences. 1. Intel 80186 microprocessor has 16 bit data bus, while 80188 contains an 8 bit data bus. 2. Intel 80186 microprocessor has 6 byte pre-fetch queue but Intel 80188 microprocessor has 4 byte queue. Memory interface

6 5 4 3 2 1

BIU

B-Bus ES CS SS DS IP

Queue

Control system unit

A-Bus

AH BH CH DH

AL BL CL DL SP BP SI

Fig. 2.3

ALU

EU Operands Flag register

Internal block diagram of intel 8086 microprocessor

The 80186/80188 contains additional reserved interrupt vectors and some powerful built in I/O features. Very often, these microprocessors are known as embedded controllers because they are not used as microprocessor baed computers but as a controller. The special feature of Intel 8086 is the inclusion of DMA controller unit, three programmable timer and programmable interrupt controller within the chip. The DMA unit transfers data between I/O and memory. The DMA controller must have source and destination pointer for data transfer from source to destination.

2.10

Embedded Systems: Design, Programming and Applications

The timer unit of Intel 80186 microprocessor has three 16 bit timer/counters. Two timers are used for following purposes. 1. Counting external events; 2. To provide waveforms from either an external clock or a CPU clock; 3. To interrupt CPU after specified number of events. The third timer counts CPU clock cycle. This timer can also be used to interrupt CPU after selected clock cycle and provides a DMA request pulse to the DMA unit within the CPU chip after a programmed number of clock cycles. The integrated interrupt controller of 80186 provides interrupt requests between internal and external sources. Two interrupt controller chips 8259A can also be cascaded with the integrated interrupt controller of 80186. In this case interrupt controller unit of 80186 performs the function of master controller. The chip select logic unit of Intel 80186 is used to enable memory or I/O devices. Six output lines are used for memory addressing and seven output lines are used for I/O addressing. The peripheral control register are located in 256 byte block of memory space or I/O space. 80186/80188 is available in four versions. The 80C186EC and 80C188EC are the most advanced version. Intel 80186 has more internal circuitry than that of Intel 8086 microprocessor. In addition to bus interface unit (BIU), execution unit (EU) and 6 byte queue, 80186 contains a clock generator, a 16 bit ALU, a programmable interrupt controller with a control register, three 16 bit programmable timers, two programmable direct memory access (DMA) controller, chip select unit and programmable control registers. For this reason, Intel 80186 requires less number of peripheral components than that of Intel 8086 microprocessor. These enhancement also increases the utility of the 80186/80188 microprocessors. As a result, many subsystems for the personal computers employ 80186/80188 as disc controller, Local area network controller etc. It is also used as switcher in cellular telephone systems. Basic features of Intel 80186/80188 microprocessors are described below.

Clock generator The internal clock generator circuit of Intel 80186 microprocessor is similar to 8284 clock generator circuit. The pin connections of the internal clock generator are X1, X2 and CLKOUT. X1 and X2 pins are connected to a crystal of operating frequency equals to twice the operating frequency of the microprocessor. The 80186/80188 microprocessors are available with operating frequency in 8 MHz, 12 MHz, 16 MHz or 25 MHz. The system clock signal is available at CLKOUT pin. This clock signal is used to drive other devices or provides timing signal to other microprocessor connected to the system. This clock generator also provides internal clock signal for synchronization READY signal.

Timer Timer section of 80186/80188 microprocessor consists of three programmable 16 bit timers. Two timers are used for counting external events and to generate waveforms for either an external clock or a CPU clock. These timers are driven by either the master clock of 80186/80188 microprocessor or by an external clock. The third timer is used to generate an interrupt after a programmed number

Embedded Processors

2.11

of clock cycles and it can provide the clock to the other timers. The third timer can also be used as a watch dog timer. The 80C186EC microprocessor has an additional timer known as watch dog timer. This is a 32 bit counter which is clocked internally by CLKOUT signal. When this counter hits zero, it generates a pulse on the WDTOUT pin. This WDTOUT pin is four CLKOUT periods wide. This output can be wired to RESET input to RESET the system. It can be connected to NMI inputs to initiate interrupt. It is programmed periodically so that it never count down to zero. Therefore, the function of this timer is to reset or interrupt the system.

Programmable interrupt controller (PIC) Programmable interrupt controller of 80186/80188 microprocessor controls all internal and external interrupts. It can also control two external 8259A programmable interrupt controller (PIC). In this case PIC of 80186/801888 functions as master interrupt controller and 8259A operates as slave PIC. When programmable controller of 80186/80188 microprocessor is not connected to any 8259A, five interrupt inputs are valid. These inputs are INT0 to INT3 and non-maskable interrupt NMI.

Programmable DMA unit Programmable direct memory access (DMA) unit has two DMA channels in lower versions and four DMA channels in the higher versions of 80186/80188 microprocessor. Data can be transferred between two memory locations, two I/O devices or memory and I/O devices.

Refresh control unit This unit generates address of refresh row at interval provided in the program. The refresh address is provided to memory system with the RFSH control signal. A refresh cycle is executed during active time of RFSH control signal.

Programmable chip select unit The chip select unit of 80186/80188 has 6 output lines for memory selection, 7 output lines for I/O selections and 10 output lines which can select either memory or I/O. In lower version of 80186/801888 the selection lines are divided into three groups which select memory. Function of each group of selection lines is described below. 1. The lower memory select signal enables memory for interrupt vectors. Start of lower memory location is 00000H and it finishes at FFFFFH; 2. The middle memory select signal enables up to four middle memory devices; 3. The upper memory select signal enables memory for reset. Therefore, the size of memory area is programmable and wait state can be inserted with selection of memory area. The programmable I/O selection signal addresses 128 byte block of I/O space. However, there is lower and upper memory chip selection pins in advanced versions of 80186/80188 microprocessor. In these versions, up to 15 wait state can be programmed.

Power save/power down unit In power save mode the system clock is divided by 4, 8 or 16 to minimize power consumption. The power save feature is achieved by software and implemented by hardware interrupt. In power down

2.12

Embedded Systems: Design, Programming and Applications

feature clock is stopped completely. This feature is available in the higher version of 80186/80188 microprocessor. This feature is achieved by executing HLT instruction. For the above mentioned special features, 80186/80188 are used as embedded controller. The Pentium brand microprocessors are also suitable for embedded system. Pentium is manufactured by using super superscalar architecture. The Pentium has two data paths (pipeline) that allow it to complete more than one instruction per clock cycle. One path can handle any instruction, while the other can handle the simplest, most common instructions. The use of more than one pipeline is a characteristic typical of RISC processors designs. 64 bit data path doubles the amount of information pulled from the memory on each fetch. This doesn’t mean that the Pentium can execute 64 bit applications; its main registers are still 32 bits wide. The Pentium series were designed to run at over 100 million instructions per second (MIPS). Pentium processors include following trade mark. 1. Pentium Pro; 2. Pentium II, Pentium II Xeon; 3. Pentium III, Pentium III Xeon; 4. Pentium 4, Mobile pentium 4, Mobile pentium 4 M, Pentium 4 Extreme edition; 5. Pentium M; 6. Pentium D, Pentium extreme edition; 7. Pentium dual or Pentium DUO. The earliest Pentiums were released at the clock speeds of 66 MHz and 60 MHz. Later on 75, 90, 100, 120, 133, 150, 166, 200, and 233 MHz versions gradually became available. 266 and 300 MHz versions were later released for mobile computing. Pentium Over Drive processors were released at speeds of 63 and 83 MHz as an upgrade option for older 486-class computers. Pentium 66 MHz and 60 MHz chips contained 3.1 million transistors. Transistor count has increased every year at a rate of about 40% per year. The release of the Pentium-III Coppermine a decade after the initial Pentium 66 release raised transistor count past 28 million. The original Pentium microprocessor had the internal code name P5. This was a pipelined in-order superscalar microprocessor, produced using a 0.8 µm process. It was followed by the P54C, a shrink of the P5 to a 0.6 µm process, which was dual-processor ready and had an internal clock speed different from the front side bus. In turn, the P54C was followed by the P54CS, which used a 0.35 µm process. The Pentium III was the first CPU to include a unique, retrievable, identification number, called Processor Serial Number (PSN). A Pentium III’s PSN can be read by software through the CPUID instruction if this feature has not been disabled in ROM BIOS. The issue was that Katmai’s hardware-implementation contradicted the parallelism model implied by the SSE instruction-set. Programmers faced a codescheduling dilemma: Should the SSE-code be tuned for Katmai’s limited execution resources, or should it be tuned for a future processor with more resources? Katmai-specific SSE optimizations yielded the best possible performance from the Pentium III family, but was suboptimal for later Intel processors, such as the Pentium 4 and Dual Core. On the other hand, the dual caches and dual pipe lines are continuously supplied data by 64 bit data bus. This also avoids conflicts between instruction pre-fetch and data access. The instruction cache of Pentium processor follows writethrough technique. As a result the memory is updated each time the processor writes into the cache.

Embedded Processors

2.13

The advantage of write through technique is that the main memory always contains the same data or instruction as cache. The code cache of the Pentium processor is write-protected.

2.4

ARCHITECTURE OF PENTIUM MICROPROCESSOR

In 1993, Intel Corporation developed Pentium microprocessor. It is a superscalar CISC microprocessor. It contains 3.3 million transistors. Pentium processor is packed in a 273 pin grid array package. Pentium microprocessor has a 32 bit address bus and 64 bit data bus. It consists of following building blocks. 1. Two arithmetic and logic units (ALU); 2. Two 8 KB cache memories; 3. On-chip floating point math coprocessor unit; 4. Pre-fetch buffers; 5. Branch target buffer; 6. Instruction decoder; 7. Control ROM; 8. Integer register file; 9. Bus unit; 10. Internal parity checker. The Pentium processor operates at 66 MHz clock frequency. The higher version of Pentium processor operates at 200 MHz clock frequency. It is designed to operate at 5 volt supply and fabricated by 0.8 micron technology. Since Pentium is a superscalar microprocessor, it can execute more than one instruction per clock cycle. Pentium employs two ALUs for dual pipe line operation. The two pipe lines are called U-pipe line and V-pipe line. Each pipe line has its own ALU, address generation circuitry and data cache interface. Each pipe line operates in following steps. 1. Pre-fetch; 2. Decode 1; 3. Decode 2; 4. Execution; 5. Write back. Pentium microprocessor uses hardwired instructions. As a result the performance of this processor is highly improved. The two cache memories of Pentium processor stores code and data separately. The organization of these cache memories is two set associative. The line size of these caches is 32 bits. Separate code and data cache saves the time of searching segments. Thus provision of separate cache makes the processor fast.

2.4.1

Pipeline in Pentium Microprocessor

The basic integer pipeline of Pentium processor is five stages long. The stages are broken down as follows on next page.

2.14

Embedded Systems: Design, Programming and Applications

1. Prefetch/Fetch: Instructions are fetched from the instruction cache and aligned in prefetch buffers for decoding; 2. Decode 1: Instructions are decoded into the Pentium’s internal instruction format. Branch prediction also takes place in this stage; 3. Decode 2: Instructions are decoded into the Pentium’s internal instruction format and microcode ROM kicks in, if necessary. Address computation takes place at this stage; 4. Execute: The integer hardware executes the instructions; 5. Write back: The results of the computation are written back to the register file. The main difference between the Pentium’s five stage pipeline and four stage pipeline prevalent at the line lies in the second decode stage.

2.4.2

Superscalar Architecture

The microprocessor architecture having more than one execution unit or pipeline is called superscalar architecture. The Pentium microprocessor has super scalar architecture. This superscalar architecture is generally provided in RISC microprocessor. For this superscalar architecture Pentium processors are suitable for Real-Time Embedded System. A digital cell phone contains a Z-80 microprocessor. The Z-80 is an 8 bit microprocessor. Intel Corporation introduced a powerful microcontroller 8051 which is a 8 bit microcontroller. The Motorola 6811 and Intel 8051 are popular microcontrollers called “PIC microcontrollers”.

2.5

MICROCONTROLLER

A microcontroller is a highly integrated chip that contains a CPU, ROM/EPROM, RAM and I/O ports. A microcontroller is designed for a very specific task to control a particular system. As a result, the parts can be simplified and reduced, which cuts down on production costs. Microcontrollers are sometimes called embedded microcontrollers, which mean that they are part of an embedded system, that is, one part of a larger device or system. A typical low-end microcontroller chip might have 1,000 bytes of ROM and 20 bytes of RAM on the chip, along with eight I/0 pins. The special characteristics of microcontroller are furnished below. 1. The microcontrollers are embedded inside some other device so that they can control the features or actions of the product. For this reason, microcontroller is also called “embedded controller”; 2. The microcontrollers are dedicated to one task and run one specific program. The program is stored in ROM; 3. The microcontrollers are low-power devices; 4. A microcontroller has a dedicated input device and often has a small LED or LCD display for output. A microcontroller also takes input from the device it is controlling and controls the device by sending signals to different components in the device; 5. A microcontroller is often small and low cost device. The components may be chosen to minimize size; 6. The actual processor used to implement a microcontroller can vary widely.

2.15

Embedded Processors Table 2.1

Difference between microprocessor and microcontroller Microprocessor

Microcontroller

1. Microprocessor consists of ALU, registers, control unit and buses fabricated on a single chip. 2. Microprocessor contains no RAM, ROM, I/O ports on chip. 3. The microprocessor system is bulkier and expensive due to addition of external RAM, ROM and peripheral chips. 4. Microprocessor system requires large circuitry for operation. 5. Microprocessor has versatility so that the designer can use the RAM, ROM and I/O ports as per their requirement. 6. Microprocessor is not suitable for many applications in which cost and space are critical.

1. Microcontroller consists of ALU, registers, control unit, buses, RAM, ROM, timers/counters, I/O ports and interrupts fabricated on a single chip. 2. Microcontroller has CPU in addition to a fixed amount of RAM, ROM, timer, interrupts and I/O ports on the same chip. 3. Microcontroller system is cheap due to RAM, ROM, timer, interrupts and I/O ports are in inbuilt the same chip. 4. Microcontroller system does not require large circuitry for operation. 5. In microcontroller system RAM, ROM and I/O ports are limited. 6. Microcontroller is ideal for many applications in which cost and space are critical.

A microcontroller is a true computer on a chip. It is a general purpose microprocessor with inbuilt RAM, ROM, I/O ports, and timers. A microcontroller has a CPU in addition to a fixed amount of RAM, ROM, I/O ports, and a timer all on a single chip. It is used to read data, perform limited calculations on that data, and control the interfaced devices based on those calculations. The microcontroller stores the program in ROM inbuilt in the microcontroller. Therefore, microcontroller is a single chip microprocessor system which consists of CPU, RAM, ROM serial and parallel I/O ports, timers and interrupts. The difference between microprocessor and microcontroller is shown in Table 2.1. The difference in block diagram of microprocessor and microcontroller is shown in Fig. 2.4.

Fig. 2.4

Difference in block diagram of microprocessor and microcontroller

2.16 2.5.1

Embedded Systems: Design, Programming and Applications

Classification of Microcontrollers

Microcontrollers are classified as follows. 1. Four bit microcontrollers; 2. Eight bit microcontrollers; 3. Sixteen bit microcontrollers; 4. Thirty two bit microcontrollers. Different types of microcontroller families are described in Table 2.2. Table 2.2

Microcontroller families 4 bit Microcontroller

IC Number

No. IC of pins

RAM capacity

ROM capacity

Number of I/O pins

No. of 16 bit Counter

No. of Other features vectored interrupt

TLCS 47

42

128 bytes

2 K bytes

35

1

Nil

Serial I/O

TMS 1000

28

64 bytes

1 K bytes

23

1

Nil

Serial I/O

COP 420

28

64 bytes

1K bytes

23

1

Nil

Serial I/O

MSM 6411

16

32 bytes

HMCS 40

28

8031

40

128 bytes

Nil

8032

40

256 bytes

8051

40

8052

40

1K bytes

11

1

Nil

Serial I/O

512 bytes

10

1

Nil

Serial I/O

32

2

5

Full duplex serial I/O

Nil

32

3

6

Full duplex serial I/O

128 bytes

4 K bytes

32

2

5

Full duplex serial I/O, UART

256 bytes

8 K bytes

32

3

6

Full duplex serial I/O

8 bit Microcontroller

8 bit Microcontroller IC Number

No. IC of pins

RAM capacity

ROM capacity

Number of I/O pins

No. of No. of 16 bit vectored Counter interrupt

Other features

8751

40

128 bytes

4 K bytes

32

2

5

Full duplex serial I/O

8752

40

256 bytes

8 K bytes

32

3

6

Full duplex serial I/O

16 bit Microcontroller HPC46164

60

512 bytes

16 K bytes

52

4

8

External memory 64 K, Full duplex UART, ADC

8096

68

256 bytes

8 K bytes

40

2

7

External memory 64 K, Full duplex UART, ADC

8094

48

256 bytes

-

24

2

7

External memory 64 K

8097

68

256 bytes

-

24

2

8

External memory 64 K Contd...

2.17

Embedded Processors Contd...

8095

48

256 bytes

-

20

2

8

External memory 64 K

8397

68

256 bytes

8 K bytes

24

2

8

External memory 64 K

8395

48

256 bytes

8 K bytes

20

2

8

External memory 64 K

80C196EA

160

1 k bytes register RAM 3 K bytes code RAM

8 K bytes

83

4

16

2.5.2

External memory 2 MB Serial I/O, ADC

Additional Circuits of Microcontrollers

Following additional circuits are added to microcontrollers to perform some special functions. 1. Analog to Digital Converters (ADC): This electronic circuit is added to convert external signals to digital signals; 2. Counter arrays: A few counter circuits are added to microcontroller for pulse generation; 3. Watchdog Timers (WDT): This timer is used to reset the microcontroller if program execution hangs up; 4. Pulse Width Modulation (PWM) circuit: PWM circuit is used for speed control of DC Motors; 5. Universal Synchronous and Asynchronous Receiver Transmitter (USART) circuit: This circuit is used for serial data transfer; 6. Phase Locked Loop (PLL) circuit: This circuit is used for synchronous communication; 7. External bus controllers: This circuit is used for controlling the bus system to connect static (RAM/ROM) and dynamic (SDRAM) memories.

2.5.3

Uses of Microcontrollers

Four bit microcontrollers are low cost microcontrollers. These microcontrollers are extensively used in electronic toys. 4 bit microcontrollers are also used in alphanumeric LED/LCD display drivers and portable battery chargers. Eight bit microcontrollers are the most popular microcontroller in use. Eight bits have proven to be suitable word size for controller tasks. One byte data word is adequate for most of the control and monitoring application. This byte size is also suitable for data communication. These microcontrollers are used in various control applications such as speed control of electric motors, position control and process control systems. Sixteen bit microcontrollers are used for high speed control systems. These microcontrollers can be programmed using high level language as well as assembly level language. The 16 bit microcontrollers are used in disc drives, modems, printers, scanners, servo control systems etc.

2.18

Embedded Systems: Design, Programming and Applications

Thirty two bit microcontrollers are used for very high speed intelligent control systems. These microcontrollers can be programmed using high level language as well as assembly level language. The 32 bit microcontrollers are used in image processing, disc drives, modems, printers, scanners, servo control systems etc.

2.6

ARCHITECTURE OF 8051 MICROCONTROLLER

In 1980s, Intel Corporation developed the 8051 microcontroller. This microcontroller is available in N-Channel Metal Oxide Semiconductor (NMOS) and complementary Metal Oxide Semiconductor (CMOS) construction in variety of package types. The 8051 chip is housed in a 40 pin DIP. The block diagram of 8051 microcontroller is shown in Fig. 2.4. The device is low power static design which offers a wide range of operating frequencies down to zero. Provision of idle mode and power-down mode operations are available in 8051. It operates with the power supply voltage range from 2.7 V to 5.5 V. The unique features of 8051 are internal ROM and RAM, I/O ports with programmable pins, timers/counters and serial data communication circuits. Table 2.3 shows the special features of 8051. The 8051 architecture shows following CPU components and specific features. 1. Arithmetic logic unit (ALU) for mathematical calculations and logical decisions; 2. Registers A and B; 3. 16 bit program counter (PC) and data pointer; 4. Eight bit program status word (PSW); 5. Eight bit stack pointer (SP); 6. Internal 4 K X 8 ROM; 7. Internal 128 X 8 RAM; 8. Four register banks, each bank containing 8 registers; 9. 80 bytes of general purpose data memory; 10. Sixteen bytes which can be addressed at the bit level; 11. Four 8 bit I/O ports, each having 8 pins; 12. Three 16 bit timer/counter; 13. Full duplex serial data Receiver/Transmitter; 14. Six control registers viz., TCON, TMOD, SCON, PCON, IP and IE; 15. Three external and two internal interrupt sources; 16. Oscillator and clock circuits; 17. Boolean processor. Table 2.3

Special features of 8051 Feature

Quantity

ROM

4 K bytes

RAM

128 byte

Timer

2 Contd...

2.19

Embedded Processors

Input output pins

32

Serial port

1

Interrupt sources

6

8051 microcontroller consists of a central processing unit which obtains the clock signal from an external oscillator. It has inbuilt 4K byte ROM and 128 byte RAM. 8051 has interrupt control unit and bus control unit. Two timers are included in this microcontroller chip. Four 8 bit I/O ports and two serial ports are also included in microcontroller 8051. Figure 2.6 shows the detailed architecture of microcontroller 8051. Functions of the different components of 8051 microcontroller are described below.

2.6.1

8051 Registers

Accumulator A:

Accumulator is 8 bit operand register. This register is used for data transfer and arithmetic instructions. It can be accessed bitwise. The result of the arithmetic operation is stored in accumulator.

B register:

This register is used with accumulator register for multiplication and division of two numbers. It stores the second operand. It is also used for storing upper 8bit of multiplication result and remainder in case of division. B register is used as temporary register. This register can be accessed through its special function register address 0F0 H. It can be used as general purpose register. The content of B register is bit addressable. Flag register:

This register is used to store the status word (PSW). It is a special function register. Single-bit flags are provided to store the result of execution of certain instruction. Another instruction may test the condition of the flag and make decision based on the status of the flag. The 8051 has seven flags. Four math flags respond automatically to the result of mathematical operations and rest three general purpose user flags that can be set or reset by the programmer as per requirement. The status bits of PSW reflect the state of microcontroller after execution of program. Figure 2.5 shows the program status word of 8051.

Bits

7

6

5

4

3

2

CY

AC

F0

RS1

RS0

OV

1

0 P Parity flag

Carry flag Auxiliary carry flag

Reserved (PSW1) Overflow flag

User flag 0

Register bank select bit

Fig. 2.5

Program status word of 8051

The math flags include Carry (c), Auxiliary carry, Overflow (OV) and Parity (P). User flags are F0, RS1 and RS0. Flags RS1 and RS0 are used to select register bank. Table 2.4 illustrates the register bank selection with address range.

2.20

Embedded Systems: Design, Programming and Applications 8051 Family microcontroller Arithmetic and logic unit A

B

PC

DPTR DPH DPL

PSW

Special function register RAM

Latch ROM

16-bit address bus EA ALE PSEN XTAL1 XTAL2 RESET

Byte/bit address

System timing

Register bank 3

System interrupts

Register bank 2

Timer data buffers memory controls

VCC GND

Latch

Port 0

I/O A0-A7 D0-D7

Port 1

I/O

Port 2

I/O A8-A15

Port 3

I/O Interrupt Counter Serial data RD-WR

Special function register IE IP

Latch

PCON SBUF SCON TCON

Register bank 1

TLO THO

Register bank 0

TL1

Latch

TH1 Internal RAM structure

Fig. 2.6 Table 2.4

Detailed architecture of microcontroller 8051

Register bank selection RS1

RS0

Register bank

Address

0

0

0

00 H – 07 H

0

1

1

08 H – 0F H

1

0

2

10 H – 17 H

1

1

3

18 H – 1F H

Bit 1 of PSW of 8051 is reserved for future use. Flag F0 is available to the user for general purpose use. The addresses of flags are D0H, D1H, D2H, D3H, D4H D5H, D6H and D7H for flags P, PSW1, OV, RS0, RS1, F0, AC, CY, respectively. Stack pointer: The stack pointer is an 8 bit register. The content of this register is incremented by one for the data is stored onto the stack. The 8 bit address of the stack top is stored in this register. Stack pointer is initialized to 07 H after execution of reset instruction and stack begins from address 08 H. Stack can be relocated in memory area 30 H to 7F H. Program counter:

Program Counter (PC) Register points to the address of the next instruction to be executed. PC is 16 bits wide i.e. range is 0000 to FFFFH. It wake up at memory address

2.21

Embedded Processors

0000 when it powered up. First opcode must be burned into memory location at 0000H. Program instruction bytes are fetched from locations in memory that are addressed by the PC. It is achieved by ORG statement. Content of PC is automatically incremented after every instruction byte is fetched. PC has no internal address. Data Pointer Register (DPTR): The data pointer is a 16 bit register. It is used to store the address of a byte in memory. The DPTR consists of two registers viz., data pointer high (DPH) and data pointer low (DPL). These are 8bit registers. DPH and DPL registers are used to provide memory address for internal and external code access and external data access. DPTR is very useful for string instructions and look up table operation. DPTR can be loaded with 16 bit address by the instruction MOV DPTR, # 16 bit data. Special Function Registers (SFRs):

The microcontroller operations are done by a group of specific internal registers. These registers are known as Special function registers (SFR). SFRs are also bit addressable so that the programmer can change the content of these registers as per their requirement. Table 2.5 shows the SFRs symbols, names and addresses.

2.6.2

Oscillator

The electronic circuitry generates the clock pulses to synchronize the operations of microcontroller. Figure 2.7 shows a crystal oscillator circuit which is used to generate the clock pulses. The crystal frequency is the basic clock frequency of the microcontroller. The 8051 operates at 12 MHz frequency. The quartz crystal with the capacitors, as shown in figure, is connected to the microcontroller externally. All other components of oscillator are inbuilt within the 8051 IC. XTAL1 pin

Crystal oscillator XTAL2 pin

Fig. 2.7 Table 2.5

Quartz crystal circuit for oscillator

Special function registers with symbols, names and addresses

Symbol

Name

Address

Symbol

Name

Address

ACC

Accumulator

0E0 H

TCON

Timer/counter control

88 H

B

B register

0F0 H

T2CON

Timer/counter 2 control

0C8 H

PSW

Program status word

0D0 H

T2MOD

Timer 2 mode control

0C9 H

SP

Stack pointer

81 H

TH0

Timer/counter 0 high byte

8C H

DPTR

Data pointer

TL0

Timer/counter 0 low byte

8A H

DPL

Data pointer low byte

TH1

Timer/counter 1 high byte

8D H

DPH

Data pointer high byte

83 H

TL1

Timer/counter 1 high byte

8B H

P0

Port 0

80 H

TH2

Timer/counter 2 high byte

0CD H

82 H

Contd...

2.22

Embedded Systems: Design, Programming and Applications

Contd...

P1

Port 1

90 H

TL2

Timer/counter 2 high byte

0CC H

P2

Port 2

A0 H

RCAP2H

Capture register 2 high byte

0CB H

P3

Port 3

0B0 H

RCAP2L

Capture register 2 low byte

0CA H

IP

Interrupt priority control

0B8 H

SCON

Serial control

98 H

IE

Interrupt enable control

0A8 H

SBUF

Serial data buffer

99 H

TMOD

Timer counter mode

89 H

PCON

Power control

87 H

2.6.3

Internal Memory

The 8051 has internal RAM and ROM for program code bytes and data storage. External memory can be added to 8051 using suitable circuits. 8051 has 128 byte internal RAM which is organized in three different areas. In RAM locations, 00 H to 1F H are used as 32 registers organized as four banks of eight registers each. The four register banks are numbered 0 to 3. Each register bank has eight registers named R0 to R7. Each register can be addressed by its RAM address or by its name. The R0 of bank-3 can be addressed as R0 or 18 H. Bank-0 is selected on reset of 8051. A bit addressable area 20 H to 2F H of 16 bytes memory area forms 128 addressable bits. 8 bits form any byte addresses from 20 H to 2F H. These addressable bits are useful for specifying binary event. Addressable area of RAM from addresses 30 H to 7F H is known as scratch pad RAM. 80 bytes of memory are available in this area. This memory area can be used as general purpose RAM. Internal ROM:

8085 has 4 KB internal ROM. This memory area occupies code address space 0000 H to 0FFF H. Program counter is used to address program code bytes from this memory area. If the program address is higher than 0FFF H, 8051 automatically fetch code bytes from external memory. Code bytes may be addressed totally in internal ROM, totally in external ROM or in combination of external ROM and internal ROM. Figure 2.8 shows the details of register banks and bit addressable area of internal RAM organization. Table 2.6 shows the address of the registers of register bank. 7F 80 byte 30 2F 20 1F 18 17 10 0F 08 07 00

Scratch pad RAM

16 bytes Register bank 3 Register bank 2 Register bank 1 Register bank 0

Fig. 2.8 Ram memory space allocation in the 8051

2.23

Embedded Processors Table 2.6

Address byte of registers of register bank

Register Bank

Register

Byte address

Register Bank

Register

Byte address

Bank 3

R7

1F

Bank 1

R7

0F

Bank 3

R6

1E

Bank 1

R6

0E

Bank 3

R5

1D

Bank 1

R5

0D

Bank 3

R4

1C

Bank 1

R4

0C

Bank 3

R3

1B

Bank 1

R3

0B

Bank 3

R2

1A

Bank 1

R2

0A

Bank 3

R1

19

Bank 1

R1

09

Bank 3

R0

18

Bank 1

R0

08

Bank 2

R7

17

Bank 0

R7

07

Bank 2

R6

16

Bank 0

R6

06

Bank 2

R5

15

Bank 0

R5

05

Bank 2

R4

14

Bank 0

R4

04

Bank 2

R3

13

Bank 0

R3

03

Bank 2

R2

12

Bank 0

R2

02

Bank 2

R1

11

Bank 0

R1

01

Bank 2

R0

10

Bank 0

R0

00

2.6.4

External Memory

External memory can be connected to microcontroller 8051. Two memory spaces are available by the 16 bit PC, DPTR and control pins for enabling external ROM and RAM chips. External RAM is needed when 128 bytes of internal RAM is not sufficient. External RAM may be added up to 64 KB in 8051 family. Figure 2.9 shows the connection diagram of 8051 with external data RAM. Rd WR

P3.7 P3.6 PSEN P2.7 A14 8051

A12

P2.0 ALE P0.7

WE CE A13 A12

OE

A8 4K RAM

AD7 G

A7

74LS373 P.00

Fig. 2.9

OC

A0

GND

D7

Connection diagram of 8051 with external data RAM

D0

2.24

Embedded Systems: Design, Programming and Applications

The external memory is accessed by output drivers of port P0 and P2 and input buffers of port P0 and P2. P0 provides the low byte and P2 provides the high byte of external memory address. All ports on reset configure as output.

2.6.5

I/O Ports

The 8051 has four 8 bit I/O ports viz., P0, P1, P2 and P3. These four ports connect the microcontroller to the outside world. Each latch and corresponding driver of port P0, P1, P2 and P3 is provided to the corresponding on chip I/O ports. All ports are bidirectional input output ports. The port addresses are stored in the special function register bank. Port 0: This port is used as either input or output port. It is also designate as AD0 – AD7, allowing this to be used for both address and data. Address Latch Enable (ALE) signal indicates whether P0 is transmitting address or data. When ALE = 0, it provides data D0 – D7. If ALE = 1, P0 transmits address A0 – A7. Port 1(Pin 1 – Pin 8): Port 1 occupies 8 pins. Generally it is an output port but it can be used also as input port. The port registers specify the value to be output on the specific output port and read value from the specified input port. Ports are also used as bit addressable. Port 2(Pin 21 – Pin 28):

Port 2 is used as I/O port. It outputs the higher byte of the external memory address, designated as A8 – A15 indicating its dual role.

Port 3 (Pin 10 – Pin 17): Port 3 can also be used as I/O ports. The pins of port 3 have different functions as shown in Table 2.7. Table 2.7

Pin functions of port 3

P3 bits

Function

Pin No.

P3.0

Serial input line RXD

10

P3.1

Serial output line TXD

11

P3.2

External interrupt line INT0

12

P3.3

External interrupt line INT1

13

P3.4

External timer input lines T0

14

P3.5

External timer input lines T1

15

P3.6

External data memory write strobe WR

16

P3.7

External data memory read strobe RD

17

Serial port data buffer: It consists of two registers viz., transmit buffer and receive buffer. The transmit buffer is a parallel in serial out register and receive buffer is a serial in parallel out register. These registers are also known as SBUF.

2.6.6 Timing and Control Registers Timing register: Timing registers of 8051 consists of two 16 bit timing registers. These registers are named as T0 and T1. Each timer register is divided into two 8 bit registers. TH0 and TL0 represent the higher byte and lower byte of T0, respectively. Similarly, TH1 and TL1 represent

2.25

Embedded Processors

the higher byte and lower byte of T1. These four registers are accessed by individual addresses allotted to them. These addresses are stored in SFR in the address range from 80H to FF H. Control registers:

The control registers of 8051 are following special function registers. Special function register bank stores the addresses of all of the control registers. 1. Interrupt priority register IP; 2. Interrupt enable register IE; 3. Timer mode control register TMOD; 4. Timer/Counter control register TCON; 5. Serial mode control register SCON; 6. Power control register PCON.

Timer mode control register TMOD: All counter action is controlled by bit states in the timer mode control register (TMOD). It is used for two timers. It may be considered as two duplicate 4 bit registers. Each 4 bit register controls the action of one of the timer. There are four modes of operation of the timer. Figure 2.10 shows the format of timer mode control (TMOD) special function register. Bits

5

6

7 Gate

C/T

3

4 M1

M0

2 Gate

0

1 C/T

M1

M0

Timer 0

Timer 1

Fig. 2.10 TMOD special function register

The functions of the different bits of the TMOD special function register is shown in Table 2.8 Table 2.8

Functions of bits of TMOD special function register Symbol

Function

7 and 3

Bit number

Gate

Bits 7 and 3 are OR gate enable bits. These bits control RUN and STOP of timer 1 and 0. These bits can be set by program to RUN the timer if TR1 in TCON ______ is set and external interrupt INT1/0 = 1. Gate = 0 enables timer to RUN if bit TR1/0 in TCON is set.

6 and 2

C/T

When these bits are set, timer 1/0 acts as counter to count pulses from external __ input. C/T = 0 enables timer for counting internal frequency.

5 and 1

M1

Timer/counter mode select bits

4 and 0

M0

Timer/counter mode select bits

The timer/counter mode select bits M1 and M0 select the mode of operation of the timer as follows (Table 2.9).

2.26

Embedded Systems: Design, Programming and Applications

Table 2.9

Mode operation M1

M0

Mode

0

0

0

13 bit Timer/Counter

Function

0

1

1

16 bit Timer/Counter

1

0

2

Auto-reload of TL from TH

1

1

3

Two 8 bit Timers using timer 0

Timer control register TCON: It is a special function register. TCON has control bits and flags for the timers in the upper nibble and control bits and flags for the external interrupts in the lower nibble. Bits af TCON special function register are addressable as TCON.0 to TCON.7. Figure 2.11 shows the format of timer control (TCON) special function register. Bits

5

6

7 TF1

TR1

Timer 1

3

4 TF0

TR0

2 IE1

0

1 IT1

IE0

IT0

Timer 0

Fig. 2.11 Timer control (TCON) special function register

The functions of the different bits of the TCON special function register are shown in Table 2.10. Instruction register (IR):

Instruction register decodes the opcode of any instruction and sends the decoded signal to the timing and control unit to generate signal for execution of the instruction. Microcontroller 8051 is a 40 pin integrated circuit. It is available in DIP, QFP and LLC packages. Table 2.10

Functions of the different bits of the TCON special function register

Bit number

Symbol

Function

7

TF1

Bit 7 is used for timer 1 overflow flag. TF1 = 1, when all bits of timer roll from 1 to 0. TF1 = 0, when processor vectors execute interrupt service routine.

6

TR1

Bit 6 is timer 1 run control bit. This bit is set to enable timer to count. It is made 0 to half timer.

5

TF0

Bit 5 is used for timer 0 overflow flag. TF0 = 1, when all bits of timer roll from 1 to 0. TF0 = 0, when interrupt service processor vectors execute routine.

4

TR0

Bit 4 is timer 0 run control bit. This bit is set to enable timer to count. It is made 0 to half timer.

3

IE1

This bit is used for external interrupt 1 edge flag. IE1 = 1 when high-to low edge signal is received by port pin P3.3. IE1 = 0, when processor vectors interrupt service routine.

2

IT1

This bit is known as external interrupt 1 signal type control bit. This bit is set to enable external interrupt 1. IT1 is reset to enable a low level signal on external interrupt 1 to generate an interrupt. Contd...

Embedded Processors

2.27

Contd...

2.6.7

1

IE0

This bit is used for external interrupt 0 edge flag. IE0 = 1 when high-to low edge signal is received by port pin P3.3. IE1 = 0, when processor vectors interrupt service routine.

0

IT0

This bit is known as external interrupt 0 signal type control bit. This bit is set to enable external interrupt 0. IT0 is reset to enable a low level signal on external interrupt 0 to generate an interrupt.

Pin Diagram of 8051

The 8051 chip is housed in a 40 pin DIP. The pin diagram of 8051 microcontroller is shown in Fig. 2.12 The pin functions of 8051 microcontroller are described in this section. T2/P1.0 T2EX/P1.1 P1.2 P1.3 P1.4 P1.5 P1.6 P1.7

1 2 3 4 5 6 7 8

RST RXD/P3.0 TXD/P3.1 INT0/P3.2 INT1/P3.3 T0/P3.4 T0/P3.4 WR/P3.6 RD/3.7 XTAL2 XTAL1 Vss

9 10 11 12 13 14 15 16 17 18 19 20

40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21

Vcc P0.0/AD0 P0.1/AD1 P0.2/AD2 P0.3/AD3 P0.4/AD4 P0.5/AD5 P0.6/AD6 P0.7/AD7 EA/Vpp ALE PSEN P2.7/A14 P2.6/A13 P2.5/A12 P2.4/A11 P2.3/A11 P2.2/A10 P2.1/A9 P2.0/A8

8051

Fig. 2.12

Pin diagram of 8051

Pin 1 to pin 8 (Port 1):

These 8 pins are used as input/output port. This port is an 8 bit quasi bidirectional bit addressable port. The port address is stored in special function register.

Pin 9 (RST): This pin is known as reset pin of 8051. The microcontroller goes to reset when RST = 1 for two or more machine cycles. Following two methods are used reset 8051. 1. Power on reset; 2. Manual reset. After reset, all values stored in registers are zero except the content of SP = 0007 H, P0 = FF H, P1 = FF H, P2 = FF H and P3 = FF H. In power on reset circuit, a capacitor and a resistor is used to supply reset voltage as shown in Fig. 2.13. In manual reset circuit, a switch is used to reset 8051 as shown in Fig. 2.14.

2.28

Embedded Systems: Design, Programming and Applications

Vcc

Vcc C C

R

R Vss

Fig. 2.13

Vss

Power on reset circuit

Fig. 2.14

Manual reset circuit

Pin 10 to pin 17: This pins are used for port 3. This port is 8 bit bidirectional bit addressable I/O port. The alternative functions of the pins of port 3 are illustrated in Table 2.11. Pin 18 and 19:

These pins are known as XTAL1 and XTAL2 respectively. These pins are used to connect crystal oscillator of frequency ~ 12 MHz to the 8051. The microcontroller’s operation synchronizes with crystal oscillator’s output signal.

Table 2.11

Alternative functions of the pins of port 3 Pin number

Function

Pin 3.0

Serial input data pin RXD

Pin 3.1

Serial output data pin RXD

Pin 3.2

External interrupt pin 0 INT0

Pin 3.3

External interrupt input pin INT1

Pin 3.4

External input to timer 0 (T0)

Pin 3.5

External input to timer 1 (T1)

Pin 3.6

Write control signal for external data memory (WR)

Pin 3.7

Read control signal for external data memory (RD)

____ ____

___ ___

Pin 20:

This pin is known as Vss pin. Actually, this pin is connected to the ground connection of the power supply.

Pin 21 to pin 28:

These pins are used as I/O port 2 pins. This port is an 8 bit quasi-bidirectional bit addressable I/O port. These pins are pulled high internally. During external program and data memory access, port 2 generates high order eight bits of address A15 to A8 if ALE = 1 and EA = 0. Pin 29:

_____

This pin is named as PSEN i.e. program store enable pin. It is an active low output control signal. The signal from this pin is used for reading data from external memory. During reading data from external memory, this pin is activated after every six clock cycles and it remains high during execution of program from internal ROM.

Embedded Processors

2.29

Pin 30: (ALE): This pin is known as address latch enable pin. It is used for de-multiplexing the address/data bus when 8051 is interfaced with external memory. Port 0 is used as address bus if ALE = 1 and port 0 is used as data bus when ALE = 0. Pin 31: This pin is known as external access (EA) pin. It is connected to either Vcc or ground. When this pin is connected to Vcc, program from internal memory is executed. Pin 32 to 39:

These pins are used as I/O port 0 pins. This port is an 8 bit quasi-bidirectional bit addressable I/O port. The pins of port 0 acts as multiplexed address/data bus and address latch enable signal de-multiplexes bits AD7 to AD0. This port provides data D7 to D0 if ALE = 0 and address A7 to A0 if ALE = 1. Each pin of the port 0 must be connected through 10 KW pull up register. Pin 40:

This pin is a power supply pin known as Vcc pin. Positive terminal of power supply is connected to this pin.

2.6.8

Interrupts

Execution of normal program by microcontroller can be interrupted by external signal or instruction written in the program. Intel 8051 microcontroller also allow interruption of execution of the program. A type code is assigned by 8051 to every interrupt for identification of interrupt. The interrupt can also be initiated by external devices or by software instructions. When interrupt is initiated, the microprocessor stops execution of the current program and calls a procedure or service routine which services the interrupt. At the end of the interrupt service routine, execution of the main program again starts from the instruction where it stopped before the interrupt. If the execution of a normal program of a microprocessor is interrupted by instruction then the interrupt is known as software interrupt. Therefore, interrupts are enabled by using software. The interrupts are also disabled by software. Actually, when a microcontroller is executing an important program then the interrupts are disabled. Sometime it is desirable to inhibit the interruption of the execution of the program. Execution of a program may be interrupted by abnormal internal condition of the microcontroller. This is known as exception. Interruption of execution of the program may also be caused by external events. This is also a type of exception. However, Exceptions includes program faults, traps and abnormal conditions generated by hardwares. All most all applications of microcontrollers involve responding to events quickly to control the events. Interrupts are only means by which real time program can be written successfully. Interrupt may be generated in chip operation or it can be applied from external source. The interrupt subroutines are stored in a predetermined address. There are five interrupts applicable in 8051. Three interrupts are generated by timer flag 0, timer flag 1 and the serial port interrupt. _____ _____ Two interrupts are initiated by external signal applied to pins INT0 and INT1. The program controls the functions of all interrupts. Programmer can change the content of interrupt enable register (IR), interrupt priority register and timer control register to perform desirable functions.

2.30

Embedded Systems: Design, Programming and Applications

Interrupts and Polling There are two ways by which a microcontroller can serve several devices. 1. Interrupt: The program associated with interrupt is called Interrupt service routine. Many devices can be served by assigning priority, but not at the same time. In interrupt method the microcontroller can ignore a device request for service. 2. Polling: In polling, the microcontroller continuously monitors the status of a given device; when the condition is met, it performs the service. The main disadvantage of polling is that it wastes much of the microcontroller’s time. It is not possible to assign priority and ignore a device for service since polling method checks all devices in a round-robin process.

Steps in executing interrupt After activation of an interrupt, the microcontroller goes through the following steps: 1. Finishes the instruction it is executing and saves the address of the next instruction on the stack. 2. Saves the current status of all the interrupts. 3. Jumps to a fixed location in memory called the interrupt vector table that holds the address of the interrupt service routine. 4. The microcontroller gets the address of the ISR from the interrupt vector table, jumps to it and starts to execute it. 5. After executing RETI instruction, the microcontroller returns to the place from where it was interrupted and starts to execute from that address. Interrupt Programming:

An interrupt is an external event that interrupts the microcontroller to inform it that a device needs its service. The 8051 has 6 interrupts, 5 of which are user-accessible. The steps of interrupt programming are shown below. 1. When this reset pin is activated, the 8051 jumps to address location 0000; 2. Two interrupts are set aside for the timers. One for timer 0 and one for timer 1. Memory locations 000BH and 001BH in the interrupt vector table belong to timer 0 and timer 1 respectively; 3. Two interrupts are set aside for external hardware_____ interrupts. Memory locations 0003H _____ and 0013H in the interrupt vector table belong to INT0 and INT1 respectively; 4. Serial communication has a single interrupt that belongs to both receive and transfer data. The interrupt vector table location 0023H belongs to this interrupt.

Interrupt Enable (IE) register:

7

6

5

EA



ET2

Bit format of IE register is shown below. 4 3 2 1 ES

ET1

EX1

ET0

0 bits EX0

Bit 7: This is known as enable interrupt bit EA. When EA = 0, all interrupts are disabled. If EA = 1 individual interrupts are enabled by their enable bits. Bit 6:

This bit is not used.

2.31

Embedded Processors

Bit 5:

This bit is known as ET2 and it is reserved for future use.

Bit 4:

This bit is known as enable serial port interrupt bit (ES). If ES = 1, serial port interrupt is enabled. When ES = 0, serial port interrupt is disabled.

Bit 3:

This bit is known as enable timer 1(ET1) overflow interrupt bit. If ET1= 1, timer 1 overflow interrupt is enabled. If ET1 = 0, timer 1 overflow interrupt is disabled. Bit 2: _____

This bit is known as enable external _____ interrupt 1 (EX1) overflow interrupt bit. If EX1= 1, INT1 interrupt is enabled. If EX1 = 0, INT1 interrupt is disabled. Bit 1:

This bit is known as enable timer 0 (ET0) overflow interrupt bit. If ET0 = 1, timer 0 overflow interrupt is enabled. If ET0 = 0, timer 0 overflow interrupt is disabled. _____

Bit 0:

This bit is known _____ as enable external interrupt 0 (EX0) bit. If EX0 = 0, INT0 interrupt is enabled. If EX0 = 0, INT0 interrupt is disabled.

Interrupt Priority (IP) register:

Bit format IP is shown below.

7

6

5

4

3

2

1





PT2

PS

PT1

PX1

PT0

Bit 7:

This bit is not used.

Bit 6:

This bit is not used.

Bit 5:

This bit is known as PT2 and it is reserved for future use.

0 bits PX0

Bit 4: This bit is known as priority of serial port interrupt (PS). If PS = 1, priority of serial port interrupt is enabled. When PS = 0, priority of serial port interrupt is disabled. Bit 3:

This bit is known as priority of timer 1(PT1) overflow interrupt. If PT1= 1, priority of timer 1 overflow interrupt is enabled. If PT1 = 0, priority of timer 1 overflow interrupt is disabled.

Bit 2:

This bit is known as Priority of external interrupt 1 (PX1) overflow interrupt. If PX1= 1, priority of external interrupt is enabled. If PX1 = 0, priority of external interrupt is disabled.

Bit 1:

This bit is known as priority of timer 0 (PT0) overflow interrupt. If PT0 = 1, priority of timer 0 overflow interrupt is enabled. If ET0 = 0, priority of timer 0 overflow interrupt is disabled.

Bit 0: This bit is known as priority of external interrupt 0 (PX0). If PX0 = 0, priority of external interrupt is enabled. If PX0 = 0, priority of external interrupt is disabled. When the microcontroller is interrupted the content of PC is stored in stack, interrupt service routine is executed and after execution of the subroutine PC address is restored by the instruction RETI. Timer flag interrupt:

If timer counter over flows, corresponding timer flag TF0 or TF1 is set. As a result, an interrupt generates a program call to the specific timer subroutine to clear the content of the flag to zero.

Serial port interrupt:

When a data byte is received in serial port, RI is set in the SCON register. When a data byte is transmitted in serial port, TI is set in the SCON register. This two signals are ORed to generate serial port interrupt. This interrupt call a program to reset RI and TI to enable the next data transfer operation.

2.32

Embedded Systems: Design, Programming and Applications

External interrupts:

Inputs to the pins INT0 and INT1 can set the IE0 and IE1 in the TCON register. The interrupt vector table is shown in Table 2.12.

Table 2.12

Interrupt vector table of 8051 Interrupt

ROM location (hex)

Pin number

Reset

0000

9

External hardware interrupt 0 INT0

0003

(P3.2) 12

Timer 0 interrupt TF0

000B

External hardware interrupt 1 INT1

0013

Timer 1 interrupt TF1

001B

Serial com interrupt R1 and T1

0023

2.6.9

(P3.3) 13

Stack Operation in 8051

The stack refers to an internal RAM where the data is stored. Stack pointer register is used to hold an internal RAM address that is called the top of the stack. When the 8051 is powered up, the SP register contains value 07 i.e. RAM location 08 is the first location being used for the stack by the 8051. The storing of a CPU register in the stack is called a PUSH. The program to store data from a register is shown below. Program: MOV R6, #25H MOV R1,#12H MOV R4, #0F3H PUSH 6 PUSH 1 PUSH 4 Figure 2.15 shows the execution of PUSH instruction. After PUSH 6

After PUSH 1

After PUSH 4

0B

0B

0B

0B

0A

0A

0A

0A

F3

09

12

09

12

08

25

08

25

09

09

08

08 Start SP = 07

25 Start SP = 08

Fig. 2.15

Start SP = 09

Start SP = 0A

Execution of PUSH instruction

POP: The loading the contents of the stack back into a CPU register is called a POP. The method of popping any data from stack is shown in Fig. 2.16.

2.33

Embedded Processors

POP POP POP

4 1 6

POP stack into R4 POP stack into R1 POP stack into R6 After POP 3

0B 0A 09 08

54 F9 76 6C Start SP = 0B

0B 0A

F9

09

76

08

6C Start SP = 0A

Fig. 2.16

2.7

After POP 5

After POP 2

0B

0B

0A

0A

09

76

09

08

6C

08

Start SP = 09

6C Start SP = 08

Execution of POP instruction

DATA COMMUNICATION

The 8051 microcontroller communicate data serially. Serial data is transferred in either asynchronous mode or synchronous mode. Distinction between asynchronous and synchronous data transmission is shown in Table 2.13. Table 2.13 Asynchronous data transmission

Synchronous data transmission

1. If speed of data transfer of microprocessor and I/O 1. If speed of data transfer of microprocessor and I/O terminal is not equal then the mode of data transfer terminal is equal then the mode of data transfer is is called asynchronous data transmission. called synchronous data transmission. 2. In asynchronous data transmission both transmitter 2. In synchronous data transmission both transmitter and receiver are not synchronous with the common and receiver are synchronous with the common clock clock signal. signal. 3. In asynchronous data transmission one character (bit) 3. In synchronous data transmission one block of data is transmitted at a time. For this reason this type of is transmitted at a time using a clock signal. For this data transfer is also called character oriented data reason this type of data transfer is also called clock transmission. oriented data transmission. 4. The framing bits of asynchronous data transmission 4. The framing bits of synchronous data transmission are transferred with a character one at the starting are transferred with a block. another at the ending of the byte. 5. The speed of asynchronous data transmission is less than 20 K bauds.

5. The speed of synchronous data transmission is more than 20 K bauds.

6. Asynchronous data transmission is implemented 6. Asynchronous data transmission is implemented using software. using hardware.

Asynchronous transmission is also called start-stop transmission because start and stop bits are transmitted with each byte. No clock is transmitted with asynchronous data transmission. In synchronous data transmission, synchronization character is transmitted with data block. A clock

2.34

Embedded Systems: Design, Programming and Applications

signal is also included with data. The comparison between asynchronous and synchronous data transmission is shown in Table 2.13.

2.7.1

Asynchronous Serial Data Transmission Format

A data transmission format is related to synchronization, direction of dataflow, speed of dataflow, medium of transmission and errors in data. In asynchronous transmission a start and a stop bit are used at start and end of the byte, respectively. Since each character is individually identified, character can be sent at any time. Figure 2.17 illustrates a typical format of transmission of a byte in asynchronous serial data mode. Figure shows that the signal line is in a constant high (marking) state, when no data is sent. The beginning of a data character is shown by a line going low for one bit time. This bit is known as start bit. The data bits are then transmitted one after another with least significant bit at first. The data word may consists of 6, 7 or 8 bits The data byte is followed by a parity bit which is used to check the errors in received data. After transmission of parity bit the signal goes high for at least one bit time to identify the end of the character. This high bit is called the stop bit. HIGH

HIGH

LOW Start D0 D1 D2 D3 D4 D5 D6 D7 D8 Parity Stop Stop One character

Fig. 2.17 Typical bit format used for transmitting asynchronous serial data

The rate of serial data transfer is called baud rate. The baud rate is defined as reciprocal of time between signal transitions. Therefore, Baud rate = 1/Time between signal transitions If signal transitions occur in every 5 ms then baud rate of data transmission is obtained as 1/1.665 ms = 600 Baud.

2.7.2

Synchronous Serial Data Transmission Format

If speed of data transfer of microprocessor and I/O terminal is equal then the mode of data transfer is called synchronous data transmission. In synchronous serial data transmission, data block is transmitted with clock pulses. Therefore, start and stop bits are not necessary in case of synchronous data transmission. Synchronization of data transfer is done by transmitting synchronization (clock) pulse with data block. Figure 2.18 illustrates the typical bi-synchronous serial data format used for synchronous serial data transmission. Bi-synchronous serial data format is a byte oriented protocol. Serial data link control (SDLC) protocol and high level data link control (HDLC) protocols are also used for synchronous serial data transmission.

2.35

Embedded Processors

SYNC

SYNC

DATA

DATA

DATA

DATA

END OF

DATA

Fig. 2.18 Typical bi-synchronous serial data format used for synchronous serial data transmission

The 8051 microcontroller has a serial data communication circuit. This circuit uses register SBUF to store data. SCON register controls data transfer and Bits of SCON are addressable as SCON.0 to SCON.7. PCON register controls data transfer rates. Bits of PCON register are not addressable. Pins TXD and RXD are connected to serial data network. SBUF consists of two registers. One holds data to be transmitted from 8051 and the other stores received data from external peripheral. Both of them use address of 99 H. There are four programmable modes for serial data communication. These modes are selected by SM0 and SM1 bits in SCON register. The bit functions of serial port control register SCON and power mode control register PCON are described below. These modes are selected by SM0 and SM1 bits in SCON register. The bit functions of serial port control register SCON is described in Fig. 2.19.

Serial Port Control SCON Special Function Register 7

6

5

4

3

2

1

0

SM0

SM1

SM2

REN

TB8

RB8

TI

RI

bit

Fig. 2.19 Serial port control register SCON

Bit functions of serial port control SCON special function register Bit 7:

Mode control bit SM0 is used to select mode of serial data communication.

Bit 6: Mode control bit SM1 is also used to select mode of serial data communication. The mode selection of serial data communication using SM0 and SM1 is shown in Table 2.19. Bit 5:

Multiprocessor bit SM2 is programmed to enable multiprocessor communication in mode 2 and mode 3. If SM2 = 1, an interrupt is generated if bit 9 of received data is 1 and no interrupt is generated if bit 9 of received data is 0.

Bit 4:

Receive enable bit REN is set to enable reception and reset to disable reception.

Bit 3:

Transmitted bit 8 (TB8) is set and reset by program in mode 2 and mode 3.

Bit 2:

Received bit 8 (RB8) indicates bit 8 is received in mode 2 and mode 3, stop bit is received in mode 1 and it is not used in mode 0.

Bit 1:

Transmit interrupt flag bit TI is set at the end of bit 7 in mode 0 and at the starting of the stop bit of other modes. It is cleared by the program.

2.36

Embedded Systems: Design, Programming and Applications

Bit 0: Receive interrupt flag RI is set at the end of bit 7 in mode 0 and at the starting of the stop bit of other modes. It is cleared by the program. Table 2.14

Modes of serial data communication

SM0

SM1

Mode

Functions

0

0

0

Shift register mode: In this mode SBUF is configured to receive or transmit eight data bits using RXD pin. TXD pin is connected to shift pulse source to transmit shift pulses. Received data arrives at pin RXD and synchronized with the shift clock at TXD. Baud rate = f/12.

1

1

Serial data mode 1(Standard UART): In this mode SBUF becomes a 10 bit full duplex receiver transmitter. Pin RXD receives all data and pin TXD transmits all data. Transmitted data consists of 8 bit data with a start bit and a stop bit as shown in Fig. 2.17. Baud rate is variable.

1

0

2

Serial data mode 2 (Multiprocessor mode): In this mode SBUF becomes an 11 bit full duplex receiver transmitter. Pin RXD receives all data and pin TXD transmits all data. Transmitted data consists of 9 bit data with a start bit and a stop bit. The ninth data bit is copied from TB8 of SCON register during transmit. When data is received the ninth data bit is stored in RB8 of SCON register: Baud rate = f/32 or f/64.

1

1

3

Serial data mode 3 (9 bit UART): In this mode SBUF becomes an 11 bit full duplex receiver transmitter. Pin RXD receives all data and pin TXD transmits all data. Transmitted data consists of 9 bit data with a start bit and a stop bit. The ninth data bit is copied from TB8 of SCON register during transmit. When data is received the ninth data bit is stored in RB8 of SCON register: Baud rate is variable.

Power Control PCON Special Function Register The bit format of this register is shown in Fig. 2.20. 7

6

5

4

3

2

1

0

SMOD







GF1

GF0

PD

IDL

Fig. 2.20

bit

Power mode control (PCON) register

Bit functions of power mode control PCON special function register Bit 7: Serial baud rate modify bit (SMOD). This bit is set to double baud rate by timer 1 for modes 1, 2 and 3. SMOD = 0 for using timer 1 baud rate. Bit 6 to bit 4: Bit 3:

These bits are not used.

General purpose user flag bit 1 (GF1). This bit is used by the programmer by writing

program. Bit 2:

program.

General purpose user flag bit 0 (GF0). This bit is used by the programmer by writing

2.37

Embedded Processors

Bit 1:

Power down bit PD. PD = 1, for entering power down configuration for CHMOS processor.

Bit 0:

Idle mode bit (IDL). PD = 1, for entering power down configuration for CHMOS processor.

2.7.3 Types of Serial Data Communication There are three types of serial data communication. 1. Simplex; 2. Half duplex; 3. Full duplex. Figure 2.21 shows the three systems of data communication. Simplex

Transmitter

Receiver

Transmitter

Receiver

Receiver

Transmitter

Transmitter

Receiver

Receiver

Transmitter

Half duplex

Full duplex

Fig. 2.21 Simplex, half duplex and full duplex data transfer

2.7.4

Serial Communication with 8051

Transmission of serial data bits begins when data is written to SBUF. TI flag of SCON register is set to 1, when data has been sent i.e. SBUF is empty. SBUF is an 8 bit register used solely for serial communication for 8051. Data is to be stored in SBUF for transmission via the TXD line. Baud rate is to be selected with the help of Timer 1 with auto reload mode. Clock for 8051 UART circuitry: Divide machine cycle by 32 before it is used by timer 1 to set the baud rate. For various baud rates, TH1 must be loaded with the following values: (XTAL = 11.0592 MHz), Baud Rate TH1 (decimal) TH1(hex) 9600 –3 FD 4800 –6 FA 2400 – 12 F4 1200 – 24 E8

2.38

Embedded Systems: Design, Programming and Applications

Serial port mode of SCON register is programmed to select data transfer mode. Description of these four modes of data transfer is shown in Table 2.14. The bits of SCON register necessary for data transmission are described below. Ren:

receive enable bit (SCON.4) When it is high, it allows the 8051 to receive data on the RXD

pin. TI:

Transmit interrupt (SCON.1) When 8051 finishes the transfer of 8 bit character, TI flag will be high to indicate that it is ready to transfer another byte.

RI:

Receive interrupt (SCON.0) When 8051 receives data, it places the byte in SBUF register (excluding start and stop bit) and raises RI flag to indicate that a byte is in SBUF to pick up.

Programming the 8051 for serial communication 1. The TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2 (8 bit auto-reload) to set the bud rate; 2. The TH1 is loaded with one of the values of baud rate for serial data transfer (assuming XTAL = 11.0592 MHz); 3. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8 bit data is framed with start and stop bits; 4. TR1 is set to 1 to start timer 1; 5. T1 is cleared by the “CLR T1” instruction; 6. The character byte to be transferred serially is written into the SBUF register; 7. The T1 flag bit is monitored with the use of the instruction “JNB T1, xx” to see if the next character, go to step 5. With XTAL = 11.0592 MHz. Find the TH1 value needed to have the following baud rates. (a) 9600, (b) 2400, and (c) 1200 Problem 1: Solutions

With XTAL = 11.0592 MHz, we have: The machine cycle frequency of the 8051 = 11.0592 MHz / 12 = 921.6 kHz, and 921.6 kHz / 32 = 28,800 Hz is the frequency provided by UART to timer 1 to set baud rate. (a) 28,800/3 = 9600 where – 3 = FD (hex) is loaded into TH1 (b) 28,800/12 = 2400 where – 12 = F4 (hex) is loaded into TH1 (c) 28,800/24 = 1200 where – 24 = E8 (hex) is loaded into TH1 Figure 2.22 shows that dividing 1/12th of the crystal frequency by 32 is the default value upon activation of the 8051 RESET pin. We can change this default setting.

Fig. 2.22 Division of crystal frequency

Embedded Processors

2.39

Program

MOV TMOD, # 20H ;timer1, mode 2 MOV TH1,# 0FAh ; MOV SCON,# 50h ; 8 bit, 1 stop bit, REN enabled SETB TR1 MOV SBUF,#“A” HERE: JNB T1, HERE CLR TI

2.7.5

Special Feature of Microcontroller

Intel introduced the 8051 microcontroller in 1980. This microcontroller has gained great popularity since its introduction. It includes several standard on-chip peripherals, including timers, counters, and UART and 4 KB of on-chip program memory and 128 bytes of data memory which are accessible directly by instructions. A 32 byte segment of this 128 byte memory is bit addressable by a subset of the 8051 bit instructions. Sixty four KB of external memory is accessible by a special instruction and four KB of program instructions can be stored in the internal memory of the 8051. Most of the 8051 instructions are executed within 12 clock cycles. The special features of Intel 8051 series are stated below. 1. The speed of operation of Intel 8051 microcontroller is high; 2. This microcontroller has enhanced instruction set including instructions for multiplication and division; 3. It has larger memory capacity; 4. Intel 8051 has full duplex serial port; 5. It has Boolean processor; 6. This processor can operate on power saving mode; 7. Intel 8051 has some special functions like DMA channels, A/D converter, pulse width modulator and watch dog timer. Intel Corporation developed 80151 and 80251 microcontrollers in 1995. The special features of these advanced microcontrollers are written below. 1. High performances; 2. Increased memory addressing; 3. High level language support; 4. Low noise; 5. Enhanced instruction set; 6. High speed of operation; 7. Operating temperature range 0°C to 70°C. Now-a-days microcontrollers are hidden inside a surprising number of products. Microwave oven contains a microcontroller. All modern automobiles contain at least one microcontroller. The engine is controlled by a microcontroller. Any device that has a remote control almost certainly

2.40

Embedded Systems: Design, Programming and Applications

contains a microcontroller. For example, TVs, VCRs and high-end stereo systems, SLR and digital cameras, cell phones, answering machines, laser printers, telephones pagers, refrigerators, dishwashers, all fall into this category. However, recently, the market for 32 bit embedded processors has been growing. Further the issues such as power consumption, cost, and integrated peripherals differentiate a desktop CPU from an embedded processor. Other important features include the interrupt response time, the amount of on-chip RAM or ROM, and the number of parallel ports. The desktop world values processing power, whereas an embedded microprocessor must do the job for a particular application at the lowest possible cost Microcontrollers are required to operate in the real world without much of interface circuitry. The input-output signals of such a processor are both analog and digital. The digital data transmission can be both parallel and serial. The voltage levels also could be different. It illustrates the various modules inside a microcontroller. Common processors will have Digital Input/Output, Timer and Serial Input/Output lines. Some of the microcontrollers also support multi-channel Analog to Digital Converter (ADC) as well as Digital to Analog Converter (DAC) units. Thus analog signal input and output pins are also present in typical microcontroller units. For external memory and I/O chips the address as well as data lines are also supported. It also has a timing unit in the form of state registers and control logic. The controller sequences through the states and generates the control signals necessary to read instructions into the IR and control the flow of data in the data path. Generally the address size is specified by the control unit as it is responsible to communicate with the memory. For each instruction the controller typically sequences through several stages, such as fetching the instruction from memory, decoding it, fetching the operands, executing the instruction in the data path and storing the results. Each stage takes few clock cycles.

2.8

DIGITAL SIGNAL PROCESSOR

DSP processors are microprocessors designed to perform digital signal processing—the mathematical manipulation of digitally represented signals. Digital signal processing is one of the core technologies in rapidly growing application areas such as wireless communications, audio and video processing, and industrial control. Along with the rising popularity of DSP applications, the variety of DSP-capable processors has expanded greatly since the introduction of the first commercially successful DSP chips in the early 1980s. Today’s DSP processors are sophisticated devices with impressive capabilities. Digital Signal Processing is carried out by mathematical operations. In comparison, word processing and similar programs merely rearrange stored data. This means that computers designed for business and other general applications are not optimized for algorithms such as digital filtering and Fourier analysis. Digital Signal Processors are microprocessors specifically designed to handle Digital Signal Processing tasks. These devices are used in everything from cellular telephones to advanced scientific instruments. Digital Signal Processing deals with algorithms for handling large chunk of data. Development of Sampling Theory followed and the design of Analog-to-Digital converters gave an impetus in this direction. The contemporary applications of digital signal processing was mainly in speech followed by Communication, Seismology, Biomedical etc. Later on the field of Image processing emerged

Embedded Processors

2.41

as another important area in signal processing. One of the biggest bottlenecks in executing DSP algorithms is transferring information to and from memory. This includes data, such as samples from the input signal and the filter coefficients, as well as program instructions, the binary codes that go into the program sequencer. Most DSP processors share some common basic features designed to support high-performance, repetitive, numerically intensive tasks. The most often cited of these features is the ability to perform one or more multiply-accumulate (MAC) operations in a single instruction cycle. The multiply-accumulate operation is useful in DSP algorithms that involve computing a vector dot product, such as digital filters, correlation, and Fourier transforms. A second feature shared by DSP processors is the ability to complete several accesses to memory in a single instruction cycle. This allows the processor to fetch an instruction while simultaneously fetching operands and/or storing the result of a previous instruction to memory. Such single-cycle multiple memory accesses are often subject to many restrictions. A third feature often used to speed arithmetic processing on DSP processors is one or more dedicated address generation units. Once the appropriate addressing registers have been configured, the address generation unit operates in the background forming the addresses of arithmetic instructions. in memory. Modulo addressing is often supported, to simplify the use of circular buffers. Some processors also support bit-reversed addressing, which increases the speed of certain fast Fourier transform (FFT) algorithms. Because many DSP algorithms involve performing repetitive computations, most DSP processors provide special support for efficient looping. Often, a special loop or repeat instruction is provided, which allows the programmer to implement a for-next loop without expending any instruction cycles for updating and testing the loop counter or branching back to the top of the loop. Most DSP processors incorporate one or more serial or parallel I/O interfaces, and specialized I/O handling mechanisms such as lowoverhead interrupts and direct memory access (DMA) to allow data transfers to proceed with little or no intervention from the rest of the processor.

2.8.1

DSP Architecture

Von Neumann architecture of Central Processing Unit (CPU) contains a single memory and a single bus for transferring data into and out of the central processing unit (CPU). Multiplying two numbers, it requires at least three clock cycles; one to transfer each of the three numbers over the bus from the memory to the CPU. Von Neumann architecture uses a single memory for both data and instructions. Figure 2.23(a) shows a traditional microprocessor using Von Neumann architecture. The Von Neumann design is quite satisfactory when you are content to execute all of the required tasks in serial mode. In fact, most computers today are of the Von Neumann design.

Fig. 2.23(a)

Von Neumann architecture

2.42

Embedded Systems: Design, Programming and Applications

Figure 2.23(b) shows the Harvard architecture of computer. The Harvard architecture uses separate memories for data and program instructions, with separate buses for each. Since the buses operate independently, program instructions and data can be fetched at the same time, improving the speed over the single bus design. Most present day DSPs use this dual bus architecture. Program memory Instructions only

PM address bus CPU

PM data bus

DM address

DM data bus

Fig. 2.23(b)

DATA memory Data only

Harvard architecture

Figure 2.23(c) illustrates the next level of sophistication, the Super Harvard Architecture. This term was coined by Analog Devices to describe the internal operation of their ADSP-2106x and new ADSP-211xx families of Digital Signal Processors. These are called SHARC® DSPs, a contraction of the longer term, Super Harvard Architecture. The SHARC DSPs are optimized in several ways. Super Harvard Architecture includes an instruction cache, and an I/O controller. Program memory Instructions and secondary data only

PM address bus

PM data

CPU

Instruction cache

DM address

DM data bus

Program memory

I/O

Instructions only

Controller

Data

Fig. 2.23(c) Super harvard architecture

Figure 2.23(c) illustrates the next level of sophistication, the Super Harvard Architecture. This term was coined by Analog Devices to describe the internal operation of their ADSP-2106x and new ADSP-211xx families of Digital Signal Processors. These are called SHARC® DSPs, a contraction of the longer term, Super Harvard Architecture. The SHARC DSPs are optimized in several ways. Super Harvard Architecture includes an instruction cache, and an I/O controller. Figure 2.24 presents a more detailed view of the SHARC architecture, showing the I/O controller connected to data memory. This is how the signals enter and exit the system. For instance, the SHARC DSPs provides both serial and parallel communications ports. These are extremely high speed connections. For example, at a 40 MHz clock speed, there are two serial ports that operate at 40 M bits/second each, while six parallel ports each provide a 40 Mbytes/second data transfer. When all six parallel ports are used together, the data transfer rate is an incredible 240 Mbytes/second.

2.43

Embedded Processors

Program memory

Instructions and secondary data only

PM address bus

PM Data address generator

DM Data address generator

DM address

Data memory Data only

Program sequencer Instruction cache DM data bus PM data bus

Data register

I/O Controller

Multiplier

(DMA)

ALU Barrel shifter

Fig. 2.24

High speed I/O

Simplified diagram of DSP

Digital signal processors are designed to implement tasks in parallel. However, DSP algorithms generally spend most of their execution time in loops. This means that the same set of program instructions will continually pass from program memory to the CPU. The Super Harvard architecture takes advantage of this situation by including an instruction cache in the CPU. The first time through a loop, the program instructions must be passed over the program memory bus. The program instructions can be pulled from the instruction cache on additional executions of the loop. This means that all of the memory to CPU information transfers can be accomplished in a single cycle. This efficient transfer of data is called a high memory access band width. Figure shows detailed view of the SHARC architecture, showing the I/O controller connected to data memory. This is how the signals enter and exit the system. This type of high speed I/O is a key characteristic of DSPs. The overriding goal is to move the data in, perform the math, and move the data out before the next sample is available. Some DSPs have on-board analog-to-digital and digital-to-analog converters, a feature called mixed signal. However, all DSPs can interface with external converters through serial or parallel ports. Figure shows two blocks labeled Data Address Generator (DAG), one for each of the two memories. These DAGs control the addresses sent to the program and data memories, specifying where the information is to be read from or written to. DSPs are designed to operate with circular buffers, and benefit from the extra hardware to manage them efficiently. The DAGs can control eight circular buffers i.e. 32 variables and the required logic. Multiple circular buffers are required

2.44

Embedded Systems: Design, Programming and Applications

for the fastest operation. The DAGs are also designed to efficiently carry out the Fast Fourier transform. For this reason, the DAGs are configured to generate bit-reversed addresses into the circular buffers. Abundance of circular buffers greatly simplifies DSP code generation. In CPU, there are 16 general purpose registers of 40 bits each. These can hold intermediate calculations and prepare data for the math processor. These general purpose register can serve as a buffer for data transfer, hold flags for program control, control loops and counters. In DSP the math processing unit is broken into following three sections. 1. Multiplier; 2. Arithmetic and logic unit; 3. Barrel shifter. The multiplier takes the values from two registers, multiplies them, and places the result into another register. The ALU performs addition, subtraction, absolute value, logical operations (AND, OR, XOR, NOT), conversion between fixed and floating point formats, and similar functions. Elementary binary operations are carried out by the barrel shifter, such as shifting, rotating, extracting and depositing segments, and so on. A powerful feature of the SHARC family is that the multiplier and the ALU can be accessed in parallel. In a single clock cycle, data from registers 0-7 can be passed to the multiplier, data from registers 8-15 can be passed to the ALU, and the two results returned to any of the 16 registers. Computers are extremely capable in two broad areas, (1) data manipulation, such as word processing and database management, and (2) mathematical calculation, used in science, engineering, and Digital Signal Processing. All microprocessors can perform both tasks; however, it is difficult (expensive) to make a device that is optimized for both. There are technical trade offs in the hardware design, such as the size of the instruction set and how interrupts are handled. Table 2.15 lists the most important differences between these two categories. Data manipulation involves storing and sorting information. For instance, consider a word processing program. The basic task is to store the information, organize the information and then retrieve the information. These tasks are accomplished by moving data from one location to another, and testing for inequalities (A = B, A < B, etc.). Data manipulation is based on moving data and testing inequalities, while mathematical calculation uses multiplication and addition. Table 2.15

Data manipulation versus mathematical calculation Operation

Data manipulation

Math calculation

Typical application

Word processing, Database manage- Digital signal processing, Motion ment, etc. control, simulation etc.

Main operation

Data movement A Æ B, Value testing if Addition A + B = C A = B then …. Multiplication A × B = C

2.8.2

Memory Organization

The organization of a processor’s memory subsystem can have a large impact on its performance. The MAC and other DSP operations are fundamental to many signal processing algorithms. Fast

Embedded Processors

2.45

MAC execution requires fetching an instruction word and two data words from memory at an effective rate of once every instruction cycle. There are a variety of ways to achieve this, including multi-ported memories to permit multiple memory accesses per instruction cycle. Most fixed-point DSPs are aimed at the embedded systems market, where memory needs tend to be small. As a result, these processors typically have small-to-medium on-chip memories and small external data buses.

2.8.3

Applications

The DSP processors find use in an extremely diverse array of applications, from radar systems to consumer electronics. Therefore, the first task for the designer selecting a DSP processor is to weigh the relative importance of performance, cost, integration, ease of development, power consumption, and other factors for the application at hand. DSP is used in high-volume embedded systems, like cellular telephones, disk drives, servo control, and portable digital audio players. In these applications, cost and integration are paramount. For portable, battery-powered products, power consumption is also critical. The important class of applications involves processing large volumes of data with complex algorithms for specialized needs. As a result, designers favor processors with maximum performance, good ease of use, and support for multiprocessor configurations. The designers assemble systems using off-theshelf development boards, and ease their software development tasks by using existing function libraries as the basis of their application software. A key measure of the suitability of a processor for a particular application is its execution speed. DSPs are increasingly being used in portable applications, such as cellular phones and portable audio players where power consumption is a major concern. Digital Signal Processor is required to do the following Digital Signal Processing tasks in real time. 1. Signal modeling; 2. Difference equation; 3. Convolution; 4. Transfer function; 5. Frequency response; 6. Signal processing; 7. Data manipulation; 8. Algorithms; 9. Filtering; 10. Estimation. In future, we will undoubtedly see more DSP-like functions merged into traditional microprocessors and microcontrollers. The internet and other multimedia applications are a strong driving force for these changes. These applications are expanding so rapidly, in twenty years it is very possible that the Digital Signal Processor may be the traditional microprocessor.

2.46

Embedded Systems: Design, Programming and Applications

Review Questions 1. 2. 3. 4. 5.

What are the differences between microprocessor and microcontroller? Draw the block diagram of 8051 microcontroller. What are the special features of 8051 microcontroller? What is the size of internal RAM and ROM of 8051 microcontroller? Draw the oscillator circuit of 8051 microcontroller. The crystal frequency of oscillator of 8051 is 16 MHz. Calculate the time to execute instruction ADD A, R1. Ans. 0.75 mS. 6. Describe the functions of program counter and DPTR in 8051. 7. What are flags? Describe the flags of 8051 with the word format of PSW. 8. What do you mean by stack in 8051? Describe the function of SP in 8051. Describe the method of storing data on the stack pointer. 9. What are the special function registers (SFRs) in 8051? Describe the functions of SFRs. 10. Describe latches and drives of four ports of 8051. 11. Describe the timing registers of 8051. State the functions of TMOD, TCON, RCAP2H, RCAP2L and SBUF. 12. What are the functions of IR, RAM address register and program address registers? 13. Describe the four ports of 8051. Describe the TCON and TMOD SFRs. 14. Why timer and counter is required for 8051? Describe the different timer modes of microcontroller. 15. Describe functions of SBUF, SCON and TCON in serial data communication of 8051. 16. What do you mean by serial data interrupts? Describe the different modes of serial data transmission. 17. What are the interrupts provided in 8051? Describe the function of interrupt enable and interrupt priority SFRs. 18. Describe the functions of the pins XTAL1, XTAL2, RXD, TXD, T0, T1, EA ALE, and PSEN. 19. Define baud rate. Calculate Execution time of a single cycle instruction if crystal frequency is 6 MHz. 20. What are the addressing modes of 8051 microcontroller? Explain each addressing mode with example. 21. Write instructions to perform the following operations. (i) Move the content of accumulator to R6. (ii) Move the content of R7 to accumulator. (iii) Move the content of internal RAM memory location 42 H to port 2. (iv) Output 22 H to port 1. (v) Input the value of port 3 to R5 register. (vi) Clear bit 3 of the accumulator. (vii) Load R2 register with 12 H.

Embedded Processors

(viii) Compare R1 with 00 and if R1 π 0, jump to A032 H. (ix) Load port 2 address into data pointer. (x) Send accumulator content into port 3. 22. Explain following instructions of 8051. (i) ADDC A, Rn (ii) SUBB A, @Ri (iii) SUBB A, direct (iv) MUL AB (v) ANL direct, #data (vi) ORL A @Ri (vii) ORL direct, #data (viii) XRL A, Rn (ix) CPL A (x) RL A (xi) SWAP (xii) MOV A, @Ri (xiii) MOV DPTR, #data 16 (xiv) MOVC A, @A + PC (xiv) MOVC A, @A + PC (xv) MOVX A, @DPTR (xvi) CPL bit (xvii) JNB bit rel (xviii) JB C bit, rel (xix) ACALL 16 bit address (xx) ACALL 16 bit address (xxi) RETI (xxii) LJMP 16 bit address (xxiii) CJNE A, direct, (xxiv) DJNZ Rn, rel (xxv) XCH A, @Ri (xxvi) XCHD A, @R 23. Write the difference between the following instructions: (i) RET and RETI (ii) LJMP and SJMP (iii) MOV and MOVX (iv) MOV and MOVC (v) CJNE and DJNZ (v) XCH and XCHD (vi) MOV direct, #data and MOV @Ri # data 24. Write following programs in ALP for 8051. (i) Add series of 5, 8 bit number. (ii) Subtract two 8 bit numbers. (iii) Find the largest number in a data array. (iv) Find the smallest number in a data array. (v) Divide 2A H by 15 H (vi) Multiply 67H by 0A H (vii) Arrange a series of number in ascending order. (viii) Arrange a series of number in descending order. (ix) SWAP 4 MSBs with 4 LSBs in accumulator. (x) Compare a 8 bit number with another 8 bit numbers. 25. Describe 8051 microcontroller based position control of stepper motor. 26. Write a program to interface A/D converter with 8051 microcontroller. 27. Describe 8051 microcontroller based traffic control system.

2.47

2.48

Embedded Systems: Design, Programming and Applications

28. Analyze the following program: CLR C MOV A, #62 H SUBB A, #92 H MOV R7, A MOV A, #27 H SUBB A, #12 H MOV R6, A 29. Analyze the following program: CLR C MOV A, #4C H SUBB A, #6E H JNC NEXT CPL A INC A NEXT MOV R1, A 30. Write a program to add two 16 bit numbers 3CE7 H and 3B8D H. Place lower byte in R6 and higher byte in R7. 31. Write a program to get hexadecimal data in the range of 00 to FF H from port 1 and convert it to decimal. 32. Write a program to create a square wave that has a high portion of 1085 microsecond and a low portion of 15 microsecond. Use timer. 33. Enumerate the similarities and differences between the Microcontroller and Digital Signal Processor. 34. Name few chips in each of the family of processors such as: Microcontroller, Digital Signal Processor and General Purpose Processor. 35. Draw the internal architecture of 8051 and explain the functions of various units. 36. State with justification whether the following statements are right or wrong Cache memory can be a static RAM Dynamic RAMs occupy more space per word storage The full-form of SDRAM is static-dynamic RAM BIOS in your PC is not a Random Access Memory (RAM).

Choose the Correct Answer 1. Addressing mode of the 8051 instruction MOV A, @R0 is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing

Embedded Processors

2.49

2. Addressing mode of the 8051 instruction MOV R0, #2F H is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 3. Addressing mode of the 8051 instruction ADD A, #data is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 4. Addressing mode of the 8051 instruction SUBB A, #data is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 5. Addressing mode of the 8051 instruction MOV DPTR, #data 16 is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 6. Addressing mode of the 8051 instruction ADD A, Rn is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 7. Addressing mode of the 8051 instruction INC DPTR is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 8. Addressing mode of the 8051 instruction SUBB A, Rn is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 9. Addressing mode of the 8051 instruction MOV A, SBUF is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 10. Addressing mode of the 8051 instruction SUBB A, Rn is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 11. Addressing mode of the 8051 instruction ADD A, @R0 is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 12. Addressing mode of the 8051 instruction DEC @ Ri is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 13. Addressing mode of the 8051 instruction SUBB A, Rn is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 14. Addressing mode of the 8051 instruction MOV @Ri, A is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing

2.50

Embedded Systems: Design, Programming and Applications

15. Addressing mode of the 8051 instruction MOVC A, @A + PC is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indexed addressing mode 16. Addressing mode of the 8051 instruction JMP @A + DPTR is (a) immediate addressing mode (b) register addressing mode (c) direct addressing (d) indexed addressing mode 17. Addressing mode of the 8051 instruction ACALL is (a) absolute addressing mode (b) register addressing mode (c) direct addressing (d) indirect addressing 18. Addressing mode of the 8051 instruction LJMP 920A is (a) absolute addressing mode (b) long addressing mode (c) direct addressing (d) indirect addressing 19. After execution of the program MOV A, #55 H ANL A. #67 H the output is (a) 67 H (b) 45 H (c) 54 H (d) 55 H 20. The instruction used for exchange the content of A and R0 is (a) XCH A, R0 (b) XCH A, @R0 (c) XCHD A, @R0 (d) XCH R0, A 21. The instruction used to swap nibbles inside accumulator is (a) SWAP A (b) RR A; RR A (c) RR A; RR A; RR A (d) RRC A; RRC A; RRC A 22. The incorrect instruction of the following is (a) SWAP B (c) CPL C (d) ) MOVC A, @A + PC 23. Suppose, A = C5 H. After execution of RRC A, the content of A is (a) 62 (b) 26 (c) 66 (d) 22 24. Digital Signal Processor is required to do (a) signal modelling (b) convolution (c) difference equation (d) all of these 25. In DSP the math processing unit has (a) registrar (b) counter (c) barrel shifter (d) timer 26. Number of clock cycles required by DSP for multiplying two numbers is (a) three clock cycles (b) four clock cycles (c) two clock cycles (d) one clock cycle

3 3.1

Embedded System Design

INTRODUCTION

Embedded Technology is now in its prime and the wealth of knowledge available is mind blowing. Almost all definitions agree on following three basic characteristics of an embedded system. 1. It is a system built to perform its duty, completely or partially independent of human intervention; 2. It is specially designed to perform a few tasks in the most efficient way; 3. It interacts with physical elements in our environment, viz., controlling and driving a motor, sensing temperature, etc. An embedded system is usually designed to be more compact, energy efficient, and inexpensive. There are three constraints in designing embedded systems. These constraints are available system memory, available processor speed and the need to limit power dissipation while running the system continuously. Advanced embedded systems exhibit multi-tasking capabilities. Embedded systems are often required to provide Real-time response. A Real-time system is defined as a system whose correctness depends on the timeliness of its response. For these systems, delay in response is a fatal error. A more relaxed version of Real-time system is the one where timely response with small delays is acceptable. Real-time systems can be classified as follows. Hard Real-Time Systems – These systems has severe constraints on the timeliness of the response. Soft Real-Time Systems – These systems tolerate small variations in response times. Hybrid Real-Time Systems – These systems exhibit both hard and soft constraints on its performance. The embedded processors are described in Chapter 2. In this chapter we shall describe design process in embedded system, challenges in embedded system design, formalization of system design, design process, design examples etc.

3.2 3.2

Embedded Systems: Design, Programming and Applications

COMPONENTS OF AN EMBEDDED SYSTEM

An embedded system is characterized by real time and multi-rate operations in which the system works, reacts to events, interrupts and schedules the system’s functioning in real-time. It controls latencies to meet deadlines. Latency refers to the waiting period between running the codes of a task or interrupt service routine and the instance at which the necessity of the task or the interrupt of an event is required. An embedded system consists of following components. 1. Microprocessor; 2. Power supply, Reset and Oscillator circuit; 3. Input devices, Interfacing and Driver circuits; 4. Timers; 5. Interrupt controller; 6. Program memory and Data memory; 7. Serial communication ports and Parallel ports; 8. Output interfacing and Driver circuits; 9. System application specific circuits.

3.2.1

Microprocessor

A microprocessor is the most important hardware unit in the system. It is the brain of the embedded system. An embedded designer must have the knowledge of basic concept of microprocessor. We have described different processors used in embedded system. The main units of microprocessors are program flow control unit and execution unit. The program flow control unit includes a fetch unit to fetch instructions from memory. The execution unit (EU) has circuit that implements the instructions. The EU consists of Arithmetic and Logic Unit (ALU) and circuits that execute instructions of a program. The processor runs a cycle of fetch and execute. The instructions are defined in the instruction set and they are executed sequentially. Microprocessor can be fabricated in a core form in an Application Specific Integrated Circuit (ASIC) or System on Chip (SoC). Core means a part of functional circuit fabricated on a Very Large Scale Integrated (VLSI) chip.

3.2.2

Microprocessor Selection for Embedded Systems

Microprocessor is the main part of a Real-Time Embedded System (RTES). The general purpose microprocessors are used for embedded systems. They are designed to meet some specific requirements. Intel 8048 is a special purpose microprocessor which is designed to meet the requirement of embedded system. The Intel 80186, 80188 and 80286 are 16 bit microprocessors. These microprocessors are used as embedded controller. Actually, the 80186/80188 family includes four CMOS versions. These versions are compared as embedded controller. The 80186/80188 contains additional reserved interrupt vectors and some powerful built in I/O features. Very often, these microprocessors are known as embedded controllers because they are not used as microprocessor based computers but as a controller.

Embedded System Design

3.3

The special feature of Intel 8086 is the inclusion of DMA controller unit, three programmable timer and programmable interrupt controller within the chip. The DMA unit transfers data between I/O and memory. The DMA controller must have source and destination pointer for data transfer from source to destination. The timer unit of Intel 80186 microprocessor has three 16 bit timer/ counters. Two timers are used for following purposes. 1. Counting external events; 2. To provide waveforms from either an external clock or a CPU clock; 3. To interrupt CPU after specified number of events. The integrated interrupt controller of 80186 provides interrupt requests between internal and external sources. Two interrupt controller chips 8259A can also be cascaded with the integrated interrupt controller of 80186. In this case interrupt controller unit of 80186 performs the function of master controller. The chip select logic unit of Intel 80186 is used to enable memory or I/O devices. Six output lines are used for memory addressing and seven output lines are used for I/O addressing. The peripheral control register are located in 256 byte block of memory space or I/O space. It also provides power save power down mode of operation. Now-a-days microcontrollers are widely used as embedded controller. A microcontroller is a true computer on a chip. It is a general purpose microprocessor with inbuilt RAM, ROM, I/O ports, and timers. A microcontroller has a CPU in addition to a fixed amount of RAM, ROM, I/O ports, and a timer all on a single chip. It is used to read data, perform limited calculations on that data, and control the interfaced devices based on those calculations. The microcontroller stores the program in ROM inbuilt in the microcontroller. Therefore, microcontroller is a single chip microprocessor system which consists of CPU, RAM, ROM serial and parallel I/O ports, timers and interrupts. Four bit Microcontrollers are low cost microcontrollers. These microcontrollers are extensively used in electronic toys. 4 bit microcontrollers are also used in alphanumeric LED/LCD display drivers and portable battery chargers. Eight bit microcontrollers are the most popular microcontroller in use. Eight bits have proven to be suitable word size for controller tasks. One byte data word is adequate for most of the control and monitoring application. This byte size is also suitable for data communication. These microcontrollers are used in various control applications such as speed control of electric motors, position control and process control system. Sixteen bit microcontrollers are used for high speed control systems. These microcontrollers can be programmed using high level language as well as assembly level language. The 16 bit microcontrollers are used in disc drives, modems, printers, scanners, servo control systems etc. Thirty two bit microcontrollers are used for very high speed intelligent control systems. These microcontrollers can be programmed using high level language as well as assembly level language. The 32 bit microcontrollers are used in image processing, disc drives, modems, printers, scanners, servo control systems etc. Digital Signal Processors (DSPs) are also used in embedded systems. These processors have been designed based on the modified Harvard Architecture to handle real-time signals. The

3.4

Embedded Systems: Design, Programming and Applications

features of these processors are suitable for implementing signal processing algorithms. One of the common operations required in such applications is array multiplication. This is accomplished by multiplication followed by accumulation and addition. This is generally carried out by Multiplier and Accumulator (MAC) units. In this processor, generally all the instructions are executed in single cycle. The MAC type of instructions can be executed faster by parallel implementation. This is possible by separately accessing the program and data memory in parallel. These DSP units generally use Multiple access and Multi-ported memory units. Multiple access memory allows more than one access in one clock period. The Multi-ported memory allows multiple addresses as well Data ports. This also increases the number of access per unit clock cycle. In addition to above mentioned processors, mobile phones and digital cameras use special purpose processors for voice and image processing. A washer and dryer may use some other type of processor for Real-time Control and Instrumentation. Application Specific Integrated Circuit (ASIC) are used for specific functions like motor control, data modulation etc. Microprocessor can be fabricated in a core form in an Application Specific Integrated Circuit (ASIC) or System on Chip (SoC). An embedded system Chip or Core are described as follows. 1. General Purpose Processor (GPP): The instruction set of General Purpose Processor (GPP) is not designed specific to the applications. Microprocessors and embedded processor are the examples of GPP. The designer must interface hardware and write software as per requirement of the applications; 2. Application Specific Instruction Set Processor (ASIP): The instruction set of Application Specific Instruction Set Processor (ASIP) is designed specific to the applications on a VLSI chip. Microcontroller, Embedded microcontroller, Digital Signal Processor (DSP), Media Processor, Network Processor and IO processor or domain-specific Programmable Processor are the example of Application Specific Instruction Set Processor. Designer need not write instruction set for Application Specific Instruction Set Processor if this processor is used; 3. Single Purpose Processors as additional processors: These processors are used for particular application. This is a coprocessor used for graphic processing, floating point processing, encrypting, deciphering, discrete cosine transformation and inverse transformation or TCP/IP protocol stacking or network functions. It is also used as Accelerator (e.g. Java code accelerator) and peripheral controller; 4. Application Specific System Processor (ASSP): An ASSP is used as an additional processing unit for running application specific tasks in place of processing using embedded software; 5. General Purpose Processor (GPP) or Application Specific Integrated Processor (ASIP) cores integrated into either an ASIC or VLSI Circuit (ASIC) or a Field Programmable Gate Array (FPGA) core integrated with processor unit in a VLSI (ASIC) chip; 6. Multi-core processors or multiprocessors: Multi-core processors or multiprocessors are used in advanced embedded systems which exhibit multitasking capabilities. A system designer must consider following points for processor selection for embedded system design.

Embedded System Design

3.5

1. Processor must operate at higher clock speed so that more instructions can be processed per second; 2. Maximum number of bits in an operand in a single arithmetical or logical operation; 3. Instruction set of the microprocessor; 4. Processing speed of the microprocessor in Million instruction per second (MIPS) and clock frequency in Mega Hertz for measuring processing performance; 5. Ability of the processor to solve complex algorithms to meet deadlines for their processing; 6. Processor must give high computing performance; 7. Processor with register windows to provide fast context switching in a multitasking system; 8. Power-efficient embedded system requires a processor that has programmable auto shut down feature; 9. Processor that has a burst mode access to external memories.

3.2.3

Microcontroller Selection

There are many versions of microcontrollers 8051. Microcontrollers are selected for embedded systems design as per application as well as its cost. When additional timer is required for embedded system then 8052 is selected in stead of 8051 microcontroller. 83C152JA microcontroller is selected where two DMA is required. When an embedded system requires direct transfer to memory from external systems, separate processing units are required for the data transfer from and to the peripherals.

3.3

ADVANTAGE OF GENERAL PURPOSE PROCESSOR (GPP)

Processing of GPP is based on the instructions available in a general purpose instruction set which results in quick system development. The board and I/O interfaces designed for a GPP can be used for a new system by changing embedded software in ROM. Compiler facilities are available and hence embedded software development is possible in high level languages. New embedded system can be developed by well-tested and debugged processor-specific Application Program Interfaces (APIs) and codes which were used previously.

3.4

EMBEDDED SYSTEM ON CHIP (SOC)

Now-a-days embedded systems are designed on a single silicon chip using VLSI technology. This chip is known as System on Chips (SoC). SoC is designed on a single silicon chip that has all necessary analog and digital circuits, microprocessor and software. A SoC is embedded with the following components. 1. General purpose processor (GPP) or Application Specific Integrated Processor (ASIP) core; 2. Multiple processors or single purpose processing cores; 3. An encryption function unit;

3.6

Embedded Systems: Design, Programming and Applications

4. Memories; 5. Field programmable gate array (FPGA) cores; 6. A network bus protocol core; 7. Programmable logic devices; 8. Discrete cosine transforms for signal processing applications; 9. Logic and analog units; 10. Intellectual property (IP) cores. Figure 3.1 shows a SoC embedded system and its common bus with internal ASIPs, internal processors, IPs, memories and peripheral interfaces. It integrates internal Application Specific IC (ASIC), Application Specific Integrated Processors (ASIP), memories and interfaces in a common bus. SoC may posses analog circuits as well.

Fig. 3.1

3.5

A SoC embedded system

FIELD PROGRAMMABLE GATE ARRAY (FPGA) CORE

FPGA core consists of a large number of programmable gates on a VLSI chip. In each FPGA cell consists of a set of gates and this cell is called macro cell. The cells are interconnected as an array and each interconnection is programmable through RAM in a FPGA programming tool. Each cell has several inputs and outputs. An FPGA core can be used with a single or multiple processor units on chip. FPGA core with IBM power PCs can be used as a data security solution with encryption engine. DSP enabled FPGA arrays can be used in embedded systems for real time video processing and line echo eliminators for public switched Telecommunication network and packed switched networks.

3.7

Embedded System Design

3.5.1

Application Specificic IC (ASIC)

Application Specific ICs are designed using VLSI technology with either General Purpose Processor or Application Specific Integrated Processor. Some analog circuits are also embedded into the design. Electronic Design Automation tool is used to design Application Specific ICs.

3.5.2

IP Core

A standard solution for synthesizing a high level component by configuring FPGA core or VLSI circuit core is available as an Intellectual Property, called IP. The high level components are fabricated on a VLSI chip and it posses gate level sophistication in the circuits like counter, register, multiplier, floating point unit and Arithmetic and Logic Unit. Several IPs are incorporated in an embedded system. An IP provides hardwired implementable design of a transform, an encryption algorithm or deciphering algorithm. IP may be designed for USB or PCI bus controller. It can provide a design for implementing Hyper Text Transfer Protocol (HTTP) or File Transfer Protocol (FTP). IP can also be used for Bluetooth Protocol to transmit web page on the internet.

3.6

EMBEDDING A PROCESSOR

A General Purpose Processor (GPP) can be embedded on a VLSI chip. There are two types of GPP e.g. CISC and RISC microprocessor. Both the types can be used in embedded systems. Table 3.1 The comparison between CISC and RISC microprocessor CISC microprocessor

RISC microprocessor

1.

CISC microprocessor employs micro-programmed 1. control unit for execution of instruction.

RISC microprocessor uses hard wired control unit for execution of instruction.

2.

CISC processors are slower than that of RISC 2. processor.

RISC processor are faster than CISC processor.

3.

CISC processor can run large number of existing 3. software.

RISC processor can run limited number of existing software.

4.

CISC processor can execute many types of instructions.

4.

RISC processor can execute few types of instructions.

5.

CISC processor has many addressing modes.

5.

Processor has a few addressing modes.

6.

Instruction set of CISC processor is complex.

6.

Instruction set of RISC processor is simple.

7.

Execution of one instruction in CISC processor requires one clock cycle.

7.

Execution of one instruction in RISC processor requires more than one clock cycle.

8.

CISC processor involves both memories and regis- 8. ters for data transfer operation.

RISC processor involves register to Register data transfer operation.

9.

Computations in CISC processor are accomplished using both memory and general purpose register.

Computations in RISC processor are accomplished using general purpose Registers.

10. Large cache memory is used in CISC processor.

9.

10. Small cache memory is used in RISC processor.

11. In CISC processor control unit occupies a large 11. In RISC processor control unit occupies small area. chip area and hence small chip area is available As a result, larger chip area is available for registers for registers. which makes the processor simple and faster.

3.8

Embedded Systems: Design, Programming and Applications

INTEL 8086 and 8088 microprocessors have many instructions set. The number of instructions of this microprocessor is about 20,000. These instruction sets are large in number and complex in operation. For this reason, these microprocessors are known as complex instruction set computers (CISC). 8086 and 8088 have more internal registers to provide more storage space than that of 8085. The 16 bit registers help to write program efficiently. Thus the first member of the advanced microprocessor family is INTEL 8086 and it is used in sophisticated applications. Large number and complexity of instructions of CISC microprocessor causes reduction in computing speed of microprocessors. For this reason, reduced instruction set computer (RISC) microprocessor is developed to increase computing speed of the microprocessor by decreasing execution time of the instruction using hardwired control unit. The comparison between CISC and RISC microprocessor is shown in Table-3.1. RISC microprocessors available in the market are Power PC 601.603, 604 etc., Intel’s PA8000, DEC’s Alpha21064, SUN’s SPARC etc. CISC microprocessors are Intel’s 486, Pentium, Pentium Pro, Pentium II, Celeron, Pentium III, Pentium IV Motorola 68000 etc.

3.6.1

Emedding a Digital Signal Processor (DSP)

Digital Signal Processor (DSP) is used to process digital signals. It is a processor core or chip. A DSP is an important unit for embedded system which is required for telecommunication processing system, mobile communication, image processing, audio system, video system, multimedia etc. DSP includes Multiply and Accumulate (MAC) unit. It can process Very Large Instruction Word (VLIW), Single Instruction Multiple Data (SIMD) instructions, Discrete Cosine Transformation (DCT) and inverse DCT (IDCT). Discrete Cosine Transformation (DCT) and Inverse Discrete Cosine Transformation (IDCT) are used in algorithms of signal analysis, coding, echo elimination, noise cancelletion, filtering, compression and decompression etc.

3.6.2

Embedding an ASIP

Application Specific Integrated Processor (ASIP) cores integrated into either an Application Specific Integrated Circuit (ASIC) or VLSI Circuit with an instruction set designed for specific applications. ASIP is programmed using the instructions to perform the following function. 1. Digital signal processing; 2. Control signal processing; 3. Discrete cosine transformations; 4. Adoptive filtering; 5. Communication protocol implementing functions.

3.6.3

Embedding Multiprocessor

Dual core processors or more than one processor are used in an embedded system for execution of the program fast when a single microprocessor does not meet the needs of the different task that executes concurrently. Many Multiply and Accumulate (MAC) operations per second is required for real time video processing. Dual core processor or multiprocessor can perform this operation more efficiently than a DSP. For this reason, Dual core processors or more than one processor are incorporated in embedded system. These processors run in synchronized manner to achieve

Embedded System Design

3.9

optimum performance. Multiple ASIPs are used in cell phone or digital camera. Synchronized multiple processors are used in mobile phone to perform the following jobs. 1. Dialing; 2. Modulating and transmitting; 3. Speech-signal compression and coding; 4. Demodulating and receiving; 5. Signal decoding and decompression; 6. Keypad interface and display interface handling; 7. Short message service (SMS) protocol-based messaging; 8. SMS message display.

3.7

MEMORY

The microprocessor and memory must co-exist on the same Power Circuit Board (PCB) or same chip. Compactness, speed and low power consumption are the characteristics required for the memory to be used in an RTES. Therefore, very low power semiconductor memories are used in almost all such devices. For housing the operating system Read Only Memory (ROM) is used. In other words the memory should be non-volatile and should be easily programmable too. It is achieved by using Flash memories. EEPROM is widely used to store the program for longer time. The content of this memory can be changed electrically. External RAM also can be used in embedded system. The memory stores the instructions as well as data. No one can distinguish an instruction and data. The CPU has to be directed to the address of the instruction codes. The memory is connected to the CPU through the following lines 1. Address; 2. Data; 3. Control. Figure 3.2 shows memory interface in an embedded system. In a memory read operation the CPU loads the address onto the address bus. Most cases these lines are fed to a decoder which selects the proper memory location. The CPU then sends a read control signal. The data is stored in that location is transferred to the processor via the data lines. In the memory write operation after the address is loaded the CPU sends the write control signal followed by the data to the requested memory location.

Fig. 3.2

Memory interface in embedded system

3.10

Embedded Systems: Design, Programming and Applications

The memory can be classified in various ways i.e. based on the location, power consumption, way of data storage etc. The memory at the basic level can be classified as: 1. Processor memory (Register Array); 2. Internal on-chip memory; 3. Primary memory; 4. Cache memory; 5. Secondary memory.

3.7.1

Processor Memory

Most processors have some registers associated with the arithmetic logic units. They store the operands and the result of an instruction. The data transfer rates are much faster without needing any additional clock cycles. The number of registers varies from processor to processor. The more is the number the faster is the instruction execution. But the complexity of the architecture puts a limit on the amount of the processor memory. Figure 3.3 shows the block diagram of memory interface with internal registers and external memories.

Fig. 3.3

Block diagram of memory interface with internal registers and external memories

Different types of memories, used in embedded systems are described below. Internal on-chip Memory:

In some processors there may be a block of memory location. They are treated as the same way as the external memory. This memory is called internal on-chip Memory. This memory is very fast.

Primary Memory:

Primary memory is semiconductor memory. This memory is placed out side the CPU. It can also stay in the same chip as of CPU. These memories can be static or dynamic.

Cache Memory:

Cache memory is situated in between the processor and the primary memory. It is also a semiconductor memory. This memory serves as a buffer to the immediate instructions or data which the processor anticipates. There can be more than one levels of cache memory. Cache memory is used to increase the speed of a processor.

Embedded System Design

3.11

Secondary Memory: This memory is generally treated as input/output device. This is a much cheaper mass storage and slower devices connected through some input/output interface circuits. This memory is generally either magnetic memory or optical memory such as Hard Disk and CDROM devices.

3.8

DESIGN METHODOLOGY

The design flow of an embedded system involves several steps. The cost and performance is tuned and fine-tuned in a recursive manner. The block diagram of an overall design methodology is enumerated Fig. 3.4.

Fig. 3.4 Design approach

3.8.1

Design Approach

Design approach of an embedded system is shown in Fig. 3.4. Actually, requirements and specifications define the problem. For this reason, a designer must consider following points for designing an embedded system. 1. Requirement of the embedded system; 2. Over all system specification; 3. System level design with node level; 4. Node level design with processor level; 5. Processor level design; 6. Task level design. A design process is called top-to-down design if it first starts with abstraction of the process and then details are created. Designer must know requirement of the embedded system. Then he should define the requirements like inputs, outputs and control. He must be aware of the inputs

3.12

Embedded Systems: Design, Programming and Applications

and outputs of the system and he should write the specification for them. Designer also specifies the signals whether they are in digital or analogue form. He must specify the voltage levels, frequency etc., required for the embedded system. The design task can be further segregated into the following steps. 1. Requirements of the embedded system; 2. Specifications; 3. Architecture; 4. Components; 5. System integration.

3.8.2

Requirements of the Embedded System

In this step, system requirement is defined and analyzed. This is done by clearly understanding the required purpose, inputs, outputs and design metrics of developed embedded system specification. Requirements must have consistency in functioning of the embedded system.

3.8.3

Specifications

Specifications of an embedded system guide customers’ expectations from the product. Therefore, specification of the embedded system must be precise. Embedded system designer requires specifications for peripherals, devices, processors, data types, memory, system behavior, constraints and expected life cycle.

3.8.4

Architecture of Embedded Systems

Any system can hierarchically divided into subsystems. Each subsystem may be further segregated into smaller systems and each of these smaller systems may consist of some discrete parts. Some of these parts may be programmable and therefore must have some place to keep these programs. This block is shown in figure as software block. Figure 3.5 shows the block diagram of embedded system architecture. The embedded system consists of following building blocks. 1. Mechanical and optical subsystem block; 2. Sensor and actuator; 3. Digital subsystem; 4. Analog subsystem; 5. Software. In Real-time Embedded Systems (RTES), the on-chip or on-board non-volatile memory stores these programs. These programs are the part of the Real-Time Operating System (RTOS) and continually run as long as the gadget is receiving power. A part of the RTOS also executes itself in the stand-by mode while taking a very little power from the battery. This is also called the sleep mode of the system. In an embedded system, both the hardware and software coexist in a coherent manner. Tasks which can be both carried out by software and hardware affect the design process of the system. Hardware based multiplication improves the speed at the cost of increased complexity of the arithmetic logic unit (ALU) of the embedded processor. On the other hand software based

Embedded System Design

Fig. 3.5

3.13

Embedded system architecture

multiplication is slower but the ALU is simpler to design. These conflicting requirements are needed to be resolved on the requirements as imposed by the overall system. This design is known as Hardware-Software Co-design or simply Co-design.

Fig. 3.6

Block diagram of a system interface

Figure 3.6 shows the block diagram of a system interface and architecture of an embedded system. When a system is assembled it starts with some chassis or a single subsystem. Subsequently subsystems are added onto it to make it a complete system. The connection of one subsystem into the other and vice versa is known as Interfacing. It is so easy to assemble because they are all standardized. Therefore, standardization of the interfaces is most essential for the universal applicability of the system and its compatibility with other systems. It may have certain key standards, which is only meant for the specific company which manufactures them.

3.14

Embedded Systems: Design, Programming and Applications

Thus there are only few subsystems left to be connected. Unlike general purpose computers a generic architecture can not be defined for a Real-time embedded systems. There are as many architecture as the number of manufacturers. Generalizing them would severely dilute the soul purpose of embodiment and specialization.

3.8.5

Components

The system components are active and passive components mounted on circuit boards that are configured for a specific task. System components can be either single- or multi-function modules that serve as highly integrated building blocks of a system. Figure 3.7 shows the hierarchical components of embedded system. A system component can be as simple as a digital I/O board or as complex as a computer with video, memory, networking, and I/O all on a single board. It is apparent from the above example that a typical embedded system consist of by and large the following units housed on a single board Fig.3.7 Hierarchical components of embedded systems or chip. 1. Processor; 2. Memory; 3. Input/output interface chips; 4. I/O Devices including sensors and actuators; 5. A-D and D-A converters; 6. Software as operating system; 7. Application software. One or more of the above units can be housed on a single PCB or single chip. In a typical Embedded systems, the Microprocessor, a large part of the memory and major I/O devices are housed on a single chip called a microcontroller. The embedded systems are required to function for specific purposes with little user programmability. The user interaction is converted into a series of commands which is executed by the RTOS by calling various subroutines. RTOS is stored in a flash memory or read-only-memory. There will be additional scratch-pad memory for temporary data storage. If the CPU sits on the same chip as memory then a part of the memory can be used for scratch-pad purposes. Otherwise a number of CPU registers will be required for the same. CPU communicates with the memory through the address and data bus. The timing and control of these data exchange takes place by the control unit of the CPU via the control lines. The memory which is housed on the same chip as the CPU has the fastest transfer rate. The data transfer rate of memory is known as the memory band-width or bit rate. The memory outside the processor chip is slower and hence has a lesser bandwidth. On the other hand input/output devices have a low bitrate. For this reason, data transfer rates are handled in different ways by the processor. The slower devices need interface chips.

Embedded System Design

3.8.6

3.15

System Integration

Many of the components of the embedded systems are integrated on to a single chip. This concept is known as System on Chip (SOC) design. The components are integrated in the embedded system. This is known as system integration. The system is made to function and validated. Appropriate tests are done to fulfill the design metrics. Debugging tools are used to correct functioning of the embedded system. Each component and its interface system is integrated after the design stage. Integrated Development Environment (IDE) and source code engineering tools may be used to follow the model, design specification and software architecture.

3.9

STRUCTURE OF AN EMBEDDED SYSTEM

The typical structure of an embedded system is shown in Fig. 3.8. Normally in an embedded system the primary memory, central processing unit and many peripheral components including analogto-digital converters are housed on a single chip. These single chip is called as Microcontrollers. This is shown in Fig. 3.8.

Fig. 3.8

Structure of an embedded system

An Embedded systems chip may just need one level DC power supply (typically +5V). In a desktop computer various units operate at different speeds. Even the units inside a typical CPU such as Pentium-IV may operate at different speeds. The timing and control units are complex and provide multi-phase clock signal to the CPU and other peripherals at different voltage levels. The timing and control unit for an embedded system may be much simpler.

3.10

SOFTWARE FOR EMBEDDED SYSTEM

The activities of embedded systems are taken care of by the Real-time operating system software stored on the non-volatile memory. The system may have various other components and Application Specific Integrated Circuits (ASIC) for specialized functions such as motor control, modulation, demodulation, CODEC. Usually assembly level language is suitable for embedded system software. High-level languages also used for software of embedded system. These high level languages are converted to code by utility programs named compilers. Because of the general nature of high-level languages, the compliers often produce excess or overhead code. Assembly language requires no extra overhead

3.16

Embedded Systems: Design, Programming and Applications

code. No standard programs (drivers) exist to write programs for special situations. When speed of response is critical, assembly-coded programs execute rapidly because of the exact fit of program code to task requirements. Use of assembly level language in embedded system reduces cost, reduces code size also reduce the cost of associated ROM. High level language named embedded C, ‘C’ CROSS COMPILER ‘CX51’ and ‘Keil’ are used in embedded system as embedded software. CX51 is a cross compiler which has some aspects of the C programming language and standard libraries. However, some aspects of C program are altered or enhanced to address the peculiarities of an embedded target processor. The CX51 compiler provides a number of include files for various 8051derivatives. Each file contains declarations for the SFRs available on that CX51. Optimizing C Compiler, complete implementation of the American National Standards Institute (ANSI) standard is achieved for the C language. CX51 is not a universal C compiler adapted for the 8051 target. It is dedicated to generate extremely fast and compact code for the 8051 microprocessor. CX51 provides the flexibility of programming in C and the code efficiency and speed of assembly language. Another software, known as Keil software, contains C cross compiler, Assembler, tiny real time operating system, and program loader. Keil is used to create embedded applications rapidly for 8051 microcontroller. It supports chips like 8051 microcontrollers, 251 and 166 microvision2. It simplifies project development for 8051 and other microcontrollers. Keil supports 8051, 251 and 166 microcontroller family. Keil is optimized for specific architecture of each microcontroller. It generates smallest code and fastest execution speed. Keil provides full control over embedded development by deciding register banks, memory areas, variable types, SFRs. It has full code including ISR which can be written in ‘C’. Object-oriented languages C++, Java, and Visual C++ are also used for software development of embedded system.

3.10.1

Software Design

Program design of embedded system is simplified by program modelling. The models of software design process of embedded system are mentioned below. 1. Object-oriented program model; 2. Sequential program model; 3. Synchronous dataflow (SDF) graph or Multi-thread graph (MTG) model; 4. Finite state machine for data-path; 5. Universal modelling language (UML). Figure 3.9 shows the activities for software design cycle during software design process of an embedded system. This cycle may be repeated till test completes the verification of specifications. The flow diagram of the activities of software design during embedded software development process is shown in Fig. 3.10. Different types of software required for software design are described on next page.

Embedded System Design

3.17

Fig. 3.9 Activities of software design during embedded software development

Fig. 3.10 Flow diagram of the activities of software design during embedded software development process

3.10.2

Device Management Software

Software is required for device drivers and device management in an operating system because an embedded system is designed to do multiple functions. It has to control multiple physical and virtual devices. The physical devices are timers, keyboards, flash memory, display, network cards and ports. The virtual devices are described on next page.

3.18

Embedded Systems: Design, Programming and Applications

File:

A file is a virtual device which transmits the records to a data sink. It stores the data from the data source. A file is stored in flash memory in the embedded system.

Pipe:

A pipe is used for sending and receiving a stream of bytes from a source to destination,

Socket:

A socket is used for sending and receiving a stream of bytes between client and server software or between source and destination computing system. RAM DISC: A RAM disc is used for using the RAM in a similar way to files in the disc.

3.10.3

Device Driver Software

A device driver is software for opening, binding or connecting, writing, reading and control action. A device driver accesses a parallel or serial port, keyboard file, pipe, and socket at specific addresses. A device driver controls following three functions. Initializing:

Initializing is activated by placing appropriate bits in the control register or

control word. Calling ISR:

Calling Interrupt Service Routine (ISR) on interrupt

Resetting the status flag:

A device driver resets the status flag after an interrupt service Device manager software provide codes for detecting the presence of devices. It also initializes the device for testing. The manager includes software for allocating and registering port addresses for various devices. Device manager software ensures one task only at any instant for a device.

3.10.4

Software Tools for Designing Embedded Systems

Following software tools are used for designing the embedded systems. 1. Editor: Editor software is used for writing C codes with the help of key board for entering the program. Using editor software a file is created for addition, deletion, insertion etc.; 2. Interpreter: Interpreter translates the program line by line into machine code; 3. Compiler: Compiler creates object file. It includes codes, functions and expression from library routine; 4. Assembler: Assembler translates assembly program into binary opcodes. It creates a binary file. This binary file is an executable file; 5. Cross assembler: The cross assembler assembles the assembly codes used in system development; 6. Simulator: Simulator simulates all functions of an embedded system; 7. Source code: The source code is used for editing, debugging, browsing, disabling and enabling the C++ features; 8. Stethoscope: It is used for tracking the changes in any program variable.It also shows the sequence of multiple processes; 9. Prototype developer: This prototype development tool is needed for the development of system software and hardware; 10. Real-Time Operating System (RTOS): An RTOS is a multitasking OS which is needed for functioning in real time constraints.

Embedded System Design

3.19

Design issues:

The constraints in the embedded systems design are imposed by external as well as internal specifications. Design metrics are introduced to measure the cost function taking into account the technical as well as economic considerations.

3.11

DESIGN METRICS

A Design Metric is a measurable feature of the system’s performance, cost, time for implementation and safety etc. Most of these are conflicting requirements i.e. optimizing one shall not optimize the other: e.g. a cheaper processor may have a lousy performance as far as speed and throughput is concerned. Following metrics are generally taken into account while designing embedded systems NRE (nonrecurring engineering) cost. It is one-time cost of designing the system. Once the system is designed, any number of units can be manufactured without incurring any additional design cost; hence the term nonrecurring. Design metrics used in the embedded systems are described below. Size:

Size of the system is measured by physical space required by the system, RAM in kilobytes, flash memory requirement for running the software, data storage and gates or transistors for hardware. Performance The execution time of the system measures the performance. Higher performance means smaller execution time.

Power consumption:

It is the amount of power consumed by the system, which may determine the lifetime of a battery, or the cooling requirements of the IC, since more power means more heat. The battery needs to be recharged less frequently if power dissipation is small. Flexibility: The ability to change the functionality of the system without incurring heavy NRE cost is known as flexibility. Flexibility in design enables development of different version of a product. Software is typically considered very flexible because software enhancement is possible by software reengineering. Maintainability:

It is the ability to modify the system after its initial release, especially by designers who did not originally design the system. It means changeability and additions to the system. Maintainability includes adding or updating software, data and hardware.

Correctness:

This is the measure of the confidence that we have implemented the system’s functionality correctly. We can check the functionality throughout the process of designing the system, and we can insert test circuitry to check that manufacturing was correct.

Process deadline:

There are many processes in a system. Each processes have deadlines within which each of them must finish computation and give results.

User interface:

User interface includes Graphic User Interface (GUI) or Video User Interface

(VUI). Engineering cost:

Cost of developing, debugging, and testing the hardware and software of an embedded system is called engineering cost. It is one time nonrecurring cost.

Manufacturing cost:

manufacturing cost.

Cost of manufacturing a single unit of embedded system is called

3.20

Embedded Systems: Design, Programming and Applications

System and user safety:

System safety is determined in terms of accidental fall from hand and user safety is measured in terms of using a product.

3.11.1 The Performance Design Metric Performance of a system is a measure of how long the system takes to execute our desired tasks. The two main measures of performance are mentioned below. 1. Latency or response time: This is the time between the start of the task’s execution and the end. For example, processing an image may take 0.25 second; 2. Throughput: This is the number of tasks that can be processed per unit time. For example, a camera may be able to process 4 images per second. These are the some of the cost measures for developing an RTES. Optimization of the overall cost of design includes each of these factors taken with some multiplying factors depending on their importance. And the importance of each of these factors depends on the type of application. For instance in defense related applications while designing an anti-ballistic system the execution time is the deciding factor. On the other hand, for de-noising a photograph in an embedded camera in your mobile handset the execution time may be little relaxed if it can bring down the cost and complexity of the embedded Digital Signal Processor.

3.12

CHALLENGES IN EMBEDDED SYSTEM DESIGN

During design process following challenges arise. Optimizing the hardware needed: Requirement of microprocessors, ASIPs and single purpose processors in the system are optimized on the basis of following performance of processors. 1. Power dissipation; 2. Cost; 3. Design metrics. These three factors are the challenges in a system design. Following appropriate hardware is to be chosen to optimize amount and type of hardware needed. 1. RAM, ROM or internal and external flash or secondary memory; 2. Peripherals and devices internal and external ports; 3. Buses; 4. Power sources or battery; 5. Physical size; 6. Number of gates; 7. Prototype development. Power dissipation and consumption during the operational and idle state of the embedded system should be optimized. Following methods are used to meet the design challenges. 1. Clock rate reduction; 2. Voltage reduction; 3. Cache disable instruction;

Embedded System Design

3.21

4. Wait and stop instruction; 5. Process deadline; 6. Upgrade ability; 7. Reliability. Power dissipation reduces with clock rate reduction. But reduction of clock rate increases the computation time and total energy requirement E is given by E = Power dissipation per second × computation time The advantages of operating the clock at lower frequency or using the processor in power down mode are described below. 1. Power loss due to heat generation is reduced; 2. Power dissipation is reduced within the gates. Power dissipation reduces if operating voltage is reduced. In case of hand set or mobile phone, power dissipation is reduced by decreasing the operating voltage. As a result the time interval for battery recharging is increased. Usually an embedded system runs continuously. So, total power consumption by the system while in running, waiting and idle state must be limited. For this reason, either wait and stop instruction may be used for the power down mode of operation or the system must operate at the lowest voltage levels in idle state. Dead line of all processes in the system, such as memory, power dissipation, processor clock rate and minimum cost are challenges to a embedded system designer. Upgrade ability of an embedded system allow development of the system to a new version with more facilities. It is a challenge to designer to design a reliable embedded system. Reliability of the product is tested to ensure that the system has been designed as per requirement.

3.13

INPUT OUTPUT DEVICES AND INTERFACES

Input/Output interfaces are necessary to make the embedded system to interact with the external world. The embedded system should also have open interfaces to other devices such as Desktop Computers, Local Area Networks (LAN) and other RTES. The I/O ports are also used for interfacing the devices to be controlled. These input/output devices along with standard software protocols in the RTOS provide the necessary interface to these standards.

3.14

ADVANTAGES AND DISADVANTAGES OF EMBEDDED SYSTEM

The scope of embedded systems has been encompassing more and more diverse disciplines of technology day by day due to its many advantages. The development of Ultra-Low-Power VLSI, mixed signal technology is the prime factor in the miniaturization and enhancement of the performance of the existing embedded systems. More and more systems are tending to be compact and portable with the embedded system technology. However, The future course of embedded systems depends on the advancements

3.22

Embedded Systems: Design, Programming and Applications

of sensor technology, mechatronics and battery technology. A few important advantages and disadvantage of embedded system are mentioned below. Advantages 1. Smaller size; 2. Smaller weight; 3. Lower power consumption; 4. Lower electromagnetic interference; 5. Lower price. Disadvantages 1. Lower mean time of failure; 2. Repair and maintenance is not possible; 3. Faster obsolesce; 4. Unmanageable heat loss; 5. Difficult to design.

3.15

FORMALIZATION

The formalization of embedded system design is done using a top-down approach. This method of design includes following steps. 1. Determining requirement and specifications of software and hardware; 2. Drawing flow diagram of architecture of software and hardware; 3. Programming and implementation as per architecture; 4. Testing, validation and verification of system for reliability. A diagrammatic design model clears the design concepts. A modelling language can be used for software design. A designer describes user diagram, object diagram, sequence diagram, state diagram, class diagram and activity diagram in Universal Modelling Language (UML). These diagrams describes following states of the embedded systems 1. Classes and objects which describes identity, attributes, components and behavior; 2. Inheritances of the classes and objects; 3. Interfaces of the objects and its implementation; 4. Structural description of the design components; 5. Behaviors of the system in terms of states, state machine and signals; 6. Description of events. The design of these embedded systems by and large is application specific. The time-gap between the conception of the design problem and marketing has been the key factor for the industry. Most of the cases for very specific applications the system needs to be developed using the available processors rather than going for a custom design.

Embedded System Design

3.23

Review Questions 1. What are the different types of Real-time systems? Mention the basic characteristics of an embedded system. 2. What do you mean by Latency of an embedded system? What are the different components of an embedded system? 3. Describe the microprocessor selection procedure for an embedded system. 4. Write short notes on GPP, ASIP, ASIC, ASSP and FPGA. 5. Describe SoC using a suitable diagram. 6. Compare CISC microprocessor and RISC microprocessor. 7. Describe embedding different types of processors in embedded system. 8. Using a block diagram, describe memory interfacing in an embedded system. 9. Describe the different types of memory in embedded system. 10. Draw a block diagram and describe design process of an embedded system. 11. Describe the architecture of an embedded system. 12. Draw the block diagrams of hierarchical components of embedded systems. Describe the different units housed on a single board or chip in an embedded system. 13. Describe the structure of an embedded system. 14. Draw the block diagram of activities involved during software design of an embedded system and state the different models of software design process. 15. Describe different types of software required for software design of an embedded system. 16. Describe the software tools for designing embedded systems. 17. Describe the design metrics used in the embedded system. 18. What are the performance design metrics in embedded system? Describe the challenges in embedded system design. 19. Describe the formalization of embedded system. 20. Write five advantages and five disadvantages of embedded system.

Choose the Correct Answer 1. Examples of embedded systems are (a) ceiling fan (c) television set (e) digital camera 2. Which is not an real-time embedded (a) hard real-time system (c) abrupt real-time system

(b) microwave oven (d) desktop keyboard system (b) soft real-time system (d) hybrid real-time system?

3.24

Embedded Systems: Design, Programming and Applications

3. Which is not a component of embedded system (a) timers (b) oscillator circuit (c) microprocessor (d) laser 4. The special feature of Intel 8086 is (a) DMA inclusion (b) ADC inclusion (c) DAC inclusion (d) cache inclusion 5. 8259A is a (a) microprocessor chip (b) interrupt controller chip (c) DMA controller chip (d) none of these 6. Intel 80188 is known as (a) embedded controller chip (b) interrupt controller chip (c) DMA controller chip (d) none of these 7. 83C152JA is (a) a microprocessor (b) microcontroller (c) SOC (d) none of these 8. FPGA core consists of (a) analog circuits (b) memory (c) ADC (d) programmable gates 9. Which is not a part of SoC embedded system (a) ASIPs (b) GPP (c) IPs (d) encoder 10. Measures of performance of embedded system are (a) latency and throughput (b) RAM and ROM (c) cost and physical size (d) none of these 11. Device driver software does not accesses (a) ports (b) keyboard file (c) socket (d) RAM 12. The virtual devices are (a) file and pipe (b) pipe and socket (c) socket and file (d) file, socket and RAM disc 13. Editor software is used for (a) writing C codes (b) creation of file (c) deletion and insertion in file (d) all of these 14. ASIP in embedded system is optimized by the performance (a) power dissipation (b) cost (c) design metrics (d) all of these 15. Which is not the advantage of embedded system (a) lower mean time of failure (b) smaller size (c) low cost (d) low power consumption

4 4.1

Interrupt

INTRODUCTION

Execution of normal program by microprocessor can be interrupted by external signal or instruction written in the program. Intel 8086 microprocessor also allow interruption of execution of the program. A type code is assigned by 8086 to every interrupt for identification of interrupt. The interrupt can also be initiated by external devices or by software instructions. When interrupt is initiated, the microprocessor stops execution of the current program and calls a procedure or service routine which services the interrupt. At the end of the interrupt service routine, execution of the main program again starts from the instruction where it stopped before the interrupt. If the execution of a normal program of a microprocessor is interrupted by instruction then the interrupt is known as software interrupt. Therefore, interrupts are enabled by using software. The interrupts are also disabled by software. Actually, when a microprocessor is executing an important program then the interrupts are disabled. Some time it is desirable to inhibit the interruption of the execution of the program. In this case, some interrupts are masked. These interrupts are known as maskable interrupt. Execution of a program may be interrupted by abnormal internal condition of the microprocessor. This is known as exception. Interruption of execution of the program may also be caused by external events. This is also a type of exception. However, Exceptions includes program faults, traps and abnormal conditions generated by hard wares. In this chapter we shall describe 8085 interrupt types and how 8085 responds to these interrupts in variety of applications. We shall also describe the 8085 interrupt vector table and its initialization. Method of writing interrupt service procedure will be described here. Programmable interrupt controller (8259A) is also required for interrupt applications. For this reason, we shall describe the block diagram and operation of 8259 for interruption of execution of normal program of Intel 8085 microprocessor. The necessary instructions for operation of 8259 are discussed elaborately in this chapter. We shall describe 8086 interrupt types and how 8086 responds to these interrupts in variety of applications. We shall also describe the 8086 interrupt vector table and its initialization. Method of writing interrupt service procedure will be described here. Programmable timer/counter

4.2

Embedded Systems: Design, Programming and Applications

8254 is also required for interrupt applications. For this reason, we shall describe the operation of 8254 for interruption of execution of normal program of Intel 8086 microprocessor. The necessary instructions to initialize programmable timer/ counter 8254 for a specified applications will be discussed elaborately in this chapter. We shall also describe the interrupt available in 8051 microcontroller also which is used for real world interfacing. Application of interrupts in real world interfacing is described in Chapter 5.

4.2

INTERRUPTS OF INTEL 8085 MICROPROCESSOR

The interrupts of Intel 8085 microprocessor include five interrupt input pins. These hardware pins are TRAP, RST 7.5, RST 6.5, RST 5.5 and INTR. These interrupts are classified into two types. 1. Maskable interrupt; 2. Nonmaskable interrupt. The interrupt which can be masked off are called maskable interrupts. The 8085 microprocessor has four maskable interrupts and one nonmaskable interrupt. Three maskable interrupts are vectored to specific location and one interrupt is nonvectored. When maskable interrupts are used they are to be enabled by instruction EI (Enable interrupt) and after completion of the task the instruction DI (Disable interrupt) is used to disable the interrupt. RST 7.5, RST 6.5 and RST 5.5 are maskable interrupt. TRAP is a nonmaskable interrupt. It is neither to be enabled nor to be disabled. It is not accessible to user. It is used for emergency situation such as power failure and energy shut off. The nonmaskable interrupt has higher priority in operation. It means that the microprocessor can delay a request of a maskable interrupt if it is performing some critical task. The microprocessor responds to interrupt request for service on demand. It remains in a checking loop to detect interrupt. This process is known as polling. When interrupt line goes high processor completes its current instruction and saves content of the program counter on the stacks and the processor’s task is completed. Each interrupt requires a program to be executed and this program is stored in a specific location known as vector location. An interrupt vector is a pointer in which the interrupt service routine is stored in memory. All vectored interrupts are mapped into a memory area called the interrupt vectored table. Figure 4.1 shows the schematic diagram of interrupt vector table of 8085 microprocessor. The interrupt vector table is generally located in memory location 0000 to 00FF H. The purpose of the interrupt vector table is to hold the address that direct the microprocessor to right place when the processor is interrupted. When an interrupt line goes high microprocessor completes its current instruction and saves the content of the program counter in stacks. It resets interrupt enable flip-flop so that the occurrence of further interrupts by other devices is prevented during the execution of interrupt service routine. The vectored interrupts are directly vectored to address specified in the interrupt vector table. Vectored interrupt RST 5.5, RST 6.5 and RST 7.5 are masked by interrupt enable flip-flop. Enable Interrupt (EI) and Disable Interrupt (DI) instructions are also used for controlling the mask of these interrupts. The vectored interrupt process must be enabled by EI instruction before using it and it must be disabled by DI instruction after performing the function. The interrupt service

Interrupt

Fig. 4.1

4.3

Schematic diagram of interrupt vector table of 8085 microprocessor

routine incorporates the instruction EI to re-enable the interrupt process. TRAP is a non-maskable interrupt. It is neither to be enabled nor to be disabled. It has top priority than other interrupts. There are two sources of interrupts in Intel 8085 microprocessor as described below. 1. Hardware interrupt: Interrupts caused by I/O devices are called hardware interrupt; 2. Software interrupt: The normal operation of a microprocessor can be interrupted by abnormal internal condition or special instructions. These interrupts are called soft ware interrupts. In 8085, RST n instructions are used for soft ware interrupt. When an RST n instruction is inserted in a program, the program is executed up to that point. When an INTR interrupt line is connected to several I/O devices, external hardware is interfaced with I/O devices. This external hardware circuit generates RST n codes to implement the multiple interrupt schemes.

4.2.1

Priority, Call Locations and Triggering Levels of Interrupts

There are eight call locations of INTR interrupts as shown in Fig. 4.1. Table 4.1 shows the call locations, priority and triggering levels of other interrupts.

4.4

Embedded Systems: Design, Programming and Applications

Table 4.1 Interrupt

Priority

Call location

Triggering level

TRAP

First

0024 H

Edge and level triggered

RST 7.5

Second

003C H

Positive edge triggered

RST 6.5

Third

0034 H

Level triggered

RST 5.5

Fourth

002C H

Level triggered

4.2.2

RST (Restart), SIM and RIM Instructions

There are eight RST instructions, used in 8085 microprocessor. These instructions are one byte call instructions that transfer the program execution to a specific location. Table 4.2 shows the hexadecimal code and call location of RST instruction. Table 4.2 Mnemonics

Hexadecimal code

Call location

RST 0

C7 H

0000 H

RST 1

CF H

0008 H

RST 2

D7 H

0010 H

RST 3

DF H

0018 H

RST 4

E7 H

0020 H

RST 5

EF H

0028 H

RST 6

F7 H

0030 H

RST 7

FF H

0038 H

The RST instruction is executed in following steps. 1. The content of the program counter is stored on the stack before the program execution is transferred to the RST call location; 2. When the RET instruction in the subroutine associated with RST instruction is encountered by the processor, the program returns to the address that was stored on the stack from the program counter; 3. In case of hardware interrupt, RST instruction is used to restart the program execution. When an INTR interrupt line is connected to several I/O devices, external hardware is interfaced with I/O devices. This external hardware circuit generates RST n codes to implement the multiple interrupt schemes.

Set interrupt mask (SIM) This is a one byte instruction. Instruction SIM is used for following three different functions. 1. SIM is used to set a mask for RST 7.5, RST 6.5 and RST 5.5 interrupts; 2. The second function of SIM is to reset RST 7.5 flip-flop; 3. The third function is to implement serial I/O.

Interrupt

4.5

RST 7.5, RST 6.5 and RST 5.5 are maskable interrupts. This interrupts are enabled by using EI and SIM. The SIM instruction is executed to enable or disable interrupts according to the bit pattern of the accumulator. Figure 4.2 shows accumulator content for SIM instruction. Figure shows that bits B2, B1 and B0 are the mask for RST 7.5, RST 6.5 and RST 5.5 interrupts respectively. When these bits in the accumulator for SIM are high the interrupts are masked. If these bits are 0 then the interrupts are available. Bit B3 is mask set enable bit. When B3 = 0 the mask is ignored and if B3 = 1, new settings are set. Bit B3 is used to force RST 7.5 flip-flop to reset. Bit B5 is not used by the SIM instruction. Bit B6 is used to output serial data and Bit B7 is used to output serial data.

Fig. 4.2 Accumulator content for SIM

Example: Enable all the interrupts in Intel 8085 microprocessor system and then remove the interrupt RST 7.5. Answer

The content of the accumulator should be 08 H to enable RST 7.5, RST6.5 and RST5.5. To reset the interrupt RST 7.5 the accumulator content should be 18 H.

Program

Instructions EI MVI A 08 H SIM MVI A, 18 H SIM

Comments Enable interrupts Load bit pattern to enable RST 7.5, RST6.5 and RST5.5 Enable RST 7.5, RST6.5 and RST5.5 Set bit 4 = 1 Reset RST 7.5 interrupt flag.

Read interrupt mask (RIM) This is a one byte instruction. This instruction is used for following three different functions. 1. RIM instruction is used to read interrupt mask; 2. This instruction is used to identify the pending interrupt;

4.6

Embedded Systems: Design, Programming and Applications

3. It is used to receive serial data; 4. The RIM instruction loads accumulator with 8 bits, which consists of the status of the interrupt mask. Figure 4.3 shows that bits B2, B1 and B0 represent the current setting of the mask for each of RST 7.5, RST 6.5 and RST 5.5 interrupts respectively. When these bits in the accumulator for RIM are high the interrupts are masked. Bits B2, B1 and B0 return the contents of the three mask flip-flops. If these bits are 0 then the interrupts are available. Bit B3 is interrupt enable flag. This bit shows whether the maskable interrupt process is enabled or not. When B3 = 0 the interrupt is disabled and if B3 = 1 the interrupt is enabled. Bit B4, B5, and B6 represent the pending interrupts. When B4, B5, and B6 are high, shows interrupts are pending and low shows the interrupts are not pending. Bit B7 is used to input serial data.

Fig. 4.3 Accumulator content for RIM instruction

Example: A microprocessor is completing an RST 7.5 interrupt request, when RST 6.5 request is pending. Write a program to enable RST 6.5 without affecting any other interrupt, otherwise return to the main program. Program

NEXT

Mnemonics Comment RIM Read interrupt mask MOV B, A Load Mask information from accumulator to B register ANI 20 H Check whether RST 6.5 is pending JNZ START Jump to label START if not zero EI Enable interrupt RET Return to main program. RST 6.5 is not pending. MOV B, A Get bit pattern. RST 6.5 is pending. ANI 0D H Enable RST 6.5 by setting B1 = 0. ORI 08 H Enable SIM by setting B3 = 1 SIM JMP SERVICE ROUTINE

Interrupt

4.2.3

4.7

Programmable Interrupt Controller 8259A

Programmable interrupt controller 8259A provides eight vectored priority encoded interrupts to the microprocessor. Using this device sixty four interrupt request inputs can be obtained by 8259A with eight 8259A slaves. Special features of 8259A are described below. 1. Microprocessor 8085 is compatible to 8259A interrupt controller; 2. It provides individual request mask capability; 3. It does not require any clock; 4. It is fabricate by NMOS technology and available as 28 pin dual in line package; 5. It can be used as programmable interrupt modes; 6. 8259A is cascadable for 64 vectored priority interrupt without additional circuitry; 7. It is designed to minimize the software and it is used on real-time overhead in handling a multilevel priority interrupt; 8. 8259 has several modes permitting optimization for variety of system requirements; 9. Software written for 8259A operates with all 8259 equivalent modes. It operates with non-buffered edge trigger. 8259 A is fabricated by NMOS technology and available as 28 pin dual in line package. The functions of 28 pins are described below. __

Pin-1 CS:

It is a chip select pin. When the signal to this ___ pin is low, it enables read and write operation. Interrupt acknowledge function is independent of CS signal. ___

___

Pin-2 WR:

When the signal to this pin and CS is active low, it enables the 8259A to accept command words from the CPU and it also enables the interrupt controller for write operation.

Pin-3 RD:

___

When the signal to this pin and CS is low, it enables the 8259A to enable the interrupt controller for read operation.

Pins-4 to 11:

These pins are used as bidirectional data bus D7 to D0. The status, control and interrupt-vector information are transferred through these pins.

Pins-12, 13, 15:

These pins are named as CAS0, CAS1 and CAS2 pins. These are I/O cascade lines. CAS0, CAS1 and CAS2 lines of 8259A bus are used to control a multiple interrupt controller connected in cascade. These pins are output pins of master 8259A and inputs to a slave 8259A. __ ___

Pin-16: (SP/EN (Slave program/Enable buffer):

This pins function for two purposes. When 8259 is used in buffered mode, this pin (EN) can be used as an output to control buffer transceivers. If 8259 is not used in buffered mode, it is used as an input to designate a master when SP = 1and slave when SP = 0. Pin-17: This is an interrupt pin (INT). It goes high when a valid interrupt request is asserted. This pin is connected to the interrupt pin of 8085. Pin-18-25: These pins are interrupt request pins (IR0-IR7). Each pin receives an interrupt request from CPU by raising an IR input low to high. The IR pin must be high until interrupt is acknowledged in edge triggered mode and only by high level for level triggered mode.

4.8

Embedded Systems: Design, Programming and Applications

Pin-26:

This is the interrupt acknowledge pin (INTA). It goes high when a valid interrupt request is asserted. It enables 8259A to place interrupt vector data on the data bus by a sequence of interrupt acknowledge pulses from CPU.

Pin-27:

This pin is the address line A0. It functions with CS, WR and RD pins. It helps 8259A to read command words from CPU and status word which the CPU wishes to read. It is connected to the address line (A0) of CPU.

Pin-28:

4.2.4

It is +5 volt supply pin (Vcc) of 8259A.

Functional Description of 8259A

Programmable Interrupt Controller 8259A consists of following building block. Function of each block is described below. Data bus interface:

This functional block consists of tri-state bidirectional 8 bit buffer. This block is used to interface the interrupt controller 8259A to the 8085 data bus. The data bus buffer transfers control word and status information.

Read Write Logic:

This functional block consists of Initialization command word (ICW) registers and operational command word (OCW) registers. This registers store the different types of control formats for device operation. Read write logic block accepts output commands from microprocessor. It also transfers status of 8259 to the data bus.

Cascade Buffer:

This functional block has three I/O pins. These pins are CAS0, CAS1 and CAS2. These pins function as output pins if 8259 is used as master and input pins when the 8259 is used as a slave. The cascade buffer block sends the IDs of all 8259 ICs used in microprocessor system. When the 8259A is used as master, it sends the ID of the interrupting slave device on the CAS0, CAS1 and CAS2 pins. Thus the slave is detected. The slave then sends its subroutine address on the data bus in the next INTA pulses.

Control Logic:

This functional block controls the interrupt and interrupt acknowledge signals. The interrupt signal INT and interrupt acknowledge signal INTA are sent to the CPU interrupt input. The INTA signal causes 8259 to release vector signal onto the data bus.

In Service Register: This functional block consists of registers. These registers are used to store all the interrupt levels which are being serviced. In service register (ISR) also keeps a track of the interrupt request being served. Priority Resolver:

This functional block determines the priorities of the interrupt request of the interrupt request register. It selects highest priority and strobe into the corresponding interrupt request of the interrupt service register (ISR) during INTA signals.

Interrupt Request Register:

The Interrupt Request Register (IRR) is used to store all the interrupt requests. It also provides service to the interrupt requests one by one on priority basis.

Interrupt Mask Register:

This functional block stores the bits that mask the interrupt. In the slave mode, bit-2 identifies the slave. The slave compares its cascade input and if they are equal, bytes 2 and 3 of the call sequences are released on 8085 data bus.

Interrupt

4.9

Sequence of Interrupt 8259A is Programmable device. It also has addressing capability of interrupt routine. It can jump to specified interrupt service routine without polling. The steps of interruption of microprocessor are described as follows. 1. Interrupt request bits are set and any number of the interrupt request lines IR7 to IR0 is made high; 2. The 8259A sends INT signal to microprocessor; 3. CPU acknowledges interrupt by sending INTA signal; 4. Receiving INTA signal, highest priority in service routine ISR bit set and corresponding IRR bit is reset; 5. The 8259A sent a CALL instruction code using data bus; 6. This CALL instruction issues two INTA pulses which causes 8259A to release sub routine through data bus; 7. In Automatic End of Interrupt (AEOI) mode, ISR bit reset. Otherwise ISR bit remains high until End Of Interrupt (EOI) command is used.

4.2.5

Operation of Programmable Interrupt Controller 8259A

The programmable interrupt controller 8259A is programmed by initialization command words (ICWs) to perform the basic operation of the device. When A0 pin is low, operation command words (OCWs) are selected except ICW1. ICW1 is used to set and read the mask register. The interrupt input is masked when mask bit is set and mask register is read if OCW1 is read. Therefore, the ICW is programmed for initialization before programming OCW1. Another command OCW2 is programmed if automatic end of interrupt (AEOI) mode is not selected. With this OCW2 commands, 8259A responds to an interrupt. Two important command of 8259A are stated below. 1. Specific end of interrupt: This command resets a specific interrupt request; 2. Rotate-on-nonspecific end of interrupt: This command functions like nonspecific end of interrupt in addition to rotation of interrupt priorities after providing service to the interrupt. As for example, if interrupt IR3 is serviced its priority then go to the lowest and IR4 will get the highest priority.

Programming of 8259A The Programmable interrupt controller is to be initialized by the following Initialization Control Words (ICWs). 1. ICW1: When a write command is input to 8259A with A0 = 0 and B4 = 1 then ICW1 is interpreted by 8259A and initialization sequence starts. The edge sense circuit is reset i.e. interrupt request (IR) input goes low to high to generate an interrupt. Then the Interrupt Mask Register (IMR) is cleared and IR7 is assigned lowest priority. The Initialization Command Word ICW1 is show in Fig. 4.4.

4.10

Embedded Systems: Design, Programming and Applications

ICW1:

In ICW1, B0 indicates whether ICW4 is needed or not. B1 indicates number of 8259A in the system. If B0 = 1, more than one 8259s are cascaded in the system. If B0 = 0, only one 8259 is interfaced in the system. Bit B2 indicates call address interval. If B2 = 0, call address interval is 8 and if B2 = 1, call address interval becomes 4. B3 indicates recognition of the interrupt. If B3 = 0 then interrupt recognition is in edge triggered mode and if B3 = 0 then interrupt recognition is in level triggered mode. Bits B5 to B7 determine the interrupt vector address.

Fig. 4.4 Initialization command word ICW1

ICW2:

Initialization Control Word ICW2 is used for selection of the processor in the system. This control word is shown in Fig. 4.5. In this control word B2 to B0 specifies address bits A10 to A8 for the interrupt vector address in 8085 mode. These bits may be set to 0 while operating on an 8086 system. to T3 to T7 are interrupt vector address when the controller operates in 8086/8088 mode. Bits B7 to B3 specify address bits A15 to A11 as interrupt vector address when operating in 8085 mode.

Fig. 4.5 Initialization command word ICW2

ICW3:

Initialization Control Word ICW3 is used only when more than one 8259s are cascaded. In this case, SNGL bit of ICW1 is zero. ICW3 loads 8 bit slave registers. Hence there are two modes of operation as described below. 1. MASTER MODE: In master mode each slave in the system is set to one. The master then releases byte 1 of the call sequence which enables the corresponding slave to release byte 2 and 3 through the cascade lines. Initialization Command Word ICW3 in master mode is shown in 4.6(a); 2. SLAVE MODE: In the slave mode bit 2 identify the slave. The slave compares its cascade input and if they are equal, bytes 2 and 3 of the call sequence are released on 8086 data bus. Initialization Command Word (ICW3) in slave mode is shown in Fig. 4.6(b).

Interrupt

4.11

Initialization Control Word in master and slave mode are shown in Fig. 4.6

Fig. 4.6(a) Initialization command word ICW3 in master mode

Fig. 4.6(b)

Initialization command word (ICW3) in slave mode

ICW4: Initialization Command Word-4 (ICW4) is loaded only if B0 bit of ICW1 is set. The format of ICW4 is shown in Fig. 4.6(c).

Fig. 4.6(c)

Initialization command word-4 (ICW4)

4.12

Embedded Systems: Design, Programming and Applications

In ICW4 B0 determines the microprocessor mode (MPM). B0 = 0 sets the 8259A for microprocessor 8080 or 8085. B0 = 1 sets the 8259A for microprocessor 8086 or 8088. B1 determines the Automatic End of interrupt (AEOI) mode. If B1 = 1, 8259A operates in auto EOI mode. When B1 = 0, 8259A operates in normal EOI mode. B2 selects the buffered mode. If B2 = 1, 8259A is programmed to be a master. If B2 = 0, 8259A is programmed to be a slave. This bit has no function if B3 = 0. B3 selects buffered/non-buffered mode of operation. If B3 = 1, 8259A is programmed to buffered mode. Bit B4 selects Special fully nested mode (SFNM). If B4 = 1, 8259A is programmed in SFNM. In SFNM, the slave is able to place an interrupt request which has higher priority. The master recognizes the higher level interrupt and transmits this interrupt request to CPU. If B4 = 0, 8259A is not programmed in SFNM.

Operation Command Words Operation command words (OCWs) command the 8259A in different interrupt modes. The operating modes are fully nested mode, rotating priority mode, special mask mode and polled mode. Three operation command words are used to program 8259A to process the interrupt. These Command words are described below. OCW1:

The operation command word 1 (OCW1) sets and clears the mask bits by programming the interrupt mask register IMR. The format of operation command word 1 (OCW1) is shown in Fig. 4.7(a). In this control word bits B7 to B0 represent the eight mask bits M7 to M0. Any one of these bits becomes high means that mask is set otherwise mask is reset.

Fig. 4.7(a) Format of operation command word 1 (OCW1)

OCW2: The operation command word (OCW2) is used to program 8259A in various modes. The format of operation command word 1 (OCW2) is shown in Fig. 4.7 (b). In this control word, bits B3 and B4 are always set to 0.

Fig. 4.7(b) Format of operation command word 2 (OCW2)

Bits L2, L1 and L0 are used to set the interrupt level. The selection of command by these three bits is shown in the Table 4.3. Bits B7, B6 and B5 are named R, SL and EOI respectively. These three bits control the rotate and end of interrupt modes. The selection of command by combination of these three bits is shown in the Table 4.5.

4.13

Interrupt Table 4.3 L2

L1

L0

IR Number

0

0

0

0

0

0

1

1

0

1

0

2

0

1

1

3

1

0

0

4

1

0

1

5

1

1

0

6

1

1

1

7

Table 4.4 R

SL

EOI

Selection

0

0

0

Rotate in automatic EOI mode (Clear)

0

0

1

Non-specific EOI command

0

1

0

No operation

0

1

1

Specific EOI command

1

0

0

Rotate in automatic EOI mode (Set)

1

0

1

Rotate in Non-specific EOI

1

1

0

Set priority command

1

1

1

Rotate on specific EOI

EOI Command:

The end of interrupt (EOI) command resets the interrupt service. This command is generated by the CPU before sending the interrupt service routine. Different types of EOI commands are described below.

1. Specific EOI command: Specific EOI command (SEOI) is sent by the microprocessor to the programmable interrupt controller when a service routine of an interrupt is completed. This command resets an ISR bit and an IR level is specified. SEOI command is suitable when priorities of interrupt levels are changed during execution of interrupt subroutine. 2. Non-Specific EOI command: A non-Specific EOI command is an OUT instruction sent by the microprocessor to programmable interrupt controller 8259A. This command is used when the recent interrupt level serviced in the highest level. Receiving the non-Specific EOI command 8259A resets the highest priority ISR bit. This operation confirms that the highest priority routine in service is finished. The non-Specific EOI command operates in fully nested mode. IR level specification is not necessary in the non-Specific EOI command. 3. Automatic EOI mode: Automatic EOI (AEOI) mode is used continuously as the ISR bit in service is reset after its acknowledgement. If any interrupt request appears during this time the interrupt is enabled and serviced. However, problem of over nesting may occur when an IR input interrupts its own subroutine.

4.14

Embedded Systems: Design, Programming and Applications

4. Automatic rotation: In case of automatic rotation all communication systems connected to a microprocessor system will be accorded with equal priority in sharing information. This method is similar to time sharing method. This time sharing is accomplished automatically assigning a peripheral lowest priority after being serviced. There are two types of automatic rotation. 5. Rotate on non-specific EOI command: This command resets the highest ISR bit which assigns lowest priority to the corresponding IR level. Figure 4.8 shows the effects on interrupt priorities due to rotation of non-specific EOI command.

Fig. 4.8(a) Priority of interrupts before command

Fig. 4.8(b) Priority of interrupts after command

6. Rotate on automatic EOI mode (AEOI): This mode functions like Rotate on non-specific EOI (NSEOI) command. In this mode, priority routine is made automatically after the last _____ INTA signal of an interrupt request. A rotate in AEOI set command is used to enter to this mode and rotate in AEOI clear command is used to exit from this mode. 7. Set priority command: This command is used to assign an IR level the lowest priority. The priorities of the interrupt levels before and after set priority command is shown in Fig. 4.9.

Interrupt

Fig. 4.9(a)

Fig. 4.9(b)

4.15

Rotating interrupt priority before set priority command

Rotating interrupt priority after set priority command

Operation Command Word 3 (OCW3) This command word is used to perform two operations. 1. Reading status of registers Interrupt Request Register (IRR) and In-service Register (ISR); 2. Set/reset special mask and polled modes. The OCW3 format is shown in Fig. 4.10.

Fig. 4.10

Format of operation command word 3

RIS bit is used to select ISR or IRR. If RIS = 0 and RR = 1, IRR is selected. If RIS = 1 and RR = 1, ISR is selected. The RR bit is used to execute read register command. If RR = 0, no action takes place. The combined operation of the bits RIS and RR is shown in the Table 4.5.

4.16 Table 4.5

Embedded Systems: Design, Programming and Applications Combined operation of RIS and RR RR

RIS

Operation

0

X

No operation

1

0

Read IR register on next read pulse

1

1

Read IS register on next read pulse

P bit of Fig. 4.10 indicates poll mode. If P = 1, the poll command is transmitted. If P = 0, the poll command is not transmitted. SMM bit stands for special mask mode. If SMM = 1, the special mask mode is selected. If SMM = 0, the special mask mode is not selected. ESMM bit stands for Enable Special Mask Mode. If ESMM = 1, the special mask mode is enabled. If ESMM = 0, the special mask mode is disabled. The combined operation of the bits SMM and ESMM is shown in the Table 4.6. Table 4.6

4.2.6

Combined operation of SMM and ESMM ESMM

SMM

0

X

No operation

Operation

1

0

Reset special mask

1

1

Set special mask

Programming Steps of 8259A

Programmable interrupt controller 8259A is programmed by writing initialization command word and operation command word. The steps of writing program are listed below. 1. Determine ICW1 and write the same; 2. Determine ICW2 and write the same; 3. If 8259A is not cascaded, determine ICW4, and write the same. Otherwise, determine ICW3 and write the same; 4. If ICW4 is not required, ready to accept interrupt sequence. Otherwise, determine ICW4 and write the same and be ready to accept interrupt request. Two interrupt acknowledge machine cycles are required in functioning the 8259A. Actually, the necessity of these two machine cycle is to obtain interrupt type from 8259A. The 8085 microprocessor floats the data bus line AD0 – AD15 at the beginning of the first interrupt acknowledge machine cycle and interrupt acknowledge pulse is placed on INTA output pin. _____ This signal acts as a ready signal to 8259A. Another INTA signal is sent by the microprocessor in the second interrupt acknowledge machine cycle. The programmable_____ interrupt controller 8259A places the interrupt type on the data bus AD0 – AD7 in response to INTA signal in the second interrupt acknowledge machine cycle. Receiving this signal, 8085 performs following functions systematically.

Interrupt

4.17

1. 2. 3. 4.

The 8085 pushes the content of flag register on the stack; TF and IF are cleared; CS and IP values of the next instruction are pushed on the stack; Type of interrupt is read from 8259A to receive the CS and IP values for interrupt service routine from interrupt pointer table. The advantage of using 8259A with 8085 is that interrupt signals from many sources can be received into the INTR input pin of 8085 so that the interrupt type corresponds to the source of the interrupt signal.

Special Features of Programmable Interrupt Controller 8259A 1. 2. 3. 4. 5. 6. 7. 8.

8259A is compatible to microprocessors 8085, 8086 and 8088; It is an eight level priority controller which can be expandable to 64 levels; It can be used in programmable interrupt mode; It has individual request mask capability; 8259A requires only +5 volt power supply; It requires no clock signal; 8259A is available in 28 pin DIP IC; It is capable to accept level-triggered or edge triggered inputs.

INTR AND INTA The interrupt request INTR must be held at logic 1 until it is recognized. For this reason, INTR is known as level sensitive. This INTR pin is made logic high by an external process and it is cleared by interrupt service procedure.

4.3

INTERRUPTS OF INTEL 8086 MICROPROCESSOR

The interrupts of Intel microprocessor family include two hardware pins INTR and NMI. Another hardware pin INTA is used to acknowledge the interrupt requested through INTR. The microprocessor also includes software interrupts INT, INTO, INT3 and BOUND. Interrupt flag (IF) and trap flag (TF) are related to the interrupt structure. There are three sources of interrupts in 8086 as described below. 1. Hardware interrupt: An interrupt caused by application of external signal to either nonmaskable interrupt (NMI) input pin or maskable interrupt INTR input pin is called hardware interrupt; 2. Software interrupt: Execution of an interrupt instruction by INT instruction is known as software interrupt; 3. Interrupt is also caused due to error condition produced in the 8086 by the execution of an instruction e.g. Divide by zero interrupt is such type of interrupt.

4.18

Embedded Systems: Design, Programming and Applications

The Intel 8086 microprocessor assigns every interrupt a type code so that it can identify the interrupt. The first five interrupt types are known as predefined interrupt and these interrupts are reserved for specific functions. These interrupts are listed below. 1. Type 0: INT0 2. Type 1: INT1 3. Type 2: INT2 4. Type3: INT3 5. Type4: INT4

4.3.1

Interrupt Vector Table

Implementation of interrupt requires an interrupt service routine which is stored in interrupt vector table. The interrupt vector table is located in the memory addresses 00000H to 0003FFH i.e. first 1 Kilobytes of memory. The interrupt vector table contains 256 number of 4 byte interrupt vectors. Figure 4.1 shows the interrupt vector table for the microprocessors. The first five interrupt vectors (Type 0 to Type 4) are common to all Intel microprocessors from 8086 to Pentium processors. The interrupt vectors are 4 byte long. First two bytes contain offset address and last two bytes contain segment address.

4.3.2 Types of Interrupts Type 0 interrupt or divide by zero interrupt This type of interrupt occurs when an attempt is made to divide any number by zero or the result of a division overflows. Intel 8086 is automatically interrupted if the result of a DIV or IDIV operation is too large to accommodate in the destination register. The microprocessor stores the content of the flag register on the stack, resets interrupt flag (IF) and TF and pushes the return address on the stack for a Type 0 interrupt. The processor then reads the CS value to start interrupt service procedure from physical address 00002H from the interrupt vector table. After performing this job the microprocessor reads the IP value for start of the procedure. The Type 0 interrupt responses automatically and it cannot be disabled. Therefore, programmer must take care of writing program with the instruction DIV or IDIV so that the result should not be large to accommodate within the related register. Another point must be considered by the programmer that the divisor must not be zero. However, interrupt service procedure of Type 0 response is written to follow a desired action when an invalid division occurs. As a result 8086 checks the problem in division and takes action automatically if there is a fault.

Type 1 interrupt or single step interrupt Single step system executes one instruction and then stops. After execution of the single instruction content of registers and memory locations can be examined to check correctness of the result and then another instruction can be executed. Type 1 interrupt implement a single step feature in 8086 microprocessor based system. When trap flag of 8086 microprocessor is set, Type 1 interrupt is automatically executed after execution of each instruction and following action takes place.

Interrupt

4.19

1. The content of flag register is pushed on stack; 2. Interrupt flag IF and trap flag TF goes to reset condition; 3. Code segment (CS) and instruction pointer (IP) values are pushed for the next instruction on the stack; 4. CS value for the start of the Type 1 interrupt service routine is received by microprocessor from address 00006H and IP value for the start of the procedure is received from 00004H. The steps to be followed for implementation of Type 1 interrupt are described below. 1. Set the trap flag TF; 2. Write the interrupt service procedure to save content of all registers on stack; 3. Load the starting address of Type 1 interrupt service routine in memory address 00006H and 00004H. There is no instruction in 8086 to set or reset trap flag. For this reason, content of flag register is pushed onto the stack and trap flag bit of the flag register is changed. Then output of flag register is popped back from the stack. The instruction for this operation is written below. PUSHF MOV BP, SP ORW PTR[BP + 0], 0100H POPF The instruction to reset the trap flag is written below. PUSHF MOV BP, SP ANDW PTR[BP + 0], 0FEFH Note that BP can be used as a pointer with displacement only. For this reason, displacement 0 must be written. Thus trap flag is set or reset if 8986 operates a Type 1 interrupt.

Type 2 interrupt or nonmaskable interrupt When signal to nonmaskable interrupt (NMI) goes low to high, Intel 8086 microprocessor automatically operates a Type 2 interrupt. Following tasks are involved in implementation of Type 2 interrupt. 1. 8086 microprocessor push the content of flag register on the stack; 2. It resets trap flag (TF) and Interrupt flag (IF); 3. Code segment (CS) and instruction pointer (IP) values are pushed for the next instruction on the stack; 4. Microprocessor receives CS value for the start of the Type 2 interrupt service routine from address 0000AH; 5. It receives IP value for start of the service procedure from 00008H. The nonmaskable interrupt can not be disabled by any program of instructions. For this reason, some condition in external system must be used to apply signal 8086 for Type 2 interrupt e.g. a

4.20

Embedded Systems: Design, Programming and Applications

sensor connected to NMI input to send the signal to 8086 if the output of sensor exceeds the preset value. The Type 2 interrupt operates to take some action by microprocessor. The most important use of Type 2 interrupt is to save program if system power supply failure occurs. In this case, a signal is sent by the electronic circuitry to the NMI input when the ac power supply system fails. The large capacitance of the dc supply, connected to the microprocessor, supplies power for a few millisecond for Type 2 interrupt operation to save the program data in the battery backed up RAM.

Type 3 interrupt or break point interrupt Type 3 interrupt is implemented for a breakpoint function in a microprocessor system. Generally, breakpoints are used in debugging assembly language programs. If breakpoint is inserted, the system executes the instructions up to the breakpoint and then calls breakpoint procedures. Breakpoint interrupt is implemented by INT 3 instruction. When a breakpoint is inserted at any point of the program, it temporarily replaces the instruction byte at that address of memory with the 8086 code CCH for INT 3 instruction. Execution of INT instruction includes following steps. 1. The content of the registers are pushed onto the stack; 2. The TF and IF are reset; 3. CS and IP values are pushed on the stack for main program instructions; 4. Microprocessor receives CS value for the start of the Type 3 interrupt service routine from address 0000EH; 5. IP value is received by microprocessor to start procedure from address 0000CH. In a single microprocessor based system the control is returned to the user so that the content of the registers can be examined by the user to check the correctness of execution of the program.

Type 4 interrupt or overflow interrupt The overflow flag (OF) of the 8086 microprocessor is set if the result of an arithmetic operation is too large to accommodate in the destination register or memory location and hence an error is shown in the result. This error is known as overflow error. There are two methods to detect and respond to an overflow error as described below. 1. The first method is to write a jump instruction JO (Jump if over flow) just after the arithmetic instruction in the program. After execution of arithmetic instruction, if there is an overflow in the result, the overflow flag is set and the execution of the program will jump to the address specified in the JO instruction. An error subroutine may be written at this address which responds to the overflow; 2. The second method for detection and responding overflow error is to write an instruction INTO (interrupt on overflow) in the program just after the arithmetic instruction. The microprocessor executes the INTO instruction as no operation (NOP) instruction, if the overflow flag is not set. When there is overflow after execution of arithmetic operation, overflow flag is set to indicate overflow error and hence microprocessor operates Type 4 interrupt after execution of INTO instruction.

Interrupt

4.21

Following steps are followed by the 8086 microprocessor for Type 4 interrupt operation. 1. Content of flag register is pushed on the stack; 2. TF and IF are reset; 3. CS and IP values are pushed on the stack for the next instruction; 4. CS value is read by the microprocessor for start of the interrupt service routine from address 00012H; 5. The IP value is read by the microprocessor for start of the interrupt service routine from address 00010H; 6. The response to the error condition is performed by the interrupt subroutine. The error routine is easily accessible from any program using INTO instruction. This is the important advantage of Type 4 interrupt.

4.3.3

Software Interrupts

The INT instruction of 8086 is used to operate 256 possible interrupts. The interrupt type is written as part of the instruction. For implementation of any one of these 256 interrupts, following operations are involved. The 8086 pushes the content of flag register on the stack 1. TF and IF are reset; 2. CS and IP values of the next instruction are pushed on the stack; 3. CS and IP values are read by the microprocessor for start of the interrupt service routine from the interrupt pointer table in memory. The IP value is at an address of four times the interrupt type e.g. for Type INT 36 has IP value at 36 × 4 = 144 i.e. 90H.and CS value is placed at the address 92H in the interrupt vector table. Software interrupts are widely used for various applications e.g. INT3 instruction is used to insert breakpoint in program for debugging. INT 0 instruction is used for execution of divide by zero interrupt service procedure. INT 2 instruction is used to send execution to an NMI interrupt service routine. This instruction can be used to test the NMI procedure without applying an external signal to the NMI input.

INTR Interrupts External signal input to the INTR pin of 8086 causes interrupt execution of a program. INTR can be disabled (masked). INTR input is disabled, if the interrupt flag IF is cleared. Clear interrupt instruction (CLI) clears IF. On the other hand, INTR input is enabled if IF flag is set. The instruction to set IF flag is STI (set interrupt instruction). Interrupt is cleared if microprocessor 8086 is in reset mode. Therefore, to activate INTR, IF is to be set by instruction STI. In 8086 microprocessor based system all the registers, ports, timers etc. are to be initialized to enable INTR. IF flag is cleared for response of an interrupt by 8086 microprocessor. Usually, higher priority interrupts are implemented before INTR. However, INTR input can be enabled with STI instruction at any time.

4.22

Embedded Systems: Design, Programming and Applications

But an INTR input signal does not interrupt 8086 continuously. For this reason, INTR is disabled after implementation. Otherwise, actual interrupt service procedure can never be achieved. The INTR interrupt signal is sent to the 8086 microprocessor through external hardware device, known as the Priority interrupt controller 8259A.

4.3.4

Special Feature of Programmable Interrupt Controller 8259A

Programmable interrupt controller 8259A provides eight vectored priority encoded interrupts to the microprocessor. Using this device sixty four interrupt request inputs can be obtained by a 8259A with eight 8259A slaves. Figure 6.2 shows the block diagram of 8259A programmable interrupt controller. Special features of 8259A are described below. 1. Microprocessor 8086/88 is compatible to 8259A interrupt controller; 2. It provides individual request mask capability; 3. It does not require any clock; 4. It is fabricate by NMOS technology and available as 28 pin dual in line package; 5. It can be used as programmable interrupt modes; 6. 8259A is cascadable for 64 vectored priority interrupt without additional circuitry; 7. It is designed to minimize the software and it is used on real time overhead in handling a multilevel priority interrupt; 8. 8259 has several modes permitting optimization for variety of system requirements; 9. Software written for 8259A operates with all 8259 equivalent modes. It operates with non-buffered edge trigger.

4.3.5

Operation

The programmable interrupt controller 8259A is programmed by initialization command words (ICWs) to perform the basic operation of the device. When A0 pin is low, operation command words (OCWs) are selected except ICW1. ICW1 is used to set and read the mask register. The interrupt input is masked when mask bit is set and mask register is read if OCW1 is read. Therefore, the ICW is programmed for initialization before programming OCW1. Another command OCW2 is programmed if automatic end of interrupt (AEOI) mode is not selected. With this OCW2 commands, 8259A responds to an interrupt. Two important command of 8259A are stated below. 1. Specific end of interrupt: This command resets a specific interrupt request; 2. Rotate-on-nonspecific end of interrupt: This command functions like nonspecific end of interrupt in addition to rotation of interrupt priorities after providing service to the interrupt. As for example, if interrupt IR3 is serviced its priority is then go to the lowest and IR4 will get the highest priority.

4.3.6

Priority of Interrupts in Intel 8086

Interrupts may be initiated by hardware or soft ware by the user. If these interrupts are not used in a system, the programmer can assign other functions to the associated types. The NMI is initiated by edge triggering and the NMI pin must be active for 2 clock cycles to ensure recognition. The best

4.23

Interrupt

use of this interrupt is for power failure. The priority of interrupt is provided to select one interrupt for operation when two or more interrupts occur at the same time. The highest priority interrupt is serviced first and then the next highest priority is serviced and so on. Table 4.7 illustrates the priority of 8086 interrupts. For example, an INTR signal is received by 8086 microprocessor during execution a DIV instruction and this divide operation results in a divide by zero (Type 0) interrupt. According to the interrupt priority Table 4.7, Type 0 interrupt has higher priority than INTR interrupt. Therefore 8086 will response to Type 0 interrupt first. As a result, IF is cleared and hence INTR input is disabled which prevents the INTR signal from interrupting the higher priority Type 0 interrupt service procedure. IRET instruction, at the end of Type 0 procedure, restores the flag status which was before Type 0 response. Then INTR input will be responded by 8086. Thus higher priority interrupt functions when two or more interrupt occurs simultaneously. Table 4.7

Priority of 8086 interrupts Interrupt

Priority

Type 0, INTn and INTO

Highest

NMI

Next highest

INTR

Next highest

Type 1

Lowest

INTR AND INTA The interrupt request INTR must be held at logic 1 until it is recognized. For this reason, INTR is known as level sensitive. This INTR pin is made logic high by an external process and it is cleared by interrupt service procedure. INTR is automatically disabled if microprocessor accepts it and it can be enabled by IRET instruction of the interrupt service procedure. Receiving the INTR signal _____ input, the microprocessor sends the interrupt acknowledge INTA signal output in anticipation of _____ receiving interrupt type number on data bus D7 to D0. There are two INTA pulses that are used to generate the vector type number. The INTR input can be made edge triggered input instead of a level sensitive input by using a D flip-flop. The clock input becomes an edge triggered input and clear input clears the interrupt request when the interrupt acknowledge signal is provided by the microprocessor. The RESET signal clears the D flip-flop initially so that any other interrupt is requested when the system power supply is connected.

4.4

INTERRUPTS OF 8051 MICROCONTROLLER

Execution of normal program by microcontroller can be interrupted by external signal or instruction written in the program. Intel 8051 microcontroller also allow interruption of execution

4.24

Embedded Systems: Design, Programming and Applications

of the program. A type code is assigned by 8051 to every interrupt for identification of interrupt. The interrupt can also be initiated by external devices or by software instructions. When interrupt is initiated, the microprocessor stops execution of the current program and calls a procedure or service routine which services the interrupt. At the end of the interrupt service routine, execution of the main program again starts from the instruction where it stopped before the interrupt. If the execution of a normal program of a microprocessor is interrupted by instruction then the interrupt is known as software interrupt. Therefore, interrupts are enabled by using software. The interrupts are also disabled by software. Actually, when a microcontroller is executing an important program then the interrupts are disabled. Some time it is desirable to inhibit the interruption of the execution of the program. Execution of a program may be interrupted by abnormal internal condition of the microcontroller. This is known as exception. Interruption of execution of the program may also be caused by external events. This is also a type of exception. However, Exceptions includes program faults, traps and abnormal conditions generated by hardwares. All most all applications of microcontrollers involve responding to events quickly to control the events. Interrupts are only means by which real time program can be written successfully. Interrupt may be generated in chip operation or it can be applied from external source. The interrupt subroutines are stored in a predetermined address. There are five interrupts applicable in 8051. Three interrupts are generated by timer flag 0, timer flag 1 and the serial port interrupt. _____ _____ Two interrupts are initiated by external signal applied to pins INT0 and INT1. The program controls the functions of all interrupts. Programmer can change the content of interrupt enable register (IR), interrupt priority register and timer control register to perform desirable functions. The content of IE and IP special function registers are shown below.

Interrupts and Polling There are two ways by which a microcontroller can serve several devices. 1. Interrupt: The program associated with interrupt is called Interrupt service routine. Many devices can be served by assigning priority, but not at the same time. In interrupt method the microcontroller can ignore a device request for service; 2. Polling: In polling, the microcontroller continuously monitors the status of a given device; when the condition is met, it performs the service. The main disadvantage of polling is that it wastes much of the microcontroller’s time. It is not possible to assign priority and ignore a device for service since polling method checks all devices in a round-robin process.

Steps in Executing Interrupt After activation of an interrupt, the microcontroller goes through the following steps: 1. Finishes the instruction it is executing and saves the address of the next instruction on the stack; 2. Saves the current status of all the interrupts;

4.25

Interrupt

3. Jumps to a fixed location in memory called the interrupt vector table that holds the address of the interrupt service routine; 4. The microcontroller gets the address of the ISR from the interrupt vector table, jumps to it and starts to execute it; 5. After executing RETI instruction, the microcontroller returns to the place from where it was interrupted and starts to execute from that address.

Interrupt Programming An interrupt is an external event that interrupts the microcontroller to inform it that a device needs its service. The 8051 has 6 interrupts, 5 of which are user-accessible. The steps of interrupt programming are shown below. 1. When this reset pin is activated, the 8051 jumps to address location 0000; 2. Two interrupts are set aside for the timers. One for Timer 0 and one for Timer 1.Memory locations 000BH and 001BH in the interrupt vector table belong to timer 0 and timer 1 respectively; 3. Two interrupts are set aside for external hardware interrupts. Memory locations 0003H and 0013H in the interrupt vector table belong to INT0 and INT1 respectively; 4. Serial communication has a single interrupt that belongs to both receive and transfer data. The interrupt vector table location 0023H belongs to this interrupt. Interrupt enable (IE) register:

7

6

5

EA



ET2

Bit format of IE is shown below. 4 3 2 ES

ET1

EX1

1

0 bits

ET0

EX0

Bit 7: This is known as enable interrupt bit EA. When EA = 0, all interrupts are disabled. If EA = 1 individual interrupts are enabled by their enable bits. Bit 6:

This bit is not used.

Bit 5:

This bit is known as ET2 and it is reserved for future use.

Bit 4:

This bit is known as enable serial port interrupt bit (ES). If ES = 1, serial port interrupt is enabled. When ES = 0, serial port interrupt is disabled.

Bit 3: This bit is known as enable timer 1(ET1) overflow interrupt bit. If ET1= 1, timer 1 overflow interrupt is enabled. If ET1 = 0, timer 1 overflow interrupt is disabled. Bit 2: _____

This bit is known as enable external _____ interrupt 1 (EX1) overflow interrupt bit. If EX1 = 1, INT1 interrupt is enabled. If EX1 = 0, INT1 interrupt is disabled. Bit 1:

This bit is known as enable timer 0 (ET0) overflow interrupt bit. If ET0 = 1, timer 0 overflow interrupt is enabled. If ET0 = 0, timer 0 overflow interrupt is disabled.

Bit 0:

_____

This bit is known _____ as enable external interrupt 0 (EX0) bit. If EX0 = 0, INT0 interrupt is enabled. If EX0 = 0, INT0 interrupt is disabled.

4.26

Embedded Systems: Design, Programming and Applications

Interrupt priority (IP) register:

Bit format IP is shown below.

7

6

5

4

3

2

1





PT2

PS

PT1

PX1

PT0

Bit 7:

This bit is not used.

Bit 6:

This bit is not used.

Bit 5:

This bit is known as PT2 and it is reserved for future use.

0

bits

PX0

Bit 4:

This bit is known as priority of serial port interrupt (PS). If PS = 1, priority of serial port interrupt is enabled. When PS = 0, priority of serial port interrupt is disabled. Bit 3:

This bit is known as priority of timer 1(PT1) overflow interrupt. If PT1 = 1, priority of timer 1 overflow interrupt is enabled. If PT1 = 0, priority of timer 1 overflow interrupt is disabled.

Bit 2: This bit is known as priority of external interrupt 1 (PX1) overflow interrupt. If PX1= 1, priority of external interrupt is enabled. If PX1 = 0, priority of external interrupt is disabled. Bit 1:

This bit is known as priority of timer 0 (PT0) overflow interrupt. If PT0 = 1, priority of timer 0 overflow interrupt is enabled. If ET0 = 0, priority of timer 0 overflow interrupt is disabled.

Bit 0: This bit is known as priority of external interrupt 0 (PX0). If PX0 = 0, priority of external interrupt is enabled. If PX0 = 0, priority of external interrupt is disabled. When the microcontroller is interrupted the content of PC is stored in stack, interrupt service routine is executed and after execution of the subroutine PC address is restored by the instruction RETI. Timer flag interrupt:

If timer counter over flows, corresponding timer flag TF0 or TF1 is set. As a result, an interrupt generates a program call to the specific timer subroutine to clear the content of the flag to zero.

Serial port interrupt:

When a data byte is received in serial port, RI is set in the SCON register. When a data byte is transmitted in serial port, TI is set in the SCON register. This two signals are ORed to generate serial port interrupt. This interrupt call a program to reset RI and TI to enable the next data transfer operation..

External interrupts:

Inputs to the pins INT0 and INT1 can set the IE0 and IE1 in the TCON register. The interrupt vector table is shown in Table 4.8.

Table 4.8

Interrupt vector table of 8051 Interrupt

ROM location (hex)

Pin number

0000

9

External hardware interrupt 0 INT0

0003

(P3.2) 12

Timer 0 interrupt TF0

000B

Reset

External hardware interrupt 1 INT1

0013

Timer 1 interrupt TF1

001B

Serial com interrupt R1 and T1

0023

(P3.3) 13

Interrupt

4.5

4.27

REAL-TIME CLOCK

Real-time clock of seconds, minutes and hours can be generated by using a 1 Hz interrupt input. A one Hz signal is applied to an interrupt input of microprocessor to generate a real-time clock. Three successive memory locations are used to store seconds count, minutes count and an hour count, respectively. Second count is incremented by one if an interrupt appears at the interrupt input. Execution of the program returns to the main line program till the second count equals sixty. The second count resets and the minute count is incremented by one when second count equals to sixty. Execution of the program returns to the main line program till the minute count equals sixty. The minute count resets and the hour count is incremented by one when minute count equals to sixty. If the hours count is not 13 then execution of the program is returned to the main line program. The hour count is reset to one when hour count equals to 13 and execution is returned to the main line program. The interrupt service routine for the real-time clock can be modified for specific timer e.g. 4 min timer, 8 min timer etc. Figure 4.11 shows a 1 Hz pulse generator circuit using 555 timer circuit. The value of R1, R2 and C are chosen so that the output of the timer gives 1 Hz pulses. The output of the timer circuit of Fig. 4.11 provides an interrupt signal to the 8085 TRAP input once in each second. An interrupt procedure counts the number of TRAP interrupts. This count provides the real-time in seconds. This count is stored in a memory location. This counter may be set for any specific time. The timer circuit, using 555 as shown in figure, is not accurate enough. A crystal controlled oscillator can be used for accurate real-time clock. But the frequency of crystal controlled oscillator is very high. However, using frequency divider, 1 Hz pulse can be obtained from crystal oscillator. Most of the microcomputer systems employ a compatible device which can be programmed with instructions to divide the input frequency by a desired number. For this purpose, the Intel 8254 programmable timer/counter is the most suitable device. So we shall describe programmable timer/ counter 8254 in details in the next section.

Fig. 4.11

One hertz pulse generator for real-time clock

4.28 4.6

Embedded Systems: Design, Programming and Applications

PROGRAMMABLE TIMER/COUNTER 8254

The programmable interval timer/counter 8254 consists of three 16 bit programmable counters which count in binary or binary coded decimal. The input frequency to any of these counters is 10 MHz. The programmable timer/counter is widely used in personal computer decoded at ports 40 H to 43 H. The applications of Intel 8254 are mentioned below. 1. 8254 is used in microprocessor systems to control real time events; 2. It can be used as real time clock; 3. Programmable timer/counter is used as events counter; 4. 8254 is used in personal computer to control the speed and direction of motors; 5. It is used to generate basic timer interrupt; 6. 8254 is used in PC to provide refresh timing of DRAM memory systems; 7. It provides timing to the internal speaker; 8. The 8254 has a read back feature which allows to latch the counts in all the counters and the status of the counter at any point. Programmable interval timer/counter 8254 consists of three counters, known as counter 0, counter 1 and counter 2. Each counter has a clock (CLK) input, a gate input and an output connection lead. The operating frequency of timer is determined by the CLK input. The gate input controls the mode of the timer and OUT pin provides the timer output. The data bus pins D7 to D0, RD, WR, CS and address inputs A1 and A0 of microprocessor are connected to the 8254 timer. Any one of the four internal registers of 8254 is selected by the address inputs for programming, reading or writing to a counter. The counter 0 is programmed to generate 18.2 Hz signal. This signal is used to interrupt the microprocessor. Counter 1 is programmed for a 15 µs output pulse which is used to request a DMA action. It is also used to provide timing to refresh the DRAM. Timer 2 is used to generate tone for internal speaker of the PC.

Pin Functions Programmable interval timer/counter 8254 is higher speed version of 8253 timer. It is a 24 pin integrated circuit. The pin diagram of programmable interval timer/counter 8254 is shown in Fig. 4.12. The function of each pin is described below. 1. Address pins A1 and A0 (Pin 19 and 20): These two pins selects one of four internal register in 8254 corresponding to address selection inputs as shown in Table 4.9; 2. Clock 0, Clock 1, Clock 2 (Pin 9, 15 and 18): This input line is connected to the timing source of the internal counters. It may be connected to PCLK signal from microprocessor; 3. Chip Select (CS) Pin 21: This input enables the programmable interval timer/counter 8254 for programming the counters; 4. Gate 0, Gate 1 and Gate 2 (Pin 11, 14 and 16): These are gate input controls the mode of operation of the counters;

4.29

Interrupt

5. 6. 7. 8. 9. 10.

GROUND (Pin 12): This pin is used for ground connection with the system ground bus; OUT (Pin 10, 13 and 17): This pin provides the counter output waveform; RD (Pin 22): This pin is used to read data from the 8254; WR (PIN 23): It is used to write data to 8254; D7 – D0 (Pin 1 to 8): These pins are used to connect bidirectional low order data bus; Vcc (Pin 24): Power supply to 8254.

Table 4.9

Address selection table A1

A0

Function

0

0

Counter 0 is selected

0

1

Counter 1 is selected

1

0

Counter 2 is selected

1

1

Counter 3 is selected

Fig. 4.12 Pin diagram of programmable interval timer/counter 8254

4.6.1

Modes of Operation

There are six modes of operation of 8254 programmable interval timer/counter. Figure 4.12 shows the six modes of operation for the 8254 programmable interval timer with the clock input, the gate control signal and the OUT signal. 1. Mode 0: In this mode 8254 can be used as an event counter. The output remains at logic 0 until count N plus the number of programmed counts. In this mode, the gate input should be logic 1. e.g. if a count of 6 is programmed the output of the counter will remain low for 6 counts starting with N as shown in Fig. 4.13(a). 2. MODE 1: Mode 1 uses the counter to function as a retriggerable monostable multivibrator or one shot multivibrator. In this mode, the counter is triggered by gate input of the counter. As a result, the counter generates a logic 0 pulse at the output which remains logic 0 for the duration of the count as shown in Fig. 4.13(b) on next page.

4.30

Embedded Systems: Design, Programming and Applications

Fig. 4.13(a) Mode 0 of 8254

Fig. 4.13(b)

Mode 1 of 8254

3. MODE 2: In this mode the counter generates a series of continuous pulses. Pulse width of one output pulse equals to the width of one clock cycle. The distance of one output pulse to the next is determined by the count. In this mode the gate input must be logic 1 to produce continuous pulses. Figure 4.13(c) shows the function of mode 2 of 8254 programmable timer.

Fig. 4.13(c)

Mode 2 of 8254

4. MODE 3: In this mode the counter generates a series of continuous square wave at the output of the counter. For even count, the output is high for one half of the count and low for one half of the count. For odd count, the output is high for one clocking period longer than its low. Figure 4.13(d) shows the function of mode 3 of 8254 programmable timer.

Fig. 4.13(d)

Mode 3 of 8254

Interrupt

4.31

5. MAODE 4: In this mode the counter generates a single pulse at the output of the counter. If the counter is programmed for 4 the output is high for 4 clocking periods and low for one period. The cycle starts only when the counter is loaded with its complete count. In this mode gate input is used to enable the counter. Figure 4.13(e) shows the function of mode 4 of 8254 programmable timer.

Fig. 4.13(e) Mode 4 of 8254

6. MODE 5: Mode 5 functions as a hardware triggered one shot multivibrator. In this mode, the counter is triggered by a trigger pulse on the gate input of the counter instead of using software. The counter is retriggerable in this mode. Figure 4.13(f) shows the function of mode 4 of 8254 programmable timer.

Fig. 4.13(f) Mode 1 of 8254

4.6.2

Control Word for 8254

Each counter of 8254 is programmed by writing control word with initial count. Control word determines the following operation of the counter. 1. Control word selects the counter; 2. It determines the mode of operation; 3. It determines the type of operation (Read or Write); 4. Control word selects either binary or BCD count. Each counter can be programmed with the count range from 0001H to FFFFH. The length of a control word is 8 bit. Figure 4.14 shows the control word format for 8254 programmable timer. The least significant bit of control word selects BCD count when bit 0 is 1 and selects binary count

4.32

Embedded Systems: Design, Programming and Applications

when bit 0 is 0. M0, M1, and M2 bits select six different modes as shown in figure. RW0 and RW1 bits select how the data is to be read or write. The SC1 and SC2 bits select the counter and read back mode of operation. The program control word of each counter select the process of counter operation. If a counter is programmed for two bytes then the first byte (Least Significant Byte) stops the count and the second byte (Most Significant Byte) starts the counter with a new count.

Fig. 4.14 Control word format for 8254 programmable timer

Read Back Control Word The programmable counter 8254 has three counters and each counter has an internal latch. These latches are read with the read counter port operation. Usually, these latches follow the count. The latches store the count when program latch control word, as shown in Fig. 4.15, is programmed accordingly and hence the content of the counter is held in a latch until it is read. If reading of counter is programmed, the latch provides the contents of the counter.

Fig. 4.15

Latch control word of counter of 8254

The read back control word is used to read the content of more than one counter simultaneously. Figure 4.16 illustrates the read back control word.

Interrupt

Fig. 4.16

4.33

Read back control word of counter of 8254 _____

Using this read back control word, when CNT is 0, counter to be latched is selected by CNT0, ___ CNT1 and CNT2. When ST = 0, the status register is latched.

4.7

INTERRUPT IN EMBEDDED SYSTEMS

An embedded system is a computer system designed for specific control functions within a larger system, often with real-time computing constraints. It is embedded as part of a complete device often including hardware and mechanical parts. Embedded systems control many devices in common use today. Embedded systems contain processing cores. The key characteristic, however, is being dedicated to handle a particular task. Since the embedded system is dedicated to specific tasks, it requires breaks in program flow to control the peripheral devices. The asynchronous breaks in program flow that occur as a result of events outside the running program is known as interrupts. They are usually hardware related, stemming from events such as a button press, timer expiration, or completion of a data transfer. Therefore, interrupt conditions are independent of particular instructions and they can happen at any time. Interrupts trigger execution of instructions that perform work on behalf of the system, but not necessarily the current program. Exceptions and traps are predictable synchronous breaks in program flow. They are synchronous because they are caused by the execution of certain instructions. Exceptions and traps trigger execution of instructions that are not part of the program, but perform work on behalf of it. Interrupts are one of the most powerful and useful features in embedded systems. They can make the system more efficient and more responsive to critical events, and they can also make the software easier to write and understand. Every embedded programmer should be aware of interrupts. They should consider interrupt as useful tools and use them whenever appropriate.

4.7.1

Interrupt Service Routine

Interrupt Service Routines (ISR) are the portions of the program code that handle the interrupt requests. When a hardware or software interrupt is triggered the processor breaks away from the current task, moves the instruction pointer to the ISR, and then continues operation. When the ISR has completed, the processor returns execution to the previous location. Embedded systems may be called interrupt driven systems, because most of the processing occurs in ISRs, and the embedded

4.34

Embedded Systems: Design, Programming and Applications

system spends most of its time in a low-power mode. Interrupt invites the attention of processor for some action on the hardware or software event. An interrupt request is generated when some device sends the interrupt request signal to the CPU. This interrupt is called hardware interrupt. When software run-time exception condition is detected, either processor hardware or software instruction generates an interrupt. This interrupt is called software interrupt or exception or trap. The CPU, if configured by the software to do so, will respond to this interrupt request by finishing the current instruction it is executing, and then jumping or “vectoring” to the correct interrupt service routine (ISR) for this interrupt. This jumping or vectoring is similar to a subroutine call. The CPU will save the program counter on the hardware stack or in a special register, and depending on design may also save some status information on the stack. Then CPU begins execution of the interrupt code that the user has designated for this interrupt source. At the end of the execution of interrupt code a return-frominterrupt instruction is executed which will restore any automatically-saved status information followed by the saved program counter, which then results in the previously running code being resumed without any indication that the interrupt has occurred. Programmer can save and restore any state information that is automatically saved and restored in the interrupt process, in any additional resources such as registers that are used in the ISR. When ISR is executed due to interrupt generated by device or port, the ISR is called device driver ISR. When ISR is executed due to interrupt generated by software interrupts, the ISR is called exception or signal or trap handler. Device driver ISRs execute on software interrupts from device functions like device open ( ), close ( ) etc. Due to interrupt, all the flags and registers should be unaltered, either by having not been modified in the ISR, or, if they are modified in the ISR. Failure to preserve the processor state across an interrupt has the effect on the interrupted code of having registers or condition flags change at random points, which is a serious error, and very difficult to debug. The general sequence for an interrupt is as follows: 1. A program is executing and interrupts are enabled; 2. Interrupt event sends an interrupt request to the CPU; 3. After completing the current instruction(s), the CPU begins the interrupt response; (i) Automatically saves current program counter (ii) Automatically saves some status (depending on CPU) (iii) jump to correct interrupt service routine for this request (iv) ISR code saves any registers and flags it will modify (v) ISR services the interrupt and re-arms it if necessary (vi) ISR code restores any saved registers and flags (vii) ISR executes a return-from-interrupt instruction or sequence (viii) return-from-interrupt instruction restores automatically-saved status (ix) return-from-interrupt instruction recovers saved program counter 4. Program code continues to run from the point it responded to the interrupt.

Interrupt

4.35

However the details of this process will depend on the CPU design. Many devices use the hardware stack for all saved data, but RISC designs typically save the PC in a register (the link register). Many designs also have separate duplicate registers that can be used for interrupt processing, thus reducing the amount of state data that must be saved and restored. System hardware has devices and devices require device drivers. Therefore the embedded software must consist of the codes for following functions. 1. Configuring or initializing; 2. Activating or opening or attaching; 3. Driving function for read; 4. Driving function for write; 5. Resetting or deactivating or closing or detaching. The above tasks are completed by using ISR. The device-driver function calls the ISR by using a software interrupt instruction (SWI). Using an ISR, each device task is completed. The device driver function calls the ISR by a software interrupt instruction SWI. Detection of error condition or exceptional run time condition is called throwing an exception by a program. An ISR executes first. This function is called catch function because it executes on catching the exception thrown by executing by SWI. Figure 4.17 shows use of SWI instruction for calling ISR in the function for throwing and catching error condition encountered during running the program.

Fig. 4.17 Use of SWI instruction for calling ISR in the function for throwing and catching error condition encountered during running the program

4.7.2

Setting up Interrupt Service Routines and Interrupt Vectors

Every microcontroller will have a documented list of interrupts that can be generated by on-chip or external events. It will also have a list of fixed addresses (often called vectors) corresponding to each of these interrupts. An interrupt vector can take one of two forms. It may be an address where actual code resides (usually, just a jump to the ISR), or it may be an address that holds the address of the ISR. So if your mC supports an interrupt N, it will have a fixed vector address for that interrupt, call it address VN. Supposing you write an ISR to handle this interrupt and the ISR is located in memory starting at address VISR, then the vector for interrupt N (the memory

4.36

Embedded Systems: Design, Programming and Applications

starting at address VN) will either consist of an instruction jump-to-VISR or it will just consist of the address VISR.

Vector holds jump to ISR .org This_Vector_Address VN: jmp VISR ;jump to ISR … VISR: ISR for Interrupt N …

Vector holds address of ISR .org This_Vector_Address VN: VISR ;address of ISR … VISR: ISR for Interrupt N … Following important considerations for the structure of an ISR are stated below. 1. All registers that will be used in the ISR must first be saved (usually, pushed onto a stack); 2. At the end of the ISR all the saved registers must be restored (if on a stack, popped off the stack in the reverse order they were pushed on); 3. Finally the correct return-from-interrupt instruction be executed, which will not only resume execution of the code that was interrupted, but will also correctly restore or adjust any status bits that were altered by the interrupt response hardware. This restoration of status bits differentiates a return-from-interrupt instruction from the standard return-fromsubroutine instruction. If the ISR is written in assembly language then the saving and restoring of registers, and the return-from-interrupt instruction, will be evident in the code. If the ISR is written in C, the compiler will insert the correct code invisible to the programmer, but to do so, the compiler must be informed that the function is related to ISR and it is not a regular function. Different compilers use different keywords to make this distinction.

4.7.3

Special Features of an ISR Call

Interrupts and ISRs play an important role in using the system hardware and devices An ISR has following special features. 1. An event is executed by call of an ISR due to interrupt; 2. An ISR call is even-based change of current sequence of instructions of a program to another sequence of instructions of the program and this sequence of executions of instruction continues till return instruction; 3. An event can be signaled by software interrupt instruction SWI;

Interrupt

4.37

4. An interrupt service mechanism exists in a system to call the ISRs from multiple sources; 5. Execution of interrupt service routine can be masked by instruction to set a mask bit and unmasked by another instruction to reset the mask bit; 6. Return from an ISR follows two mechanisms. In one mechanism, ISR on beginning the execution can automatically disable interrupt services of other devices and automatically enabled any one device before a service call of that device. In another interrupt mechanism, ISR on beginning the execution does not automatically disable interrupt services of other devices and there can be diversion in case of higher priority interrupt.

4.7.4

Interrupt Handling

An interrupt handling mechanism must exist in each system to handle interrupts from various processes and simultaneously to keep pending for service. A system provides an interrupt handling mechanism for executing the ISRs in case of the interrupts from physical devices, systems, software instructions and exceptions. The hardware response to the interrupt automatically saves the most essential state, but the first lines of ISR code are usually dedicated to saving additional state like saving condition flags if not saved by the hardware along with saving additional registers. This two-step process is used because every ISR will have different requirements for the number of registers it needs. Thus every ISR may need to save different registers A very simple ISR may not need to use any registers, another ISR may need to use only one or two registers, while a more complicated ISR may need to use a large number of registers. In every case, the ISR should only save and restore those registers it actually uses. The characteristics of handling an interrupt are stated below: 1. A Software is required to handle the interrupting event (ISR); 2. The software to handle the interrupting event (ISR) is executed as quickly as possible after the event occurs; 3. The foreground code can be interrupted at almost any point in its execution; 4. The immediate state of the interrupted code must be saved and restored so that the interrupted code can resume running without error. Some of this saving and restoring is automatic, while the rest must be done by the ISR; 5. The “extended” state of the system will be changed by the ISR. Thus both foreground code and interrupt code must take precautions to insure that all data and resources affected by the interrupt remain uncorrupted. The interrupt handler is the routine that is executed when an interrupt occurs and an ISR is a routine that acts on a particular interrupt. An interrupt handling mechanism must exist in each system to handle interrupts from various processes and simultaneously to keep pending for service. A system provides an interrupt handling mechanism for executing the ISRs in case of the interrupts from physical devices, systems, software instructions and exceptions. The actual process of determining a good handling method is complicated. Numerous actions are occurring simultaneously at a single point and these actions have to be handled fast and efficiently. The methods of interrupt handling are listed on next page.

4.38

Embedded Systems: Design, Programming and Applications

1. Non-nested interrupt handler; 2. Nested interrupt handler; 3. Re-entrant nested interrupt handler; 4. Prioritized interrupt handler. All registers that will be used in the ISR must be pushed onto a stack so that at the end of the ISR all the saved registers must be restored and finally that the correct return-from-interrupt instruction be executed, which will not only resume execution of the code that was interrupted, but also correctly restore or adjust any status bits that were altered by the interrupt response hardware. It is this restoration of status bits that differentiates a return-from-interrupt instruction from the standard return from subroutine instruction. If the ISR is written in assembly language then the saving and restoring of registers, and the return-from-interrupt instruction, will be evident in the code. If the ISR is written in C, the compiler will insert the correct code invisible to the programmer, but to do so, the compiler must be informed that the function is an ISR and not a regular function. Different compilers use different keywords to make this distinction. The hardware response to the interrupt automatically saves the most essential state, but the first lines of ISR code are usually dedicated to saving additional state like saving condition flags if not saved by the hardware along with saving additional registers. This two-step process is used because every ISR will have different requirements for the number of registers it needs. Thus every ISR may need to save different registers A very simple ISR may not need to use any registers, another ISR may need to use only one or two registers, while a more complicated ISR may need to use a large number of registers. In every case, the ISR should only save and restore those registers it actually uses. The characteristics of handling an interrupt are stated below. 1. A Software is required to handle the interrupting event (ISR). The software to handle the interrupting event (ISR) is executed as quickly as possible after the event occurs. The code can be interrupted at almost any point in its execution. The immediate state of the interrupted code must be saved and restored so that the interrupted code can resume running without error. Some of this saving and restoring is automatic, while the rest must be done by the ISR; 2. The “extended” state of the system will be changed by the ISR. Thus both foreground code and interrupt code must take precautions to insure that all data and resources affected by the interrupt remain uncorrupted; 3. Handling interrupts is at the heart of an embedded system. By managing the interaction with external systems through effective use of interrupts can dramatically improve system efficiency and the use of processing resources. The actual process of determining a good handling method can be complicated, challenging and fun; 4. Numerous actions are occurring simultaneously at a single point and these actions have to be handled fast and efficiently. Interrupt Handling 1: Embedded systems have to handle real world events such as the detection of a key being pressed, synchronization of video output, or handle the transmission and reception of data packets for a communication device. These events have to be handled in real time, which means an action has to take place within a particular time period to process the event. For

Interrupt

4.39

instance, when a key is pressed on an embedded system it has to respond quickly enough so that the user can see a character appearing on the screen, without any noticeable delay. If an inordinate delay occurs the user will perceive the system as being non-responsive. Interrupt Handling 2:

An embedded system has to handle many events. An event halts the normal flow of the processor. For ease of explanation, events can be divided into two types. 1. Planned and unplanned Type: Planned events are events such as a key being pressed, a timer producing an interrupt periodically. 2. Unplanned events: Unplanned events are data aborts, instruction aborts, and undefined instruction aborts. Planned events will be called interrupts and unplanned events will be called exceptions. When an event occurs the normal flow of execution from one instruction to the next is halted and re-directed to another instruction that is designed specifically to handle that event. Once the event has been serviced the processor can resume normal execution by setting the program counter to point to the instruction after the instruction that was halted. At a physical level, an interrupt is raised when the IRQ pin on the ARM core is set. Interrupt Handling 3:

This type includes a controller which provides a set of programmable registers. These registers are used to read or write masks and obtain the interrupt status.

Interrupt Handling 4: It is a process like a task except that it executes in its own virtual address space and has a stack and heap located within that virtual space. Processes can be implemented on embedded systems that include a special device which changes address space and paging. In this process, to handle multiple tasks a RTOS uses a number of different scheduling methods. Each method has different advantages and disadvantages depending upon the application. It is important that the tasks can communicate with each other, since they will probably have to share memory or peripherals. RTOS context switching occurs periodically when a timer interrupt is raised. The context switch will first save the state of the currently active task and then will restore the state of the next task to be active. The next task chosen depends upon the scheduling algorithm. For instance, an ISR for a key being pressed might determine which key has been pressed and then assign a character that is then placed into a keyboard buffer. Interrupt Handling 5:

It is a nested interrupt handling system that allows further interrupts to occur even when servicing an existing interrupt. This is achieved by re-enabling the interrupts only when enough of the processor context has been saved onto the stack. Once the nested interrupt has been serviced then control is relinquished back to the original interrupt service routine. The second method is to have some form of prioritization. Prioritization works by allowing interrupts with an equal or higher prioritization to interrupt a currently serviced routine. This means that the processor does not spend excessive time handling the lower priority interrupts.

Interrupt Handling 6:

It is three level nested interrupt handling system. If the embedded system is memory constrained. Then the handler and the ISR should be written in Thumb code since Thumb provides higher code density on the ARM processor. If Thumb code is used then the designer has to be careful in swapping the processor back into Thumb state when an interrupt occurs since the ARM processor automatically reverts back to ARM state when an exception or interrupt

4.40

Embedded Systems: Design, Programming and Applications

is raised. The entry and exit code in an interrupt handler must be written in ARM code, since the ARM automatically switches to ARM state when servicing an exception or interrupt. The exit code must be in ARM state, because the Thumb instruction set does not contain the instructions required to return from an exception or interrupt. As mentioned above the main body of the interrupt handler can be in Thumb code to take advantage of code density and faster execution from 16 bit or 8 bit memory devices.

Enabling and Disabling Interrupts Every interrupt source will have some way to enable or disable it. Usually an enable bit is stored in a configuration register. At the end of the interrupt configuration sequence for that peripheral, the interrupt will be enabled. The CPU has a global interrupt enable mechanism. The bit in a configuration register allows to process interrupts. This global interrupt enable is set after all the individual interrupt enables have been set. It means tht all the individual interrupt sources have been configured. The initialization sequence is stated below. Configure and enable interrupt source 1 Configure and enable interrupt source 2 ... … … … … … … … … … Configure and enable interrupt source N Enable Global Interrupts After being enabled, individual interrupt sources can be disabled and re-enabled as needed at any point in the program, and global interrupts can also be disabled and re-enabled at any point in the program.

Some Common Interrupt Sources The microcontroller contains additional onboard peripherals which can generate interrupts. The common sources of interrupts on a microcontroller are shown below. 1. Timer overflow; 2. Timer compare/match; 3. Timer capture; 4. UART RX char ready; 5. UART TX ready; 6. UART TX complete; 7. SPI transfer; 8. I2C transfer; 9. ADC conversion complete; 10. Watchdog. All of these events are asynchronous, meaning that they can happen at any time. Since interrupts can occur at any point in the execution of a program, in most cases the execution time of the

Interrupt

4.41

interrupt service code should be as short as possible. All other processing related to the interrupt should be moved outside the ISR and into the foreground code. Interrupts introduce possibilities for data corruption which must be explicitly accounted for in both the interrupt code and the background code. Following steps are necessary to be followed for prevention of data corruption. 1. ISR saves and restores any working registers it uses; 2. ISR saves and restores status/condition code register; 3. Foreground code uses atomic accesses for any data it shares with ISR. Above cases are known as critical section. A critical section is a section of code which must have complete and undisturbed access to a block of data or any other resource. Disabling interrupts before entering a critical section is effective. Only any interrupts that could potentially affect the data accessed in the critical section is to be disabled.

Interrupt Priorities There is a possibility that interrupt requests from two different sources can be generated at the same time. If the CPU checks and finds two pending interrupts from different sources, it will use the assigned priorities of each interrupt source to determine which interrupt to run first. The other interrupt will then run when the first ISR is finished. Some devices have interrupt priorities built into their hardware design, but for other devices the programmer can specify the priorities of the different interrupt sources. This allows the programmer to control which interrupts get the fastest servicing.

4.7.5

Interrupt Vectoring vs. Polling

Each interrupt source is vectored to its own private ISR. It is also possible to have multiple interrupt sources all connected to the same interrupt request line. Any of the sources can request an interrupt by asserting the line, and the ISR must then poll each device that is on the interrupt request line to see which device requested an interrupt. There may be cases where two or more external devices are connected to a single interrupt pin on a micro computer with interrupt vectoring. Hence it is possible to add polling into the mix as well. Some times a second interrupt occurs while the ISR for another interrupt is being executed. In this case, either the ISR for the second interrupt will not run until the code for the first interrupt has finished, or the second interrupt will interrupt the ISR for the first interrupt and the second ISR will run, and thus the ISR for the first interrupt will be delayed in finishing. Working of these two cases will depend on the design of the device, and on how the programmer has configured it. If the interrupt request did not cease as soon as the ISR finished, the interrupt request would cause the ISR to be re-entered, trapping the code in an endless interrupt response to a single interrupt request. Clearly, as part of the servicing of an interrupt, the interrupt request must be cleared so that endless response does not happen. In general, there are two methods for clearing the interrupt request. The first method is automatic. i.e. CPU vectors to the ISR automatically clear the interrupt request. In this case, the request is cleared by the hardware. The second method requires that code in the ISR clear the interrupt request manually. This method clears an interrupt request flag in an

.

4.42

Embedded Systems: Design, Programming and Applications

interrupt control/status register associated with the interrupt source. It is common that clearing such flags is accomplished by actually writing a ‘1’ to the flag bit location.

4.7.6

Edge-Triggered and Level-Triggered Interrupts

External interrupts, which are triggered by a voltage on a pin, are unique in one aspect. In many device families, external interrupts can be configured as either edge-triggered or as level-triggered. With an edge-triggered interrupt, the interrupt request is generated once for each edge depending on design and configuration. This may be a negative-going or falling edge, a positive-going or rising edge, or either edge. With a level-triggered interrupt, it is not the edge but the level that causes the interrupt request. What this means is that if one has an external interrupt low signal that goes active and stays active, if the external interrupt was configured for low edge-triggering, exactly one interrupt request would be generated, no matter how long the interrupt line was held low. But if the external interrupt was configured for low level-triggering, interrupt requests would continue to be generated for as long as the interrupt line was held low. As soon as the ISR returned from one such interrupt, the CPU would vector to the ISR again unless, other higher priority interrupts were pending. Exceptions and traps are predictable, synchronous breaks in program flow. They are synchronous because Normal execution of a given software application is contained within the bounds of one program, or instruction stream. Such execution is provable, as well as traceable. Interrupts break in program flow. Program flow breaks fall into two general types. 1. Program flow breaks are caused by the execution of certain instructions like divide by zero, illegal memory access or software interrupts. Execution of exceptions and traps trigger instructions that are not part of the program, but perform work on behalf of it; 2. Events outside the running program breaks in program flow. Interrupts are usually hardware related, stemming from events such as a button press, timer expiration, or completion of a data transfer. Interrupt conditions are independent of particular instructions. Interrupts trigger execution of instructions that perform work on behalf of the system, but not necessarily the current program. As a system’s functional requirements and the size of the software grow, it becomes more difficult to ensure that time-critical items (such as capturing incoming data before it is overwritten by the hardware) are performed properly. This difficulty can be overcome by using a faster processor or the time-critical functions can be separated from the others and executing them in a prioritized manner. The non-time-critical functions within the main loop continue to execute as quickly as they can, but time-critical functions are executed on demand-in response to interrupts from the hardware.

Hardware When a device asserts its interrupt request signal, it must be processed in an orderly fashion. All CPUs, and many devices, have some mechanism for enabling/disabling interrupt recognition and processing:

Interrupt

4.43

1. At the device level, there is usually an interrupt control register with bits to enable or disable the interrupts that device can generate; 2. At the CPU level, a global mechanism functions to inhibit/enable (often called the global interrupt enable) recognition of interrupts; 3. Systems with multiple interrupt inputs provide the ability to mask (inhibit) interrupt requests individually and/or on a priority basis. This capability may be built into the CPU or provided by an external interrupt controller. Typically, there are one or more interrupt mask registers, with individual bits allowing or inhibiting individual interrupt sources; 4. There is often also one non-maskable interrupt input to the CPU that is used to signal important conditions such as pending power fail, reset button pressed, or watchdog timer expiration.

Software Some older CPUs routed all interrupts to a single ISR. Upon recognizing an interrupt, the CPU saved some state information and started execution at a fixed location. The ISR at that location had to poll the devices in priority order to determine which one required service. However, the basic process of interrupt handling is the same as in the more complex case. Most modern CPUs use the same general mechanism for processing exceptions, traps, and interrupts: an interrupt vector table. Some CPU vector tables contain only the address of the code to be executed. In most cases, a specific ISR is responsible for servicing each interrupting device and acknowledging, clearing, and rearming its interrupt; in some cases, servicing the device automatically clears and rearms the interrupt. Interrupts may occur at any time, but the CPU does not instantly recognize and process them immediately. First, the CPU will not recognize a new interrupt while interrupts are disabled. Second, the CPU must, upon recognition, stop fetching new instructions and complete those still in progress. Because the interrupt is totally unrelated to the running program it interrupts, the CPU and ISR work together to save and restore the full state of the interrupted program (stack, flags, registers, and so on). The running program is not affected by the interruption, although it takes longer to execute. Many interrupt controllers provide a means of prioritizing interrupt sources, so that, in the event of multiple interrupts occurring at (approximately) the same time, the more timecritical ones are processed first. These same systems usually also provide for prioritized interrupt handling, a means by which a higher-priority interrupt can interrupt the processing of a lowerpriority interrupt. This is called interrupt nesting. In general, the ISR should only take care of the time-critical portion of the processing, then, depending on the complexity of the system, it may set a flag for the main loop, or use an operating system call to awaken a task to perform the non-timecritical portion.

Latency The interrupt latency is the interval of time measured from the instant an interrupt is asserted until the corresponding ISR begins to execute. The worst-case latency for any given interrupt is a sum of many things, from longest to shortest. All the interrupt handler suffers delay due to latency. The conditions of latency are described below.

4.44

Embedded Systems: Design, Programming and Applications

1. The longest period global interrupt recognition is inhibited; 2. The time it would take to execute all higher priority interrupts if they occurred simultaneously; 3. The time it takes the specific ISR to service all of its interrupt requests; 4. The time it takes to finish the program instructions in progress and save the current program state and begin the ISR. Higher-priority interrupts can have much lower latencies. In simple cases, latency can be calculated from instruction times, but many modern systems with 32 bit CPUs, caches, and multiple interrupt sources, are complex for exact latency calculations. Interrupt latency must be considered at design time, whenever responsiveness matters. Latency can be calculated in following methods. 1. If interrupt service starts immediately on context switching, the interrupt latency Tsw equals the context switching period; 2. If instructions in a processor take variable clock cycles, maximum clock cycles for an instruction are taken into account for calculating the latency. 3. When interrupt service does not start immediately and the sum of time intervals to complete the higher priority ISRs is STex, interrupt latency is (STex + Tsw).

4.8

IO-APIC INTERRUPTS

A multiprocessor shows the concept of a Local-Advanced-PIC in the CPU and these IO-APICs connected to devices. Each IO-APIC (82093) has 24 interrupt lines and allows the priority of each interrupt to be set independently. The OS of does not have to interact with the IO-APIC until it sends the end of interrupt notification. The IO-APCI provides backwards compatibility with the older XT-PIC model. As a result, the lower 16 interrupts are usually dedicated to their assignments under the XT-PIC model. This assignment of interrupts provides only eight additional interrupts, which forces sharing. The sequence for IO-APIC delivery and servicing is described as follows. 1. When a device required servicing from the CPU, it drives the interrupt line into the IO-APIC associated with it; 2. The IO-APIC writes the interrupt vector associated with its driven interrupt line into the Local APIC of the CPU; 3. The interrupted CPU begins running the ISRs associated with the interrupt vector it received. The MSI model eliminates the devices’ need to use the IO-APIC, allowing every device to write directly to the CPU’s Local-APIC. The MSI model supports 224 interrupts, and with this high number of interrupts, IRQ sharing is no longer allowed. The following is the sequence for MSI delivery and servicing. (a) A device requiring servicing from the CPU generates an MSI, writing the interrupt vector directly into the Local-APIC of the CPU servicing it. (b) The interrupted CPU begins running the ISR associated with the interrupt vector it received. The device is serviced without any need to check and clear an IRQ pending bit.

Interrupt

4.9

4.45

PCIe* INTERRUPT

ISR may be divided into two parts. 1. Top-half is a faster part of ISR which should quickly store minimal information about interrupt and schedule slower bottom-half at a later time. When a connected device needs servicing by the CPU, it drives the signal on the interrupt pin to which it is connected. Top-half includes fast interrupt handler, First-Level Interrupt Handler (FLIH); 2. Bottom-half consists of slow interrupt handler and Second-Level Interrupt Handlers (SLIH)). From the Intel 8259 PIC, the OS is able to determine what interrupt is pending. The CPU masks that interrupt and begins running the ISR associated with it. The ISR will check with the device with which it is associated for a pending interrupt. If the device has a pending interrupt, then the ISR will clear the Interrupt Request (IRQ) pending and begin servicing the device. Once the ISR has completed servicing the device, it will schedule a task if more processing is needed and return control back to the OS, indicating that it handled an interrupt. Once the OS has serviced the interrupt, it will unmask the interrupt from the Intel 8259 PIC and run any task which has been scheduled.

Overlapping Interrupts If a second interrupt occurs while the ISR for another interrupt is being executed either the ISR for the second interrupt will not run until the code for the first interrupt has finished, or the second interrupt will interrupt the ISR for the first interrupt and the second ISR will run, and thus the ISR for the first interrupt will be delayed in finishing. Which of these two scenarios plays out will depend on the design of the device, and on how the programmer has configured it. Actually reading switches and buttons directly via interrupts is generally not a good idea, for the simple reason that switch bouncing can generate a large number of interrupts for a single switch event. But this time, instead of monitoring the buttons in a loop, the buttons will generate interrupts and the LED will be turned ON and OFF inside the corresponding ISRs. The problem of multiple interrupts from a single switch event does not pertain in this case, since turning an LED ON or OFF multiple times is no different than turning it ON or OFF just once.

Review Questions 1. What do you mean by interrupt in microprocessor systems? List the interrupt pin found in Intel 8086 microprocessor. 2. Write five interrupt instructions for the microprocessor. 3. What is an interrupt vector? Where are the interrupt vectors located in the microprocessor’s memory? 4. What is interrupt vector table? Explain its structure. (WBUT 2007) 5. Explain the interrupt response sequence of 8086 microprocessor. (WBUT 2007) 6. What is the interrupt vector address of the following interrupt in 8086 microprocessor? (i) INTO (ii) NMI (iii) INT 20H (WBUT 2007)

4.46 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37.

Embedded Systems: Design, Programming and Applications

How many interrupt vectors are found in the interrupt vector table? Which interrupt vectors are reserved by Intel? Explain how a Type 0 interrupt occurs. What memory location contain the vector for an INT 44H? Explain the operation of IRET instruction. What is the purpose of interrupt vector type number 7? List the events that occur when an interrupt becomes active. Explain the purpose of interrupt flag IF and TF. The NMI interrupt input automatically vectors through which vector type number. Draw a circuit that places interrupt type number CCH on the data bus in response to the INTR input. Draw the internal architecture of 8254 timer/counter and describe its different functional unit in brief. Discuss the functions of different bits/group of bits of the control word of 8254 timer/ counter. (WBUT 2006) What do you mean by read back of 8254? Describe the read back control word of 8254. Describe the different modes of operation of 8254 timer counter. (WBUT 2005) Draw a circuit diagram to generate NMI signal for real-time clock using IC 555. Draw the circuit diagram to generate INTR signal using D flip-flop. Draw the timing diagram of INTR input, LOCK input, INTA output for vector number on the data bus. Draw the circuit diagram for power failure circuit using power line signal. What are the different sources of interrupt? Describe the different types of interrupts available in advanced microprocessor. Distinguish between software interrupt and hardware interrupt. Draw the internal architecture of 8259A programmable interrupt controller and describe its different functional unit in brief. What are the special features of 8259 programmable interrupt controller? Draw the circuit diagram to interface 8259 with 8086 microprocessor and describe its working principle. Draw and describe the interrupt acknowledge machine cycles of 8086. What is the purpose of the IR0 TO IR7 pins on the 8259A? What is the use of CAS2 to CAS0 pins of 8259A? Where is a slave INT pin connected on the master 8259A in a cascaded system? What are ICW and OCW? How many ICWs are needed to program the 8259A when operated in a single master in a system? Where is the vector type number stored in the 8259A? What is a non-specific EOI? Describe priority rotation in the 8259A.

Interrupt

4.47

38. An 8086 Type 2 interrupt service routine starts from 5000:0100H memory. How will this address be stored in interrupt vector table? (WBUT 2005) 39. What are the advantages and disadvantages of busy and wait transfer mode for the I/O devices? 40. What are the advantage and disadvantages of interrupt driven data transfer? What are the advantages of DMA based data transfer over interrupt driven data transfer? 41. How is the vector address used for an interrupt source? 42. How do you initialize and configure a device? 43. Define context, interrupt latency and interrupt service dead line. How do the device driver functions and ISRs differ? How do the ISR calls differ in 8086 and 8051? 44. What are the uses of hardware-assigned priorities in an interrupt service mechanism? 45. What are the uses of software-assigned priorities in an interrupt service mechanism? 46. How is break point interrupt important for debugging embedded software? 47. How do you write device driver? List different steps for writing device driver. 48. What are the interrupt in 8086, which generate software error?

Choose the Correct Answer 1. The interrupt pins of 8086 are (a) TRAP, INTR (b) NMI, TRAP (c) NMI, RST 7.5 (d) NMI, INTR (WBUT 2007) 2. How many interrupt requests can an 8259 process? (a) 4 (b) 8 (c) 16 (d) 64 (WBUT 2007) 3. In mode 3, the 8254 can be used as WBUT 2007 (a) software triggered strobe (b) rate generator (c) programmable mono-shot-multivibrator (d) square wave generator 4. Vector location of NMI is (a) 00000H (b) 00008H (c) 00010H (d) 0014H (WBUT 2007) 5. In the interrupt instructions of the Type INT n the maximum value of n is (a) 31 (b) 127 (c) 63 (d) 255 (WBUT 2007) 6. What is the maximum operating frequency of 8254 (a) 1 MHz (b) 2 MHz (c) 4 MHz (d) 8 MHz (WBUT 2007)

4.48

Embedded Systems: Design, Programming and Applications

7. What is the vector location for INT0 (a) 00000H (b) 00008H (c) 00010H (d) 00014H 8. In mode 0, the 8254 can be used as (a) event counter (b) rate generator (c) programmable mono-shot-multivibrator (d) square wave generator 9. In mode 1, the 8254 can be used as (a) event counter (b) rate generator (c) refriggerable monostable multivibrator (d) square wave generator 10. In mode 2, the 8254 can be used as (a) event counter (b) rate generator (c) pulse generator (d) square wave generator 13. In mode 4, the 8254 can be used as (a) event counter (b) rate generator (c) single pulse generator (d) square wave generator 14. In mode 5, the 8254 can be used as (a) event counter (b) rate generator (c) one shot multivibrator (d) square wave generator 15. The number of counter in 8254 is (a) 1 (b) 2 (c) 3 (d) 4

(WBUT 2006)

5 5.1

Real World Interfacing

INTRODUCTION

Interfacing is a way to communicate and transfer information in either way without ending into deadlocks. It is a process of effective communication in real time which involves addressing, arbitration and protocols. An interfacing circuit consists of decoders and demultiplexers and is designed according to the available control signals and timing plan of bus signals. The circuit connects all the units like processors, memory I/O bus bridge controller and I/O devices through the system buses and I/O buses. I/O bus bridge controller may be a part of the glue interfacing circuit used in the system. It is also used in Programmable Logic Device (PLD), Generic Array Logic (GAL) and FPGA. The traditional definition of input-output is the devices those create a medium of interaction with the users. The I/O devices are printer, visual display units, keyboard, cameras, plotters, scanners etc. An embedded controller needs to communicate with a wide range of devices namely, Analog to Digital (A-D) and Digital to Analog (D-A) Converters, CODECs, Small Screen Displays, Antennas, Cameras, Microphones, Touch Screens etc. Three sets of buses (lines) are required for interfacing memory and I/O devices with the microprocessor. These buses are called system buses. The system bus interconnects the subsystems, which interconnects the processors with the memory systems and I/O devices. In this chapter we shall discuss interfacing the processor with memory and I/O devices. The interrupts and bus arbitration are also discussed in this chapter because knowledge of interrupts is very essential to realize real world interfacing. Finally, serial, parallel, synchronous and asynchronous data transfer processes are discussed in this chapter elaborately.

5.2

INTERFACING THE PROCESSOR WITH MEMORY AND I/O DEVICES

Interfacing the processor memory and I/O devices is obtained by interconnection of the devices using the system buses. The interconnections for a simple bus structure for interfacing processor memory and I/O devices are shown in Fig 5.1. Three sets of buses called as address bus, data bus

5.2

Embedded Systems: Design, Programming and Applications

and control bus are used for interconnection. The microprocessor transmits the address of the instruction or data to memory or I/O devices through the address bus. The address bus actually provides the location of memory where the instruction or data is stored. Address bus consists of 8 or 16 or 32 lines. Data bus carries the instruction or data from memory or I/O devices. When microprocessor transmits the address of the data, data from memory or I/O devices is transmitted through data bus. The control bus transmits signals to control the timing of actions during interconnections. Control signal synchronizes the operation of subsystems. When the microprocessor transmits the address through address bus, it also transmits control signal through control signal. Then data is placed on the data bus. The processor must place either read or a write signal on control bus to read memory content or write onto memory.

Fig. 5.1 Interconnections for a simple bus structure for interfacing

The address and data buses may be Time Division Multiplexed (TDM). The interfacing circuit demultiplexes the buses by a control signal. In a microprocessor system, data transfer always maintains a protocol. The literal meaning of protocol is a set of rules. There is a set of formal rules describing how to transfer data, especially between two devices.

Fig. 5.2 Timing diagram of a data read protocol

Timing diagram of a data read protocol is shown in Fig. 5.2. The set of rules or the protocol for data transfer between two devices is mentioned on next page.

Real World Interfacing

5.3

1. The CPU must send the memory address; 2. The read line must be enabled; 3. The processor must wait till the memory is ready; 4. Accept the bits in the data lines. Timing diagram of a data write protocol is shown in Fig. 5.3. The set of rules or the protocol is mentioned below: 1. The CPU must send the memory address; 2. The write line must be enabled; 3. The microprocessor sends the data over the data bus; 4. The processor must wait till the memory is ready.

Fig. 5.3 Timing diagram of a data write protocol

5.2.1

Input Output Operations

Embedded System design requires that I/O devices receive servicing in an efficient manner so that total system tasks can be done by the processor with no effect on throughput. The most common method of servicing such devices is known as polling. Using polling method the microprocessor tests each I/O device in sequence. As a result a large portion of the main program makes looping through this continuous polling cycle. Hence system throughput limits the tasks that the microcomputer can do. A more desirable method is that which allow the microprocessor to be executing its main program and only stop to service peripheral devices when it is required to do so by the device itself. In effect, the processor would complete the execution of the instruction and fetch a new routine to serve the requesting I/O device. This method can be efficiently handled by interrupts. When a processor receives an interrupt signal, it takes a specified action depending on the priority. Interrupt can cause a program to suspend itself temporarily to service the interrupt by branching into another program called Interrupt Service Subroutines (ISS). Input output devices are connected with system bus using a separate bus called I/O bus. Figure 5.4 shows the system bus and I/O buses. A microprocessor can be interfaced with a wide range of I/O

5.4

Embedded Systems: Design, Programming and Applications

Fig. 5.4 Two-level bus structure

devices using an I/O bus. It is two-level bus architecture. It can support many I/O devices. Users can add devices to a system even after it has been hardwired. Devices can be designed to interface with the bus, allowing those devices compatible with the system that uses the same type of bus. I/O buses are designed for maximum compatibility and flexibility. For this reason I/O buses are slower then the dedicated buses between the processor and a single I/O device. Generally, an interfacing circuit consists of decoders, demultiplexers and I/O bus bridge controller. The circuit is designed according to availability of control signals and timing diagrams of bus signals. I/O bridge controller glue interfacing circuit. Glue interfacing circuit includes the decoder for interfacing the system buses between the processor memory and I/O devices. This circuit is also used in Programmable Logic Device (PLD), Generic Array Logic (GAL) or FPGA.

5.2.2

Input Output Addressing

I/O device and port addresses are interfaced in such a way that I/O address and memory address should be distinct from each other. I/O addresses are used for connection between microprocessor and I/O where as memory address is used for data and instructions. There are two methods for I/O addressing. 1. Memory addresses mapped I/O; 2. I/O addresses mapped I/O. In memory addresses mapped I/O the processor has no separate I/O address ports and devices. The instructions and control signals for operation on memory content, I/O port and device address are the same. There is no separate instruction for input output and memory loading. The arithmetic, logical and bit manipulation instructions are similar for both memory and I/O operations. For this reason, there is no separate instruction for I/O processing.

Real World Interfacing

5.5

In I/O addresses mapped I/O operation the processor has a separate I/O address for ports and devices. The instructions and control signals for operation on memory content, I/O port and device are distinct. I/O devices and port addresses are interfaced independently of memory. There are separate instructions for input output and memory loading. The arithmetic, logical and bit manipulation instructions that are available in memory are operated firstly by accumulator and then bytes are transferred from accumulator to I/O devices. For this reason, all I/O ports and devices have addresses. A microprocessor communicates with other devices using some of its pins. Broadly we can classify them as port based I/O (parallel I/O) and bus-based I/O. Figure 5.5 shows parallel I/O added to a bus based I/O processor and extended parallel I/O. In port-based I/O, processor has one or more N-bit ports and Processor’s software reads and writes a port just like a register. In bus based I/O, processor has address, data and control ports that form a single bus and communication protocol is built into the processor. In this system, single instruction carries out the read/write protocol on the bus.

Fig. 5.5

Parallel I/O and extended parallel I/O

When processor only supports bus-based I/O then parallel I/O peripheral is needed. Each port on peripheral connected to a register within peripheral that is read or written by the processor. In extended parallel I/O, processor supports port-based I/O and hence more ports needed. One or more processor ports interface with parallel I/O peripheral extending total number of ports available for I/O.

5.2.3

Device Addresses in Interfacing

The address of device depends on the system hardware configuration. Most processor follow memory mapped I/O where devices and port addresses are interfaced in such a way that they are distinct from the memory addresses. Memory addresses points the location of data and instructions where as I/O addresses are meant for I/O locations. In memory mapped I/O the processor has no separate I/O address for ports and devices. I/O port and device addresses are same for the instructions as well as control signals for the bytes stored in memory. In memory mapped I/O system the processor has no separate input-output memory store instruction. The arithmetic, logical and bit manipulation instructions are similar for both memory and I/O operations. For

5.6

Embedded Systems: Design, Programming and Applications

this reason, there is no separate instruction for I/O processing. Some processors use I/O mapped I/O. In I/O addresses mapped I/O operation the processor has a separate I/O address for ports and devices. The instructions and control signals for operation on memory content, I/O port and device are distinct. I/O devices and port addresses are interfaced independently of memory. There are separate instructions for input output and memory loading. The arithmetic, logical and bit manipulation instructions that are available in memory are operated firstly by accumulator and then bytes are transferred from accumulator to I/O devices. For this reason, all I/O ports and devices have addresses. A device when addressed by a processor, it is selected. The device then communicates with system bus or I/O bus using a set of addresses. These addresses are selected either as per the device driver program for a controller for I/O bus or as per decoder circuit design. During a read or write operation the device addresses are accessed to following registers. 1. Device data registers or buffer RAM for data storage; 2. Device status registers for storage of flag bits to show device status; 3. Device control registers to store control and configuration bits. The flag bit indicate the need for servicing or device interrupt. Therefore each device register must be provided addresses at the memory map. Hence, each set of I/O device addresses is fixed by the system hardware. So at a particular device address there is one or several device registers. The peripheral devices which create a medium of interaction with the human users are known as input output devices. They fall into the following categories such as: 1. Printers; 2. Visual display units; 3. Keyboard; 4. Cameras; 5. Plotters; 6. Scanners. However in Real-time embedded systems the definition of I/O devices is very different. An embedded controller needs to communicate with a wide range of devices namely: 1. Analog to Digital (A-D) and Digital to Analog (D-A) converters; 2. CODECs; 3. Small screen displays such as TFT, LCD etc.; 4. Antennas; 5. Cameras; 6. Microphones; 7. Touch screens. A serial line I/O device has addresses assigned for the device register. These addresses are fixed by hardware configuration of Universal Asynchronous Receiver Transmitter (UART) port interface circuit. The device has three sets of registers e.g. data buffer registers, control registers and status registers. The device can have one or more device registers at a device address.

Real World Interfacing

5.3

5.7

INTERRUPTS-DRIVEN I/O

The interrupts allow devices to request that processor stops its currently doing work and execute interrupt service routine (ISR) to process the device’s request. ISR is initiated by an event at external device rather than by a program instruction. Interrupts are also used when a processor needs to perform an operation on some input/output device. Interrupts can be broadly classified as: 1. Hardware Interrupts: These are interrupts caused by the connected devices; 2. Software Interrupts: These are interrupts deliberately introduced by software instructions to generate user defined exceptions; 3. Trap: These are interrupts used by the processor alone to detect any exception such as divide by zero depending on the service. The interrupts also can be classified as: 1. Fixed interrupt: In this type of interrupts, address of the ISR built into microprocessor, cannot be changed. Either ISR stored at address or a jump to actual ISR stored if not enough bytes available; 2. Vectored interrupt: In this type of interrupts Peripheral must provide the address of the ISR and it is Common when microprocessor has multiple peripherals connected by a system bus. The fixed and vectored interrupts both have one interrupt pin, a table in memory holding ISR addresses (may be 256 words). In both the cases peripheral doesn’t provide ISR address, but rather index into table. Fewer bits are sent by peripheral to the fixed and vectored interrupts. Both the fixed and vectored interrupts can move ISR location without changing peripheral The interrupts also can be classified as Maskable and Non-maskable interrupts. 1. Maskable Interrupt: Using this interrupt programmer can set bit that causes processor to ignore interrupt. This is important when the processor is executing a time-critical code; 2. Non-maskable Interrupt: A separate interrupt pin that can’t be masked. Typically this interrupt is reserved for drastic situations, like power failure requiring immediate backup of data to non-volatile memory. Functioning of an I/O device is slower than that of a microprocessor. For this reason, an interrupt driven I/O device is used. The processor waits till the input is ready with the data and performs a read operation from port followed by a write operation to another port. This is called Programmed Data Transfer. The other option is when the input/output device is slow then the device whenever is ready interrupts the microprocessor through an INT pin The processor uses the interrupts to handle an event in asynchronous mode. Interrupts stops the currently performing job of the processor and call interrupt service routine (ISR) which initiates by an event of external device. When a processor needs to do an operation on some external device it requires interrupts. Figure 5.6 shows a method of data transfer from and to a port using Receiver Buffer Ready (RXRDY) interrupt. When a key is pressed in interrupt driven mode, an interrupt signal RXRDY is transmitted to the processor unit and then service routine is executed and ISR program reads the byte for

5.8

Embedded Systems: Design, Programming and Applications

Fig. 5.6 Mechanism of data transfer from and to a port using receiver buffer ready (RXRDY) interrupts

the code. Then the microcontroller sends interrupt acknowledged signal. After receiving the acknowledgement signal microcontroller port receives the data from keycode buffer. Figure 5.7 shows the mechanism of data transfer from and to a port using Transmitted Data buffer Empty (TxDE) interrupts. In interrupt driven mode, an interrupt signal TXDE to the printer controller will cause the execution of a service routine. The service routine will send a data byte as output and hence print of a character is completed.

Fig. 5.7 Mechanism of data transfer from and to a port using transmitted data buffer empty (TXDE) interrupts

5.4

BUS ARBITRATION

When the same set of address/data/control lines are shared by different units then the bus arbitration logic comes into play. Access to a bus is arbitrated by a bus master. Each node on a bus has a bus master which requests access to the bus, called a bus request when the node requires for using the bus. This is a global request sent to all nodes on the bus. The node which is currently has access to the bus, responds with either a bus grant or a bus busy signal. This is also globally known to all bus masters. Following terms are used in bus arbitration. 1. Wire: It is just a passive physical connection with least resistance; 2. Bus: A group of signals (such as data, address etc.). It may be augmented with buffers latches etc. A bus has standard specification such as number of bits, the clock speed etc.; 3. Port: It is the set of physical wires available so that any device which meets the specified standard can be directly plugged in. Example is the serial, parallel and USB port of the PC; 4. Time multiplexing: This is to Share a single set of wires for multiple pieces of data. It saves wires at expense of time.

Real World Interfacing

5.9

The microprocessors/microcontrollers share the same bus. Figure 5.8 shows how the system buses are shared between the controllers. System buses are shared between the controllers when IO processor and multiple controllers access the bus.

Fig. 5.8 System buses are shared between the controllers

One of the controllers is granted the bus master status at an instance. A number of DMA controllers or other controllers or processors try to get access to a bus at the same time, but access can be given to only one of the controllers. So, only one controller will be the bus master to control the access to the bus. The controller, which has access at an instance, is called bus master. Therefore, only one processor or controller can be the bus master. Hence, bus arbitration process is a process using which current bus master accesses and after completion of its job it hands over the control to another bus requesting processor unit. There are three bus arbitration methods. 1. Daisy chain method; 2. Independent bus request and grant method; 3. Polling method.

5.4.1

Daisy Chain Method

The daisy chain method is a centralized bus arbitration process. Bus control passes from one bus master to the next and so on. Figure 5.9 shows a daisy chain bus arbitration method.

Fig. 5.9 Bus arbitration by daisy chain method

Figure 5.9 shows that bus control passes from controller unit Controller 0 to Controller 1, Controller 1 to Controller 2, Controller 2 to Controller 3 and so on. A Bus Grant (BG) signal first sent to Controller 0. If Controller 0 does not require the signal it passes it to Controller 1. If the controller needs the bus a Bus Request (BR) signal is generated to raise the bus. When the

5.10

Embedded Systems: Design, Programming and Applications

controller becomes bus master, a bus busy signal is passed. If bus master does not need the bus, the BR and BUSY signal are deactivated. The signal cycle again started from Controller 0 to other controllers one by one according to their priorities.

5.4.2

Bus Request Method

In independent bus request method, controller has separate Bus Request (BR) signals. Figure 5.10 shows the bus arbitration by independent bus request method where bus request signals is BR0, BR1, BR2 etc. In this method, there are separate Bus Grant (BG) signals like BG0, BG1, BG2 etc., for each controller.

Fig. 5.10

Bus arbitration by bus request method

A controller sends BR signal for granting bus. When the controller receives bus grant signal (BG), it uses bus and activates busy signal. Any other controller does not send any BR signal when it finds the bus is busy. However, any one of the controller can be programmed to provide highest priority to the bus.

5.4.3

Polling Method

Figure 5.11 shows the bus arbitration by polling bus method with two poll lines for four controllers. In this method, bus controller sends a poll count value to the controllers to access the controller. This poll count is incremented to provide access to the next.

Fig. 5.11 Bus arbitration by polling bus method

Real World Interfacing

5.11

Let us consider four controllers in the bus arbitration by polling bus method. Poll count signals successively change from 00, 01, 10, 11, 00….. On a particular count if BR signal is received then increment of count is stopped and busy signal is activated when controller becomes the bus master. When BR is deactivated, busy also deactivate and increment of count starts. The advantage of this method is that the controller next to the current bus master gets highest priority to access the bus.

5.4.4

Bus Arbitration of the DMA Controller

When the same set of address/data/control lines are shared by different units then the bus arbitration logic comes into play. Access to a bus is arbitrated by a bus master. Each node on a bus has a bus master which requests access to the bus, called a bus request, when then node requires to use the bus. This is a global request sent to all nodes on the bus. The node that currently has access to the bus responds with either a bus grant or a bus busy signal, is also globally known to all bus masters. Figure 5.12 shows the bus arbitration of the DMA, known as direct memory access controller which is responsible for transferring data between an I/O device and memory without involving the CPU. It starts with a bus request to the CPU and after it is granted it takes over the address/data and control bus to initiate the data transfer. After the data transfer is complete it passes the control over to the CPU.

Fig. 5.12 Bus arbitration of the DMA

5.4.5

Interfacing Microcontroller with Keyboard

Interfacing microcontroller with keyboard using keyboard controller is shown in Fig. 5.13. The keypad controller consists of Keys; Scan clock, Counter, Decoder; Debouncer, ROM, Key code Buffer. Bounces of key are created on pressing a key due to a natural spring like action of key. The bounce results in a false pulse. This bouncing action is neutralized by the electronic circuit in keyboard controller. Keyboard controller has an encoder to encode the keyboard output for a ROM. The ROM generates ASCII code output of the pressed key. The code bits are serially transferred to TXD out put which is received by RXD input of serial input port (SI) of the microcontroller. At time t0, TXRDY Transmit buffer ready interrupt output signal from keyboard controller passes to Interrupt (INT) terminal as INT0 (Keyboard Interrupt, KBINT) of Microcontroller. Then

5.12

Embedded Systems: Design, Programming and Applications

Fig. 5.13

Interfacing microcontroller with keyboard using keyboard controller

at time t1 Interrupt is acknowledged by RXRDY signal from microcontroller. From time t2 onwards the data bit TXD is transmitted to serial input port (SI) of the microcontroller as RXD (Received data).

5.4.6

Interfacing Microcontroller with Analog to Digital Converter (ADC)

The function of ADC is to produce a digital word corresponding to the magnitude of some analog voltage or current. Different types of commonly used A/D converters are mentioned below. 1. Parallel converter A/D converter; 2. Dual slope A/D converter; 3. Successive approximation type A/D converter. The available A/D converter ICs, manufactured by National Semiconductor Corporation are ADC0801, ADC 0802, ADC0803, ADC 0804, ADC0808, ADC 0809 etc. These A/D converters are CMOS 8 bit successive approximation A/D converters that use a differential potentiometric ladder. These converters are designed to allow operation with derivative control bus with tri-state output latches driving the data bus directly. These ADCs do not require any interfacing logic to locate memory or I/O devices. The voltage reference input to these ADCs can be adjusted to encode any smaller analog voltage span to the full 8 bits of resolution. Special features of these ADCs are mentioned below. 1. Compatible with microprocessors; 2. No interfacing logic is needed; 3. Easy interface to all microprocessors through programmable peripheral interface; 4. They accept differential analog voltage inputs; 5. Logic inputs and outputs of these ADCs meet both MOS and TTL voltage level; 6. They work with 2.5 volts reference voltage; 7. These ADCs have on chip clock generator; 8. Zero adjustment is not required; 9. Input voltage level range is 0 to 5 volts; 10. Resolution 8 bits; 11. Maximum conversion time is 100 µs.

Real World Interfacing

5.13

An analog to digital converter (ADC) requires a start pulse for conversion of analog signal using a short duration single pulse generator circuit, a sample and hold circuit and negative and positive reference voltages. In a microcontroller, a four or eight channel ADC is inbuilt in microcontroller. An external ADC can be used interfacing with the microcontroller in embedded system. Figure 5.14 shows an ADC interfaced with a microcontroller when internal ADC is not used.

Fig. 5.14

Interfacing microcontroller with ADC

5.4.7 Interfacing Microcontroller to Digital to Analog Converter (DAC) The output signal from a microprocessor is a digital signal. This digital signal is to be converted to analog signal for different applications like audio system, measurement of a physical quantity or Industrial control systems. For this reason, a digital to analog signal converter is required to be interfaced with microprocessor. Three types of digital to analog converters are available in the market. 1. Current output type: It provides current output corresponding to input digital signal. 2. Voltage output type: It converts the current signal into voltage signal internally and provides voltage output corresponding to input digital signal. 3. Multiplying type: The out put of multiplying type DAC represents the product of the input signal and the reference signal. Digital to analog converters (DAC) are available as integrated circuit specially designed to be compatible with microprocessor. These DAC includes a latch on the chip. Figure 5.27 shows the block diagram of 10 bit microprocessor compatible DAC AD7522 which includes a latch, control logic circuit, a reference voltage and a buffer amplifier using op-amp. The pin numbers of the DAC chip is shown in figure. The figure also shows the interfacing scheme of DAC AD7522 with 8086 microprocessor. In this case, memory mapped I/O is used with multiple addresses. A 3 to 8 decoder is used to generate signals for least significant byte (LBS) pin, most significant byte (HBS) pin and update DAC input (LDAC) pin. To enable the LBS line the input (A, B, C) to the decoder should be 000 which results in the port address 8000H. When input (A, B, C) of the decoder 001 then the address 8001 is enabled which enables most significant byte (HBS) line and update DAC output line (LDAC). Following instructions are used to the maximum input of ten bits into a DAC AD7522.

5.14

Embedded Systems: Design, Programming and Applications

A DAC requires a Pulse Width Modulation circuit. This PWM circuit is a built in device in microcontroller. For a desirable analog output a pulse width register is programmed. Two internal interrupts are generated by a timer circuit. One interrupt is generated on timer overflow and other after an interval proportionally equal to PWR. The output becomes high on first interrupt and low on second interrupt. An external integrator generates the analog output. Figure 5.15 shows an interface to an external DAC to a microcontroller when internal DAC of microcontroller is not used. Reference voltage (Vref) is supplied to DAC. At time t0, data flow starts from microcontroller port to DAC. After t0, at time t1 Chip select signal is transmitted from microcontroller to DAC. At t2 after t1, Read/Write signal is transmitted from WR terminal of microcontroller to DAC. Analog signal output from DAC is filtered by using filter circuit at the output of DAC.

Fig. 5.15

5.4.8

Interfacing microcontroller to keyboard using keyboard controller

Interfacing Microcontroller to External Memory

8051 has three 8 bit ports through which it can communicate with the outside world. Ports P0 and P2 support port-based I/O when 8051 internal memory being used. Those ports serve as data/address buses when external memory is being used 16 bit address and 8 bit data are time multiplexed. Lower 8 bits of address must therefore be latched by using ALE (address latch enable) signal. The lower byte of the address is placed along P0 and the address latch enable signal is enabled. The higher byte of the address is placed along P2. The ALE signal enables the 74373 chip to latch the address as the P0 bus will be used for data. The P0 bus ___ goes into high impedance state of tri-state logic device and switches internally for data path. The RD (read) line is enabled. The bar over the read line indicates that it is active when low. The data is received from the memory on the P0 bus. Similarly a memory write cycle writes data to the external memory by using WRITE instruction. External memory can be connected to microcontroller 8051. Two memory spaces are available by the 16 bit PC, DPTR and control pins for enabling external ROM and RAM chips. External RAM is needed when 128 bytes of internal RAM is not sufficient. External RAM may be added up to 64 KB in 8051 family. Figure 5.16 shows the connection diagram of 8051 with external data RAM.

Real World Interfacing

Fig. 5.16

5.15

Connection diagram of 8051 with external data RAM

The external memory is accessed by output drivers of port P0 and P2 and input buffers of port P0 and P2. P0 provides the low byte and P2 provides the high byte of external memory address. All ports on reset configure as output.

5.4.9

Interfacing Microcontroller to LCD Display

An embedded system requires an interfacing circuit and programs to display the message. An LCD screen shows a multiple display of characters or graph or icon. A display controller is used for matrix display of LCD. Figure 5.17 shows an interface to LCD to a microcontroller. There are 8 output data and, one enable bit (E), one register select bit and one R/W bit. Microcontroller transmits the signal bits E, RS and RW to the LCD display unit. One 8 bit port is used for output data.

Fig. 5.17

Interfacing microcontroller to keyboard using keyboard controller

5.16 5.5

Embedded Systems: Design, Programming and Applications

PROCESSOR AND MEMORY ORGANIZATION

Some memory organization requires loaded data stored data to be aligned. It means that the address of a memory reference must be multiple of the size of the data being loaded or stored. i.e. 8 byte store must have an address multiple of 8. There are two organization orders to write the bytes at the memory. 1. Little-endian system: In a little endian system, the least significant byte of a word is written into the lowest address byte, and other bytes are written in increasing order of significance; 2. Big-endian systems: In a big endian system, the most significant byte of a word is written into the lowest address byte, and other bytes are written in decreasing order of significance. The memory organization has a tremendous impact on computer system performance and it also determines the execution time of an instruction. The memory system design also includes memory protection and interaction of memory with I/O systems. Processor memory organization also depends on architecture of microprocessor. Following two types of architecture are found in microprocessor. 1. Princeton architecture; 2. Harvard architecture. Figure 5.18 shows the processor and memory organization of Princeton architecture. 8086 processors have Princeton architecture of main memory. In Princeton architecture, vectors, pointers, program segments, variables and memory blocks for data and stacks have different address in the program.

Fig. 5.18 Shows the processor and memory organization of Princeton architecture

Figure 5.19 shows the processor and memory organization of Harvard architecture. The microprocessor, having Harvard architecture, has distinct address spaces, control signals, processor instructions and data paths for the bytes of both data and program. The 8051-family microcontrollers have Harvard architecture of main memory.

Real World Interfacing

Fig. 5.19

5.7

5.17

Shows the processor and memory organization of Harvard architecture

CASE STUDIES

1. Automatic Washing machine There are four states of automatic washing machine. (i) Rinse Cycle 1; (ii) Rinse Cycle 2; (iii) Drying. An EEPROM is required to store the state. First byte of EEPROM is required to store the state which it has been completed. The second byte of EEPROM stores the time spent in the current stage. Status of the user set buttons is stored in the third byte. In this way, 128 byte EEPROM are used in a microcontroller. 4 Kb ROM of microcontroller can be used to store embedded software. 128 byte internal RAM is used for variables and stacks. No external memory is required for the microcontroller used to control the function of automatic washing machine.

2. Real-time Robot control system A robotic system consists of motors which require signaling at the rate of 50 to 100 ms. Therefore, enough time is available for signaling the motors of a robot control system using a microcontroller with instruction cycle time of 1 microsecond.

5.18

Embedded Systems: Design, Programming and Applications

High speed processor is not required for real-time robot control system. No caches or advanced processing units is required. In a robot system two types of motors are used. (i) Four-coil stepper motor; (ii) DC motor. Four coil stepper motor requires four bit input and DC motor requires one bit PWM output. Hence an 8 bit processor is sufficient to control the robot system. CISC architecture is sufficient because frequent accesses and bit manipulations at IO port is required. 4 Kb internal ROM on chip is sufficient to store the program. The program required to control the robot system is small. So, 256 or 512 Kb ROM is sufficient to run the program. Therefore, 8051 or 80196 can be used for robot control system.

3. Mobile phone system In a mobile phone system, voice compression-decompression and encryption-decryption algorithms are required. It also require DSP processor algorithms. As a result ROM size should be large. Let us consider a 64 MB ROM. ROM image is stored in a compressed format. In mobile system a boot-up program firstly runs a decompression program. Then the application program runs. Size of the RAM is also bigger in this system. 8 KB RAM is needed to store the decompressed program and data. The important telephone numbers is stored in phone memory and for this purpose 16 KB flash memory or EEPROM is required. 64 KB flash memory is required for recording messages and MMS pictures. 8GB memory is required for storing songs and videos. Block RAM at subunits improves the system performance. Thus the mobile system requires 1 MB ROM, 16 KB EEPROM, 16 KB flash 1 MB RAM and block memory at subunits.

Review Questions 1. What do you mean by interfacing a processor to I/O devices? 2. Describe the interconnections for a for a simple bus structure for interfacing processor to memory and I/O devices. 3. Describe the timing diagram of a data read and data write protocol. 4. Draw a suitable diagram of two level bus structure and describe the I/O and O/P operations. 5. What are the different types of input/output addressing? Using suitable diagram, describe the parallel I/O and extended parallel I/O operations. 6. Describe device addresses in interfacing. 7. Draw a suitable diagram to show the mechanism of data transfer from and to a port using Receiver Buffer Ready (RXRDY) interrupts and describe its working principle. 8. What do you mean by interrupt driven I/O? 9. What do you mean by bus arbitration? How do system buses share between the controllers?

Real World Interfacing

5.19

10. Using a suitable diagram describe bus arbitration by daisy chain method. 11. What are the different types of bus arbitration methods? Using a suitable diagram describe bus arbitration by bus request method. 12. Using a suitable diagram describe bus arbitration by polling method. 13. Describe bus arbitration of a DMA controller. 14. Draw the diagram to show interfacing microcontroller with keyboard and describe the functioning of the circuit. 15. Using suitable diagram, describe the interfacing microcontroller to ADC. 16. Draw the connection diagram of 8051 with external data RAM and describe the operation of the circuit. 17. Does memory organization depend on architecture of microprocessor? Describe the processor and memory organization of Princeton architecture and Harvard architecture. 18. Describe the little-ending system and big-ending system to write the bytes in the memory. 19. Discuss the following case studies. (i) Automatic washing machine (ii) Real time robot control system (iii) Mobile phone system.

Choose the Correct Answer 1. Size of RAM to store the application program in mobile phone system is (i) 2 KB (ii) 4 KB (iii) 6 KB (iv) 8 KB. 2. Size of EEPROM to store the state of automatic washing machine is (i) 2 KB (ii) 128 B (iii) 6 KB (iv) 8 KB. 3. The Princeton structure of main memory is found in (i) 8085 microprocessor (ii) 8086 microprocessor (iii) 486 microprocessor 8051 microcontroller. 4. Types of microcontroller available in the market is (i) 1 (ii) 2 (iii) 3 (iv) 4 5. Number of bus arbitration methods is (i) 2 (ii) 3 (iii) 4 (iv) 5

5.20

Embedded Systems: Design, Programming and Applications

6. In bus arbitration bus means (i) a group of signals (ii) a group of wires (iii) a group of bits (iv) a group of bytes 7. Number of methods of I/O addressing is (i) 2 (ii) 3 (iii) 4 (iv) 5 8. Number of buses required for interfacing memory and I/O devices is (i) 2 (ii) 3 (iii) 4 (iv) 5 9. An embedded controller needs to communicate (i) 4 (ii) 8 (iii) many (iv) 16 10. Functioning of an I/O device is (i) slower (ii) faster (iii) both of these (iv) none of these

6 6.1

Programmable Communication Interface

INTRODUCTION

The microprocessor is a programmable logic device which can be used as processing unit or computing unit of a computer. The processed data or computed result is to be sent to another microprocessor or computing system. For this reason, the microprocessor must be able to communicate with each other in an organized manner. This data communication from a microprocessor to any other system may be established in following two ways. 1. Serial data communication; 2. Parallel data communication. The comparison between serial data communication and parallel data communication are described in Table 6.1. Table 6.1 Serial data communication

Parallel data communication

1. In serial data communication, the bits of the data 1. In Parallel data communication the bits of the data word are transmitted one after another serially word is transmitted simultaneously using number of through single data bus. data buses equal to the word length. 2. In serial data communication the parallel word is to be converted into a stream of serial bits.

2. In parallel data transmission the bits of data word are transferred simultaneously over data lines.

3. Serial data communication requires parallel to serial 3. No parallel to serial converter is required in parallel converter. data communication. 4. Only one or a pair of conductors is required for serial 4. In parallel data communication, required number of data communication. wires is equal to number of bits in a word. 5. Serial data communication is cheap.

5. Parallel data communication is costly. Contd...

6.2

Embedded Systems: Design, Programming and Applications

Contd...

6. In serial data communication one bit is transferred 6. In parallel data communication one word is transferred at a time. at a time. 7. Serial data communication is used in long distance 7. Parallel data communication is used with parallel communication. It is also used to communicate serial peripheral and short distance data transfer. peripheral like floppy disk, CRT etc. 8. Serial data communication is slow.

8. Parallel data communication is fast.

9. Recommended standard RS-232C, RS-422, RS423 9. IEEE-488 is an example of parallel data transfer are serial data transfer protocols. protocol.

6.2

SERIAL DATA TRANSMISSION

Serial data is transferred in either asynchronous mode or synchronous mode. Asynchronous transmission is also called start-stop transmission because start and stop bits are transmitted with each byte. No clock is transmitted with asynchronous data transmission. In synchronous data transmission, synchronization character is transmitted with data block. A clock signal is also included with data. The comparison between asynchronous and synchronous data transmission is shown in Table 6.2. Table 6.2 Asynchronous data transmission

Synchronous data transmission

1. If speed of data transfer of microprocessor and I/O 1. If speed of data transfer of microprocessor and I/O terminal is not equal then the mode of data transfer terminal is equal then the mode of data transfer is is called asynchronous data transmission. called synchronous data transmission. 2. In asynchronous data transmission both transmitter and receiver are not synchronous with the common clock signal.

2. In synchronous data transmission both transmitter and receiver are synchronous with the common clock signal.

3. In asynchronous data transmission one character (bit) 3. In synchronous data transmission one block of data is transmitted at a time. For this reason this type of is transmitted at a time using a clock signal. For this data transfer is also called character oriented data reason this type of data transfer is also called clock transmission. oriented data transmission. 4. The framing bits of asynchronous data transmission are transferred with a character one at the starting another at the ending of the byte.

4. The framing bits of synchronous data transmission are transferred with a block.

5. The speed of asynchronous data transmission is less than 20 K bauds.

5. The speed of synchronous data transmission is more than 20 K bauds.

6. Asynchronous data transmission is implemented 6. Asynchronous data transmission is implemented using software. using hardware.

6.2.1

Asynchronous Serial Data Transmission Format

A data transmission format is related to synchronization, direction of data flow, speed of data flow, medium of transmission and errors in data. In asynchronous transmission a start and a stop bit are used at start and end of the byte, respectively. Since each character is individually identified, character can be sent at any time. Figure 6.1 illustrates a typical format of transmission of a byte in

Programmable Communication Interface

6.3

asynchronous serial data mode. Figure 6.1 shows that the signal line is in a constant high (marking) state, when no data is sent. The beginning of a data character is shown by a line going low for one bit time. This bit is known as start bit. The data bits are then transmitted one after another with least significant bit at first. The data word may consists of 6, 7 or 8 bits The data byte is followed by a parity bit which is used to check the errors in received data. After transmission of parity bit the signal goes high for at least one bit time to identify the end of the character. This high bit is called the stop bit.

Fig. 6.1 Typical bit format used for transmitting asynchronous serial data

The rate of serial data transfer is called baud rate. The baud rate is defined as reciprocal of time between signal transitions. Therefore, Baud rate = 1/(time between signal transitions) If signal transitions occur in every 1.665ms then baud rate of data transmission is obtained as 1/1.665ms = 600 Bd.

6.2.2

Synchronous Serial Data Transmission Format

If speed of data transfer of microprocessor and I/O terminal is equal then the mode of data transfer is called synchronous data transmission. In synchronous serial data transmission, data block is transmitted with clock pulses. Therefore, start and stop bits are not necessary in case of synchronous data transmission. Synchronization of data transfer is done by transmitting synchronization (clock) pulse with data block. Figure 6.2 illustrates the typical bi-synchronous serial data format used for synchronous serial data transmission.

Fig. 6.2 Typical bi-synchronous serial data format used for synchronous serial data transmission

6.4

Embedded Systems: Design, Programming and Applications

Bi-synchronous serial data format is a byte oriented protocol. Serial data link control (SDLC) protocol and high level data link control (HDLC) protocols are also used for synchronous serial data transmission.

6.3

SERIAL DATA TRANSMISSION METHODS AND STANDARDS

In current signal systems, like teletypewriters, 20 mA current is sent to represent a mark or ‘1’ and no current to represent a space or ‘0’. This system is called 20 mA current loop. Other manufactures of data transmission system uses a nominal current of 60 mA is sent to represent a mark or ‘1’ and no current to represent a space or ‘0’. This system is called 60 mA current loop. Generally, serial data transfer between a microprocessor and any other device takes place along a single data line or a pair of wires. Serial interface is used for long distance communication for low cost of the cable and minimum requirement of line drivers. Moreover, it enables data equipment to provide commercial data communication facilities. A serial link requires handshaking between transmitter and receiver for proper functioning of data transfer equipments. The recommended standards (RS) of serial data transfer protocols are RS-232, RS-422, RS-423 etc. These standards implement single ended (RS-232C) interface, balanced differential (RS-422C) interface and unbalanced differential (RS-423C) interface. Serial data communication also can be accomplished by using MODEM. Special integrated circuits Universal Asynchronous Receiver Transmitter (UART) and Universal Synchronous Asynchronous Receiver Transmitter (USART) are also used for serial data transmission.

6.3.1

RS232C For Serial Data Communication

The Electronic Industries Association (EIA) developed EIA standard RS-232C for data transmission between Data Terminal Equipment (DTE) and data communication equipment (DCE) using handshaking mode. This standard shows the function of 25 signals and hand shake pin for serial data transfer. It specifies impedance level, voltage level, rise time and fall time of the signal, maximum capacitance and maximum bit rate. It also specifies that the DTE and DCE connectors should be male and female connectors, respectively. Figure 6.3(a) shows a DB-25P 25-pin male connector used for RS232C and Fig. 6.3(b) shows a DB-9P 9-pin male connector used for RS232C. Table 6.3 shows pin function of these two connectors. Pin 1 is used for protective ground which connects the cases of the device or the cable shield. Pin 2 is the transmitted data (TXD) pin on the DTE and pin 3 is the received data (RXD) pin on the DCE device. Actually these are the serial data lines connected between connector and data terminal equipments.

Fig. 6.3(a) 25 pin connector for RS-232C

Fig.6.3(b)

9 pin connector for RS-232C

6.5

Programmable Communication Interface Table 6.3 9 pin connector’s pin number

25 pin connector’s pin number

Pin name

Pin function

Direction



1

GND

Protected ground

3

2

TXD

Transmitted data

In

2

3

RXD

Received data

Out

7

4

RTS

Request to send

In

8

5

CTS

Clear to send

Out

6

6

DSR

Data set ready

Out

5

7

GND

Signal ground

1

8

CD

Received line signal

out

detector 9



Reserved for data set

10



Reserved for data set

11



Unassigned

12

SCF

Secondary received line

testing testing Out

signal detector 13

SCB

Secondary clear to send

14

SBA

Secondary transmitted

15

DB

Transmission signal element timing

Out

16

SBB

Secondary received data

Out

17

DD

Receiver signal element timing

Out

18



Unassigned

19

SCA

Secondary request to

20

DTR

Data terminal ready

In

21

CG

Signal quality detector

Out

22

CE

Ring indicator

Out

23

CH/CI

Data signal rate selector

In/Out

24

DA

Transmit signal element timing

In

data

send

25

Unsigned

Out In

In

6.6

Embedded Systems: Design, Programming and Applications

Pin 4 is the request to send (RTS) pin which is activated by transmitter to send the data over the line till data transfer is accomplished. Pin 5 is the clear to send (CTS) pin is used to send ready signal of the receiver and remain active till data transmission is accomplished. Data set ready (DSR) pin is used to send modem condition signal when a modem is powered on. This pin is low for data mode and high for voice mode transmission. Pin 7 SG is connected to the ground. Pin 8 is the received line signal detector, named as data carrier detector (DCD) pin used by a modem to transmit a enabling signal of the link. Pin 9 and 10 are reserved for data set testing and pin 11, 18 and 25 are unsigned. Pin 20 is a data terminal ready (DTR) pin which is used to indicate DTE that the on line mode data communication is possible. Pin 22 is the ring indicator (RI) which is activated by a modem when it detects incoming call on the telephone line.

6.3.2

Single Ended Interface (RS232C)

Figure 6.4 shows the single ended serial interface Standard way to interface between RS232C and TTL levels with MC1488 quad TTL to RS232C drivers and MC1489 quad RS232C to TTL receivers. Both the chips are TTL NAND gates. MC1488 require ± supply and MC1489 requires only +5 volt supply. The rise and fall time for RS232C signals are limited to 30V/µs. The hand shake signal of RS232C is active low signal.

Fig. 6.4

6.3.3

Single ended serial interface RS 232C

EIA RS232C Signal Levels

Two electrical voltage levels are used for the driver and two other voltage levels are used for the receiver. The signal levels of RS232C standard is shown in Fig. 6.5. For driver, the voltage level between –5 to –15 is used as low or logic 1 and +5 to +15 volt is used as high or logic 0. –5V to +5V range is taken as invalid. For receiver, the voltage level between +3 volts to +25 volts is used as data 0 and – 3 to – 25 volt is used as logic 0. In receiver ± 3 volt is taken as invalid range. This range minimizes electrical noise problems in long cable. It also allows operation with 15 m separation between the terminal and the modem. Hand shaking signals are active at positive voltages.

6.3.4

Modems

Modem is a device that modulates an analog carrier signal to encode digital information and demodulates such a carrier signal to decode the transmitted data. The main objective of the modem is to produce a signal that can be transmitted easily and decoded to reproduce the original digital data.

Programmable Communication Interface

Fig. 6.5

6.7

RS232 signal

The capacity of modem is specified by the amount of data it can send in unit time. The modem capacity is measured either by bits/second or Baud. The modulator of the modem changes either amplitude or phase or any other characteristic of a sinusoidal carrier signal to represent 1 or 0. This modulated carrier is transmitted by either simplex or half duplex or duplex transmission system to a data receiving terminal where another modem demodulates the signal. Thus, data is received by the receiver modem. Different types of modulation techniques are also employed in modem device. The major forms of modulation techniques are amplitude shift keying (ASK), frequency shift keying (FSK) and phase shift keying (PSK).

Amplitude Shift Keying Amplitude shift keying or on off keying (OOK) changes the amplitude of the carrier corresponding to digital signal. It represents the presence of carrier signal for 1 and no carrier signal for 0. Figure 6.6 shows the representation of carrier signal 1’s and 0’s using amplitude shift keying.

Fig. 6.6 Representation of carrier signal 1’s and 0’s using amplitude shift keying

6.8

Embedded Systems: Design, Programming and Applications

Frequency Shift Keying Frequency shift keying (FSK) uses one frequency to represent 0 and other frequency to represent 1. Figure 6.7 shows representation of carrier signal 1’s and 0’s using frequency shift keying. Here two different frequencies are used for representation of digital data 0 and 1. Four different frequencies are often used for full duplex system.

Fig. 6.7

Representation of carrier signal 1’s and 0’s using frequency shift keying

Phase Shift Keying The phase shift keying is also called differential phase shift keying (DPSK). In this system, the phase of the sinusoidal carrier is shifted by 180° to represent a change in the data from 0 to 1 or change in the data from 1to 0. Figure 6.8 shows the representation of carrier signal 1’s and 0’s using Phase shift keying. When digital data changes from 0 to 1, the phase of the carrier signal is shifted by 180°. Again phase of the carrier signal is shifted by 180° in opposite direction if digital data changes from 1 to 0. A more complex phase shift keying scheme is called quadrature phase shift keying (QPSK). This QPSK enables modems to transmit full duplex data. QPSK allows higher data rates but accurate demodulation of QPSK signal is difficult. The solution to this problem is to use transitions in the transmitted signal to synchronize a phase locked loop oscillator in the receiver.

Fig. 6.8

Representation of carrier signal 1’s and 0’s using Phase shift keying

Programmable Communication Interface

6.9

The different types of modems are cable modems, satellite modems, DSL modems and Dial up modems. A 300-bps modem is a device that uses frequency shift keying (FSK) to transmit digital information over a telephone line.

6.3.5

Digital Data Transmission using Modem and Phone Lines

The standard telephone system is a convenient path to transmit serial data over a long distance because the system already exists over a long distance. These telephone lines are switched lines i.e. two nodes of these telephone networks are connected by a series of switches. The band width used in this telephone system is 300 Hz to 3000 Hz. For this reason, asynchronous serial data can not be transmitted directly over standard phone lines. But a main frame computer can be connected to a remote terminal over a phone line using two modems. When a terminal’s modem dials a computer’s modem, the terminal’s modem is called the originate modem. Using FSK, it transmits a 1,070-hertz tone for a 0 and a 1,270-hertz tone for a 1. The computer’s modem is called the answer modem, and it transmits a 2,025-hertz tone for a 0 and a 2,225-hertz tone for a 1. Since originate and answer modems transmit different tones, they can use the line simultaneously. This is known as full-duplex operation. Modems that can transmit in only one direction at a time are known as half-duplex modems. Half duplex modems are rarely used. Digital data can be transmitted using modems and standard phone lines. Modems and other equipment are used to transmit serial data over long distance are referred to data communication equipment (DCE). On the other hand, data terminal equipment (DTE) consists of the terminals and computers that are transmitting or receiving the serial data. The signals used for serial data communications standard RS232C is described in section 6.3.1. Figure 6.9 shows schematic block diagram of digital data transmission using modems and phone lines. When the terminal is made on, it provides the data terminal ready (DTR) signal to indicate that DTE is ready for data transmission. In reply to this signal, modem asserts the data set ready (DSR) signal to the terminal. The modem then dials up the computer.

Fig. 6.9 Schematic block diagram of digital data transmission using modems and phone lines

A specified tone is sent back, if the computer is available. After receiving the tone from the computer the terminal equipment transmits a request to send (RTS) signal to the modem. The modem then send a carrier detect (CD) signal to DTE to indicate that the modem contacted the

6.10

Embedded Systems: Design, Programming and Applications

computer. Then the modem becomes ready to transmit data and sends clear to send (CTS) signal back to the DTE. Receiving clear to send signal DTE sends serial data to the modem. When all the data is sent by the DTE, it makes RTS signal high so that the modem can disable its clear to send signal and stop data transmission. Similarly, hand shake occurs between the modem and the computer at the other end of the data link.

6.4

UNIVERSAL ASYNCHRONOUS RECEIVER TRANSMITTER (UART - 8250)

Asynchronous serial data communication allows transmission of one character at a time. Asynchronous transmission format of a 7 bit character with a even parity and a stop bit is shown in Fig. 6.10. The bits are transmitted one after another to send one byte. Figure 6.10 also shows that the transmitted character is represented by 1101101. The start bit is sent just before the data bits. This start bit is used to inform start of data transmission to the receiver. Logic 1 voltage level signifies 1 and logic 0 signifies 0.

Fig. 6.10

Asynchronous transmission format of a 7 bit character with even parity and stop bit

On the other end, the receiver samples the data line half a bit later to ensure that detected signal for 0 is valid. With this valid start the receiver forms a character as per specification of the character length and parity type. The stop bit signifies the end of the character. After sending one character, if the transmitter is not ready to send any character then a sequence of 1 is transmitted by the transmitter. Otherwise, the transmitter sends one 0 start bit before sending the next character. In this serial data transfer technique, the clock frequency of both receiver and transmitter should be same. A special integrated circuit 8250 is used as universal asynchronous receiver/transmitter (UART). It is a 40 pin IC. The pin diagram of UART 8250 is shown in Fig. 6.11.

Pin Functions of Uart 8250 Pins 1 to 8 (Data bus): Eight bit data bus, (D7 – D0) are connected to this pins. This bus transmits bidirectional data between 8250 and microprocessor. This bus is connected through eight tri-state buffer. Pin 9 Receiver clock (RCLK): This pin is used to connect suitable baud rate clock for the

receiver section of 8250. Pin 10 Serial input (SIN):

device like MODEM.

This pin is connected for serial data input from the peripheral

6.11

Programmable Communication Interface

Fig. 6.11

Pin 11 Serial output (SOUT):

Pin diagram of UART 8250

This pin is connected for serial data output from the peripheral

device like MODEM. Pins 12 to 14 Chip select CS0,CS1,CS2:

____

The 8250 chip is selected if CS0 = 0, CS1 = 1 and

CS2 = 1. Pin 15 Band out (BANDOUT):

This pin is connected to a clock to provide clock signal for the transmitter section. The clock frequency equals to the reference oscillator frequency divided by the divisor of the Baud rate generator.

Pin 16 and pin 17 External clock (XTAL1, XTAL2):

These two pins are connected to

crystal oscillators to provide timing reference signal to 8250.

______

Pin 18 and pin 19 Data output strobe (DOSTR, DOSTR): _______

These two pins are also used as chip select pins for 8250. When DOSTR = 1 and DOSTR = 0 then microprocessor is allowed to write data onto the register of 8250. _____

Pin 21 and pin 22 Data input strobe (DISTR, DISTR):

Input to these two pins allow microprocessor to read status information or data from a selected register of 8250 if DISTR = 1 ______ OR DISTR = 0.

Pin 23 Driver disable (DDIS):

This pin becomes low when microprocessor reads data from

8250. Pin 24 Chip select out (CSOUT):

selected by CS0, CS1 and CS.

This is a output pin. This pin goes high when chip is

6.12

Embedded Systems: Design, Programming and Applications

Pin 25 Address strobe (ADS):

This pin indicates two conditions of 8250. Low signal of this pin provides latching for the register select and chip select signals. High signal to this pin is required when register select signals are not stable for complete read or write cycle. Pin 26 – 28 Register select pins (A0, A1, A2): These inputs are required to select registers. The function of these pins together with divisor latch access bit (DLAB) is shown in Table 6.4.

Pin 30 Interrupt (INTRPT):

This pin gives high output when any interrupt goes high.

_____

Pin 31 OUTPUT2 (OUT2): This pin is user defined output pin and can be set by programming the MODEM control register to high. ____

Pin 32 Request to send (RTS):

It is a low active pin which provides signal to MODEM to indicate that 8250 is ready to transmit data.

Pin 33 data terminal ready (DTR): This pin is a low active pin which provides signal to MODEM to indicate that 8250 is ready to communicate. The DTR signal is set in a master reset operation. Table 6.4

Register address table of UM8250B

DLAB

A2

A1

A0

Register

0

0

0

0

Read receiver buffer and write transmitter holding register.

0

0

0

1

Interrupt enable

X

0

1

0

Read interrupt

X

0

1

1

Line control

X

1

0

0

MODEM control

X

1

0

1

Line status

X

1

1

0

MODEM status

X

1

1

1

None

1

0

0

0

LSB divisor latch

1

0

0

1

MSB divisor latch

Pin 34 OUTPUT1 (OUT1):

This pin is user defined output pin and can be set by programming the MODEM control register to high.

Pin 35 Master reset (MR): When MR pin is high it clears all the registers and control logic of 8250 except receiver buffer, transmitter holding and divisor latches. ___

Pin 36 Clear to send (CTS):

It is a MODEM controlled input signal which indicates the condition of MODEM status register. ____

Pin 37 Data set ready (DSR):

It is a low active pin. When this signal is low, it indicates that the MODEM or data set is ready to transfer data through 8250. ____

Pin 38 Data carrier detect (DCD):

goes low.

When the data carrier has been detected, this signal

Programmable Communication Interface

6.13

__

Pin 39 Ring indicator (RI):

This signal indicates that a telephone ringing signal has been received by the MODEM. There are ten accessible registers in UART 8250. 1. Receiver buffer register (Read only); 2. Transmitter holding register (Write only); 3. Interrupt enable register; 4. Interrupt identification register; 5. Line control register; 6. MODEM control register; 7. Line status register; 8. MODEM status register; 9. Divisor latch for LSB; 10. Divisor latch for MSB. These registers may be accessed and controlled by the programmer through microprocessor. They may be used to control operation and to transmit or receive data. Line control register is used to format the asynchronous data transfer. The interrupt identification register of 8250 provides interrupt capability to the UART. It also controls the priorities of the interrupts in the following sequence. Priority-1 Receiver line status Priority-2 Received data priority Priority-3 Transmitter holding register empty Priority-4 MODEM status Interrupt identification register (IIR) stores the information about the pending priority of the interrupt.

6.4.1

Universal Synchronous/Asynchronous Receiver/Transmitter 8251

Universal synchronous/asynchronous receiver/transmitter (USART)-8251 is a 28 pin integrated circuit used for data communication with Intel microprocessors. It is a programmable communication interface which is programmed by the system software. USART receives data from microprocessor in parallel format and convert the parallel data into continuous serial data stream for serial data transmission. It can also receive serial data stream, and convert the serial data into parallel format for transmission to microprocessor. Figure 6.12 shows the block diagram of USART 8251. Figure shows that it consists of following building blocks. 1. Data bus buffer; 2. Read/Write control Logic; 3. MODEM control; 4. Transmitter buffer; 5. Transmitter control;

6.14

Embedded Systems: Design, Programming and Applications

6. Receiver buffer; 7. Receiver control. The interfacing signals are also shown in Fig. 6.12. Function of each block of USART 8251 is described here.

Data Bus Buffer Tri-state bidirectional buffers are used to interface USART to the system data bus. Data is transmitted and received through the data bus buffer. Separate 8 bit registers are used to provide double buffering.

Fig. 6.12

Block diagram of USART 8251

Read/Write Control Logic The Read/Write control logic block consists of data register, control register and status register. It has six input signals. The RESET signal initializes the USART 8251. The clock signal provides internal device timing. This CLK pin is connected to the output of a clock generator. The clock frequency should be thirty times greater than transmitter and receiver bit rates. C/D, RD, WR and CS signals are used to determine the direction of dataflow as shown in Table 6.5.

Programmable Communication Interface

6.15

Table 6.5 C/D

RD

WR

CS

0

0

1

0

USART data register to system data bus

Direction of Data Flow

0

1

0

0

System data bus to USART data register

1

0

1

0

Status register to system data bus

1

1

0

0

System data bus to control register

X

1

1

0

System data bus to tri-state buffer

X

X

X

1

System data bus to tri-state buffer

Modem Control Unit MODEM control block has four active low signals. These signals are used to interface the MODEM with USART 8251. For this reason these signals are called MODEM control signals. These signals are data set ready signal DSR, data terminal ready signal DTR, request to send signal RTS, and clear to send signal CTS. The input signal DSR is used to test the condition of 8251 by the microprocessor. Generally this signal is used to test the MODEM. The output signal DTR is used for MODEM control i.e. to know whether the data terminal is ready or not. It can be made low by programming. Request to send signal RTS is an output signal. It is used to control the MODEM. This signal signifies a request to send the data. Clear to send signal CTS is a low active input signal. This signal enables the USART 8251 to transmit serial data if the enable bit in the command byte is set to a ‘1’.

Transmitter Buffer The transmitter buffer block receives parallel data from the data bus buffer, converts it into a serial bit stream and finally transmits a serial stream data at the TXD output. The transmission is enabled when CTS equals to zero.

Transmitter Control All activities of transmission of serial data is controlled by transmitter control block. This block receives signals internally or externally to complete the transmission. Transmitter ready signal TXRDY is an output signal which informs microprocessor that the transmitter is ready to receive data. Transmitter empty signal TXE goes high if USART has no data to be transmitted. TXE signal is used to indicate the end of transmission mode. Transmitter clock signal TXC control the rate of data transmission. In synchronous mode, data transmission the baud rate is equal to transmitter clock signal frequency. In asynchronous mode, data transmission baud rate is a fraction of transmitter clock signal frequency.

Receiver Buffer Receiver buffer block receives the serial data, converts it into parallel format and finally, send the data to microprocessor. The RXD pin accepts the serial data and it is clocked at RXC signal

6.16

Embedded Systems: Design, Programming and Applications

on the rising edge. The RXD signal initializes the USART. This signal prevents false starting of data transmission. Receiver ready signal RXRDY is an output signal which indicates that USART contains ready data for input to the microprocessor. RXRDY can be used either for polled operation or for interrupt structure of the microprocessor. In asynchronous mode, receiver must be enabled to set RXRDY. Receiver clock RXC controls the rate of data reception. In synchronous mode, baud rate is equal to receiver clock signal frequency. In asynchronous mode, baud rate is a fraction of receiver clock signal frequency. Synchronous detect pin SYNDET is used in synchronous mode and may be used either as input or output by the programmable control word. The SYNDET pin goes high to show that USART located the SYNC character. In case of by-sync character SYNDET goes high at the middle of the last bit of the second sync character.

6.4.2

Pin Function of Usart 8251

USART 8251 is a 28 pin integrated circuit. The pin diagram of the USART 8251 is shown in Fig. 6.13. Functions of different pins are described in the Table 6.6. Table 6.6

Pin funcion

Pin Name D7 – D0

Pin function EIGHT BIT DATA BUS

C/D

CONTROL/DATA TO BE READ/ WRITTEN

RD

READ DATA COMMAND

___

WR

WRITE DATA OR CONTROL COMMAND

___

CS

CHIP SELECT

CLK

CLOCK PULSE

RESET TXC

RESET TRANSMITTER CLOCK

TXD

TRANSMITTER DATA

RXC

RECEIVER CLOCK

RXD

RECEIVER DATA

DSR

DATA SET READY

DTR

DATA TERMINAL READY

SYNDET/BD SYNC DETECT/ BREAK DETECT RTS

REQUEST TO SEND DATA

CTS

CLEAR TO SEND DATA

TXEMPTY

TRANSMITTER EMPTY

VCC

+ 5 VOLT SUPPLY

GND

GROUND

Fig. 6.13 USART 8251

Programmable Communication Interface

6.4.3

6.17

Special Features of Usart 8251

USART 8251 has following special features. 1. USART 8251 is double buffered. It means that one character can be loaded into a holding buffer while another character is transmitted out of the actual transmit shift register; 2. 8251 is suitable for both synchronous and asynchronous transmission; 3. It uses 1, 1.5 or 2 stop bits at the end of transmission; 4. The clock rate of 8251 is either same or 16 times or 64 times the baud rate when it operates in synchronous mode; 5. USART 8251 has automatic break detect and handling capacity; 6. In synchronous mode, baud rate of 8251 is zero to 64 Kilo-baud; 7. The range of baud rate of this USART is 0 to 19.2 K baud in asynchronous mode; 8. In transmitter and receiver mode operations, the transmitter is full duplex and double buffered; 9. Parity, over run and the framing error detection is available with USART 8251; 10. The inputs and outputs of 8251 are TTL compatible; 11. Double buffered data paths with separate I/O registers for control, status, data input and data output of 8251 simplifies control programming; 12. Initialization of receiver prevents starting in break state; 13. TXD line of 8251 returns to high state unless STBRK is programmed; 14. The logic enhancement of 8251 prevents transmitter from turning off at the middle of the word; 15. Sync detection and break detection facility is provided by SYNDET/BD pin of 8251; 16. If double____ character sync is programmed, the characters are detected continuously; ___ 17. RD and WR signal of 8251 do not affect internal operation of 8251 if it is not selected; 18. Status of 8251 can be read at any time but status can not be updated during status read.

6.4.4

Operation of 8251A

USART 8251A should be initialized first for its successful operation. A mode word is sent first and then a command word is sent to the control register address for 8251A. The format of the mode word of 8251 is shown in Fig. 6.14. It is an 8 bit word which includes baud rate factor, character length, parity enable/disable, even parity generation/check and number of stop bits. Two least significant bits of the mode word determines the baud rate. Character length is determined by bits D3 and D2. Bits D4 and D5 specify the parity and D6-D7 determines number of stop bits. Command word is to be sent after sending the mode word. Figure 6.15 shows the format of command word of 8251A. It is a 8 bit word which consists of the operations like transmit enable, data terminal ready, receive enable, send break character, error reset, request to send, internal reset and enter hunt mode.

6.18

Embedded Systems: Design, Programming and Applications

Fig. 6.14

Fig. 6.15

Format of the mode word of 8251

Format of the command word of 8251A

Least significant bit of the command word____ enables the transmitter of the 8251A. When the 8251A is enabled, TXRDY signal goes high if CTS input is made low. Thus the transmitter holding buffer is ready for data from the microprocessor. To transmit the data on interrupt basis the TXRDY signal may be connected to the interrupt input of the microprocessor. TXRDY signal goes low when data is written to the data address of 8251A. This TXRDY pin will remain low till the holding buffer is ready for another data. When the D1 bit of the command word is 1, the DTR output goes low. This signal will inform the MODEM that a terminal or computer is operational. If D3 is made 1, a break character is transmitted i.e. output 8251A are all 0s. The break character indicates the end of the data transmission. D4 = 1 cause the 8251A to reset parity, over run and framing error flags. D5 = 1 indicates a request to send data showing RTS = 0. This signal also seek information whether the MODEM is ready or not for data transfer. D6 = 1 causes the 8251A to be reset internally. D7 bit is used only in synchronous mode of data transfer. Figure 6.16 illustrates the status word format of 8251A. Data set ready (DSR) bit D7 of status word of 8251A is normally used to test MODEM conditions such as whether data set is ready or not. When D6 is set, it indicates that character synch is obtained and 8251A is ready to receive or transmit data. Framing error (FE) flag bit D5 is set when a valid stop bit is not detected at the end of every character. FE flag does not inhibit the operation of 8251A. The overrun error (OE) flag bit D4 of status word is set when the microprocessor does not read a character before the availability of the next one. OE flag does not inhibit the operation of 8251A.

Programmable Communication Interface

Fig. 6.16

6.19

Illustrates the status word format of 8251A

However overrun character is lost. Parity error (PE) flag bit D3 is set if a parity error is detected. PE flag does not inhibit the operation of 8251A. Transmitter empty flag (TXE) bit D2 indicates that parallel to serial converter in transmitter is empty. Receiver ready (RXRDY) bit D1 indicates 8251A has received a character on its serial input and ready to transfer it to microprocessor. Transmitter ready (TXRDY) bit D0 of status word indicates that the USART 8251A is ready to receive a data character. There are two methods to send and read data character from the 8251A. These methods are known as follows. 1. Interrupt basis data transfer; 2. Polled basis data transfer. Transmission of data on interrupt basis is accomplished by connecting the TXRDY pin of the USART 8251A to an interrupt input of the microprocessor through 8259A priority interrupt controller. The bit D1 of the control word is made 1 to enable the transmitter and TXRDY output. If CTS pin of 8251A is made low buffer is ready for a character and TXRDY pin goes high. Now the interrupt path of processor and interrupt controller 8259A is enabled. As a result, the processor will execute interrupt service procedure and data character is written to the 8251A data address. This operation causes the USART 8251A to reset its TXRDY output until the buffer is ready to accept character. A counter may be employed to count the number of data sent by this method. For receiving data by 8251A on interrupt basis data transfer, RXDY output of the 8251A RXDY output is connected to an interrupt input of the processor and RXDY output is enabled by setting D2 bit of command word to 1. After transmitting a character into the 8251A the character in receiver buffer is ready to be read and then the RXDY pin goes to high. If the interrupt is enabled, the processor executes the interrupt service routine and reads the data character. When reading of data character is accomplished, the output pin RXDY will reset until another character is ready to be read. Transferring data character to USART 8251A on polled basis, the status register of 8251A is read and checked again and again until the TXRDY bit D0 is 1. Bit D7 of the status register may be checked to be sure that DSR input is asserted by a signal form. When the required bit is high the data character is then written to the 8251A. The required instruction sequences for this purpose are written on next page.

6.20

Embedded Systems: Design, Programming and Applications

Instruction sequences for transmitting data with an 8251a on a polled basis Label

Instruction Comments MVI H, FFF2H Address at control register Loop IN A, H Read status AND A, 81H Check status of DSR and TXRDY CMP A, 81H Check JNE TEST If not ready continue to poll MVI H FFF0H Otherwise point at data address MOV B, M Load A register with data to be sent OUT B Send data The status register has same internal address as the control register. AND and CMP operation is performed in the instruction sequence to determine the high status of the both the desired bits. After writing a character TXRDY bit goes low. In case of reading a character in polled basis data transfer RXRDY bit D1 of the status register of 8251A is polled. If D1 is high, a character is read in from USART 8251A data address. The required instruction sequences for this purpose are written below.

Instruction sequences for receiving data with an 8251a on a polled basis Label

Instruction Comments MOV H, FFF2H Address at control register Test IN A, H Read status AND AL, 02H Check status of RXRDY CMP A, 81H Check JZ TEST If not ready continue to poll MOV H, FFF0H Otherwise point at data address MOV A, M Load DX register with data to be read IN B, A Read data Bits D3, D4 and D5 of status register are checked to know that whether parity error, over run error or framing error has occurred or not. For any such error a message of retransmit of data is sent to transmitter.

6.4.5

Data Transfer by Asynchronous Mode

Transmission:

In asynchronous mode, when the data is sent by microprocessor then the USART 8251A adds a low level start bit automatically at the beginning of the data format. Data bits are transmitted as a serial data stream on the TXD output with lowest significant bit (LSB) first followed by a parity bit generated by the 8251A. Finally the transmission is stopped with a stop bit till another data set is ready for transmission. Figure 6.17 shows the data format for asynchronous ____ transmission. The serial data is transmitted at the falling edge of the TXC at a rate either equal

6.21

Programmable Communication Interface ____

____

____

to clock frequency of TXC or 1/16 times that of TXC or 1/64 times that of TXC as per mode instruction. TXD output again goes high when no data is available to transmit.

Fig. 6.17 Transmission data format in asynchronous mode

Reception In asynchronous mode data reception, the RXD line of the USART 8251 is normally high. The beginning of START bit is triggered at the falling edge of RXD line. The bit counter starts counting bits just after start bit. Then data bits D0, D1……DN, parity bit and START bits are received. The parity flag is set if parity error occurs. Data and parity bits are sampled on RXD pin using rising edge of RXC. The receiver stops its function when STOP bit appears. Figure 6.18 shows the received data format in in asynchronous mode.

Fig. 6.18 Received data format in asynchronous mode

6.4.6

Data Transfer by Synchronous Mode

In synchronous mode, TXD output remains high until CPU transmits first SYNC character to USART 8251A. The first character is serially transmitted out when CTS pin goes low. Then the characters are transmitted at the falling edge of TXC at the same rate of the TXC. Thus data stream must be transmitted at the TXD output. If transmitter buffer is empty, the SYNC character is automatically inserted in the TXD data stream and TXEMPTY pin goes high showing that data buffer of USART is empty. TXEMPTY becomes reset by a data character being stored in data buffer of 8251A. Figure 6.19 shows the transmitted data format in synchronous mode.

Fig. 6.19 Transmitted data format in synchronous mode

6.22

Embedded Systems: Design, Programming and Applications

Receiver in Syncronous Mode In synchronous mode character synchronization is obtained either internally or externally. ENTER HUNT command should be included as first command instruction. Then data is sampled on the rising edge of RXC signal. Receiver buffer content is then compared at every bit boundary with the first SYNC character. Figure 6.20 shows receiver data format in synchronous mode.

Fig. 6.20

Receiver data format in synchronous mode

If two SYNC character is used both the SYNC character will be compared and then 8251A ends the HUNT mode. The SYNDET pin is then set and this pin is reset automatically by reading the status. If synchronization is lost the microprocessor commands the receiver of 8251A to ENTER HUNT mode. The USART 8251A will not be ready for functioning just after programming mode instruction. The command register is to be programmed in synchronous data transfer. The command word performs the following functions. 1. The command word enables the transmitter and receiver; 2. It controls data terminal ready (DTR) signal and request to send (RTS) signal; 3. It sends a break character in asynchronous mode; 4. Command word reset errors; 5. It resets USART 8251A. During data communication, some time, it is necessary to examine the status of the USART 8251A if errors in data transmission is found. The 8251A provides the facility to a programmer to read the status of the USART at any time during operation of 8251A. This function is accomplished by a normal read command issued by CPU with C/D signal.

6.4.7

Interfacing 8251A with 8085

Serial port is required by most systems so that data communication between MODEM and other devices can be accomplished in serial form. Figure 6.21 shows the connection diagram of microprocessor 8086 with an USART 8251A as a serial port. 8251A may be considered as a device, consisting of two back to back shift registers. Parallel bytes from 8086 system data bus is

Programmable Communication Interface

6.23

received by one shift register and transmits the data through TXD output in serial form. The other shift register transfers serial data from the RXD input and converts it to parallel bytes which can be read by microprocessor from the system data bus. The number of data input line of USART 8251A is eight. Therefore, only one byte of data can be read from or written to the 8251A at a time. For this reason lower 8 bits (D0 – D7) of data bus are connected to data lines of 8251A. Shift registers of 8251A operates with a clock signal of frequency 16 or 64 times the rate of data transfer. The transmit shift register clock is denoted by TXC and receiving shift register clock is known as RXC pin of the 8251A. TXC and RXC pins are connected together to transmit and receive data at same rate. In practice, the clock for RXC/TXC input is generated by dividing 2.45 MHz PCLK signal from 8284 clock generator. The TXC/RXC frequency is selected by a divider chain in baud rate generator 74LS393. Baud rate is the specification of data transmission or reception in serial data transfer mode. Baud rate is defined as,

Fig. 6.21

Connection diagram of microprocessor 8086 with an USART 8251A as a serial port

If time per bit is 104 µs then baud rate of data transfer is 9600. Wire wrap jumper pins W19 to W25 are used to select the desired TXC and RXC frequency from the divider chain of baud rate generator. Serial port jumper matrix W1 to W18 Provides input output path of data.

Review Questions 1. What is USART? 2. Why USART is used? 3. What are the function of command word and status word in 8251A?

(WBUT 2007) (WBUT 2007) (WBUT 2007)

6.24

Embedded Systems: Design, Programming and Applications

4. Differentiate between synchronous and asynchronous data transfer in 8251A. (WBUT 2006) 5. If in 8251A, TXE and RXE, the applied clock frequency is 38.6 GHz, transmit receive rate is 2400, calculate the baud rate. (WBUT 2006) 6. What are the functions of command word and status word of 8251 USART? (WBUT 2005) 7. Differentiate between synchronous and asynchronous serial data transfer in 8251A. (WBUT 2005) 8. Design the hardware interface circuit for interfacing 8251 with 8086. Set the 8251 in asynchronous mode as a transmitter and receiver with even parity enabled, 2 stop bits, 8 bit character length, baud rate 10K. The frequency is 160 kHz. Write an ALP to (a) Transmit 100 bytes of data stored from 2000:5000 H (b) Receive 100 bytes of data and store it from3000:4000H (WBUT 2007) 9. What are the different types of data communication using 8251A? 10. Distinguish between serial and parallel data communication by USART. 11. Draw asynchronous data transmission forma and explain it. 12. Draw synchronous data transmission forma and explain it. 13. What are the recommended standards (RS) of serial data transfer protocols? 14. Describe standard RS-232C for data transmission between Data Terminal Equipment (DTE) and data communication equipment (DCE) using hand shaking mode. 15. Describe the pin function of following pins of 25 pin connector for RS-232C. (a) TXD (b) RXD (c) RTS (d) CTS (e) DSR (f) CD (g) SCF (h) SCB (i) SBA (j) SBB (k) DB (l) DD (m) SCA (n) DTR (o) CG (p) CE (q) CH/CI (r) DA 16. With the help of diagram describe the signal level of RS232 standard. 17. What is a MODEM? What are the different types of modulation may be used in MODEM? Describe digital data transmission using modem and phone lines. 18. Describe the word format of universal asynchronous receiver transmitter (UART – 8250). 19. What are the functions of following pins of UART 8250? (a) RCLK (b) SIN (c) SOUT (d) BANDOUT (e) XTAL1____ (f) XTAL2 ____(g) DOSTR (h) DISTR (i) DDIS (j) CSOUT (k) ADS (l) INTRPT (m) RTS (n) DTR (o) OUT1 (p) MR (q) CTS (r) DSR (s) DCD (t) RI 20. Draw the block diagram of USART 8251 and describe the function of each block. 21. What are the special features of USART 8251? 22. Describe the operational procedure of 8251. 23. Describe the following pin function of USART 8251. (a) C/D (b) TXC (c) TXD (d) RXC (e) RXC (f) RXD (g) RXRDY (h) TXRDY (i) SYNDET/BD (j) TXEMPTY

Programmable Communication Interface

24. Describe the following word format of USART 8251. (a) Mode word format (b) Command word format (c) Status word format 25. Describe the operation of 8251A. 26. Describe the data transfer in synchronous mode by 8251A. 27. Describe the data transfer in asynchronous mode by 8251A. 27. Describe interfacing of 8251A to 8086 microprocessor.

Choose the Correct Answer 1. RS232 is a (a) recommended standard for (b) recommended standard for (c) recommended standard for (d) none of these 2. RS232 is a (a) recommended standard for (b) recommended standard for (c) recommended standard for (d) none of these 3. RS423 is a (a) recommended standard for (b) recommended standard for (c) recommended standard for (d) none of these 4. IEEE488 is a (a) recommended standard for (b) recommended standard for (c) recommended standard for (d) none of these 5. RS422 is a (a) recommended standard for (b) recommended standard for (c) recommended standard for (d) none of these

serial data transfer protocol parallel data transfer protocol both serial and parallel data transfer protocol

serial data transfer protocol parallel data transfer protocol both serial and parallel data transfer protocol

serial data transfer protocol parallel data transfer protocol both serial and parallel data transfer protocol

serial data transfer protocol parallel data transfer protocol both serial and parallel data transfer protocol

serial data transfer protocol parallel data transfer protocol both serial and parallel data transfer protocol

6.25

6.26

Embedded Systems: Design, Programming and Applications

6. Serial data communication is suitable for (a) long distance communication (b) short distance communication (c) both long and short distance communication (d) none of these 7. Parallel data communication is suitable for (a) long distance communication (b) short distance communication (c) both long and short distance communication (d) none of these 8. Speed of asynchronous data communication is (a) less than 20 K baud (b) more than 20 K baud (c) equal to 20 K baud (d) none of these 9. Speed of synchronous data communication is (a) less than 20 K baud (b) more than 20 K baud (c) equal to 20 K baud (d) none of these 10. RS232 is a (a) IEEE standard (b) EIA standard (c) RCCA standard (d) none of this 11. 8250 is a (a) UART (b) USART (c) DTE (d) DCE 12. 8251 is a (a) UART (b) USART (c) DTE (d) DCE 13. The baud rate of data transfer by 8251 is (a) 300 (b) 256 (c) 150 (d) 9600 14. 8251 is a (a) USART (b) interrupt controller (c) counter (d) PPI 15. The number of stop bits in asynchronous data transfer is (a) 2 (b) 3 (c) 4 (d) 5 16. 8251 operates in (a) synchronous mode (b) asynchronous mode

Programmable Communication Interface

17.

18.

19.

20.

(c) synchronous and asynchronous mode (d) none of these The command word of 8251A (a) enables the transmitter and receiver (b) enables the DTE (c) enables the DTE (d) disables the DCE In synchronous mode, baud rate of 8251 is (a) zero to 64 Kilo-baud (b) zero to 32 Kilo-baud (c) zero to 128 Kilo-baud (d) zero to 256 Kilo-baud In asynchronous mode the range of baud rate of USART is (a) 0 to 19.2 K baud (b) 0 to 16 K baud (c) 0 to 32 K baud (d) 0 to 64 K baud Shift registers of 8251A operates with a clock signal of frequency (a) 16 or 64 times the rate of data transfer (b) 16 or 32 times the rate of data transfer (c) 16 or 128 times the rate of data transfer (d) 16 or 256 times the rate of data transfer

6.27

7 7.1

Software Design

INTRODUCTION

The activities of embedded systems are taken care of by the Real-Time Operating System software stored on the non-volatile memory of the RTES. Besides the above an RTES may have various other components and Application Specific Integrated Circuits (ASIC) for specialized functions such as motor control, modulation, demodulation, CODEC. The design of a Real-Time Embedded System has a number of constraints. Assembly level language is suitable for embedded system software. High-level languages are converted to code by utility programs named compilers. Because of the general nature of highlevel languages, the compliers often produce excess or overhead code. Assembly language requires no extra overhead code. No standard programs (named drivers) exist to write programs for special situations. When speed of response is critical, assembly-coded programs execute rapidly because of the exact fit of program code to task requirements. Use of assembly level language in embedded system reduces cost, Reduces code size also reduce the cost of associated ROM. In order to fully understand what is going on “under the hood” of the CPU, assembly level language is suitable. High level language embedded C, ‘C’ CROSS COMPILER ‘CX51’ and ‘Keil’ are used in embedded system as embedded software. CX51 is a cross compiler, some aspects of the C programming language and standard libraries are altered or enhanced to address the peculiarities of an embedded target processor. The CX51 compiler provides a number of include files for various 8051derivatives. Each file contains declarations for the SFRs available on that CX51. Optimizing C Compiler, complete implementation of the American National Standards Institute (ANSI) standard is achieved for the C language. CX51 is not a universal C compiler adapted for the 8051 target. It is dedicated to generate extremely fast and compact code for the 8051 microprocessor. CX51 provides the flexibility of programming in C and the code efficiency and speed of assembly language. Keil software contains C cross compiler, Assembler, tiny real time operating system, and program loader. Keil is used to create embedded applications rapidly for 8051 µcontroller. It supports chips like 8051 microcontrollers, 251 and 166. µVision2. It simplifies project development for 8051 and

7.2

Embedded Systems: Design, Programming and Applications

other microcontrollers. Keil supports 8051, 251 and 166 microcontroller family. Keil is optimized for specific architecture of each microcontroller. It generates smallest code and fastest execution speed. Keil provides full control over embedded development by deciding register banks, memory areas, variable types, SFRs. It has full code including ISR which can be written in ‘C’. Object oriented language C, C++, Java, and Visual C++ are also used for software development of embedded system.

7.2

SOFTWARE

Program design of embedded system is simplified by program modelling. The models of software design process of embedded system are mentioned below. 1. Object oriented program model; 2. Sequential program model; 3. Synchronous dataflow (SDF) graph or multi-thread graph (MTG) model; 4. Finite state machine for Data-path; 5. Universal modelling language (UML).

Device Management Software Software is required for device drivers and device management in an operating system because an embedded system is designed to do multiple functions. It has to control multiple physical and virtual devices. The physical devices are timers, keyboards, flash memory, display, network cards and ports. The virtual devices are described below. FILE: A file is a virtual device which transmits the records to a data sink. It stores the data from the data source. A file is stored in flash memory in the embedded system. PIPE: A pipe is used for sending and receiving a stream of bytes from a source to destination, SOCKET: A socket is used for sending and receiving a stream of bytes between client and server software or between source and destination computing system. RAM DISC: A RAM disc is used for using the RAM in a similar way to files in the disc.

Device Driver Software A device driver is software for opening, binding or connecting, writing, reading and control action. A device driver accesses a parallel or serial port, keyboard file, pipe and socket at specific addresses. A device driver controls following three functions. INITIALIZING: Initializing is activated by placing appropriate bits in the control register or control word. CALLING ISR: Calling Interrupt Service Routine (ISR) on interrupt RESETTING THE STATUS FLAG: Resetting the status flag after an interrupt service. Device manager software provide codes for detecting the presence of devices. It also initializes the device for testing. The manager includes software for allocating and registering port addresses for various devices. Device manager software ensures one task only at any instant for a device.

Software Design

7.3

7.3

SOFTWARE TOOLS FOR DESIGNING EMBEDDED SYSTEMS

Following software tools are used for designing the embedded systems. 1. Editor: Editor software is used for writing C codes with the help of keyboard for entering the program. Using editor software a file is created for addition, deletion, insertion etc; 2. Interpreter: Interpreter translates the program line by line into machine code; 3. Compiler: Compiler creates object file. It includes codes, functions and expression from library routine; 4. Assembler: Assembler translates assembly program into binary opcodes. It creates a binary file. This binary file is an executable file; 5. Cross assembler: The cross assembler assembles the assembly codes used in system development; 6. Simulator: Simulator simulates all functions of an embedded system; 7. Source code: The source code is used for editing, debugging, browsing, disabling and enabling the C++ features; 8. Stethoscope: It is used for tracking the changes in any program variable.It also shows the sequence of multiple processes; 9. Prototype developer: This prototype development tool is needed for the development of system software and hardware; 10. Real Time Operating System (RTOS): An RTOS is a multitasking OS which is needed for functioning in real time constraints. DESIGN ISSUES The constraints in the embedded systems design are imposed by external as well as internal specifications. Design metrics are introduced to measure the cost function taking into account the technical as well as economic considerations.

Design Metrics A Design Metric is a measurable feature of the system’s performance, cost, time for implementation and safety etc. Most of these are conflicting requirements i.e. optimizing one shall not optimize the other: e.g. a cheaper processor may have a lousy performance as far as speed and throughput is concerned. Following metrics are generally taken into account while designing embedded systems NRE cost (nonrecurring engineering cost). It is one-time cost of designing the system. Once the system is designed, any number of units can be manufactured without incurring any additional design cost; hence the term nonrecurring.

Size The physical space required by the system, often measured in bytes for software, and gates or transistors for hardware. Performance:

embedded system.

The execution time of the system is the main criteria of the performance of an

7.4

Embedded Systems: Design, Programming and Applications

Power Consumption:

It is the amount of power consumed by the system, which may determine the lifetime of a battery, or the cooling requirements of the IC, since more power means more heat.

Flexibility:

The ability to change the functionality of the system without incurring heavy NRE cost. Software is typically considered very flexible. Maintainability:

It is the ability to modify the system after its initial release, especially by designers who did not originally design the system.

Correctness:

This is the measure of the confidence that we have implemented the system’s functionality correctly. We can check the functionality throughout the process of designing the system, and we can insert test circuitry to check that manufacturing was correct.

The Performance Design Metric:

Performance of a system is a measure of how long the system takes to execute our desired tasks. The two main measures of performance are mentioned below. 1. Latency or response time: This is the time between the start of the task’s execution and the end. For example, processing an image may take 0.25 second; 2. Throughput: This is the number of tasks that can be processed per unit time. For example, a camera may be able to process 4 images per second. These are the some of the cost measures for developing an RTES. Optimization of the overall cost of design includes each of these factors taken with some multiplying factors depending on their importance. And the importance of each of these factors depends on the type of application. For instance in defense related applications while designing an anti-ballistic system the execution time is the deciding factor. On the other hand, for de-noising a photograph in an embedded camera in your mobile handset the execution time may be little relaxed if it can bring down the cost and complexity of the embedded Digital Signal Processor. The design flow of an RTES involves several steps. The cost and performance is tuned and fine-tuned in a recursive manner. An overall design methodology is enumerated below.

Fig. 7.1 Design approach

7.5

Software Design

7.4

SOFTWARE DESIGN METHODOLOGY

Programming is the essential part of any embedded system design. Programming is required for computational task. Programming is required for the ISR called on software interrupts from yraps, exceptions, errors, signals and interrupts from physical and virtual devices. Software instructions are required according to the given processor, memory and device hardware and as per the system interrupt servicing mechanism. System software is required for using any device in simple and sophisticated applications. For designing software of embedded system following points are to be considered. 1. Define of the problem; 2. Requirement of the embedded system; 3. Define the requirements (inputs, outputs, control); 4. Types of the signals (digital or analogue); 5. Voltage levels, frequency etc.

7.5

PROGRAMMING EMBEDDED SYSTEMS

Following programming languages are used for embedded system programming. 1. Assembly language; 2. C programming assembly language; 3. Mixed C and assembly programming; 4. I/O Programming; 5. Serial and parallel I/O programming; 6. Super loop architecture; 7. Protected mode and real mode (X86) programming; 8. Boot loaders and boot sectors; 9. Terminate and stay resident (TSR).

7.5.1

Assembly Level Language

It is easier to write the program in hexadecimal codes. The program written in hexadecimal code is called assembly level language. However, the assembly level language is to be translated into machine language for execution of instruction by the microprocessor. Assembly level language uses letters to write mnemonics to represent the instructions. Table 7.1 shows the instructions written by mnemonics in assembly level language. Table 7.1

Instructions written by mnemonics in assembly level language

Mnemonics

Operand

Hexadecimal Code

Machine code

Explanation

MOV AL,

53H

B0 53

10110000 0101 0011

Move 53 to AL register

ADD CX,

BX

03 CA

10010011 11001010

Add content of CX with Content of BX

7.6 7.5.2

Embedded Systems: Design, Programming and Applications

Programming 8051 Microcontroller Using Assembly Level Language

The instruction set of 8051 microcontroller has been discusses in Chapter 2. This microcontroller has five addressing modes to locate operand in the instruction. In this chapter we shall discuss these addressing modes with examples. Then we shall describe different types of instructions. All the instructions will be explained elaborately and some assembly level language programs for 8051 have been shown. Detailed architecture of microcontroller 8051 is shown in Fig. 2.5. The registers of 8051 are described in Chapter 2. Interfacing external memory to 8051 is also illustrated in the same chapter. Stack operation of 8051 is described in section 2.6.9. Bit functions of Serial port control SCON special function register is described in section 2.7.2. In this section we shall describe the programming of microcontroller 8051 in Assembly Level Language.

7.5.3

8051 Data Types and Directives

The 8051 microcontroller has only one data type. It is 8 bits, and the size of register is also 8 bits. It is the job of the programmer to breakdown data larger than 8 bits to be processed by the CPU. DB (define byte):

The DB directive is the most widely used data directive in the assembler. It is used to define data of 8 bit. When DB is used to define data, the numbers can be in decimal, binary, hex or ASCII format. For decimal, the D after the decimal number is optional, but B binary and H hexadecimal is required. Regardless of which is used, the assembler will convert the number to hex. To indicate ASCII, simply place it in quotation marks.

Example: ORG 200H DATA1: DB 28; DATA2: DB 10110111B; DATA3: DB 42H; ORG 210H DATA4: DB .1621. ; ASCII NUMBERS

7.5.4

Assembler Directives

ORG (origin): The ORG directive is used to indicate the beginning of the address. The number that comes after ORG can either in HEX or in decimal. EQU (equate):

This is used to define a constant without occupying a memory location. The EQU directive does not set aside storage for a data item but associates a constant with a data label so that when the label appears in the program, its constant value will be substituted for the label.

Software Design

7.7

Example: COUNT EQU 25 ……………….. .... ....................... MOV R3, #COUNT When executing the instruction .MOV R3, #COUNT. , the register will be loaded with the value 25. what is the advantage of using EQU? Assume that there is a constant used several times in the program body and you need to change the value. Using EQU directive it can be done easily. Otherwise one need to change the value throughout the program body. END directive: This indicates to the assembler the end of the source file. The END directive is the last line of an 8051 program. where it looks for the first instruction when it is booted.

7.5.5

8051 Flag Bits and the PSW Register

Like any other microprocessor the 8051 has a flag register to indicate arithmetic conditions such as carry bit. The flag register in the 8051 is called the program status (PSW) register. PSW register the program status word register is an 8 bit register only 6bits of which are used by the 8051. The two unused bits are user definable flags. Four of the flags are called conditional flags meaning that they indicate some conditions that resulted after an instruction was executed. These four are CY (carry), AC (auxiliary carry), P (parity), and OV (overflow). CY PSW, (Carry flag), AC auxiliary carry flag. PSW.5 is available to the user for general purpose. RS1 PSW.4 Register bank selector bit1. RS0 PSW.3 Register bank selector bit0. OV PSW.2 is overflow flag. PSW.1 is user definable bit. PSW.0 is parity flag.

7.5.6

I/O Port Pins and their Functions

The four ports P0, P1, P2 and P3 each use 8 pins making them 8 bit ports. Port 0: It can be used as either input or output port. To use port 0 as input or output, each pin must be connected to a 10 K ohm pull up resistor. This is due to the fact that P0 is an open drain, unlike P1, P2 and P3. Open drain is a term used for MOS chips in the same way that open collector is used for TTL chips. With external pull-up resistors connected upon reset, port 0 is configured as an output port. Port 0 as input: With resistors connected to port 0, in order to make it an input, the port must be programmed by writing 1 to all the bits. In the following code, port 0 is configured as an input port by writing 1s to it, and then data is received from that port and sent to P1. MOV A, # 0FFH; A=FFH MOV P0, A; Make P0 an input port; by writing all 1s to it BACK: MOV A, P0; Get data from P0 MOV P1, A ; Send it port 1 SJMP BACK; Keep doing it

7.8 7.5.7

Embedded Systems: Design, Programming and Applications

Dual Role of Port 0

Port: Port 0 is also designated as AD0 - AD7, allowing it to be used for both address and data. The 8051multiplexes address and data through port 0 to save pins. ALE indicates if P0 has address or data. If ALE = 0, it provides data D0, D7, but when ALE = 1 it has address A0. A7. Therefore, ALE is used for demultiplexing address and data with the help of a 74LS373 latch. Port 1: In contrast to port 0, this port does not need any pull up resistors since it already has pull up resistors internally. Upon reset port 1 is configured as an output port. To make it an input port, it must be programmed as such by writing 1 to all its bits. Port 2: Similar to port 1 in all aspects except its dual role in an 8031 based system. In an 8031 based system, port 2 must be used along with P0 to provide the 16 bit address for the external memory. Port 2 is also designated as A8. A15, indicating its dual role. Port 3: It can be used as input Port 3: it can be used as input/ output. P3 does not need any pull up resistors, the same as P1 and P2 did not. Although P3 is configured as an output port on reset it is not the way, but it is most commonly used.

7.5.8

Addressing Modes of 8051 Microcontroller

The CPU can access data in various ways. The data could be in a register or memory. 8051 provides a total of five distinct addressing modes. Data is transferred from source to destination by using instructions. Source and destination may be register, internal memory, and external memory and I/O peripherals. The method used for specifying operand is called addressing mode. These various ways of accessing data are called addressing modes. There are six addressing modes of 8051 microcontroller Immediate addressing mode:

This mode uses a constant for the source operand. The immediate data must be preceded by the ‘#’. Inimmediate addressing mode, as the name implies, when the instruction is assembled, the operand comes immediately after the opcode. The immediate data must be preceded by the .#. sign. This addressing mode can be used to load information into any of the registers, including the DPTR register.

Example: MOV MOV MOV MOV

A, #25H 0E0 H, #25H R4, #62H DPTR, #4521H

Load 25H into A Store 25 H in the address 0E0 H Load 62 H in register R4 Load 4521 H into data pointer register

Register addressing mode:

This mode involves the use of registers to hold data to be manipulated. Source and destination register must match in size. Register addressing mode: Register addressing mode involves the use of registers to hold the data to be manipulated.

Example: MOV R6, A Movement of data from R6 register. MOV A, R0 ;

Software Design

7.9

MOV R2, A ; MOV A, R5 ; ADD A, R7 ; Register indirect addressing mode:

In the register indirect addressing mode, a register is used as a pointer to the data. If the data is inside the CPU, only registers R1 and R2 are used for this purpose. In other words, R2. R7 cannot be used to hold the address of an operand located in RAM when using this addressing mode. When R0 and R1 are used as pointers, that is, when they hold the address of RAM locations, they must be preceded by the @ sign.

Example MOV A @ R0; MOV B @ R1; One of the advantages of register indirect addressing mode is that it makes accessing data dynamic rather than static as in the case of direct addressing mode. It should be noted that the source anddestination registers must match in size.

SFR registers and their addresses In the 8051, register A, B, PSW, and DPTR are part of the group of registers commonly referred to as SFR (Special Function Registers). The SFRs can be accessed by their names or by their addresses. The following two points should be noted about the SFR addresses. 1. The SFR have addresses between 80H and FFH. These addresses are above 80H, since the addresses 00 to 7FH are addresses of RAM memory inside the 8051. 2. Not all the address space of 80 to FF is used by the SFR. The unused locations 80H to FFH are reserved and must not be used by the 8051 programmer.

Direct addressing mode Another major use of direct addressing mode is the stack. In the 8051 family, only direct addressing mode is allowed for pushing onto the stack. Therefore an instruction such as .PUSH A. is invalid. Pushing the accumulator onto the stack must be coded as .PUSH 0E0H. where 0E0H is the address of register A.

Indexed addressing mode Indexed addressing mode is widely used in accessing data elements of look up table entries located in the program ROM space of the 8051. The instruction The 16 bit register DPTR and register A are used to form the address of the data element stored in on-chip ROM. Because the data elements are stored in the program space is widely used in accessing data elements of look up table entries located in the program ROM space of the 8051. The instruction used for this purpose is .MOVCA,@A+DPTR. The 16 bit register DPTR and register A are used to form the address of the data element stored in on-chip ROM.

Example: Assuming that clock pulses are fed into pin T1, write a program for counter1 in mode 2 to count the pulses and display the state of the TL1 count on P2.

7.10

Embedded Systems: Design, Programming and Applications

Solution

MOV TMOD, #01100000B MOV TH1, #0 SETB P3.5 AGAIN: SETB TR1 BACK: MOV A, TL1 MOV P2, A JNB TF1, BACK CLR TF1 SJMP AGAIN

Short jump Instruction

Example: AJMP ACALL Long jump Instruction:

In this addressing mode long addressing is used with the

instructions.

Example: LJMP LCALL Absolute addressing mode:

In this addressing mode, 11 least significant bits of the destination address comes from the opcode and the upper five bits comes from program counterexist. When speed of response is critical, assembly coded programs execute rapidly because of the exact fit of program code to task requirements. 1. In ALP, code size is reduced. As a result cost of associated ROM is reduced. 2. Assembly level language is suitable for programming 8051 microcontroller in order to fully understand what is going on “under the hood” of the CPU.

SPECIAL FUNCTION SIGNAL: 1. AD15:0 (Address/Data Lines): These lines serve as input as well as output pins. The function of these pins depends on the bus width and mode. When a bus access is not occurring, these pins revert to their I/O port function. AD15:0 drive address bits 0–15 during the first half of the bus cycle and drive or receive data during the second half of the bus cycle. 2. Bus Control and Status Signals (i) ALE: (Address Latch Enable): This is an output signal and is active-high output. It is asserted only during external memory cycles. ALE signals the start of an external bus cycle and indicates that valid address information is available on the system address/ data bus (A20:16 and AD15:0 for a multiplexed bus; A20:0 for a demultiplexed bus). An external latch can use this signal to demultiplex address bits 0–15 from the address/ data bus in multiplexed mode. (ii) BHE: Byte High Enable- During 16 bit bus cycles, this active-low output signal is asserted for word and high-byte reads and writes to external memory. BHE# indicates that valid data is being transferred over the upper half of the system data bus.

Software Design

7.11

(iii) WRH (Write High): This is an output signal During 16 bit data transfers from the cpu to external devices, this active-low output signal is asserted for high-byte writes and word writes to external memory. (iv) BREQ (Bus Request): This is an output signal. This active-low output signal is asserted during a hold cycle when the bus controller has a pending external memory cycle. (v) CS2:0 (Chip-select Lines 0–2): Output Signal. The active-low output is asserted during an external memory cycle when the address to be accessed is in the range as programmed. (vi) HOLD (Input Signal): Hold Request An external device uses this active-low input signal to request control of the bus. (vii) HLDA (Output Signal): Bus Hold Acknowledge This active-low output indicates that the CPU has released the bus as the result of an external device asserting HOLD. (viii) INST (Output Signal: When high, INST indicates that an instruction is being fetched from external memory. The signal remains high during the entire bus cycle of an external instruction fetch. (ix) RD (Read Signal Output): It is asserted only during external memory reads. (x) READY (Ready Input): This active-high input can be used to insert wait states in addition to those programmed in the chip configuration. (xi) WR (Write): Output Signal: This active-low output indicates that an external write is occurring. This signal is asserted only during external memory writes. Output Signal: During 16 bit bus cycles, this active-low output signal is asserted for high-byte writes and word writes to external memory. (xii) WRL (Write Low): Output Signal: During 16 bit bus cycles, this active-low output signal is asserted for low-byte writes and word writes to external memory. Processor Control Signals: (xiii) CLKOUT (Clock Out): It is the output of the internal clock generator. This signal can be programmed to have different frequencies and can be used by the external devices for synchronization etc. (xiv) EA (External Access): Input Signal: This input determines whether memory accesses to the upper 7 Kbytes of ROM (FF2400–FF3FFFH) are directed to internal or external memory. These accesses are directed to internal memory if EA# is held high and to external memory if EA# is held low. For an access to any other memory location, the value of EA# is irrelevant. (xv) EXTINT (External Interrupt Input): In normal operating mode, a rising edge on EXTINT sets the EXTINT interrupt pending bit. EXTINT is sampled during phase 2 (CLKOUT high). The minimum high time is one state time. If the EXTINT interrupt is enabled, the CPU executes the interrupt service routine. (xvi) NMI (Nonmaskable Interrupt Input): In normal operating mode, a rising edge on NMI generates a nonmaskable interrupt. NMI has the highest priority of all prioritized interrupts.

7.12

Embedded Systems: Design, Programming and Applications

(xvii) ONCE (Input): On-circuit emulation (ONCE) mode electrically isolates the microcontroller from the system. By invoking the ONCE mode, you can test the printed circuit board while the microcontroller is soldered onto the board. (xviii) PLLEN (Input Signal): Phase-locked Loop Enable This active-high input pin enables the on-chip clock multiplier. The PLLEN pin must be held low along with the ONCE# pin to enter on-circuit emulation (ONCE) mode. (xix) RESET (I/O Reset): A level-sensitive reset input to, and an open-drain system reset output from, the microcontroller. Either a falling edge on or an internal reset turns on a pull-down transistor connected to the RESET for 16 state times. In the power down and idle modes, asserting RESET causes the microcontroller to reset and return to normal operating mode. (xx) RPD (Return-From-Power-Down Input Signal): Return from Power down Timing pin for the return-from-power down circuit. (xxi) TMODE (Test-Mode Entry Input): If this pin is held low during reset, the microcontroller will enter a test mode. The value of several other pins defines the actual test mode. (xxii) XTAL1 (Input Crystal/Resonator or External Clock Input): Input to the on-chip oscillator and the internal clock generators. The internal clock generators provide the peripheral clocks, CPU clock, and CLKOUT signal. When using an external clock source instead of the on-chip oscillator, connect the clock input to XTAL1. Programes

8051 can be programmed using assembly level language programming (ALP). This ALP is suitable for 8051 for following reasons. High-level languages are converted to code by utility programs named compliers. Because of the general nature of high-level languages, the compliers often produce excess or overhead code. Assembly language requires no extra overhead code. For this reason size of the program is reduced. In ALP there is no standard programs.

7.6

FEATURES OF ASSEMBLY LANGUAGE: 1. One instruction appears per line. An assembly language instruction consists of four fields: (i) Label (ii) Mnemonic (iii) Operands (iv) Comment (i) Labels are the memory locations and it occupies the first column of the ALP. (ii) Instructions must start in the second column or after to distinguish them from labels. (iii) Comments starts from some designated comment character to the end of the line.

7.6.1

Advantage of Assembly Level Language Programming

Assembly level language programming has the following advantages over high level language programming.

Software Design

7.13

(i) The processors, memory, ports and devices hardware are sensitive to assembly codes. Instruction sets and its addressing modes provide a precise control of the processor internal devices. (ii) Assembly codes are processor and memory sensitive because the codes for declaring the conditions, rules and data type do not exist. The program is not also compiler specific and library functions dependent. (iii) Device driver codes require only a few assembly instructions. Program 1

(i) (ii) (iii) (iv) (v) (vi)

Write ALP to store 2A H in A 67 H in R0 and 8B H in R1 Content of external memory location 900B H into A 6E H in external memory location in 850C H 54 H in address 920A H and increment the same by one. 0A H, 0B H, 0C H 0D H in register R0, R1, R2, R3 respectively and exchange the content of R0 with R1 and R2 with R3.

Program (i)

Mnemonics MOV

Opcode A, #2A H

Comments Store 2A H in accumulator (A)

Opcode R0, #67H A, @DPTR

Comments Store 67 H in R0 register. Copy content of address 800B H into A

Opcode DPTR, #900B H R0, #8B H

Comments Store 800B H in data pointer register. Store 8B H in R1 register.

Opcode DPTR, #850C H A, #6E H @DPTR,

Comments Store 850C H in data pointer register. Store 6E H in A register. A Copy content of A into address 850C H

Opcode DPTR, #920A H A, #54 H @DPTR, A

Comments Store 920A H in data pointer register. Store 6E H in A register. Copy content of A into address 920A H

Program (ii)

Mnemonics MOV MOVX Program (iii)

Mnemonics MOV MOV Program (iv)

Mnemonics MOV MOV MOVX Program (v)

Mnemonics MOV MOV MOVX

7.14

Embedded Systems: Design, Programming and Applications

Program (vi)

Mnemonics A, R0 XCH MOV XCH

Opcode Comments copy content of R0 into A. A, R1 Exchange content of A and R1 A, R2 Copy content of R2 into A. A, R3 Exchange content of A and R3

Program 2 Write a program to

(a) Load the accumulator with the value 55H (b) Complement the ACC 700 times. Solution Since 700 is larger than 255 (the maximum capacity of any register), two registers are used to hold the count. The following program shows to use R2 and R3 for the count. MOV A, #55H ; A=55H MOV R3, #10 ; R3=10, the outer loop count

NEXT:

MOV

R2, #70

; R2=70, the inner loop count

AGAIN:

CPL

A

; complement A register

DJNZ R2, AGAIN ; repeat it 70 times “DJNZ R2, AGAIN”, whenever R2 becomes 0 it falls through and “DJNZ R3, NEXT” is executed. This instruction forces the CPU to load R2 with the count 70 and the inner loop starts again. This process will continue until R3 becomes zero and the outer loop is finished. Program 3:

BACK:

Program 4

Port program MOV A, #0FFH MOV P0,A MOV A, P0 MOV P1, A SJMP BACK DJNZ R3, NEXT

; A=FF hex ; make P0 an input port by writing all 1s to it ; get data from P0 ; send it to port 1 ; keep doing it (inner loop)

Bit manipulation

Read-modify-write features:

This feature saves size of the program. A sample program is

shown below. AGAIN:

MOV P1, #55H XRL P1, #0FFH ACALL DELAY SJMP AGAIN

Program 5 Single bit addressability of ports. Different bits of ports can be accessed separately using the following instructions.

Software Design

7.15

SETB X.Y CLR X.Y CPL X.Y JB X.Y JNB X.Y Program 6

Bit addressability of special function register ACC, B, PSW, IP, IE, SCON, TCON, are bit addressable registers. Sample program of bit addressability of special function register is shown below. MOV B, # 2H JNB ACC.0, YES INC A YES: DIV AB This example is checking whether the accumulator contains and even number. If so divide it by 2. If not, make it even Program 7

Assuming that ROM space starting at 250H contains “America”, write a program to transfer the bytes into RAM locations starting at 40H.

Program

A single counter is used in this program. ORG 0000 MOV DPTR, #MYDATA ; LOAD ROM POINTER MOV R0, #40H ; LOAD RAM POINTER MOV R2, #7 ; LOAD COUNTER BACK: CLR A ; A=0 MOVC A, @A+DPTR ; MOVE DATA FROM CODE SPACE MOV @R0, A ; SAVE IT IN RAM INC DPTR ; INCREMENT ROM POINTER INC R0 ; INCREMENT RAM POINTER DJNZ R2, BACK ; LOOP UNTIL COUNTER=0 HERE: SJMP HERE ;--------------------ON-CHIP CODE SPACE USED FOR STORING DATA ORG 250H MYDATA: DB “AMERICA” END

Program 8

Write a program to get the x value from P1 and send x2 to P2, continuously.

Program

ORG MOV MOV

0 DPTR, #300H A, #0FFH

; Load look-up table address ; A=FF

7.16

BACK:

Embedded Systems: Design, Programming and Applications

MOV MOV MOVC MOV SJMP ORG

P1, A A, P1 A, @A+DPTR P2, A BACK 300H

; Configure P1 as input port ; GRT X ; Get x square from table ; Issue it to P2 ; Keep doing it

XSQR_TABLE: DB 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 END Answer the following questions for this example. (a) Indicate the content of ROM locations 300 – 309H. (b) At what ROM locations is the square of 6, and what value should be there? (c) Assume that P1 has a value of 9: what value is at P2 (in binary)? Solution

(a) 300 = (00 H) 301 = (01 H) 302 = (04 H) 304 = (10 H) Comment: 4 * 4 = 16 = 10 in hex 305 = (19 H) Comment: 5 * 5 = 25 = 19 in hex 306 = (24 H) Comment: 6 * 6 = 36 = 24H 307 = (31 H) 308 = (40 H) 309 = (51H) (b) 306 H; 24H (c) 01010001B which is 51H and 81 H in decimal (92 = 81).

303 = (09 H)

Program 9 Assume that RAM locations 40 – 44 have the following values. Write a program to find the sum of the values. At the end of the program, register A should contain the low byte and R7 the high byte. 40 = (7D H), 41= (EB H), 42= (C5 H), 43= (5B H), 44= (30 H) Program

AGAIN:

NEXT: Program 10

MOV MOV CLR MOV ADD JNC INC INC DJNZ

R0, #40H R2, #5 A R7, A A, @R0 NEXT R7 R0 R2, AGAIN

; load pointer ; load counter ; A=0 ; clear R7 ; add the byte pointer to by R0 ; if CY=0 don’t accumulate carry ; keep track of carries ; increment pointer ; repeat until R2 is zero

Write a program to add two 16 bit numbers. The numbers are 3CE7 H and 3B8D H. Place the sum in R7 and R6; R6 should have the lower byte.

Software Design

7.17

MOV A, #47H MOV B, #25H ADD A,B DA A Program 11

Assume that 5 BCD data items (71, 11, 65, 59, 37) are stored in RAM locations starting at 40H. Write a program to find the sum of all the numbers in BCD. Program 12

Subtraction of unsigned numbers.

Solution

In 8051, there is only one instruction, SUBB. SUB is equivalent to SUBB with CY = 0. Steps of the hardware of the CPU in executing SUBB instruction are described below. 1. Take the 2’s complement of the subtrahend. 2. Add it to the minuend (A). 3. Invert the carry. Show the steps involved in the following: CLR C MOV A, #3FH MOV R3, #23H SUBB A, R3 Analyze the following program: CLR C MOV A,#4CH SUBB A,#6EH JNC NEXT CPL A INC A NEXT: MOV R1,A SUBB when CY = 1 Analyze the following program: CLR C MOV A, #62H SUBB A, #96H MOV R7, A MOV A, #27H SUBB A, #12H MOV R6, A Program 13 Write a program to get hex data in the range of 00-FF H from port 1 and convert it to decimal. Analyze the problem, assuming that P1 has a value of F0H for data.

7.18

Embedded Systems: Design, Programming and Applications

MOV A, #0FFH MOV P1, A MOV A, P1 MOV B, #10 DIV AB MOV R7, B MOV B, #10 DIV AB MOV R6, B OV R5, A Program 14 Assume that P1 is an input port connected to a temperature sensor. Write a program to read the temperature and test it for the value 75. According to the test results, place the temperature. Value in to the registers indicated as fallows. If T = 75 then A = 75 If T< 75 then R1 = T If T> 75 then R2 = T MOV P1, #0FFH ; make P1 an input port MOV A, P1 ; read P1 port, temperature CJNE A, #75, OVER ; jump if A not equal to 75 SJMP EXIT ; A=75, exit OVER: JNC NEXT ; if CY=0 then A>75 MOV R1, A ; CY=1, A75, save it in R2 EXIT: ……. Program 15

Assume internal RAM memory locations 40H – 44H contain the daily temperature for five days, as shown below. Search to see if any of the values equals 65. if value 65 does exist in the table, give its location to R4; otherwise, make R4 = 0. 40H= (76) 41H= (79) 42H= (69) 43H= (65) 44H= (62)

Program

BACK:

MOV MOV MOV MOV CJNE MOV SJMP

R4, #0 R0, #40H R2, #05 A, #65 A, @R0, NEXT R4, R0 EXIT

; R4=0 ; load pointer ; load counter ; A=65, value searched for ; compare RAM data with 65 ; if 65, save address ; and exit

Software Design

NEXT: EXIT:

INC R0 DJNZ R2, BAC …….

7.19

; otherwise increment pointer ; keep checking until count = 0

Program 16 Creating a square wave of 50% duty cycle (with equal position high and low) on the P1.5 bit.Timer 0 is used to generate the time delay. MOV TMOD,#01 ;Timer 0,mode 1 (16-bit mode) HERE: MOV TL0,#0F2H ;TL0=F2H, the low byte MOV TH0,#0FFH ;TH0=FFH, the high byte CPL P1.5 ; Toggle P1.5 ACALL DELAY SJMP HERE ;load TH,TL again ;----------------delay using timer 0 DELAY: SETB TR0 ; start the timer 0 AGAIN JNB TF0, AGAIN ; monitor timer flag 0 until it rolls over CLR TR0 ; stop timer 0 CLR TF0 ; clear timer 0 flag RET Program 17

Mode 2 programming 8 bit timer, range is 00 to FFH to be loaded into the timer register TH After loading copy to TL automatically. Start timer by SETB instruction. Timer starts to count up by incrementing the TL register up to FFH, rolls over to 00, set the timer flag, TL is reloaded automatically with the original value in TH register. 5. Clear TF.

1. 2. 3. 4.

Program

BACK:

MOV MOV SETB JNB CPL CLR SJMP

TMOD, #20H TH1, #5H TR1 TF1, BACK P1.0 TF1 BACK

Program 18 Find the frequency of the square wave generated on pin 1.0 and the smallest frequency achievable in this program. Assuming that XTAL = 11.0592 MHz, write a program to generate a square wave of 2 kHz frequency on pin P1.5. Program

Here bit is toggled generate the square wave.

7.20

Embedded Systems: Design, Programming and Applications

T = 1 / f = 1 / 2 kHz = 500 µs the period of square wave. (a) 1 / 2 of it for the high and low portion of the pulse is 250 µs. (b) 250 µs / 1.085 µs = 230 and 65536 – 230 = 65306 which in hex is FF1AH. (c) TL = 1A and TH = FF, all in hex. The program is as follows: MOV TMOD, #10H ; timer 1, mode 1 (16 – bit) AGAIN: MOV TL1, #1AH ; TL1 = 1A, low byte of timer MOV TH1, #0FFH ; TH1 = FF, Hi byte SETB TR1 ; start the timer 1 BACK: JNB TF1, BACK ; stay until timer rolls over CLR TR1 ; stop timer 1 CPL P1.5 ; comp. P1.5 to get hi, lo CLR TF1 ; clear timer flag 1 SJMP AGAIN ; reload timer since mode 1 ; is not auto-reload Program 19 Counters: When C/T=1, in TMOD register the timer is used as a counter and

gets its pulses from pin 14 and 15.This pins are called T0 and T1 and belongs to port 3. TMOD, #01100000B MOV TH1,#0 SETB P3.5 AGAIN SETB TR1 BACK MOV A, TL1 MOV P2, A JNB TF, BACK Assuming that clock pulses are fed into pin T1, write a program for counter 1 in mode 2 to count the pulses and display the state of the TL1 count on P2. MOV TH1, #0 CLR TR1 CLR TF1 SJMP AGAIN Program 20 Assuming that clock pulses are fed into pin T1, write a program for counter 1 in mode 2 to count the pulses and display the state of the TL1 count on P2. Program

AGAIN: BACK:

MOV MOV SETB SETB MOV MOV

TMOD, #0110000B TH1, # 0 P3 . 5 TR1 A, TL1 P2, A

; counter 1, mode 2, C/T= 1; external pulses ; clear TH1 ; make T1 input ; start the counter ; get copy of count TL1 ; display it on port 2

Software Design

7.21

JNB TF1, BACK ; keep doing it if TF =0 CLR TR1 ; stop the counter CLR TF1 ; make TF=0 SJMP AGAIN ; keep doing it In this program the role of the instruction “SETB P3. 5” are set up for output, when the 8051 is powered up. Port P 3. 5 is made input port by making it high or it must be configured (set high) the T1 pin (pin P3. 5) to allow pulses to be fed into it.

7.6.2 Time Delay Generation and Calculation CPU to execute an instruction takes a certain number of clock cycles. These clock cycles are referred as ‘Machine Cycles’. The length of the machine cycle depends on the frequency of the crystal oscillator. One machine cycle lasts for 12 oscillator periods. Therefore, to calculate the machine cycle, we take 1/12 of the crystal frequency, then take the inverse.

Example 1: Calculation of machine cycle for 16 MHz crystal oscillator is shown below. 16MHz/12=1.333MHz Machine cycle=1/1.333MHz=0.75microseconds

Example1 2: Find the size of the delay in the following program, if the crystal frequency is 11.0592 MHz. AGAIN:

DELAY: HERE:

MOV MOV ACALL CPL SJMP MOV DJNZ RET

A, #55H P1, A DELAY A AGAIN R3, #200 R3,HERE

Solution From Table A-1 in Appendix A, the following machine cycles for each instruction of the DELAY subroutine. Machine cycle DELAY: MOV R3,#200 1 HERE: DJNZ R3,HERE 2 RET 1 Therefore, the total time delay = [(200*2) +1+1]*1.085 ms=436.17 µs.

Example 3 Find the time delay in the following subroutine for a machine cycle of 1.085 ms.

7.22

Embedded Systems: Design, Programming and Applications

DELAY:

Machine cycle 1 1

MOV R2,#200 AGAIN: MOV R3,#250 HERE: NOP 1 NOP 1 DJNZ R3, HERE 2 DJNZ R2, AGAIN 2 RET 1 For “HERE” loop, time delay = (4*250)1.085 ms = 1085 ms. The “AGAIN” loop repeats the “HERE” loop 200 times. Therefore, 200*1085 ms = 217000 ms, if overhead is not included. However, the instructions “MOV R3, #250” and “DJNZ R2, AGAIN” at the beginning and end of the “AGAIN” loop add (3*200*1.085 ms) = 651 ms to the time delay. As a result Total time delay = 217000 + 651= 217651 ms = 217.651 milliseconds.

7.6.3

Data Types and Directives

The 8051 microcontroller has only one data type of 8 bits and the size of each register is 8 bits. data may be unsigned or signed. DB:

DB is used to define data, that can be in decimal, binary or ASCII formats.

Example:

DATA1 DATA2 DATA3 DATA4

DB DB DB DB

28 00110101B 39H 2591

Decimal (1C in hexadecimal) Binary (35 in hex) Hexadecimal ASCII number

ASSEMBLER DIRECTIVES ORG:

The ORG directive is used to indicate the beginning of the address.

EQU (equate):

Example: END:

This is used to define a constant without occupying a memory location. COUNT MOV

EQU 25 R3,#COUNT

This indicates the assembler about the end of the source file.

Problem 1 Show the status of the CY, AC, and P flags after the addition of 38H and 2FH in the following instructions. MOV A, #38H ADD A, #2FH Problem 2

Show the status of the CY, AC, and P flags after the addition of 9CH and 64H in the following instructions. State the contents of the RAM locations after the following program:

Software Design

SETB MOV MOV MOV MOV MOV

PSW.4 R0,#99H R1,#85H R2,#3FH R7,#63H R5,#12H

7.23

; select bank 2 ; load R0 with value 99H ; load R1 with value 85H ; load R2 with value 3FH ; load R7 with value 63H ; load R5 with value 12

Answer

By default, PSW.3=0 and PSW.4; therefore, the instruction “SETB PSW.4” sets RS1=1 and RS0=0, thereby selecting register bank 2. Register bank 2 uses RAM location 10H-17H. After the execution of the above program we have the following: RAM location 10H has value 99H RAM location 11H has value 85H RAM location 12H has value 3FH RAM location 17H has value 63H RAM location 15H has value 12H Stack in the 8051: When the 8051 is powered up, the SP register contains value 07 i.e. RAM

location 08 is the first location being used for the stack by the 8051. MOV R6,#25H MOV R1,#12H MOV R4,#0F3H PUSH 6 PUSH 1 PUSH 4 Program 1 Write a program to 1. (a) clear ACC, then (b) add 3 to the accumulator ten times. 2. What is the maximum number of times that the loop in the program can be repeated? Program

This program adds value 3 to the ACC ten times MOV A, #0 ; A=0, clear ACC MOV R2, #10 ; load counter 2=10 AGAIN: ADD A, #03 ; add 03 to ACC DJNZ R2, AGAIN ; repeat until R2= (10 times) MOV R5, A ; save A in R5 Since R2 holds the count and R2 is an 8-bit register, it can hold a maximum of FFH (255 decimal); therefore, the loop can be repeated a maximum of 256 times.

Program 2

Write a program to (a) load the accumulator with the value 55H, and (b) complement the ACC 700 times.

Program

Since 700 is larger than 255 (the maximum capacity of any register), we use two registers to hold the count. The following code shows to use R2 and R3 for the count. MOV A, #55H ; A=55H MOV R3, #10 ; R3=10, the outer loop count

7.24

Embedded Systems: Design, Programming and Applications

NEXT: AGAIN:

MOV R2, #70 ; R2=70, the inner loop count CPL A ; complement A register DJNZ R2, AGAIN ; repeat it 70 times (inner loop) DJNZ R3, NEXT In this program, the inner loop starts again. This process will continue until R3 becomes zero and the outer loop is finished. Program, R2 is used to keep the inner loop count. In the instruction “DJNZ R2, AGAIN”, whenever R2 becomes 0 it falls through and “DJNZ R3, NEXT” is executed. This instruction forces the CPU to load R2 with the count 70 Mnemonics Opcode Comments MOV DPTR, #850C H Store 850C H in data pointer register. MOV A, #6E H Store 6E H in A register. MOVX @DPTR, A Copy content of A into address 850C H R1, #0D H Store 0D H in R3 register. MOV Since 700 is larger than 255 (the maximum capacity of any register), two registers are used to hold the count. The following program shows to use R2 and R3 for the count. MOV A, #55H ; A=55H MOV R3, #10 ; R3=10, the outer loop count NEXT: MOV R2, #70 ; R2=70, the inner loop count AGAIN: CPL A ; complement A register DJNZ R2, AGAIN ; repeat it 70 times “DJNZ R2, AGAIN”, whenever R2 becomes 0 it falls through and “DJNZ R3, NEXT” is executed. This instruction forces the CPU to load R2 with the count 70 and the inner loop starts again. This process will continue until R3 becomes zero and the outer loop is finished.

7.7 ASSEMBLY LEVEL LANGUAGE FOR EMBEDDED CONTROLLER 8051 Program to Display Decimal Count 0 to 20

RPT:

DSPCHR EQU PUTBYTE EQU CLRLCD EQU Mnemonics ORG 8000 H MOV R2, #00 H MOV DPTR, #0E904 H MOVX A, @DPTR JNB ACC.3, L1 LCALL CLRLCD

03E6 H 13D2 H 03BBH Comments ; Store count 00 in R2 ; Read the dipswitch ; Clear the LCD display

Software Design

L1:

LOOP:

DELAY: BACK1: BACK2

MOV MOV LCALL SJMP MOV MOV LCALL MOV MOV LCALL DJNZ LCALL LCALL LCALL LCALL MOV ADD DA MOV CJNE LJMP MOV MOV DEC CJNE DEC CJNE RET

A, R2 71 H, A PUTBYTE L2 A, R2 71 H, A PUTBYTE R3, #03 H A, #08 H DSPCHR R3, LOOP DELAY DELAY DELAY DELAY A, R2 A, #01 H A R2, A R2, #21 H, RPT 0000 H R3, #0FF H R4, #0FF H R3 R3, #00 H, BACK1 R4 R3, #00 H, BACK1

7.25

; Display the count on LCD

; Display the count on LCD

; Perform decimal adjust ACC ; Repeat the process till the count is 20 ; Delay routine

Program to Display 24 Hours Digital Clock OUTPUT EQU PUTBYTE EQU DSPCHR EQU MNEMONICS ORG 8000 H MOV DPTR, #STG LCALL OUTPUT

0404 H 13D2 H 03E6 H COMMENTS ; Keep data from 80F3 H program memory ; Display routine

7.26 START: LOOP:

LOOP1 LOOP 2

LOOP 3

Embedded Systems: Design, Programming and Applications

MOV MOV MOV MOV PUSH LCALL MOV LCALL MOV LCALL MOV MOV LCALL MOV LCALL MOV LCALL MOV LCALL POP PUSH MOV MOV MOV MOV LCALL MOV MOV LCALL DJNZ LCALL MOV ADD DA A MOV CJNE

R5, #23 H R7, #58 H A, R5 71 H, A 05 PUTBYTE A, # 20 H DSPCHR A, #20 DSPCHR A, R7 71H, A PUSHBYTE A, #20H DSPCHR A, #20H DSPCHR A, #20H DSPCHR 05 05 R1, #00H A, R1 71H, A A, #20H PUTBYTE R3, #02H A, #08H DSPCHR R3, LOOP3 DELAY A, R1 A, #01H R1, A R1, #60H

; Store hours in R5 ; Store minutes in R7

: Routine to put character on console : Provide space

;DELAY ROUTINE

: CHECK FOR 60 SECOND OVER OR NOT

Software Design

LOOP 4

LOOP 5

LOOP 6

DELAY BACK3:

MOV ADD DA MOV CJNE MOV MOV A, LCALL DJNZ MOV MOV MOV LCALL MOV MOV LCALL DJNZ POP MOV ADD DA MOV CJNE MOV MOV LCALL DJNZ ADD MOV LCALL MOV MOV LCALL LJMP MOV MOV

A, R7 A, #01H A R7, A R7, #60H R3, #07H #08H DSPCHR R3, LOOP 4 A, #01H R7, A 71H, A PUTBYTE R3, #07H A, #08H DSPCHR R3, LOOP 5 05 A, R5 A, #01H A R5, A R5, #24H R3, #04H R3, #04H DSPCHR R3, LOOP 6 A, #00H 71H, A PUTBYTE R5, #00H R7, #00H CURSOR LOOP R2, #05H R4, #0FFH

7.27

: CHECK FOR 60 MINUTE OVER OR NOT

; CHECK FOR 24 HOURS

7.28 BACK2: BACK1:

Embedded Systems: Design, Programming and Applications

MOV DEC CJNE DEC CJNE DEC CJNE RET

R3, #0FFH R3 R3, #00H, BACK1 R4 R4, #00H, BACK2 R2 R2, #00H, BACK3

Subroutine to Display Minutes MIN: RPT4:

MOV MOV LCALL DJNZ MOV MOV LCALL MOV LCALL MOV LCALL LJMP

R3, #04H A, #08H DSPCHR R3, RPT4 A, R7 71H, A PUTBYTE A, #20H DSPCHR A, #20H DSPCHR LOOP1

Subroutine to Move the Cursor three Times Back CURSOR: RPT5

MOV MOV LCALL DJNZ RET

R3, 03H A, #08H DSPCHR R3, RPT5

Subroutine to Display Hours HRS:

MOV MOV LCALL MOV LCALL

A, R5 71H, A PUTBYTE A, #20H DSPCHR

Software Design

MOV LCALL MOV MOV LCALL MOV MOV MOV LCALL MOV LCALL LJMP RET

7.8

7.29

A, #20H DSPCHR A, #00H 71H, A PUTBYTE R7, #00H R6, #00H A, #20H DSPCHR A, #20H DSPCHR LOOP

HIGH LEVEL LANGUAGE PROGRAMMING

High level languages have powerful features for embedded systems. Processor directives, header files, include files, source files, macros, functions, data types, pointers, data structures, arrays, like arrays, queues, stacks, lists and trees are used in embedded system program for application. Modifiers, conditional statements, loops, function calls, multiple functions, function pointers, function queues and service routine queues are useful for embedded system programming. Objectoriented program concepts, embedded programming in C, C++, Java and J2ME are also suitable for embedded systems. High level languages, like C, C++ or Java, have following advantages over assembly language in embedded system. 1. High level program development cycle is short because of using routines, library functions, object-oriented design, modular programming approach. The software is based on operating system, file systems, device and network drivers. When a function is called, sets of statements and commands are run. In high level language, library functions are available to programmer and the codes for library functions are not defined by the programmer. The standard library functions [square root ( )’, delay ( ), wait ( ), sleep ( )] saves the programmer time. Device drivers are used in high level language, which use the functions specified in OS. Simply the device ID is specified by the programmer. Use of modular programming approach also make the high level program development cycle short even for complex system. A module consists of a set of functions. The module is tested for well defined goal and for data input and output. It should have one calling method and one return point from the module. There should be data encapsulation i.e. it should not affect any data other than the operand. In high level language, Object-oriented design approach or top down approach can be used. In this method main program is first designed, then its modules, sub-modules and finally the functions.

7.30

Embedded Systems: Design, Programming and Applications

2. High level language facilitates data type declaration. In high level language, there is a facility to declare data type. Four types of integers can be declared by mentioning int, unsigned int, short and long. Short means 16 bit data and int means 32 bit data, long means 64 bit data. Another data type char is used to manipulate the text and string for a character. Declaration of data type permits manipulation representation and defining a set of operation on that data. 3. High level program are less error prone because it has facility for type checking. Type checking does not permit subtraction, multiplication and division on ‘char’ data type. 4. High level language facilitates ‘control structure’ and conditional statement like if, if-else, switch case, while, do while, break etc. 5. High level program has non-processor specific codes. As a result, if the hardware is changed the program can be used after a few modifications.

7.9

C PROGRAM ELEMENTS

C language is a structured programming language. It has following structural elements and preprocessor structural elements. Structural elements: 1. Definitions, declaration and statements 2. Main function 3. Functions exceptions and ISRs Pre-processor structural elements 1. Definitions of constants 2. Include directive for file inclusion 3. Declarations of global data type, macros and functions 4. Definition of global processor variables In a C program, header and source files are included first. The comments in C program are written as /*……*/. The use of files may be written in the comments. Include is a processor directive to include the content of the file. For example # include “sysLib.C” /*Include system library for system unctions)/ # include “taskLib.h” /*Include multitasking function library)/ There are many files are also available for inclusion in the program. These files are described below. 1. Header files: Header files includes the contents (codes or data) of source files. For string manipulation, header file ‘string.h’ is included. For mathematical expression, header file ‘math.h’ is included for mathematical operation; 2. Basic variable files: Basic variable files are included for the global or local static variables which are stored in the RAM. Any embedded system has only one real time clock. So there is one address of the clock variables. The basic variable of the clock are stored in the file with the extension ‘.bss’;

7.31

Software Design

3. Code files: Content of code files are codes or data e.g. “ # include prctlHaandlers.C”. It includes files for the codes already available; 4. String data files: Content of string data files are strings (.str) or texts (.txt) e.g. “# include netDrvConfig.txt”. It includes a text file that provides the network driver configuration; 5. Constant data files: These files are the codes and may have the extension ‘.const’; 6. Initial data files: These files are used for the initial or default data for the shadow ROM of the embedded system. These may have the extension ‘.init’; 7. Source files: Source files are program files. These files are used for the function of application software. Source file is to be compiled. It indicates the first function from where the processing will start. The first function is called main function and its codes starts with void main ( ). 8. Configuration files: This files are used for the configuration of the system. These files have device configuration file of basic variables. The file stores the code in ‘SerialLine_cfg.h’ and hence ‘# include SerialLine_cfg.h’ will function as processor directive. Many other files or directives are included in the high level language program e.g. ‘conio.h’ for input/output operation for the OS functions and RTOS functions. ‘# include VxWorks.h’ is directive to the compiler, which includes VxWorks RTOS functions. Uses of program elements are shown in Table 7.2 below: Table 7.2 Program element

Uses

Macro: A macro is a collection of codes

It executes a named small collection of codes

Function

Function executes a named set of codes with values. It returns a data object till void declaration. Function has context saving and retrieving overheads.

Main function

Declaration of functions and data types either executes a named set of codes or starts OS Kernel.

Reentrant function

Reentrant function is used by the several tasks and routine synchronously with retrievable argument values from a stack of the local variables, data structure and objects.

Interrupt service routine (ISR)

Declaration of functions and data types executes a named set of codes known as interrupt service routine.

Process or thread or task

A process runs on scheduling by OS (Kernel) which provides the control of CPU to the process. A thread is a process or sub-process within a process. Thread schedules the multiple processes. Tasks are embedded program computational units. Task is used for the process in the RTOSes for the embedded system.

Recursive function

Recursive function is used to call the function itself. Recursive call may choke the memory space availability. For this reason, its use is avoided in embedded system.

7.32 7.9.1

Embedded Systems: Design, Programming and Applications

C Compiler

The C compiler is a Small C-compatible compiler that generates MCS-51 relative assembly language from C source. The output is intended to be assembled by the Reads51v4 relative assembler and subsequently be linked by the linker. The C compiler has some of the limitations of Small C. However, it also introduces some significant extensions and improvements over standard Small C. The C-Compiler has the following limitations. 1. Structures and Unions are not implemented; 2. Only one-dimensional arrays are allowed; 3. Only one level of indirection (pointer) is allowed; 4. Only int and char types are allowed. Advantages of C compiler 1. Uses the more modern (ANSI C) function argument definition syntax; 2. Arguments are passed to the functions in the C convention. This allows a variable number of arguments to be passed on to functions. Such as in printf(); 3. Supports MCS-51 interrupts; 4. Supports function prototypes; 5. Supports the void type; 6. Uses Rigel.s proprietary macropreprocessor; 7. Supports sfr and sfrbit types; 8. Supports single-chip mode.

Programmes 1. Write a program in C for use of polling for an event or message in a program Let us assume: 1. The function main has a waiting loop and simply passes control to an RTOS. 2. Each task controlled by the RTOS have codes in infinite loop # define false 0 # define true 1 void main (void){ rtos.run ( ); /* Call RTOS run*/ while (1) { } } void task1(….){ /*declaration)*/ . . .

Software Design

. void task1(….){

. void task1(….){

while (true){ /*Codes that repeatedly execute*/ . . . /* Codes that execute on an event*/ if (flag1){….;}; flag1=0; /* Codes that execute for sending message to the Kernel*/ Message1 ( ) } } /*declaration)*/ . . . while (true){ /*Codes that repeatedly execute*/ . . . /* Codes that execute on an event*/ if (flag1){….;}; flag1=0; /* Codes that execute for sending message to the Kernel*/ Message1 ( ) } } /*declarations)*/ . . . while (true){ /*Codes that repeatedly execute*/ . . .

7.33

7.34

Embedded Systems: Design, Programming and Applications

/* Codes that execute on an event*/ if (flag1){….;}; flag1=0; /* Codes that execute for sending message to the Kernel*/ Message1 ( ) } }

.

void task2(….){ /*declarations)*/ . . . while (true){ /*Codes that repeatedly execute*/ . . . /* Codes that execute on an event*/ if (flag2){….;}; flag2=0; /* Codes that execute for sending message to the Kernel*/ Message2 ( ) } } . . . . void taskN(….){ /*declaration)*/ . . . while (true){ /*Codes that repeatedly execute*/ . . .

Software Design

7.35

/* Codes that execute on an event*/ if (flagN){….;}; flagN=0; /* Codes that execute for sending message to the Kernel*/ MessageN ( ) } . } In this program, the code inside-infinite loop waits for an inter-process communication (IPC) message or event flag or a set of events through the OS. The code inside the loop of the running task generates a message that transfers to the Kernel which passes to the waiting task message, detects it. Then the instruction SWI executes to send the message to another task function for a service. 2. Following program depicts how a square wave can be generated in the output port (P1) The program is written in C using Reads51 Compiler. The Reads51 Compiler supports assembly language, C language, as well as combination of both. Program

#include void delay(int k); void SetP1_0(void); void ClrP1_0(void); int i,j; void SetP1_0(void){ P1_0=1; } void ClrP1_0(void){ P1_0=0; } void delay(int k){ for(i=0;i MAXBYTES) nbytes = MAXBYTES; if ( (semid=semget( (key_t)key,1, 0666 | IPC_CREAT ))== -1) { printf(“semget error \n”); exit(1); } /* Initialise the semaphore to 1 */ V(semid); if ( (segid = shmget( (key_t) key, MAXBYTES, 0666 | IPC_CREAT ) ) == -1 ) { printf(“shmget error \n”); exit(1); } /*if ( (addr = shmat(segid, (char* )0,0)) == (char *)-1) */ if ( (addr = shmat(segid, 0, 0)) == (char *) -1 ) { printf(“shmat error \n”); exit(1);

8.29

Interprocess Communication

} switch (fork()) { case -1 : printf(“Error in fork \n”); exit(1); case 0 : /* Child process, receiving messages */ for (i=0; i < no_of_mess; i++) if(receive(semid, message, sizeof(message))); exit(0); default : /* Parent process, sends messages */ for ( i=0; i < no_of_mess; i++) { for ( j=i; j < nbytes; j++) message[j] = ‘d’; if (!send(semid, message, sizeof(message))) printf(“Cannot send the message \n”); } } } }

/* end of for loop */ /* end of switch */ /* end of else part */ /* Semaphores */ #include #include #include #include #include int sid; cleanup(semid, segid, addr) int semid, segid; char *addr;

{ int status; /* wait for the child process to die first */ wait(&status); semctl(semid, 0, IPC_RMID, 0); shmdt(addr); shmctl(segid, 0, IPC_RMID, 0); };

8.30

Embedded Systems: Design, Programming and Applications

P(sid) int sid; {

/* Note the difference in this and previous structs */ struct sembuf *sb; sb = (struct sembuf *) mallo c(sizeof(struct sembuf *)); sb -> sem_num = 0; sb -> sem_op = -1; sb -> sem_flg = SEM_UNDO; if( (semop(sid, sb, 1)) == -1) puts(“semop error”);

}; V(sid) int sid; { struct sembuf *sb; sb = (struct sembuf *) malloc(sizeof(struct sembuf *)); sb -> sem_num = 0; sb -> sem_op = 1; sb -> sem_flg = SEM_UNDO; if( (semop(sid, sb, 1)) == -1) puts(“semop error”); }; /* send message from addr to buf */ send(semid, addr, buf, nbytes) int semid; char *addr, *buf; int nbytes; { P(semid); memcpy(addr, buf, nbytes); V(semid); } /* receive message from addr to buf */ receive(semid, addr, buf, nbytes) int semid; char *addr, *buf; int nbytes; { P(semid);

Interprocess Communication

8.31

memcpy(buf, addr, nbytes); V(semid); } From the above programs, we notice that any process is capable of accessing the shared memory area once the key is known to that process. This is one clear advantage over any other method. Also, within the shared area the processes enjoy random access for the stored information. This is a major reason why shared memory access is considered efficient. In addition, shared memory can support many-to-many communication quite easily.

8.10.3

Message-Based Interprocess Communication

Messages are a very general form of communication. Messages can be used to send and receive formatted data streams between arbitrary processes. The type of messages helps in message interpretation. The type may specify appropriate permissions for processes. Usually at the receiver end, messages are put in a queue. Messages may also be formatted in their structure. This again is determined by the application process. Messages are also the choice for many parallel computers such as Intel’s hyper-cube. The following four system calls achieve message transfers amongst processes. 1. msgget() returns (and possibly creates) message descriptor(s) to designate a message queue for use in other systems calls; 2. msgctl() has options to set and return parameters associated with a message descriptor. It also has an option to remove descriptors; 3. msgsnd() sends a message using a message queue; 4. msgrcv() receives a message using a message queue. The syntax of the system call msgget() is as follows: int msgget(key_t key, int flag); The msgget()system call has one primary argument, the key, a second argument which is a flag. It returns an integer called a qid which is the id of a queue. The returned qid is an index to the kernel’s message queue data-structure table. The call returns, if there is an error. This call gets the resource, a message queue. The first argument key_t, is defined in sys/types.h file as being a long. The second argument uses the following flags: 1. MSG_R : The process has read permission; 2. MSG_W : The process has write permission; 3. MSG_RWAIT : A reader is waiting to read a message from message queue; 4. MSG_WWAIT : A writer is waiting towrite a message to message queue; 5. MSD_LOCKED : The msg queue is locked; 6. MSG_LOCKWAIT : The msg queue is waiting for a lock; 7. IPC_NOWAIT : Interprocess communication does not waite; 8. IPC_EXCL : In most cases these options can be used in bit-ored manner. It is important to have the readers and writers of a message identify the relevant queue for message exchange.

8.32

Embedded Systems: Design, Programming and Applications

This is done by associating and using the correct qid or key. The key can be kept relatively private between processes by using a makekey()function (also used for data encryption). For simple programs it is probably sufficient to use the process id of the creator process (assuming that other processes wishing to access the queue know it). Usually, kernel uses some algorithm to translate the key into qid. The access permissions for the IPC methods are stored in IPC permissions structure which is a simple table. Entries in kernel’s message queue data structures are C structures. These resemble tables and have several fields to describe permissions, size of queue, and other information. The message queue data structure is as follows. struct meqid_ds { struct ipc_perm meg_perm; struct msg *msg_first; struct msg *msg_last; ushort msg_cbytes; ushort msg_qnum; ushort msg_qbytes; ushort msg_lspid; ushort msg_lrpid; time_t msg_stime; time_t msg_rtime; time_t msg_ctime;

/* permission structure */ /* pointer to first message */ /* ........... last ..........*/ /* no. of bytes in queue */ /* no. of messages on queue */ /* Max. no. of bytes on queue */ /* pid of last msgsnd */ /* pid of the last msgrcv */ /* last msgsnd time */ /* .....msgrcv................*/ /* last change time */

} There is one message structure for each message that may be in the system. struct msg { struct msg *msg_next; /* pointer to next message */ long msg_type; /* message type */ ushort msg_ts; /* message text size */ ushort msg_spot; /* internal address */ It is noted that several processes may send messages to the same message queue. The type of message is used to determine which process amongst the processes is the originator of the message received by some other process. This can be done by hard coding a particular number for type or using process-id of the sender as the msg_type. The msgctl() function call is a system call which enables following three basic actions. 1. The first action allows a user to remove message queue data structure from the kernel; 2. The second action allows a user to examine the contents of a message queue data structure by copying them into a buffer in user’s data area;

Interprocess Communication

8.33

3. The third action allows a userto set the contents of a message queue data structure in the kernel by copying them from a buffer in the user’s data area. The system call has the following syntax. int msgctl(int qid, int command, struct msqid_ds *ptr); This system call is used to control a message queue). The first argument is the qid which is assumed to exist before call to msgctl(). Otherwise the system is in error state. Note that if msgget() and msgctl() are called by two different processes then there is a potential for a \race” condition to occur. The second argument command is an integer which must be one of the constants, defined in the header file sys/msg.h.

IPC STAT This command places the contents of the kernel structure indexed by the first argument, qid, into a data structure pointed to by the third argument, ptr. This enables the user to examine and change the contents of a copy of the kernel’s data structure, as this is in user space. IPC SET command places the contents of the data structures in user space pointed to by the third argument, ptr, into the kernel’s data structure indexed by first argument qid, thus enabling a user to change the contents of the kernel’s data structure.

IPC RMID IPC RMID command removes the kernel data structure entry indexed by qid. The msgsnd() and msgrcv() system calls have the following syntax. int msgsnd(int qid, struct msgbuf *msg_ptr, int message_size, int flag ); int msgrcv(int qid, struct msgbuf *msg_ptr, int message_size, int msgtype, int flag ); Both of these calls operate on a message queue by sending and receiving messages respectively. The first three arguments are the same for both of these functions. The syntax of the buffer structure is as follows. struct msgbuf{ long mtype; char mtext[1]; } This captures the message type and text. The flags specify the actions to be taken if the queue is full, or if the total number of messages on all the message queues exceeds a prescribed limit. With the flags the following actions take place. If IPC_NOWAIT is set, no message is sent and the calling process returns without any error action. If IPC_NOWAIT is set to 0, then the calling process suspends until any of the following two events occur. 1. A message is removed from this or from other queue. 2. The queue is removed by another process. If the message data structure indexed by qid is removed when the flag argument is 0, an error occurs (msgsnd() returns -1). The fourth arg to msgrcv() is a message type. It is a long integer. The type argument is used as follows.

8.34

Embedded Systems: Design, Programming and Applications

1. If the value is 0, the first message on the queue is received; 2. If the value is positive, the queue is scanned till the first message of this type is received. The pointer is then set to the first message of the queue. If the value is -ve, the message queue is scanned to find the first message with a type whose value is less than, or equal to, this argument. The flags in the msgrcv() are treated the same way as for msgsnd(). A successful execution of either msgsnd(), or msgrcv() always updates the appropriate entries in msgid_ds data structure. With the above explanation, let us examine the message passing program which follows. #include #include #include main(argc, argv) int argc; char *argv[]; { int status, pid, pid1; if (( pid=fork())==0) execlp(“./messender”, “messender”, argv[1], argv[2], 0); if (( pid1=fork())==0) execlp(“./mesrec”, “mesrec”, argv[1], 0); wait(&status); /* wait for some child to terminate */ wait(&status); /* wait for some child to terminate */ }

Message Sender Program #include #include #include main(argc, argv) int argc; char *argv /* This is the sender. It sends messages using IPC system V messages queues.*/ /* It takes two arguments : */ /* No. of messages and no. of bytes */ /* key_t MSGKEY = 100; */ /* struct msgformat {long mtype; int mpid; char mtext[256]} msg; */ { key_t MSGKEY = 100; struct msgformat { long mtype; int mpid; char mtext[256];

Interprocess Communication

8.35

} msg; int i ; int msgid; int loop, bytes; extern cleanup(); loop = atoi(argv[1]); bytes = atoi(argv[2]); printf(“In the sender child \n”); for ( i = 0; i < bytes; i++ ) msg.mtext[i] = ‘m’; printf(“the number of ‘m’ s is : %6d \n”, i); msgid = msgget(MSGKEY, 0660 | IPC_CREAT); msg.mtype = 1; msg.mpid = getpid(); /* Send number of messages specified by user argument */ for (i=0; i