ES

You might also like

Download as pdf
Download as pdf
You are on page 1of 311
A. P. Godse A. O. Mulani @ Embedded Systems {SBN 9788184317138 ‘A rights reserved with Technical Publications. No pat of this book should be reproduced in any form, Electronic, Mechanical, Photocopy o° any information storage and retrieval sysiem without prior permission in writing, from Tachrical Publications, Pure. Published by = ‘Technical Publications Pune” #1, Ait Residency, 412, ShasiwerPth, Pure - 411 030, Inc Printed at: VIKRAM PRINTERS PVT, LTD Pune Satara ous Pure 41 608 Table of Contents : Embedded Computing (1-1) to (1-30) Chapter-4 Chapter-2 The ANS4 Architecture (2-4) to (2-36) Chapter-3 Assembly Language Programming and Instruction Set of 8051 {3 - 1) to (3 - 92) Chapter-4 8051 Timer Serial Communication and Interrupt Programming in Assembly _(4 - 1) to (4-40) Chapter-5 Applications : Interfacing 8051 to External World (6- 1) to (5 - 102) Chapter-6 Introduction to Real-Time Operating Systems (6-1) to (6 - 20) | Chapter-7 Basic Design using a RTOS (7-1) to (7-12) Chapter-8 Introduction to Advanced Architectures (8-1) to (8-28) CAEL Ee: | Syllabus : (Embedded Systems) UNIT -I (Chapter - 1) Embedded Computing : Introduction, Complex systems and_microprocessor, The embedded system design process, Formalisms for system design, Design examples. UNIT - If (Chapter - 2) ‘The 8051 Architecture : Introduction, 8051 microcontroller hardware, Input/output ports and circuits, External memory, Counter and timers, Serial data input/output, Interrupts. UNIT - U1 (Chapters - 3 and 4) “ Basic Assembly Language Programming Concepts : The assembly language programming process, Programming tools and techniques, Programming the 6051, Data transfer and logical instructions. UNIT -1V (Chapters -3 and 4) Arithmetic operations, Decimal arithmetic, Jump and call instructions, Further details on interrupts. UNIT - V (Chapter -5) Applications : Interfacing with keyboards, Displays, D/A and A/D conversions, Multiple interrupts, Serial data communication. UNIT - VI_(Chapter - 6) Introduction to Real - Time Operating Systems : Tasks and task states, Tasks and data, Semaphores, and shared data; Message queues, Mailboxes and pipes, Timer functions, Events, Memory management, Intrrupt routines in an RTOS environment. UNIT - VII (Chapter -7) Basic Design using a Real-Time Operating System : Principles, Semaphores and queues, Hard real-time scheduling considerations, Saving memory and power, An example RTOS like uC-OS (Open source); Embedded software development Tools: Host and target machines, Linker/Locators for embedded software; Getting embedded software into the target system. Debugging techniques : Testing on host machine, Using laboratory tools, An example system. UNIT - VHT (Chapter - 8) Introduction to Advanced Architectures : ARM and SHARC, Processor and memory organization and instruction level parallelism; Networked embedded systems : Bus protocols, 12 C bus and CAN bus, Internet-enabled systems, Design example-elevator controller. SL a ee Copyrighted material Table of Contents (Detail) 1.1 Introduction... 1.2 Complex Systems and Microprocessors. 1.2.1 Embedding Computers. 1.2.1.1 Processor Embedded into a System... . 1.2.2 Characteristics of Embedded System Applications . . 1.3 Embedded System Design Process 1.4 Formalisms for System Design 1.4.1 Structural Description. . 14.1.4 Class Diagram... 1.4.1.2 Object Diagram... 1.4.2 Behavioral Description . . 1.4.2.4 Sequence Diagram ._. 1.5 Design Example ... 1.5.1 Model Train Controller . Review Questions... 1-19 2.2 Features of 8051 .. 2.3 8051 Microcontroller Hardware 2.3.1 Pin-out of 8051 2.3.2 Central Processing Unit (CPU) 2.3.3 Intemal RAM. 2.3.4 Intermal ROM . 2.3.5 Input/Output Ports . . 2.3.6 Register Set of 8051 2.3.6.1 Register A (Accumulator)... LAE LA ET 236.2RegsterB 2... ew. an 2.38.3 Program Status Word ra Fa Register) 1.4 2 Sy 2.36.5 DataPointer(DPTR) . . .. « 2.366 Program Counter... 2.38.7 Special Function Registers... 2.4 Memory Organization in 8051 ... 2.5 Input/Output Pins, Ports and Circuits 2.6 Timers and Counters .. 2.6.1 Timer/Counter Control Logic. 26.2 Timer O and Timer 1. 2.7 Serial Port... 2.7.1 Operating Modes for Serial Por. 2.7.2 Serial Port Control Register .. 2.7.3 Generating Baud Rates 2.8 Interrupt Structure .. 2.8.1 Priority Level Structure 2.8.2 External Interrupts 2.8.3 Single-Step Operation . 2.9 Clock and Oscillator... 2.10 Power Saving Options 2.10.1 Idle Mode 2.40.2 Power Down Mode . 2.11 Multiprocessor Communication in MCS-51 Review Questions Cha ter - 3 Assembly Language Pro. rammin ani Instruction Set of 8051 3.1 Introduction .... 3.44 Steps Involved in Programming 3.1.2 Flow Chart 3.4.3 Languages used for Programming... 3.1.3.1 Machine Language 3. BEI Se pay g ggg 3-3 Se AEE RE SaaS EEA .2 Assembly Language 34.33 High-Level Language 6. eee 3.1.3.4 Comparison between Programming Languages. 3.2 Addressing Modes and Instruction Set 3.3 Addressing Modes... 3.4 Data Moving (Data Transfer) Instructions . 3.4.1 Instructions to Access Extemal Data Memory 3.4.2 Instructions to Access External ROM / Program Memory . 3.4.3 PUSH and POP Instuctions........... 3.43. PUSH . 34.32 POP. . 3.4.4 Data Exchange Instructions 3.5 Logical Instructions ... 3.5.1 Byte Level Logical Operations. 3.5.2 Bit Level Logical Operations . 3.5.3 Rotate and Swap Operations 3.6 Arithmetic Instructions. 36.4 Flags ......s..0 : 3.6.2 Incrementing and Decrementing . 3.6.3 Addition... 3.6.4 Subtraction... m 3.6.5 Multiplication and Division . 3.6.6 Decimal Arithmetic. 3.7 Jump and CALL Instructions. 3.7.1 Jump and Call Program Range... 3-51 3.7.3 CALL and Subroutines 3.8 Programming Examples... Review Questions . Chapter = 4 8051 Timer Serial Communication and wee . Interrupt Programming in Assembly. (4-1) to (4-40) 4.1 8051 Timers 4.1.1 Timer Registers 4.1.2 Programming 8051 Timers . le litt cs OORT 4AQAModeD 4.1.22 Mode 1 CRD) eae an io 4.4.24 Mode 3. 4.1.3 Loading Timer Registers 4.2 Programming Counters. 4.3 Serial Communication... 43.12Simplex ... se wee . 4-13 WAT SHMODEE. 65, eee ees a oe oe sere wi od vo NE. 43.14 Full Duplex An 14 4.3.2 8051 Connections to RS 2326 4.3.3 8051 Serial Communication Programming 43.3.1 Operating Modes for Serial Port . 43.3.2 SBUF ae 4.3.33 Serial Port Control Register. 43.34 GoneratingBaudRates. 43.35 Programming 6051 for Serid Data Transfer... . whos ga Ba 4-24 4.3.3.6 Programming 8051 for Recelving Serial Data. . 43.37 Doubling the Baud Rate in the 8054 4.3.4 Programming the Second Serial Port. 43.4.4 Addresses for all SCON and SBUF Registers. Parner arene er 2 4-29 4.3.4.2 Programming the Second Serial Port using Timer 1 5 4-29 43.43 More Examples... . 4.4 Interrupt Programming .. 4.4.1 8051 Interrupts ...... 4.4.2 Interrupt Vector Table 4.43 Enabling and Disabling an Interrupt . 4.44 Programming Timer Interrupts... . 4,45 Programming External Hardware Interrupts... . . interrupis BN 4-32 4-32 woe 4-33 2. 4-33 4-8 44.7 Interrupt Priority in the 8051/52 . - 4-38 4.4.7.1 Nested Interupts. .. . « : + 4-39 4.4.1.2 Software Triggering of interupt . 4-39 Review Questions ...... 4-39 5.1 Introduction .....:ssssssee 5.2 External RAM and ROM 5.2.1 Program Memory ..... 5.2.2 Data Memory §.2.3 Important Points to Remember in Accessing Extemal Memory 5.2.4 Memory Interfacing. . 5.2.5 Interfacing Example . 5.3 Interfacing Keyboard... 5.3.1 Key Debounce using Hardware . 5.3.2 Key Debouncing using Software a 5.3.3 Simple Keyboard interface... oso. eee tee ee ee ees ee se setts ees 5.3.4 Matrix Keyboard Interface 5.4 Interfacing Display 5.4.1 LED Displays . 54.2 Interfacing LED Displays 5-1 5-4 5.5 Interfacing LCD Display 5.6 Interfacing DAC to 805 58.1 IC DAC 1408 . cesses 5-33 5.6.1.1 Important Electrical Characteristics for IC 1408 . 5-37 5.6.2 Interfacing DAC 1408 / DAC 0808 with 8051 5.7 Interfacing ADC to 805 5.7.1 ADC 0804 Famiy... 5.7.2 ADC 0808/0809 Family ..... 5.7.3 Interfacing of ADC 0803/0804/0805 with 8051. 5.7.4 Sensor Interfacing - Practical Application. 5.7.5 Interfacing of ADC 0844/0848 é 5.7.6 Serial ADC Chip MAX1112/ MAX1113..... 0 sss se seston eee eee eeeeee sree PSE aa 5.8 Stepper Motor Interface 5.9 DC Motor Interfacing 5.9.1 Pulse Width Modulation (PWM)...... 5.9.2 DC Motor Control with Optoisolator . 5.10 Interfacing Examples... 5.11 Multiple Interrupts 5.12 I/O Expansion using 8255. 5.12.1 8255 Programmable Peripheral Interface (PPI) 5.1244 Features of 8255A . 2.6... 5.124.2Pin Description... 2... . 5.121.3 Block Diagram . 5.12.1.4 Operation Modes 5.121.5 Control Word Formats. 5.12.2 Connecting the 8031/51 to 8255 5.12.3 8031 System with 8255 .... 5.12.4 Typical MCS-51 Based System 5.12.5 8255 Interfacing .......... 5.125.1 Stepper Motor Interfacing using 8255... siesta SAS ZLCU inentdolh MENG EI oe sees ces eee es 5.125.3 ADC Interfacing using 8255... . 5.12.6 Interfacing Examples ........ Review Questions... 6.1 Introduction 6.2 Tasks and Task States 6.3 Tasks and Data...... 6.4 Semaphores and Shared Data 6.4.1 Counting Semaphore 6.4.2 Multiple Semaphores 6.4.3 Binary Semaphore .. 6.4.4 Semaphores as a Signalling Device 6.4.5 Semaphore Problems. 6.5 Priority Inversion 6.6 Message Queues... 6.7 Mailboxes... 6.8 Pipes....... 6.9 Timer Functions 6.10 Event: 6.11 Memory Management 6.12 Interrupt Routines in an RTOS Environment 6.13 Comparison of the Methods for Intertask Communication 6.14 Comparison of the Three Methods of Protecting Shared Data. Review Questions... 7.4 Principles ce wo 7.2 Encapsulating Semaphores and Queues “ 7.3 Hard Real Time Considerations 7.4 Saving Memory Space 7.5 Saving Power .. 7.6 Micro C/OS-I1.... 7.7 Embedded Software Development Tools . 7.7.4 Host and Target Machines 7.8 Getting Embedded Software into the Target system 7.8.1 PROM Programmers 7.8.2 ROM Emulators . 7.8.3 Incircuit Emulator 7.84 Flash. 7.8.5 Monitors: 7.9 Debugging Techniques... 7.9.4 Testing on Host Machine . 7.9.2 Using Laboratory Tools .. Review Questions..... Ghapter=8 Introduction 8.1 Introduction 8.2 ARM Processor (Advanced | RISC Machine Processor) 8.2.1 Processor and Memory Organization 8.2.2 Programming Model... 8.2.3 ARM Instruction Set . . 8.2.4 Computing an Absolute Address using PC 8.3 SHARC Processor... 8.3.1 Memory Organization . 8.3.3 Instruction Level Parallelism (et) 8.4 Networked Embedded Systems...... 8.4.1 Bus Protocols 8.4.21°C Bus (Inter Integrated Circuit Bus) . 8.4.3 CAN Bus (Controller Area Network Bus) 8.5 Internet Enabled Systems ............ Review Questions Embedded Computing 1.1 Introduction Embedded systems are playing an important roles in our lives every day. Embedded systems are everywhere - homes, offices, cars, factories, hospitals and consumer electronics. Some of the embedded systems we use every day - control the menu system on TV, the timer in a microwave oven, a cellphone, an MP3 player or any other device with some amount of intelligence built-in. All of these have wide ranging impacts on society including security, privacy and modes of working and living. More than 98 % of processors applied today are in embedded systems and are no longer visible to the customer as ‘computers’ in the ordinary sense. New processors and methods of processing, sensors, actuators, communications and infrastructures are enablers for this very pervasive computing. They are almost invisible to the user and almost omnipresent. As such, they form the basis for a significant economic push. 1.2 Complex Systems and Microprocessors Embedded computer system is a physical system that employs computer control for a specific purpose rather than for general purpose computation. OR Embedded system is a special-purpose computer system designed to perform one or few dedicated functions. Since, the embedded system is dedicated to perform specific tasks, design engineers can optimize it, reducing the size and cost of the product or increasing the reliability and performance. Application areas : 1) Automotive electronics 6) Military applications 2) Aircraft electronics * ‘Authentication 3) Trains 8) Consumer electronics 4) Telecommunication 9) Fabrication equipment 5) Medical systems 10) Robotics (1-4) Embedded Systems 1-2 Embedded Computing Examples of Embedded Systems : Embedded systems have very diversified applications. A few examples of embedded system applications are as follows : i) Digital camera : A digital camera is a popular consumer electronic device that can capture images or take pictures and store them in a digital format. A digital camera is the best example of Embedded system being very widely used all over the world. It includes a powerful processor capable of handling complex signal processing operations because image capturing, storing and displaying is involved. Fig. 1.1 shows a general block diagram of a digital camera. - Optical sensors Lens ‘Computer interface ToPc User switches Image storage System controller Fig. 1.1 General block diagram of digital camera In a digital camera, an array of optical sensor is used to capture images. ‘These sensors are the photodiodes which convert light intensity into electrical voltage. Charge-Coupled Devices (CCD) is a special type of sensor which can give high quality images. 2. An image is made up of picture elements (pixels) of different luminance and chrominance. The number of pixels in a picture determine the quality of the picture, which is called resolution of the image. More the number of pixels, higher is the resolution and better is the quality. Each sensing element generates a charge that corresponds to one pixel. Since, the charge is analog quantity, it is converted into digital form using ADC. Embedded Systems 1-3 Embedded Computing 3. After ADC, a digital representation of an image is obtained. The colour and intensity of each pixel is represented by number of bits. The digitized image is now considered as a two dimensional matrix having p x q pixels and each pixel is given a equivalent decimal or hexadecimal number. 4. The important functional block of a digital camera is the system controller. System controller consists of a processor, memory and different interface circuitry t6 connect to other parts of the system. Processor processes the digitized image data to generate images represented in standard formats suitable for use in computers, printers and display devices. Processing tasks performed on an image are : brightness modification, contrast stretching, smoothing, sharpening etc. For compressed images, the format is called JPEG (Qoint Photographic Experts Group) while for uncompressed images, the format used in BMP (Bit Mapped) or TIFF (Tagged Image File Format). 5. The processed images are stored in Image storage device. Flash memory cards, floppy disks or miniature hard drives can be used for this purpose. The number of images that can be taken and saved depends on the capacity of image storage device. It also depends on the resolution of the image. Higher resolution image takes more memory space because the number of pixels are more. An uncompressed image takes more memory space than a compressed image. 6. The image is displayed on a LCD screen in the camera. The LCD display normally consumes more power than the processor. 7. A standard computer interface provides a mechanism for transferring images to a computer or a printer. This interface may be serial or parallel interface or a connector for a standard bus such as PCI or USB. If flash cards are used, images can be transferred by physically removing the card and inserting into the slot of the computer. 8. There are some other electromechanical parts such as switches to be operated by the user, motor to rotate the camera for focussing purposes etc. The system controller must be capable generating signals to co-ordinate and control all such activities. ii) Microwave oven : Microwave oven is based on a magnetron unit, which generates microwaves used to heat food in a confined space. When turned ON, magnetron generates its maximum power output. Lower power levels can be obtained by turning the magnetron: ON and OFF for controlled time intervals. User can have many options for cooking different dishes using power levels and heating time. Microwave oven should produce an audio alert signal when cooking operation is completed. It should have an exhaust fan and a light bulb inside. A switch should be Embedded Systems 1-4 Embedded Computing provided, which turns the magnetron OFF when the door of the oven is open. All these functions can be controlled by the controller or processor. Microwave oven needs some input/output capability to communicate with the user. These are 1. Input keys : Consisting of a number pad having digits 0 to 9 for selecting time etc. and function keys such as reset, start, stop, auto defrost, clock set, autocooking, fan control etc, Some of the functions can be multiplexed to reduce the total number of keys to be provided. 2. Visual output in the form of LCD display. 3. A small speaker that produces the beep tone. Fig. 12 shows a simple block diagram of microwave oven. Embedded processor Bus Speake , Fig. 1.2 Block diagram of microwave oven In microwave oven, a simple microprocessor with small RAM and ROM units is sufficient. The various operations performed by processor include : maintaining the time-of-day clock, determining the actions required in various cooking options, decrementing timer/counter, generating display information and activating control signals to turn ON or OFF devices such as magnetron and fan. The routine needed for this is small and it can be stored in ROM, which is non-volatile. The system includes a smail RAM to hold the user entered data which can be using during computations. The main requirement of the system is to have good input/output capability to deal with all the devices like keys, displays, speaker etc. Parallel input/output ports can be used to deal with external input and output signals. The total system design is simple and cost effective. Embedded Systems 1-5 Embedded Computing Home telemetry : Telemetry deals with accessing and controlling the devices located at a distance from the control station. Home telemetry is a home automation system which can be used to provide remote access to the devices in the house using a display telephone. In addition to standard telephone features, a processor controlled telephone can be used to provide remote access to other devices in the home that can communicate as computer. Using this type of telephone, various functions can be performed from remote area. Some of the functions are = 1. Communicating with 2 computer controlled home security system. 2. Monitoring and controlling the activities of various electronic in the house. 3. Setting a desirable temperature for an air conditioner to maintain. 4. Setting the start time, cooking time and temperature for food that has been placed in the oven earlier. 5. Reading the electricity and water meters. Such functions can be implemented by providing a link between device processor and processor in the telephone. The links can be provided as a simple bit-serial communication, if the processor includes a UART interface or USB interface. Fig. 1.3 shows the general block diagram of home telemetry. Embedded processor Display —--- Air conditioner tehite Door locking system Fig. 1.3 General structure of home telemetry Design issues : ‘The constraints in an 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 economic as well as technical considerations. Embedded Systems 1-6 Embedded Computing Design metrics : ‘A design metric is a measurable feature of the system's performance, cost, time for implementation and safety etc. Design metrics typically compete with one another : Improving one often leads to worsening of another. e.g. If the implementation's size is reduced, the implementation's performance may suffer. Power 1 Performance size Fig. 1.4 Design metric competition.improving one may worsen others Following design metrics are generally taken into account while designing an embedded systems. i) NRE (Non-recurring Engineering) cost : It is the one-time monetary 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 name non-recurring. Suppose three technologies are available for use in a particular product. Assume that implementing the product using technology A would result in an NRE cost of $1500 and unit cost of $ 100, technology B would have an NRE cost of $ 2500 and unit cost of § 30 and technology C would have an NRE cost of $ 90,000 and unit cost of $2. Ignoring all other design metrics like time-to-market, the best technology choice will depend on the number of units we plan to produce ii) Unit cost : It is the monetary cost of manufacturing each copy of the system, excluding NRE cost. Embedded Systems 1-7 Embedded Computing ill) Size : It is the physical space required by the eystem, often measured in bytes for software and gates or transistors for hardware. iv) Performance : . It is the execution time of the system. v) 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 IC, since more power means more heat. vi) Flexibility : ~ It is the ability to change the functionality of the system without incurring heavy NRE cost. Typically software is considered very flexible. vii) Time-to-prototype : It is the time needed to build a working version of the system, which may be bigger or more expensive than the final system implementation, but it can be used to verify the system's usefulness and correctness and to refine the system's functionality. vil) Time-to-market It is the time required to develop a system to the point that it can be released and sold to customers. This design metric has become especially demanding in. recent years. Introducing an embedded system to the marketplace early can make a big difference in the system's profitability. The main contributors are design time, manufacturing time and testing time. It is the ability to modify the system after its initial release, especially by designers who did not originally design the system. x) Correctness It is the measure of the confidence that we have implemented the system's functionality correctly. The functionality can be checked throughout the process of designing the system and test circuitry can be inserted to check that manufacturing was correct. xi) Safety ; It is the probability that the system will not cause harm. Embedded Systems 1-8 . Embedded Computing Classification of embedded systems : Embedded systems can be classified into three types as follows : 1. Small-scale embedded systems : Small-scale embedded systems are designed with a single 8 or 16-bit microcontroller. They have little hardware and software complexities and involve board level design. 2. Medium-scale embedded systems : Medium-scale embedded systems are usually designed with a single or a few 16 or 32-bit microcontrollers, DSPs or RISCs. They have both hardware and software complexities. 3. Sophisticated embedded systems : Sophisticated embedded systems are designed with several ASIPs (Application Specific Instruction set processors, scalable processors or configurable processors and PLAs (Programmable Logic Arrays). They have enormous hardware and software complexities. 1.2.1 Embedding Computers Computers have been embedded into applications since the earliest days of computing. Computer is a system that has following components : Processor 2. Large memory (primary and secondary) 3.1/0 units such as modem, touch screen etc. 4, Input units such as keyboard, mouse etc. 5. Output units such as monitor, printer etc. 6. Operating system that has general purpose user and application software in the Secondary memory. 7. Networking units such as ethernet card, bus drivers etc. Embedded system is a system that has three main components embedded into it : 1. It embeds hardware. Fig. 1.5 shows the units in the hardware of an embedded system. The inputs to the system usually take the form of sensors and probes, communication signals or control knobs and buttons. The cutputs are typically displays, communication |"! == signals or changes to the physical world. Processor (—> Outputs Fig. 1.5 Components of embedded system hardware Embedded Systems 1-9 Embedded Computing 2. It embeds main application software. The application software may concurrently perform a series of tasks or processes or threads. 3. It embeds a real time operating system that supervises the application software running on hardware and organizes access to a resource according to the priorities of tasks in the system. 1.2.1.1 Processor Embedded into a System A processor is an important unit in the hardware of embedded system. It is the heart of embedded system. Processor technology relates to the architecture of the computation engine used to implement a system's desired functionality. Embedded system processor can be one of the following : 4. General Purpose Processors (GPP) GPP is a processor with instruction set designed not specific to the applications. Microprocessor is a well known type of GPP. Using a GPP in an embedded system may result in several design benefits. Flexibility is high because changing functionality requires changing only the program. Time to market would be low and unit cost would be low in small quantities compared to designing your own processors, Performance may not be as great for some more computation intensive applications. 2. Single Purpose Processor A single purpose processor is a digital circuit designed to execute exactly one program. Some of the examples of single purpose processor are coprocessor, controllers ete. Using a single purpose processor in an embedded system results in several design metric benefits. Performance may be fast, size and power may be small and unit cost may be low for large quantities. 3. Application Specific Instruction Set Processor (ASIP) An ASIP is a processor with an instruction set designed for specific application Microcontrollers and digital signal processors are two well known types of ASIPs that have been used for several decades. Using an ASIP in an embedded system can provide the benefit of flexibility while still achieving good performance, power and size. 1.2.2 Characteristics of Embedded System Applications Embedded systems generally exhibit rich functionality-complex functionality is usually the reason for introducing CPU in the design. Following are some of the characteristics of embedded systems : Embedded Systems 1-10 Embedded Computing L Single function : An embedded system usually executes a specific program repeatedly. 2. Tightly constrained : All computing systems have constraints on design metrics, but these constraints can be extremely tight on embedded systems. » Reactive and real time : An embedded system must continually react to the changes in the system's-environment and must compute certain results in real time without delay. e . Device programmability : The functioning of specific hardware part on a smart device can be easily changed by simply changing the software associated with it. wn . Multirate operation : Embedded systems have several real-time activities going on at the same time. They may simultaneously control different operations running at distinct rates. 6. Low power consumption. 7. Low manufacturing cost which often means limited code size. 1.3 Embedded System Design Process An embedded system is designed keeping in view three constraints : 1. Available system memory. 2. Available processor speed. 3. Need to limit power dissipation when running the system continuously in cycles of wait, run, stop, wake-up and sleep. There are two approaches of embedded system design process : namely bottom-up design and top-down design. In bottom-up design, we start with components to build a system. In top-down design, we start with abstraction of the system and then the details are created. There are basically five steps which describe every design problem, be it mathematical, physical, engineering or any other. These steps are : 1, Requirement definition 2. System specification 3. System architecture development 4. Components 5. System integration Embedded Systems 1-11 Embedded Computing \ Bottom-up Top-down ey design ‘System integration Fig. 1.6 Embedded system design process Requirements Requirement is the process of gathering an informal description from the customers. At this stage, the product can be viewed as a black box. What happens inside is unimportant ? Requirements may be functional or non-functional. The designer must capture the basic functions of the embedded system, but functional description is not sufficient. Non-functional requirements include : 1. Performance : The instruction execution time or throughput of the system. 2. Cost : Cost has typically two major components : i) Manufacturing cost : The cost of components and assembly. ii) Non-recurring engineering cost : The monetary cost of designing the system. 3. Size : The physical space required by the system, often measured in bytes for software and gates or transistors for hardware. 4. Power consumption : The amount of power consumed by the system, which determines the lifetime of a battery. Specifications Specifications need to be more precise. Specifications guide customer expectations from the product. They also guide system architecture. Designer needs specifications for hardware specifications, data types and processing specifications, system behaviour Embedded Systems 41-12 Embedded Computing specifications, design constraints, life cycle specifications. Process specifications are analyzed by making lists of inputs, outputs and how the processes activate on each input. Architecture Specification only describes what the system does while architecture describes how the system implements those functions. Architecture is a plan for overall system structure that will be used to design the components that make the architecture. Components ‘The architectural description gives us the idea about the required components. Basically, there are two types of components namely hardware and software. Common hardware components are processor, memory, peripherals and devices, ports and buses and battery in the system. During software development process, components can be modelled as object oriented software. System Integration : After the components are built, they are integrated in the system. But. after integration, these components may not fulfil the design metrics. The system is made to function and validated by choosing appropriate tests. Debugging tools are used to correct the erroneous functioning. 1.4 Formalisms for System Design There are different design tasks at different levels of abstraction ‘which can be conceptualized in diagrams. Unified Modelling Language (UML) is a textual and graphical notation i.e. language, used to quantify and formalize our understanding of systems. UML has its roots in a branch of computer software development industry known as Object Oriented Analysis and Design (OOA&D) but has applications beyond this field-especially in the field of understanding and documenting business processes. Goals of UML The primary goals in the design of UML were : 1. Provide users with a ready-to-use, expressive visual modelling language so that they can develop and exchange meaningful models. 2. Provide extensibility and specialization mechanisms to extend the core concepts. 3. Be independent of particular programming languages and development processes. 4. Provide a formal basis for understanding the modelling language. Embedded Systems 1-13 Embedded Computing 5. Support higher level development concepts such as _ collaborations, frameworks, patterns and components. 6. Integrate best practices. 1.4.1 Structural Description Structural description mean basic components of the system. 1441.4 Class Diagram A dlass diagram is a diagram showing a collection of classes and interfaces, along, with the collaborations and relationships among classes and interfaces. A class diagram is a pictorial representation of detailed system design. Design experts who understand the rules of modelling and designing systems design the system's class diagrams. A class diagram is composed primarily of following elements that represent the system's entities : a, Class : ‘A dlass represents an entity of a given system that provides an encapsulated implementation of certain functionality of a given entity. These are exposed by the class to other classes as methods. The properties of a class are called attributes. A class is represented by a rectangle. ‘The class name typically has the first alphabet capitalized e.g. Student Attributes! {-— 4 2g. studentld : int OR Variables studentName : string }+— [Alist of methods goes in here. eg. string get student Name (int stucentiD) List of ft list of attributes of class goes in here. Fig. 1.7 Structure of a class b. Interface : An interface is a variation of class. An interface provides only a definition of business functionality of a system. A separate class implements the actual business functionality. c. Package : A package provides the ability to group together classes and/or interfaces that are either similar in nature or related. Grouping these design elements in a package element provides for better readability of class diagrams, especially complex class diagrams. Embedded Systems 1-14 | Embedded Computing 1.4.1.2 Object Diagram ‘An object diagram is a pictorial representation of the relationships between instantiated classes at any point of time (called objects). A dass diagram for multiplicity relation between college and students is as shown below : Fig. 1.8 An example college-student class diagram This class diagram shows that many students can study in a college. If we were to add attributes to the classes “college” and "student", then it would be as shown below. univName : string nameOfStudent : string neOfCourse : int studentid : int capacity : int age :int argaName : string es Fig. 1.9 Class diagram with attributes Now, when an application with class diagram as shown above is run, instances of college and student class will be created with values of attributes initialized. The object diagram for such scenario will be as represented below : nemeOiStudent : "Sachin* studentid = 1 age =21 College student no.2: Student univName : "NTU" noO {Course = 10 capacty = 6000 areaName : "Hyderabad" nameOfStudent : “Alvia” studentid = 2 age = 20 Fig. 1.10 Object diagram for college-student class diagram Embedded Systems 1-15 Embedded Computing As shown in Fig, 1.10, the object diagram shows how objects are instantiated in the running system represented by college-student class diagram. The class diagram shows that a college has many students and defines the variables. The object diagram for the same system shows instantiated classes of student (student #1 and student #2) enrolled in college (Graduate School of Engineering). The object diagram shows the name of the instantiated object, separated from class name by ":" and underlined to show an instantiation. e.g. Graduate School of Engineering : College In the diagram, values are assigned to variables and represented using notation : variable name = variable value There are several types of relationships that can exist between objects and classes : 1. Association : When two classes are connected to each other in any way, an association relation is established. - coiese |Site [_swcen ] 2. Aggregation : When a complex class is formed as a collection of smaller classes, it is called an aggregation relation between these classes. [ammo 3. Composition : It is a type of aggregation in which the owner does not allow access to component class. [eee jo ——— rer] 4, Inheritance / Generalization : It is the basic type of relation used to define reusable elements in class diagram. Embedded Systems . 1-16 Embedded Computing 1.4.2 Behavioral Description State machine is used to specify the behaviour of the system. A state machine (diagram) consists of following behavioural elements : i) Initial state : This shows the starting point or first activity of the flow. This is also called a pseudo state, where the state has no variables describing it further and no activities. Symbol of initial state is @ ii) State : Represents the state of object at an instant of time. In a state diagram, there will be multiple of such symbols, one for each state of object. Symbol of state is : ‘State Name ‘State Variables ‘Action iii) Transition : An arrow indicating the object to transition from one state to other. The actual trigger event and action causing the transition are written beside the arrow separated by a slash. Transitions that occur because the state completed an activity are called “triggerless” transitions. If an event has to occur after the completion of some event or action, the event or action is called the guard condition. The transition takes place after the guard condition occurs. ~ Symbol is : Event / Action iv) History states : A flow may require that the object go into a trance, or wait state, and on the occurrence of a certain event, go back to the state it was in when it went into a wait state - its last active state. Symbolis: — @ v) Event and action : A trigger that causes a transition to occur is called as an event or action. Symbelig Event / Action vi) Signal : When an event causes a message / trigger to be sent to a state that causes the transition, then that message sent by the event is called signal. Symbol is : << Signal >> Event / Action Embedded Systems 4-17 Embedded Computing vii) Time-out event : A time-out event causes the machine to leave a state after a certain amount of time. The label tm (time-value) on the edge gives the amount of time after which the transition occurs. A time-out is generally implemented with an external timer. Symbol is ; —-time-value) viii) Final state : The end of state diagram is also called a final state. A final state is another example of a pseudo state because it does not have any variable or action described. Symbol is : © Consider an example of state diagram for an order object. When the object enters the checking state it performs the activity "check items". After the activity is completed the object transitions to the next state based on the conditions. If an item is not available the order is cancelled. If all items are available the order is dispatched. When the object transitions to the dispatching state the activity "initiate delivery” is performed. After this activity is complete the object transitions again to delivered state. [An item is not available] Dispatching Dofinitiate delivery [All items available] Fig. 1.11 State diagram for order object 4.42.1 Sequence Diagram A sequence diagram depicts the sequence of actions that occur in a system. The invocation of methods in each objects and the order in which the invocation occurs is Embedded Systems 1-18 Embedded Computing caplured in sequence diagram. This makes the sequence diagram a very useful tool to easily represent the dynamic behaviour of a system. A sequence diagram is two dimensional in nature. On the horizontal axis, it shows the life of the object that it represents, while on the vertical axis it shows the sequence of the creation or invocation of these objects. A sequence diagram consists of following behavioural elements : 1. Object : The primary element involved in a sequence diagram is an object-an instance of a class. A sequence diagram consists of sequences of interaction among different objects over a period of time. An object is represented by a named rectangle. The name to the left of ':" is the object name and to its right is class name. Symbol abc : ABC 2. Message : The interaction between different objects in a sequence diagram is represented as messages. A message is denoted by a directed arrow. Depending on the type of message, the notation differs. symbol testMessage() _createMessage( ) { destroyMessage( ) (a) (b) (ce) (a) In the Fig. 1.12 sample sequence diagram is shown indicating the general elements of a sequence diagram. om an Simple call i Synchronous call 7 ' Asynchronous t fi call ' Fig. 1.12 Sequence diagram Embedded Systems 1-19 Embedded Computing 1.5 Design Example 1.5.1 Model Train Controller Receiver, motor controller Power supply System setup Track ° Console Fig. 1.13 A model train control system The user sends message to the train with a control box attached to the tracks. The control box can send signals to the train over the tracks by modulating power supply voltage {since train receives its electrical power from two rails of the track]. The control panel sends packets over the tracks to the receiver. The train includes analog, electronics to sense the bits being transmitted and control system to set motor's speed and direction. Each packet includes an address to control several trains on the same track and Error Correction Code (ECC) to correct transmission errors. Embedded Systems 1-20 Embedded Computing Requirements The requirements of the system are as follows : Name Model train controller Purpose Control speed of trains Inputs Throttle, inertia setting, emergency stop, train no. Outputs Train control signals Functions Set engine speed based on inertia settings; respond to emergency stop Performance can update train speed atleast 10 times/sec. Manufacturing cost Rs. 2500 Power dissipation 10 W (plugs into wall) Specifications : Consider how the console controls the train by sending messages over the tracks. The transmissions are packetized. Each packet includes an address and a message. Fig, 1.14 shows a typical sequence of train control commands. Both the console and receiver run continuously. Packets can be sent at any time. A set_inertia message will be sent rarely since train’s mass would change only when cars are added or removed. Set_speed messages will be sent frequently to speed up or slow down the train smoothly. An emergency stop (Estop) command may be received occasionally to shut down the train motor immediately. 2 Console LTrain_revr Set_inertia Set_speed Set_speed Fig. 1.14 Typical sequence of train control commands using UML Embedded Systems 1-21 Embedded Computing The console needs to perform three functions : i) Read the state of front panel. ii) Format the messages. iii) Transmit the messages. ‘The train receiver must perform three functions : i) Receive the messages. i) Interpret the messages. Control the motor. Fig. 1.15 shows a UML collaboration diagram for major subsystems of train controller. Fig. 1.15 UML collaboration diagram for major subsystems of train controller The console and receiver are both represented by objects. The console sends a sequence of packets to the receiver as shown by arrow. On the arrow both the types of message sent and its sequence in a flow of messages are provided. Messages are carried over the track. Since the track is not a computer component, it does not appear in the diagram. Fig. 1.16 shows UML class diagram to represent the design. The console class uses three classes that defines its components. 1) Panel class describes the console's front panel, which contains analog, knobs and hardware to interface to digital parts of system. 2) Formatter class includes behaviours that know how to read the knobs and creates a bit stream for the required message. 3) Transmitter class interfaces to analog electronics to send message. There will be one instance of console class and one instance of each of the component class, as shown by numeric values at each end. There are two classes that represent analog components : i) Knobs * describes actual analog knobs, buttons and levers on panel. ii) Sender * describes analog electronics that send bits along track. Embedded Systems 41-22 Embedded Computing Similarly, the train uses three other classes that defines its components : 1) Receiver class knows how to turn analog signals into digital 2) Controller class includes behaviours that interpret the commands and find out how to control the motor. 3) Motor interface class defines how to generate analog signals required to control the motor. — Interface += Physical object Fig. 1.16 UML class diagram for train controller There are two classes to represent analog components = i) Detector* detects analog signals on the track and converts them into digital form. ii) Pulser* converts digital commands into analog signals required to control motor speed. Train set is a special class to indicate that system can handle multiple trains. Detailed specification : Here, we need to define the analog components in more detail as their characteristics will strongly influence the formatter and controller. Fig. 1.17 shows a class diagrams for analog components. Embedded Systems 1-23 Embedded Computing train-knob - integer pulse-width ; unsignedinteger |speed-knob : integer direction : boolean inertig-knob : un-integer Jemergency-stop : boolean set-knobs ( ) ‘sond-tit ( ) Fig. 1.17 Classes describing analog components Panel has three knobs : train no., speed and inertia. It also has emergency stop button. When the train no. setting is changed, the other controls must also be set to proper values for that train. For this purpose, knobs* must provide set-knobs behaviour that allows the rest of the system to modify the knob settings. The motor system takes its motor commands in two parts : Sender class simply put out a bit and detector class pick up a bit. Pulser class can be understood by considering the actual process of motor's speed control. Fig. 1.18 shows how the speed of motors is controlled using pulse width modulation. Power is applied for a fraction of time. The fraction of time that power is applied determines the speed. The digital interface to the motor system specifies pulse width as an integer (maximum value indicating maximum engine speed). Binary value controls the direction. +o Fig. 1.18 Motor speed control using pulse width modulation Embedded Systems 1-24 Embedded Computing Motor interface ‘speed : integer train-number ( ): integer speed (): integer inertia () + integer estop ( ) : bootean new-settings ( ) Fig. 1.19 Class diagram for panel and motor interface Classes for panel and motor interface form the software interfaces to their respective physical devices. Panel class defines a behaviour for each of the controls on the panel. The new-settings behaviour uses the set-knobs behaviour of the knobs* class to the knobs settings. Motor interface defines an attribute for speed that can be set by other classes. Fig. 1.20 shows the transmitter and receiver classes. Transmitter Receiver current : command new : boolean send-speed (adrs : integer, read-cmd ( ) speed : integer) new-cmd () : boolean send-intarta (adrs integer, rev-type (msgrtype : command) val : integer) rev-speed (val: integer) send-estop (ads : integer) rovinerta (val: integer) Fig. 1.20 Class diagram for transmitter and receiver These classes provide the software interface to their respective physical devices. The transmitter provides a distinct behaviour for each type of message that can be sent. It also takes care of formatting the message. The receiver provides read-cmd behaviour to read the message. This behaviour run continuously to monitor the tracks and intercept the next command. Two variables are used : one hold the current command and other holds a flag showing when the command has been processed. Separate behaviours read the parameters for each type of command. These messages also reset the new flag to show that command has been processed. Embedded Systems 1-25 Embedded Computing Fig. 1.21 shows the formatter class which holds the current control settings for all the trains. The send-command function serves as a interface to the transmitter. The operate function performs basic actions for the object. The panel-active behaviour returns true whenever panel's values does not correspond to current values. Formatter currenttrain integer current-speed [ntrains] : integer current-inertia [ntrains} : unsigned-integer current-estop [ntrains] : boolean send-command ( ) panel-active ( ) : boolean operate () Fig. 1.21 Class diagram for formatter class Fig. 1.22 shows the role of formatter during panel's operation by sequence diagram. There are two changes to knob settings : first to throttle, inertia or Panel-active Change in control setting send-command send-speed, send-inertia, send-estop ‘Change in speediinertia/estop Change in train no, Read panel Panel settings New-settings £ £ £ S é & Operate Fig. 1.22 Sequence diagram for transmitting a control input Embedded Systems 1-26 Embedded Computing emergency stop; then to train number. The panel is periodically called by formatter to determine the changes in the control settings. If current-train setting has changed, formatter issue a send-command behaviour to cause the transmitter to send the bits. Transmitter takes sometime to finish a command because transmission is serial. In the meantime, formatter continues to check control settings of the panel. If the train number has changed, formatter must cause the knob settings to be reset to proper values. Fig. 1.23 shows the state diagram of the formatter operate behaviour. update-pane! ( ) new train no. send-command () panel-active ( Fig. 1.23 State diagram for formatter operate behaviour This behaviour watches the panel : if train no. changes, it updates the panel display otherwise it causes the messages to be sent. Fig. 1.24 shows the state diagram for panel active behaviour. Refer Fig. 1.24 on next page. Controller class and controller operate behaviour are illustrated in Fig. 1.25 and Fig. 1.26 respectively. Receiver calls operate behaviour when it gets a new command. Operate observes the contents of the message and uses the issue-command behaviour to change speed, direction and inertia settings. Fig. 1.27 shows the operation of controller class during reception of set-speed command. Controller's operate behaviour must execute several behaviours to determine nature of message. Once the speed command is received, it must send a sequence of commands to motor to change the train's speed. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. Embedded Systems 1-28 Embedded Computing Wait for _ ‘command from current-train : integer current-speedintrains] : unsigned-integer curtent-ditection{ntrains] : boolean current-inertia(ntrains] : unsigned-integer operate ( ) issue-command ( ) Fig. 1.25 Class diagram for Fig. 1.26 State diagram for controller class controller operate behaviour set-pulse set-speed operate Fig. 1.27 Sequence diagram for set-speed command Review Questions 1. Define an embedded system. Give some examples 2. What are the various components of embedded system ? Explain in brief. 3. Explain in brief the characteristics of an embedded system. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. (1-30) The 8051 Architecture 2.1 Introduction To make a complete microcomputer system, only microprocessor is not sufficient. It is necessary to add other p eripherals such as read only memory (ROM), read/write memory (RAM), decoders, drivers, number of input/output devices to make a complete microcomputer system. In addition, special purpose devices, such as interrupt controller, programmable timers, programmable I/O devices, DMA controllers may be added to improve the capability and performance and flexibility of a microcomputer system. The key feature of microprocessor based computer system is that it is possible to design a system with a great flexibility. It is possible to configure a system as large system or small system by adding suitable peripherals. On the other hand, the microcontroller incorporates all the features that are found in microprocessor. However, it has also added features to make a complete microcomputer system on its own. The microcontroller has built-in ROM, RAM, parallel 1/0, serial I/O, counters and a clock circuit. The microcontroller has on-chip (built-in) peripheral devices. These on-chip peripherals make it possible to have single-chip microcomputer system. There are few more advantages of built-in peripherals : Built-in peripherals have smaller access times hence speed is more. © Hardware reduces due to single chip microcomputer system. © Less hardware, reduces PCB size and increases reliability of the system. The 8051 is an 8-bit microcontroller designed by Intel. It was optimized for 8-bit math and single bit Boolean operations. Its family-MCS-51 includes 8031, 8051 and 8751 microcontrollers. The Table 2.1 gives the summary of MCS-51 microcontrollers. Internal memory Timer / Device Program Data Event counters Interrupts 8052AH 8Kx 8ROM | 256 x8 RAM 3 x 16-Bit 6 8051AH 4Kx 8ROM | 128 x8 RAM 2 x 16-Bit 5 8051 4K x 8 ROM 128_x 8 RAM 2 x 16-Bit 5 2-1) Embedded Systems 2-2 The 805% Architecture 8032AH none 256 x 8 RAM 2 x 16Bit 6 8031AH Aone 128 x 8 RAM 2 x 168it 5 8031 none x 16-Bit e751 4K x 8 EPROM x 16-Bit 8751H-12 4Kx 8 EPROM x 16-Bit Table 2.1 MCS-51 family Different types of microcontrollers There are various types of microcontrollers. They can be classified according to data bus width, according to architecture they support. For example, 8051 is an eight bit microcontroller whereas 8096 is a sixteen bit microcontroller. The 8051 microcontroller has 4K x 8 ROM whereas 8751 microcontroller has 4K x 8 EPROM. On the other hand, 89C51 has on-chip flash program memory upto 64 kbytes with in-system programming. The AVR and PIC microcontrollers use RISC architecture. In this chapter we are going to see features and the intemal hardware details (architecture) of 8051 microcontroller. 2.2 Features of 8051 The features of the 8051 family are as follows : 1 4096 bytes on-chip program memory. 2. 128 bytes on-chip data memory. 3. Four register banks. 4. 128 User-defined software flags. 5. 64 kilobytes each program and external RAM addressability. 6. One microsecond instruction cycle with 12 MHz crystal. 7. 32 bidirectional I/O lines organized as four 8-bit ports (16 lines on 8031). 8. Multiple mode, high-speed programmable serial port. 9. Two multiple mode, 16-bit Timers /Counters. 10. Two-level prioritized interrupt structure. 11. Full depth stack for subroutine return linkage and data storage. 12. Direct byte and bit addressability. 13. Binary or decimal arithmetic. 14. Signed-overflow detection and parity computation. 15. Hardware multiple and divide in 4 psec. 16. Integrated Boolean processor for control applications. 17. Upwardly compatible with existing 8084 software. ‘The 8051 Architecture Embedded Systems 2.3 8051 Microcontroller Hardware é 5 & nenenece sn nennnnenec cc nenee cena : 3 s1eysi621 uojoun; jesads = = 2 : iT 5 49)8/603 : 4 en uoHONASUI “pod jeues: wesGorg e g ydnueyur is & wou Wa INOeda e a 5 } T Nasd E wou og PP R008 aasi601 saysi6ou E stunoo sseippe sseuppe Lo Fig. 2.1 Block diagram of 8051 yeweWasOU) od aaqunoo wesBoig ge ‘ i ' ' The Fig. 2.1 shows the internal block diagram of 8051. It consists of a CPU, two kinds of memory sections (data memory aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. Embedded Systems 2-7 The 8051 Architecture Bank 3 Bank 2 Byte address _Bit addresses oF 2e 20 2c 2B 2A 29 28 27 26 Bank 4 Bank 0 30 General purpose Working register Fig. 2.3 Organization of internal RAM of 8051 Embedded Systems 2-8 The 805 Architecture 1, First thirtytwo bytes from address 00H to 1FH of internal RAM constitute 32 working registers. They are organised into four banks of eight registers each. The four register banks are numbered 0 to 3 and are consists of eight registers named Rg to R;. Each register can be addressed by name or by its RAM address. Only one register bank is in use at a time. Bits RS, and RS, in the PSW determine which bank of registers is currently in use. Register banks when not selected can be used as general purpose RAM. On reset, the bank 0 is selected. 2. The 8051 provides 16 bytes of a bit-addressable area. It occupies RAM byte addresses from 20H to 2FH, forming a total of 128 (16 x 8) addressable bits. An addressable bit may be specified by its bit address of 00H to 7FH, or &bits may form any byte address from 20H to 2FH. For example, bit address 4EH refers bit 6 of the byte address 29H. 3. The RAM area above bit addressable area from 30H to 7FH is called general purpose RAM. It is addressable as byte. 2.3.4 Internal ROM The 8051 has 4 kbyte of internal ROM with address PO] Program space from 0000H to OFFFH. It is programmed by address manufacturer when the chip is built. This part cannot be ppTR—=| resister erased or altered after fabrication. This is used to store final version of the program It is accessed using program address register. The OFFFH program addresses higher than OFFFH, which exceed the 4k internal ROM capacity will cause the 8051 to automatically EPROM fe : OM fetch code bytes from external program memory. However, 000K code bytes:can also be fetched exclusively from an external memory addresses O000H to FFFFH, by connecting the external access pin (EA) to ground. 2.3.5 Input/Output Ports ‘The 8051 has 32 1/O pins configured as four eightbit parallel ports (PO, Pl, P2, and P3). All four ports are bidirectional, i. each pin will be configured as input or output (or both) under software control. Each port consists of a latch, an output driver, and an input buffer. The output drives of Ports 0 and 2 and the input buffers of Port 0, are used to access external memory. As mentioned earlier, Port 0 outputs the low order byte of the external memory addrgss, time multiplexed with the data being written or read, and Port 2 outputs the high order byte of the external memory address when the address is 16-bits wide. Otherwise Port 2 gives the contents of special function register P2. Embedded Systems The 8051 Architecture 2-9 tacno LT Buffer 0 Buffer 1 1 taten + La] Latch2 Pot2 7 vO auaare ofp Driver ; feds 7 vo Latch3) -—+| Interruy Por'3 * courte Buter3 f+—y OP ver sot Ga 7}+—~) aoa Fig. 2.4 VO Ports All port pins of Port 3 are multifunctional. They have special functions as shown Table 2.3 including two external interrupts, two counter inputs, two special data lines and two timing control strobes. Symbol | Position Name and Significance RD P37 Read data control output. Active low pulse generated by hardware when external data memory is read. WR P3.6 | Write data control output, Active low pulse generated by hardware when external data memory is written. " P3.5__| Timer/counter 1 external input or test pin. To P3.4 | Timer/counter 0 external input or test pin. INTi_| 3.3 _| Interrupt 1 input pin. Low-level or falling-edge triggered. INTO P3.2__| Interrupt 0 input pin. Low-level or falling-edge triggered. TxD | P31 | Transmit data pin for serial port in UART mode. Clock output in shift register mode. 5 RxD | P3.0 | Receive data pin for serial port in UART mode. Data W/O pin in shift register modi Table 2.3 2.3.6 Register Set of 8051 2.3.6.1 Register A (Accumulator) It is an. 8bit register. It holds a source operand and receives the result of the arithmetic instructions (addition, subtraction, multiplication, and division). The accumulator can be the source or destination for logical operations and a number of special data movement instructions, including look-up tables and external RAM expansion. Several aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. Embedded Systems 2-14 The 8051 Architecture (On-chip RAM On-chip RAM On-chip RAM [ 08 08 sp] —> 07 08 sae 06 SP —= 7 im Stack pointer —| & Sp sprt -————_—_—] 7 (0) Status of stack and (b) Store operation stack pointer of reset Data7__| 09 09 ‘SP ]—+{__Data2] 08 08 Data3__| 07 SP = SP-1—e Stack pointer —_ 7 23.65 Data Pointer (DPTR) The data pointer (DPTR) consists of a high byte (DPH) and a low byte (DPL). Its function is to hold a 16-bit address. It may be manipulated as a 16-bit data register or as two independent 8-bit registers. It serves as a base register in indirect jumps, lookup table instructions and external data transfer. The DPTR does not have a single internal address; DPH (83H) and DPL (82H) have separate internal addresses (©) Read operation Fig. 2.6 16-bit DPTR —— Memory [ , aren 6 steers —— bit sit 2.3.6.6 Program Counter The 8051 has a 16-bit program counter. It is used to hold the address of memory location from which the next instruction is to be fetched. Due to this the width of the program counter decides the maximum program length in bytes. For example, 8051 is 16-bit hence it can address upto 2'® bytes (64 K) of memory. The PC is automatically incremented to point the next instruction in the program sequence after execution of the current instruction. It may also be altered by certain instructions. The PC is the only register that does not have an internal address. Embedded Systems 2.3.6.7 Special Function Registers Unlike other microprocessors in the Intel family, 8051 uses memory mapped 1/O through a set of special function registers that are implemented in the address space immediately ebove the 128 bytes of RAM. Fig. 2.7 shows special function bit addresses. All access to the four I/O ports, the CPU registers, interrupt control registers, the timer /counter, UART and power control are performed through registers between 80H and FFH. Direct byte dere OFFH OFOH EH OBSH 0B0H OABH OAH 98H ‘90H 88H Bit address ss (NSB) (Ls3) Fig. 2.7 SFR bit address The 8051 Architecture Hardware register symbol ACC Ps P2 SCON p1 TCON aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. Embedded Systems 2-15 The 8051 Architecture Each memory type has different addressing mechanism, different control signals, and a different function. Each may be added independently, and each uses the same address and data buses, but with different control signals. In addition to the program and data memory, there is another physical address space, some of these - B, SP, PSW, DPH and DPL registers are discussed earlier. Others-I/O ports and peripheral function registers collectively referred as special function registers will be introduced in the following sections. 2.5 Input/Output Pins, Ports and Circuits The 8051 provides four port for 1/O interfacing. Fig. 2.9 shows a functional diagram of a typical bit latch and I/O buffers in each of the four ports. The bit latch is nothing but the one bit in the port's SFR. It is represented as a D flip-flop. The signal “write to latch” acts as clock input for D flip-flop. The data from the intemal bus is clock-in in response to a “write to latch” signal from the CPU. The Q output or Q output after inversion from D flip-flop is connected at the gate: input of the driver FET. The ON and OFF state of the driver FET due to the data available at the output of latch decides the status of the output pin. It is possible to read Q output of latch by activating “read latch” signal from the CPU. The actual port status can be read by activating “read pin” signal, as shown in Fig. 2.9. ADDR/DATA BUS v CONTROL 3 READ LATCH POX PIN INT BUS WRITE re rO. LarcH Control ogic READ PIN (a) Port 0-bit Embedded Systems 2-16 The 8051 Architecture Voc varcn INTERNAL PULL-UP (b) Port 1-bit ADDR BUS, READ conte Larcu neous write 10 Laren (c) Port 2-bit ALTERNATE, oars IneTER NAL SUNT PULL-UP READ ALTERNATE INPUT FUNCTION 5 (d) Port 3-bit Fig. 2.9 8051 port bit latches and I/O buffers aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. Embedded Systems 2-19 ‘The 8051 Architecture 2.6.2 Timer 0 and Timer 1 In this timers, "Timer" or Counter" mode is selected by control bits C/T in the Special Function Register TMOD (Fig.2.11). These two Timer/Counters have four operating modes, which are selected by bit-pairs (MI, M0) in TMOD. Modes 0, 1 and 2 are same for both Timer/Counters. Mode 3 is different. The four operating modes are described as follows. (MSB) (LSB) Timer 1 Timer 0 GATE Gating control when set. M1 MO. Operating Mode teased oy wie TE . a Soavol ts tot When Coured'rinar rs © © S8RTimedCouner Tx win Tle Sot ‘ratte whenever Toor Oss - 01 6b Tmaountr “Tie th “TL are CAF Ter oF Courter selector cere for Tier cascaded eter prone ‘operation linput from internal system clock). Set forCounteroperaton(inputtrem™Deinputpn). | 9‘ S-itauto-reload Timer/Counter “THx" holds 2 value which is to be reloaded into “TLx" teach tme toveriows 11 (Timer 0) TLO is an 8-bit TimeriCounter Conirlled by the standard Timer 0 cortrol bits. THO is an 6-bit imer only controlled by Timer’ control bits. 11 (Timer 1) TmeriCounter 1 stopped. Fig. 2.11 TMOD : Timer/counter mode control register MODE 0 Fig. 2.12 Timericounter 1 mode 0 : 13-bit counter aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. Embedded Systems 2-23 The 8051 Architecture 2.7 Serial Port The serial port of 8051 is full duplex, means it can transmit and receive simultaneously. It uses register SBUF to hold data. Register SCON controls data communication, register-PCON controls data rates, and pin RXD (P3.0) and TXD (P3.1) do the data transfer. The serial port receive and transmit registers are both accessed at special function register SBUF. Writing to SBUF loads the transmit register, ané; reading SBUF accesses a physically separate receive register. Both mutually exclusive registers use address 99H. The serial port of 8051 is receive-buffered, meaning it can commence reception of a second byte before a previously received byte has been read from the receive register. (However, if the first byte still hasn’t been read by the time reception of the second byte is complete, one of the bytes will be lost). The 8051 provides four programmable modes for serial data communication. A particular mode can be selected by setting the SMO and SMI bits in SCON. The mode selection also decides the baud rate. The Fig. 2.17 (a) and (b) shows the bit patterns for SCON and PCON. 2 (usb) (use) 7 6 5 4 3 2 1 0° - smo | swi | sw2 | ren | tas | res | ti | rt | Symbol |Position Name and Si SMO} SCON.7 | Serial port Mode control bit-0. Seticleared by software (see note). SM1 | SCON.6 | Serial port Mode contro! bit-1. Seticleared by software (see note). sm2_| SCONS | Ser Set by software to disable reception of frames for which bit 8 is zero. port Mode control bit-2 REN | SCON4 | Receiver Enable contro! bit Seticleared by software to enable/disable serial data reception ‘Transmit bit-6. Seticleared by hardware to determine state of ninth data bit transmitted in 9-bit UART mode. Receive bit-8. Sel/cleared by hardware to indicate state of ninth data bit received, ‘Transmit Interrupt flag. Set by haraware when bye transmitted, Cleared by sofware attr serving. | aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. Embedded Systems 2-27 The 8051 Architecture SMOD = 1, Baud rate = 4 Ose. freq. SMOD = 0, Baud rate = %, Ose. freq. To set the SMOD bit : ORL PCON,#80H. The address of PCON is 87 H. Serial Port in Mode 3 The baud rate in mode 3 is variable and sets up exactly the same as in mode 1. 2.8 Interrupt Structure The 8051 provides 5 interrupt sources. The 8052 provides 6. These are shown in Fig. 2.18. The external Interrupts INTO and INT] can each be either level-activated or transition-activated, depending on bits ITO and ITI in Register TCON. The flags that actually generate these interrupts are bits IEO and IE1 in TCON. When an external interrupt is generated, the flag that generated it is cleared by the hardware when the service routine is vectored to only if the interrupt was transition-activated. If the interrupt was level-activated, then the external requesting source is what controls the request flag, rather that the on-chip hardware. Po No in a4 ‘TPO > nat —_—elt ‘UH Interrupt L fe Sources Ft yo] > RI 2.18 MCS - 51 Interrupt structure The Timer 0 and Timer 1 Interrupts are generated by TFO and TF1, which are set by a rollover in their respective Timer/Counter registers (except see Timer 0 in Mode 3). The timer flag set upon generation of interrupt is cleared by the on-chip hardware when. microcontroller starts execution of particular interrupt service routine. The Serial port Interrupt is generated by the logical OR of RI and TI. Neither of these flags is cleared by hardware when the service routine is vectored to. In fact, the service aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. Embedded Systems 2-31 The 8051 Architecture consists of 12 oscillator periods, numbered SIP1 (State 1, Phase 1), to S6P2 (State 6, Phase 2) or 1 psec. If the oscillator clock frequency is 12 MHz. Each phase lasts for one oscillator period. Each state lasts for two oscillator periods. Typically, arithmetic and logical operations take place during Phase 1 and internal register-to-register transfers take place during Phase 2. The diagrams in Fig 2.21 show the fetch/execute timing referenced to the internal states and phases. Since these internal clock signals are not user accessible, the XTAL2 oscillator signal and the ALE (Address Latch Enable) signal are shown for external reference. ALE is normally activated twice during each machine cycle : once during $1P2 and $2P1, and again during S4P2 and S5P1. St Pipa oem ULL 82 Pip 83 Pipa $6 Pipa St PIP 82 Pipe 6 PtP st Pt a St | 85 Ptp2 | Pi Po 33 | s4 | $5 ipo |Ptp2 | Pipe ooepocnscscscscseceee READ NEXT opcone oPcone 2NDBYTE PEPE] (B)2-byte 4-cycle instruction, e.g, ADD A, # data f READNEXT OPCODE AGAIN READ READ NEXT BPCODE (DSCAFD) i ! EAD READ 1 1 READ (OPCODE (OVX) READNEXT (OPCODE (DISCARD) ACCESS EXTERNAL MEMORY Fig. 2.21 Fetch/Execute sequence aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. Embedded Systems 2-35 ‘The 8051 Architecture Using Power Down Mode : The software invoked Power Down feature offers a means of reducing the power consumption in some applications, Vcc to part of the system may be tured off during Power Down, so that even quiescent and standby currents are eliminated. But before switching off Vcc of any chip signal lines connected to the chip must be brought to a logic low, whether the chip in question is CMOS, NMOS, or TTL. CMOS pins have parasitic p-n junctions to Vcc, which will be forward biased if Vcc is reduced to zero while the pins are held at a logic high. NMOS pin 3 often have FETs that look like diodes to Vec. TTL circuits may actually be damaged by an input high if Voc = @. To ensure safe power down operation it is necessary that Voc for secondary circuit must be shut off after the 8051 is in power down and Vcc for secondary circuit must be switched on before the 8051 is out off power down. The Fig. 2.23 shows a circuit that can be used to turn Vcc off to part of the system ( secondary circuit ) during power down. 9 Ycct Voce Fig. 2.23 Power switching ci it for power down mode In Fig. 2.23 when Vcc is switched on to the 8051 capacitor C1 provides a power-on reset. The reset function writes 1s to all the port pins. The 1 at P2.6 turns Qi on, enabling Vc to the secondary circuit through transistor Q2. As the 8051 comes out of reset, Port 2 commences emitting the high byte of the program counter, which results in the P2.7 and P26 pins outputting 0s, The 0 at P27 ensures continuation of Vcc to the secondary circuit ‘The system software must now write a 1 to P27 and a 0 to P2.6 in the Port 2 SFR, P2. These values will not appear at the Port 2 pins as long as the device is fetching instructions from external program memory. However, whenever the 8051 goes into Power Down, these values will appear at the port pins, and will shut off both transistors, disabling Vcc to the secondary circuit. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. aa You have either reached a page that is unavailable for viewing or reached your viewing limit for this book. Assombly Language Programming and Embedded Systems 3-3 Instruction Set of 8051 3.1.3 Languages Used for Programming There are three language levels that can be used to write a program. Level 1 : Machine language Level 2 : Assembly language Level 3 : High level language Level 1 is a machine level which microprocessors understand. The programs written in other levels have to be converted into level 1 ie. machine level language for execution. 3.1.3.1 Machine Language A program which has simply a sequence of the binary codes for the instructions is called machine level language program. This binary form of the program is referred to as machine language because it is the form required by the machine. However, to write a program in machine language, programmer has to memorize the thousands of binary instruction codes for a processor. This task is difficult and error prone. 3.1.3.2 Assembly Language To make programming easier, usually programmers write programs in assembly language. They then translate the assembly language program to machine language so that it can be loaded into memory and executed. Assembly language uses two, three or four letter words to represent each instruction types. These words are referred to as mnemonics. The letters in an assembly language mnemonic are usually initials or a shortened form of the English word(s) for the operation performed by the instruction. For example, the mnemonic for addition is ADD, the mnemonic for logic AND operation is AND, and the mnemonic for the instruction for copy data from one location to another is MOV. Therefore, the meaning expressed by mnemonics help us to remember the operation performed by the instruction. Assembly language statements are usually written in a standard form and assembly language has its own unique syntactical structure, such as requiring upper case or lower case, or requiring colons after label definitions. Here we discuss the common features that assembler shares. The assembly text is usually divided into fields, separated by spaces and tabs. A format for a typical line from assembly language program can be given as. Label: Mnemonic Operandi, Operand2 ; Comment The first field, which is optional, is the label field, used to specify symbolic labels. A label is an idenfifier that is assigned to the address of the first byte of the instruction in which it appears. As mentioned earlier, the presence of a label is optional, but if present, the label provides a symbolic name that can be used in branch instructions to branch to the instruction. The second field is mnemonic, which is compulsory. All instructions must contain a mnemonic. The third and following fields are operands. The presence of the operands

You might also like