Exploring Microcontroller Technology, Programming ...

2 downloads 0 Views 2MB Size Report
The major single-chip microcontrollers were introduced by Motorola as the 6800 .... Special Function Registers (SFRs by Intel) or Control Registers (Motorola).
Exploring Microcontroller Technology, Programming, Interfacing & Implementation

MSc. Session 2000-2002 Project Supervisor Dr. Azher Iqbal Submitted By Mian Ahmed Jehanzeb Anwer Noorpuri

M0M036

A dissertation submitted to Punjab University College of Information Technology, University of The Punjab, Lahore, in partial fulfillment of the requirements for the degree of M. Sc. in Computer Science.

Date: 30th May 2003 University College of Information Technology University of The Punjab, Lahore

Statement of Submission: The project Exploring Microcontroller Technology, Programming, Interfacing & Implementation covers all the required aspect and requirements. The exposition includes all the necessary details required for understanding and running the system. This dissertation provides the deeper insight, which is required for the understanding of the system. This is hereby certified that the document and the project is complete in all the aspects, which were required for its completion Approved by:

________________________

________________________

Dr Azher Iqbal

Mr. Abdul Khaliq

Project Supervisor

Internal Supervisor

________________________

________________________

Dr Javed Sikander Mirza

Dr M.Anwaar Pasha

External Examiner

Principal

Exploring Microcontroller Technology

i

Dedicated To Aba jee & Abu They dreamed a zenith For Me They both passed But Dreams are never to be pass.

Exploring Microcontroller Technology

ii

The Last Pen Stroke I am very thankful to Rub-i-Zuljalal to give me strength and courage to complete my mission with success. I felt his almighty supremacy and kindness during the every moment of my struggle in the way of distinction. I am one of those persons who want to make their life to more difficult. This project is also an effort in this way. I faced a lot of difficulties in this project. Once I was forced to be thinking that all worries are made only for me. But, I didn‟t gave up my courage and remain dedicated to marching the final detonation. I admit, I did not achieve my desired goal, but I tried our best according to the state of affairs. It was very difficult to complete this project without any support and technical facilities. If all facts are gathered to analyze then result will be positive for me. There is list of personalities to whom I acknowledge, but especially our project supervisor Dr. Azhar Iqbal always encouraged us. Our internal supervisor Abdul Khaliq always remains cooperative with us. I am very much thankful to Dr. Saleem Incharge of the Communication Lab University of Engineering and Technology, who permitted us to use his high tech lab on crucial moments. A special thanks for Engineer Faisal Masood (research officer), who guided us with full devotion during the implementation. I am very thankful to Engineer Bilal Muhammad Hashmi (NU-FAST), to guide us in the starting days but I also feel sorry because I did not fulfill my commitment with him due to lake of resources. I am grate full to Dr. Naveed Akhtar Malik (Rector VU) for those moments, which he scheduled for me from his busy life. I am very thankful to Engineer Bilal Muhammad Hashmi (NU-FAST), to guide us in the starting days, but I also feel sorry because I did not fulfill my commitment with him due to lack of resources. I am grate full to Dr. Naveed Akhtar Malik (Rector VU) of those moments, which he scheduled for me from his busy life. There is a lot of contribution of my friends who encouraged me during the nerve breaking moments of projects. I am very much grateful to Imaran Javed Bhatti & Imaran Shaban Bhatti, who supported me not only during the project and as well as in all days of M.Sc. There is also a lot of contribution of Faisal Fayyaz & Mohsin Lodhra, those preferred to me on their own activities. There is another personality, Engr Zakria my great friend, who always encouraged me from the day of applying in M.Sc to the day of final presentation. I am also indebted to someone, whose imagination was a source of escape from the cruel realities of life during the hard time of the project. In the last I want to say thank to Syed Waqar jaferry (Project Coordinator), who reviewed that manuscript of documentation various time to make it flawless.

Exploring Microcontroller Technology

iii

We have tried to introduce a new dimension of development in Punjab University in the computer science when there is slumming in application software development. The research report is written with that intention that will prove as a reference manual for the next coming generation of PUCIT who want to travel toward the embedded systems software development Research report has three shades i.e. first one is all hardware and application aspect of microcontroller second is the programming the microcontroller and third one is implementation. First two are research based third one is based on the implementation. The main purpose of this heavy documentation is providing a manual reference to the next coming students. So they would save their time for further development.

I hope our effort will be resulted in the best way.

Project Innovator MIAN AHMED JEHANZEB ANWER NOORPURI

Exploring Microcontroller Technology

iv

Table of Contents CHAPTER 1 Introducing the Embedded Arena ..................................................... 1 1.1

Defining the Embedded systems ................................................................. 2

1.2. Basic Constituents of Embedded systems ...................................................... 3 1.2.1. Embedded system characteristics ............................................................ 3 1.2.2. Embedded system constraints .................................................................. 3 1.3. History and Application Areas of Embedded systems ..................................... 4 1.3.1. Application Areas of Embedded systems.................................................. 6 1.3.1.1. Consumer Appliances ........................................................................ 6 1.3.1.2. Communication .................................................................................. 8 1.3.1.3. Automotive ......................................................................................... 8 1.3.1.4. Defense .............................................................................................. 8 1.3.1.5. Industrial............................................................................................. 8 1.3.1.6. Medical diagnostics, monitoring and life support ................................ 8 CHAPTER 2 Discovering the Microcontrollers ........................................................... 9 2.1. Defining the Microcontroller ........................................................................... 10 2.1.1. Acronym of Microcontroller ..................................................................... 10 2.1.2. Why we use a microcontroller? ............................................................... 12 2.2. History of Microcontroller ............................................................................... 12 2.3. Classification of Microcontrollers ................................................................... 12 2.4. Design Techniques for Microcontrollers ........................................................ 12 2.4.1. Architectures for Microcontrollers ........................................................... 14 2.4.1.1. Princeton (Von Neumann) architecture ............................................ 14 2.4.1.2. Harvard architecture ......................................................................... 14 2.4.2. Instruction Set for Microcontrollers ...................................................... 14 2.4.2.1. CISC (Complex Instruction Set Computer): ...................................... 15 2.4.2.2. RISC (Reduced Instruction Set Computer): ..................................... 15 2.5. Building Blocks of Microcontrollers ................................................................ 17 2.5.1. Central Processing Unit (CPU) ............................................................... 18 2.5.2. Memory ................................................................................................... 18 2.5.2.1. Control Storage ................................................................................ 18 2.5.2.2. Data storage ..................................................................................... 20 2.5.3. Special Function Register (SFR‟s) .......................................................... 20 2.5.4. Input and Output Ports ............................................................................ 20 2.5.4.1. Types& Modes of Ports .................................................................... 22 2.5.5. Counter /Timer ........................................................................................ 22 2.5.5.1: Auto Reload feature ......................................................................... 22 2.5.5.2. Application of Counter/Timer ............................................................ 24 2.5.6. Interrupt System ..................................................................................... 24 2.5.6.1. Interrupt service routine (ISR) .......................................................... 25 2.5.6.2. Interrupt vector ................................................................................. 25

Exploring Microcontroller Technology

v

2.5.6.3. Interrupt Priority ................................................................................ 25 2.5.6.4. Triggered Classification of Interrupts ................................................ 25 2.5.7. Buses ...................................................................................................... 28 2.5.7.1. Address bus ..................................................................................... 28 2.5.7. 2. Data bus .......................................................................................... 28 2.5.7. 3. Control bus ...................................................................................... 28 2.5.8. Clocking Affairs ....................................................................................... 28 2.5.9. Watch Dog Timer .................................................................................... 29 2.5.9.1. Kicking the dog .................................................................................... 29 2.6. Choosing the Microcontroller ......................................................................... 31 2.7. General Introduction to Microcontroller Families ........................................... 32 2.7.1. 8051 ........................................................................................................ 32 2.7.2. Zilog Z8 ................................................................................................... 32 2.7.3. AVR ........................................................................................................ 33 2.7.4. PIC .......................................................................................................... 34 2.7.5. HC05....................................................................................................... 34 2.7.6. HC11....................................................................................................... 35 CHAPTER 3 Microcontrollers Based System Fundamentals ............................. 36 3.1. Embedded systems and Microcontroller ....................................................... 37 3.2. Control system concepts ............................................................................... 39 3.2.1. Basic definitions ...................................................................................... 39 3.2.1.1. Sensor .............................................................................................. 39 3.2.1.2. Actuator ............................................................................................ 40 3.2.1.3. Process/Plant ................................................................................... 40 3.2.1.4. Controller Unit .................................................................................. 40 3.2.1.5. Set point: .......................................................................................... 40 3.2.1.6.Error .................................................................................................. 40 3.2.1.7. Defining the Control system ............................................................. 40 3.2.2. Composition of a control system ............................................................. 40 3.2.3. Types of control system .......................................................................... 42 3.2.3.1. Open Loop system ............................................................................... 42 3.2.3.1. Closed loop/Feedback system ............................................................. 42 3.2.4. PID Control Strategies ............................................................................ 42 3.2.4.1. Proportional ...................................................................................... 42 3.2.4.2. Integral ............................................................................................. 42 3.2.4.3. Differential: ....................................................................................... 43 3.3. Interfacing issues of Microcontroller systems ................................................ 43 3.4. Analog matters .............................................................................................. 43 3.4.1. Analog to digital conversion .................................................................... 43 3.4.2. Digital to analog conversion .................................................................... 45 3.4.2.1 Digital to analog converter ................................................................. 46 3.4.2.2 Plus width modulation (PWM) ........................................................... 46 3.5. Interfacing the with external devices ............................................................. 48 3.5.1. Keypad Interfacing .................................................................................. 48 Exploring Microcontroller Technology

vi

3.5.2. Display Devices ...................................................................................... 48 3.5.2.1. Seven-segment light emitting diode display ..................................... 50 3.5.2.2. Liquid crystal display (Hitachi (HD44780)......................................... 50 3.6. Microcontroller based Serial communication ................................................. 57 3.6.1. Some basic concepts .............................................................................. 58 3.6.2. Serial communication protocols .............................................................. 58 3.6.2.1. RS-232 ............................................................................................. 59 3.6.2.2. I2C .................................................................................................... 61 3.6.2.3. Control Area Network protocol (CAN) .............................................. 63 3.6.2.4. Other Protocols ................................................................................ 68 CHAPTER 4 A Quick view of 8051 ........................................................................ 70 4.1. The Hardware ................................................................................................ 71 .4.1.1.Basic constituent of 8051 ........................................................................ 71 4.1.2. Pin outs– Arrangements of pins .............................................................. 72 4.1.3. Clock matters .......................................................................................... 74 4.2. Memory organization of 8051 ........................................................................ 74 4.2.1. Data memory .......................................................................................... 76 4.2.1.1. Register banks ................................................................................. 76 4.2.1.2. BDATA ............................................................................................. 76 4.2.1.3. General purpose RAM...................................................................... 76 4.2.1. Internal Program memory ............................................................... 77 4.2.3. External Program memory & Data memory ......................................... 77 4.2.4. Special Function Registers memory .................................................... 77 4.3. The Registers of 8051 ................................................................................... 79 4.3.1. General Purpose register ........................................................................ 79 4.3.1.1 The Accumulator ............................................................................... 79 4.3.1.2. B Register ........................................................................................ 79 4.3.1.3. R registers ........................................................................................ 81 4.3.1.4. The Data Pointer (DPTR) ................................................................. 81 4.3.1.6. The Stack Pointer (SP)..................................................................... 82 4.4.2. Special Function Registers ..................................................................... 82 4.4.2.1. P0 (Port 0, Address 80h, Bit-Addressable)....................................... 82 4.4.2.2. SP (Stack Pointer, Address 81h) ...................................................... 83 4.4.2.3. DPL/DPH (Data Pointer Low/High, Addresses 82h/83h) .................. 83 4.4.2.4. PCON (Power Control, Addresses 87h) ........................................... 83 4.4.2.5. TCON (Timer Control, Addresses 88h, Bit-Addressable) ................. 83 4.4.2.6. TMOD (Timer Mode, Addresses 89h) .............................................. 83 4.4.2.7. TL0/TH0 (Timer 0 Low/High, Addresses 8Ah/8Ch) .......................... 83 4.4.2.8. TL1/TH1 (Timer 1 Low/High, Addresses 8Bh/8Dh) .......................... 83 4.4.2.9. P1 (Port 1, Address 90h, Bit-Addressable)....................................... 83 4.4.2.10. SCON (Serial Control, Addresses 98h, Bit-Addressable) ............... 84 4.4.2.11. SBUF (Serial Control, Addresses 99h) ........................................... 84 4.4.2.12. P2 (Port 2, Address A0h, Bit-Addressable) .................................... 84 4.4.2.13. IE (Interrupt Enable, Addresses A8h) ............................................. 84 4.4.2.14. P3 (Port 3, Address B0h, Bit-Addressable) .................................... 84

Exploring Microcontroller Technology

vii

4.4.2.15. IP (Interrupt Priority, Addresses B8h, Bit-Addressable).................. 84 4.4.2.16. PSW (Program Status Word, Addresses D0h, Bit-Addressable) .... 86 4.5. Timer operation in 8051 ................................................................................ 86 4.51. TIMERS TO MEASURE TIME ................................................................. 86 4.5.2. Timer SFRs............................................................................................. 86 4.6. 8051 Serial Communication .......................................................................... 88 4.6.1. Serial Interface Modes of Operation ....................................................... 88 4.6.3. Setting the Serial Port Baud Rate ........................................................... 90 4.6.4. Writing to the Serial Port ......................................................................... 91 4.6.5. Reading the Serial Port ........................................................................... 92 4.7. Interrupt system of 8051 ................................................................................ 92 4.7.1. Interrupt Priority Register ........................................................................ 92 4.7.2. Interrupt Enable Register ........................................................................ 94 4.7.3. External Interrupt Signals........................................................................ 94 CHAPTER 5 Burning the 8051 ................................................................................ 95 5.1. Prerequisite for programming the Microcontroller .......................................... 96 5.2. Design process of Microcontroller based system .......................................... 96 5.3. From source file to .HEX ............................................................................. 100 5.3.1. Intel Hex file format ............................................................................... 100 5.3.1. 1.Record Format ................................................................................... 100 5.4. Programming the 8051 ................................................................................ 102 5.5. An abridged review of ASM 51 .................................................................... 102 5.5.1. Special Assembler Symbols ................................................................. 102 5.5.2. Addressing Modes ................................................................................ 103 5.5.2.1. Immediate Addressing.................................................................... 103 5.5.2.2. Direct Addressing ........................................................................... 103 5.5.2.3. Indirect Addressing ....................................................................... 103 5.5.2.4. External Direct Addressing ............................................................. 104 5.5.2.5. External Indirect Addressing .......................................................... 104 5.5.3. Code Addressing .................................................................................. 105 5.5.3.1. Using relative jumps ....................................................................... 105 5.5.3.2. Using in-block jumps and calls ....................................................... 105 5.5.3.3. Using Long jumps and calls ........................................................... 105 5.5.4. Numbers, Characters ............................................................................ 105 5.5.5. Arithmetic, Binary and Relational Operators ......................................... 106 5.5.6. Assembler Directives ............................................................................ 106 5.5.6.1. Segment Control ............................................................................ 107 5.5.6.2. Symbol Definition ........................................................................... 108 5.5.6.3. Memory Initialization & Reserving .................................................. 110 5.5.6.4. Address Control ............................................................................. 110 5.5.7. Macro and Label ................................................................................... 111 5.5.8. Template of ASM51 .............................................................................. 112 5.6. An introduction to C51 ................................................................................. 113 Exploring Microcontroller Technology

viii

5.6.1. Memory affairs ...................................................................................... 114 5.6.2. Supported memory model..................................................................... 114 5.6.2.1. Memory Types ............................................................................... 115 5.6.3. New keywords ...................................................................................... 115 5.6.4. Absolute Variable Location ................................................................... 116 5.6.4. Pointers................................................................................................. 117 5.6.4.1. Generic pointers ............................................................................. 117 5.6.4.2. Memory-specific Pointers ............................................................... 117 5.6.5. Function Declarations ........................................................................... 117 5.6.5.1. Interrupt functions........................................................................... 118 5.6.5.2. Reentrant Functions ....................................................................... 119 5.6.6. Using Inline assembly ........................................................................... 119 5.7. Downloading the HEX File........................................................................... 120 CHAPTER 6 REATIME UML ................................................................................. 121 6.1. Introduction to RT-UML ............................................................................... 122 6.2. Capsule ....................................................................................................... 122 6.3. Ports ............................................................................................................ 123 6.3.1. Ports and protocols ............................................................................... 123 6.3.2. Classification of ports ............................................................................ 123 6.3.2.1. Visibility .......................................................................................... 123 6.3.2.2. Connector type ............................................................................... 123 6.4. Protocols ..................................................................................................... 125 6.4.1. Binary protocols ................................................................................ 125 CHAPTER 7 Implementation ............................................................................... 126 7.1. An overview of implementation.................................................................... 127 7.1.1. Basic components of implementation ................................................... 127 7.1.2. Deliverable Functionality ....................................................................... 127 7.2. Analysis and Design Model ......................................................................... 129 7.2.1. Description of Use cases ...................................................................... 129 7.2.1.1. Use case: Transfer Analog temperature input ................................ 129 7.2.1.2. Use case: Interface ADC ................................................................ 130 7.2.1.3. Use case: Interface Display ............................................................ 131 7.3. The Embedded Code .................................................................................. 136 7.3.1. Embedded Hex file .......................................................................................... 143

Exploring Microcontroller Technology

ix

Exploring Microcontroller Technology

x

CHAPTER 1 Introducing the Embedded Arena

Exploring Microcontroller Technology

1

We are surrounded by a lot of computing systems in our life. A large number of computing systems are built every year destined for desktop computers (Personal Computers, or PC‟s), workstations, mainframes and server. But there are surprisingly billions of computing systems are built every year for a very different purpose: they are embedded within larger electronic devices, carrying out a particular function, often going completely unrecognized by the device‟s user. But it is not easy to create a precise definition of such embedded computing systems, or simply embedded systems. These are found in the every wrap of life in different variety from home appliances (Toasters, Ovens, Washing machine, central heating systems) to office automations devices (Photocopier, Card reader), from medical devices (Dialysis machines, Pacemaker) to military weapons (Smart weapons, Missile guidance system). An embedded application refers to a situation where a computer is used in a product whose outward appearance gives little or no indication that it contains a computer. For example, a traffic stoplight has no attached keyboard or monitor, yet employs a microprocessor to count off the seconds for its cycle of lights. A car's anti-lock braking system requires a computer to constantly monitor all four wheels for signs of slippage. But this computer has no floppy drive, no hard drive, and no mouse. In an embedded application, a computer is powered up ready to perform a single job and then continues to perform that one job until it is powered down. Hence, there is no need for a user interface that would allow a human being to direct its activities.

1.1

Defining the Embedded systems

Embedded systems can be defined in different ways i.e. 

     

“An embedded system implies a fixed set of functions programmed into a non-volatile memory (ROM, flash memory, etc.) in contrast to a generalpurpose computing machine & sometimes single board computers and rack mounted computers are called "embedded computers” are used to control device.” [1] “An embedded system whose principle function is not computational, but which is controlled by a computer embedded inside it.” [2] “A system that uses a computer as a component but whose prime function is not as computer.” [3] “A system that performs a specific dedicated operation where the computer is hidden in or embedded inside the machine.” [4] “Embedded system is an electronic system that includes a programmable computer but is not itself a general-purpose computer.” A digital system that uses a microprocessor usually, runs a software for its functions & frequently use as a controller, but not as for processing & PC or for traditional scientific applications. Those systems, in which information processing is embedded in a larger system and in which information processing is not visible to the user.

Exploring Microcontroller Technology

2



Computing systems embedded within electronic devices, Hard to define. Nearly any computing system other than a desktop computer . [15]

1.2. Basic Constituents of Embedded systems: Any type of embedded system beside of its function is comprised of two pillars i.e.  

Hardware: The physical topology including electrical and mechanical components. Firmware: The software that executes from the non-volatile memory of the computer based systems.

Since the perfection of embedded system systems depends on both of its constituents, therefore the relevant persons who are responsible to produce the quality of functions within both try to best for their pride according to the general characteristics and constraints. 1.2.1. Embedded system characteristics Any embedded system has the following characteristics     

must be reliable, safe, and secure must be efficient mostly fixed set of the applications systems frequently reading, processing and controlling physical quantities Easily marketable & cost effective

1.2.2. Embedded system constraints And every embedded system is subject to the following constraints    



Single-functioned  Executes a single program, repeatedly Small Size, Low Weight  Handheld electronics  Transportation applications -- weight costs money Low Power  Battery power for 8+ hours (laptops often last only 2)  Limited cooling may limit power even if AC power available Harsh environment  Heat, vibration, shock  Power fluctuations, RF interference, lightning  Water, corrosion, physical abuse Safety-critical operation  Must function correctly  Must not function incorrectly

Exploring Microcontroller Technology

3

By considering the above facts electrical engineers try to prepare minimal configuration based hardware. This trend is resulting in the form of single chip hardware i.e. Microcontroller. Whereas software engineers who are responsible to create an efficient, timely and reliable piece of code as firmware to burn in the ROM of embedded system try to their best by using better tools and advanced languages to develop the sophisticated programs. As shown in Figure 1.1 the core of the embedded system functionalities. An embedded system is responsible to receive the information and then process it according to burned code for controlling or displaying purposes. The burned code implies the set of instructions to perform a specific function according to the application. The embedded code is a pivot element of the system as like its complement i.e. hardware. All the process and efficiency of embedded system depends upon the perfection & compactness of algorithm embedded in its ROM as well as upon its hardware configuration.

1.3. History and Application Areas of Embedded systems The first recognizably modern embedded system was the Apollo Guidance Computer (aircraft simulator), developed by Charles Draper and the MIT Instrumentation Laboratory in late 40‟s In 1968, the Volkswagen 1600 used a microprocessor in its fuel injection system, launching the first embedded system in the automotive industry. The first DSP chip used in a commercial product was believed to be from TI, which was used in its very popular Speak & Spell game in the late 1970s. The world of embedded systems is subdivided in many disciplines     

General purpose system (involving Microprocessor) Control System (involving Microcontroller) Signal Processing system (involving DSP) Communication system (Bluetooth based & etc) Real time operating system

These all sub domains have a familiar aspect, i.e. microprocessor. The microprocessor is the brain and center point; around it, all of development revolves. So that embedded system would have any of following as fundamental & director element.   

General purpose processor Microcontroller: dedicated processor with all necessary peripherals on a single silicon chip Digital signal processor: Ultra fast mathematical instruction sequence based processor or specialized microcontroller doing fast Fourier and other transformations i.e. Fuzzy logic

Exploring Microcontroller Technology

4

Figure 1.1: The essence of the Embedded system

Figure 1.2: Embedded system design cells on many discipline Exploring Microcontroller Technology

5

So that whenever any microprocessor based system is discussed then ultimately an embedded system is discussed. Because the microprocessor in any shapes, either its general purpose or dedicated to the application is the main object to monitor all the circumstances and decide the best solution for whole system according to the embedded algorithm. The embedded algorithm that is responsible for overall system performance is based on different strategies & techniques which are based on mathematics. There are some of theses some these will be discussed in the next chapters     

Control Laws  PID control  Neural Network, Fuzzy Neural logic Sequencing logic  Finite state machines  Switching modes between control laws Signal processing  Multimedia data compression  Digital filters Application-specific interfacing  Buttons, Bells, Lights, LASER, Displays  High-speed I/O Fault response  Detection & reconfiguration  Diagnosis

1.3.1. Application Areas of Embedded systems Embedded systems come in many forms and guises. They are extremely common in the home, the motor vehicle and the workplace. Most modern domestic appliances, washing machines, dishwashers, ovens, and central heating and burglar alarms are embedded systems. The motor car is full of them, in engine management, security (for example, locking and anti-theft devices), air-conditioning, brakes, radio, and so on. They are found across industry and commerce, in machine control, factory automation, robotics, electronic commerce and office equipment. The list has almost no end, and it continues to grow. As shown in the Figure 1.2. [2] There is a long list of embedded applications in the daily life some are given below with functionalities perform with an embedded computer system with specification of related discipline. Some of theses disciplines are shown pictorially in the fig 1.3. 1.3.1.1. Consumer Appliances    

Washing machine: ES controls the water and spin cycles. Remote Control: ES accepts the input and generates IR pulses. Game & toys: ES controls the joystick input and video output Ovens: ES controls the temperature set by the user.

Exploring Microcontroller Technology

6

Figure 1.3: Embedded Arena

Figure 1.4: Embedded Applications in Automotive Exploring Microcontroller Technology

7

1.3.1.2. Communication     

Answering Machine: ES plays and manages the messages. Telephone System: ES controls the switching and retrieval of Information. Cellular Phone and pagers: ES manage keypad input, sound I/O & Communicates with central station. ATM machine: ES provides both security and banking convenience. Data switching equipment: ES controls the frame relay and packet Switching.

1.3.1.3. Automotive    

Automatic brake: ES optimizes stopping on slippery surfaces. Theft deterrent devices: ES maintains alarm system and key less entry. Electronic ignition: ES controls sparks and fuel injectors. Instrumentation: ES collects and displays the necessary information on dash board for convenience of driver.

1.3.1.4. Defense     

Smart Weapons: ES recognize friendly targets. Missile guidance system: ES directs ordinance at the desired Target. Air Traffic Control Systems: ES monitors the traffic of planes. Autopilot plane: ES totally manage all the system of the plane. Radar systems: ES control the alarm & monitoring system

1.3.1.5. Industrial   

Robot System: ES takes input from sensor and control actuators. Traffic control System: ES senses the car positions and control Traffic light. Barcode Scanner & Writer: ES control the scanner input & output to Writer for inventory control and shipping.

1.3.1.6. Medical diagnostics, monitoring and life support   

Apnea monitors: ES detects breathing of baby and alarms if it stops. Cardiac monitor: Es measure heart of patient. Pacemaker: ES helps the heart beat regularly.

Exploring Microcontroller Technology

8

CHAPTER 2 Discovering the Microcontrollers

Exploring Microcontroller Technology

9

Microcontroller “solution looking for a problem” was introduced when skill of semiconductor industry allows several functions such as CPU, memory & I/O to be integrated on a single chip This in turn reduced the microprocessor based solution for any problem. Therefore microcontroller is called “Microprocessor based controller”. Since embedded system development has evolved as a separate field of development from Real-time control system. So we call microprocessor based controller with all necessary peripheral on a single chip as Microcontroller because these are used to perform the control functions. According to Gilmore “Microcontroller was developed to meet a need of microprocessor for the low cast product. Building a complete microprocessor system on a chip reduces the cost of building a simple product which uses microprocessor’s power to implement their functions because the microprocessor for low-cost product those were 8-bit microprocessor were not effective. This reason that was microprocessor needed many additional parts whose cost money so that all parts made system costly.” [5]

2.1. Defining the Microcontroller Microcontroller can be defined as 

“A microprocessor based controller is an entire computer manufacture on a single silicon chip. It is an I.C that comprises a processor as “core”, I/O port, Code memory, Data memory, serial and parallel port, timer/counter & interfacing logic.”



"A single microprocessor based Large scale integrated (LSI) chip containing all logic element needed for a computer control system.”



“A microcontroller is a programmable single chip, self-contained computer which Incorporates all the basic components of a personal computer on a much smaller scale to control a process or system” [6]



“A chip who has a computer processor with all its support functions (Clocking, & Reset), memory (Program storage (ROM) and Data storage (RAM)) And I/O (including bus interface) to minimize the need for external circuit and devices to be designated in the final application.” [7]



“A programmable processor which programming interface is not accessible to the end-user of the product, the only user-interaction is through the actual application.”

2.1.1. Acronym of Microcontroller The microcontrollers are called as MCU (Microcontroller unit) or MCS in short for convince in writing and speaking. Exploring Microcontroller Technology

10

Fig 2.1: First Microcontroller/Microprocessor of the Universe (Intel 4004)

1/4"

RAM

I/O Control Unit

Clock

ROM

An entire computer on a single chip.

Processor (CPU)

Fig 2.2: Microcontroller Layout

Exploring Microcontroller Technology

11

2.1.2. Why we use a microcontroller?    

Reduce chip count Many applications do not require as much computing power Reduced power consumption Reduced design cost

2.2. History of Microcontroller First microprocessor with ROM, RAM on a single chip was designed by Marcian E. "Ted" Hoff at Intel in 1971 after a considerable debate about its utility and marketability, it was a 4-bit, general-purpose CPU initially developed for the Japanese Busicom calculator. The 4004 consisted of 2300 transistors and was clocked at 108 KHz (i.e., 108,000 times per second). Compare this to the 42 million transistors and the 2 GHz clock rate (i.e., 2,000,000,000 times per second) used in a Pentium 4. [3] Texas Instrument introduced TMS-100 series of microcontrollers in the mid 70‟s & at same time Fairchild introduced two–chip (F8) but both used special and limited architectures. The major single-chip microcontrollers were introduced by Motorola as the 6800 series and Intel series of product based on 8008 architecture. Those are still in use in the market. [5] But after coming days these basic microcontrollers are modified to meet the need for specific purposes like data communication, computer networks. There are many other manufactures like National semiconductor, Hitachi, Zilog.

2.3. Classification of Microcontrollers Although the microcontrollers are defined as “Processor with necessary peripherals on a single chip” but those is more classified on basis of external or built in code & data memory (ROM, RAM). 

Embedded Microcontrollers: A processor with all of its support functions (clock, RST, timer), memory (code & data) & I/O (CU, ports) provided on a single chip by minimizing the external circuitry to run an application. [7]



External memory based Microcontrollers: An embedded microcontroller with an external memory (code & data) is referred as external memory based microcontrollers see Figure 2.4.

2.4. Design Techniques for Microcontrollers During the designing the structure of microcontrollers two things are considered Exploring Microcontroller Technology

12

Fig 2.3: A typical Busicom desktop calculator

Address Bus RAM

I/O Clock Control Unit

ROM Control Bus Processor

External RAM/ROM

(CPU)

Data Bus Micocontroller

Fig 2.4: Microcontroller with External memory External Memory Wired to MCS

Exploring Microcontroller Technology

13

 

Selection of Architecture Selection of Instruction Set

2.4.1. Architectures for Microcontrollers There are two types of architecture are used for the microcontrollers  

Princeton (Von Neumann) architecture Harvard architecture

2.4.1.1. Princeton (Von Neumann) architecture The Princeton architecture ( known as Von Neumann) support a computer system with a common memory for storing the control program as well as variable & other data structure and have a single "data" bus that is used to fetch both instructions and data. When such a controller addresses main memory, in the first cycle of execution, it fetches an instruction from memory, and then it fetches the data to support the instruction. The two separate fetches slows up the controller's operation. See Figure 2.5 

Advantages: This architecture support simplicity and economy. And RAM is available for both data and program variables. This allows greater flexibility in developing the software

2.4.1.2. Harvard architecture Harvard architecture based computer systems have separate memory areas for program instructions and data. There are two or more internal data buses which allow simultaneous access to both instructions and data. It supports the parallelism so that when an instruction is being "pre-fetched", the current instruction is executing on the data bus. Once the current instruction is complete, the next instruction is ready to go. This pre-fetch theoretically allows for much faster execution than Von-Neumann architecture. See fig 2.6 

Advantages: It provide more fast execution than its rival

2.4.2. Instruction Set for Microcontrollers There are two types of instruction which are used for microcontroller  

CISC RISC

Exploring Microcontroller Technology

14

2.4.2.1. CISC (Complex Instruction Set Computer): The traditional architecture of a computer which uses microcode to execute very comprehensive instructions & has multiple addressing formats, and contain only a small number of general-purpose registers is called CISC computer. Common characteristics of CISC: I. II. III. IV.

Allows multiple operands Multiple addressing modes Variable length instructions Instructions take multiple clock cycles

a) Advantages: I. Assembly programming is easier  Mapping from C to assembly instructions II. Ease of upward compatibility  Lots of instructions to use III. Fewer instructions per task  Reduced code size IV. Less complicated compilers  Easy to map from higher level to lower level V. This architecture support simplicity and economy b) Disadvantages: I. Complex hardware & instruction sets  Difficult to scale up speed-wise due to complexity II. Different instructions take different amounts of time  Difficult to pipeline instructions – more later on III. Many specialized instructions  Use only about 20% of actual instructions in a program  80% of complexity in chip is not used IV. Most instructions cause side effects in a CCR (Condition Code Register) 2.4.2.2. RISC (Reduced Instruction Set Computer): a) Common characteristics of RISC I. The CPU does not make use of micro coding. II. Memory is accessed via load and store instructions only; the requirement to operate on memory contents is achieved by multiple instructions. III. All instructions are executed in one machine cycle; this means that each instruction must be represented by one word only hence all op codes must be equal to or within the instruction bus size, and must include the operand within them. Exploring Microcontroller Technology

15

Memory Space Program Rom

Instruction Decode

Variable RAM Data

Memory Interface Unit

Addr

Processor and built-in Register

Cycle 1: b) Read instruction

Cycle 2: b) Read data out of RAM and Put in ACC

Ctrl

Stack RAM

Figure 2.5: Execution of instruction Mov ACC, Reg in Von Neumann Architecture

Data

Control Space

Addr

Cycle-1:

Instruction Decode

a)Complete previous instruction b) Read the Mov ACC, Reg

Ctrl

PC Stack

Register Space

ROM Data

Processor and register interface

Addr

Ctrl

Cycle 1: a) Execute the Mov ACC, Reg b) Read next instruction

Figure 2.6: Execution of instruction Mov ACC, Reg in Harvard architecture

Exploring Microcontroller Technology

16

b) Advantages I. II. III. IV.

Speed increase - 2 to 4 times if properly optimized Simpler hardware Shorter design cycle because of simpler hardware Code Expansion  More instructions  large code size V. System Design  Requires large amounts of fast memory  Power consumption of higher speed processor

c) Disadvantages I. Code Quality  Performance of the program directly correlates to the quality of compiler and ability to pipeline commands II. Debugging  Code may not be executed as listed in the source code in order to optimize execution of code

2.5. Building Blocks of Microcontrollers There is lot of variety in the microcontrollers with respect to their specialization, i.e. from general purposes to networking & from Graphics display to Atomic reactors and each has its own unique combination of core & peripherals.  

Core: The element which remains constant for the whole family of microcontroller. Peripherals: Any hardware component which varies with respect to type application and connected to the core.

Ideally, all memory is on-chip, and several different technologies may be applied to meet the different needs of program and data storage. Interconnection to the outside world is through a number of parallel and serial ports. A counter/timer is available for event counting, or to measure or generate timing intervals. See fig 2.7. The general building blocks of a MCS are following        

Central processing unit (CPU) Memory (Control & Data) Special Function Register Input and Output ports Counter /Timer Interrupt System Buses Watch Dog Timer

Exploring Microcontroller Technology

17

2.5.1. Central Processing Unit (CPU) The central processing unit (CPU) does all the computing: it fetches, decodes and executes program instructions and directs the flow of data to and from memory. The CPU performs the calculations required by program instructions and places the results of these calculations, if required; into the memory space. Most CPUs are synchronous. This means that they depend on the cycles of a processor clock. A clock generates a high-frequency square wave usually driven by a crystal, an RC (resistor capacitor) or an external source. The clock is sometimes referred to as an oscillator. The clock speed, or oscillation rate, is measured in megahertz (MHz) which represents one million cycles/seconds. For example, if the clock speed is 3 MHz then there are, 3,000,000 clock cycles/second. One part of the CPU is responsible for performing calculations and executing instructions. This part is called the arithmetic logic unit, or ALU. There are a variety of subsidiary components, which support the ALU. These components include the decoder, the sequencer and a variety of registers. The decoder converts instructions stored in program memory into codes, which the ALU can understand. The sequencer manages the flow of data along the microcontroller‟s data bus. Registers are used by the CPU to temporarily store vital data, which are volatile: they can change during program execution. Most microcontroller registers are memory-mapped, associated with a memory location, and can be used like any other memory location. See Figure 2.8 . Every CPU has some certain type of registers which are common to most of microcontroller    

Accumulator Stack Pointer Index Register Program Counter

2.5.2. Memory The memory or a microcontroller is easily subdivided in two types  

Control Storage Data Storage

2.5.2.1. Control Storage Control Storage is known by a number of different names including program memory & firmware. In other words for the storage of the program microcontroller has a ROM. Microcontrollers are differentiated on the basis on the type of ROM.

Exploring Microcontroller Technology

18

Parallel Port

Parallel Port

Program Memory Data Memory

Core

Parallel Port

Counter/ timer

Serial Port

Serial Port

Fig 2.7: Block Diagram of Micro controller

Figure 2.8: Central Processing Unit

Exploring Microcontroller Technology

19

   



ROMless Microcontroller: ROMless micros are those with an external bus interfaced external ROM Mask Microcontroller: It contains ROM that is programmed by the factory from code you supply OTP (One-Time Programmable) Microcontroller: A OTP microcontroller has PROM (Programmable Read-Only-Memory) . Once program is written into it with a standard EPROM programmer, it can not be erased or modified. EEPROM Based Microcontroller. Many microcontrollers have limited amounts of EEPROM (Electrically Erasable Programmable Read Only Memory) on the chip. EEPROM seems more suited (because of its economics) for small amounts of memory that hold a limited number of parameters that may have to be changed from time to time. This type of memory is relatively slow, and the number of erase/write cycles allowed in its lifetime is limited. Flash Based Microcontroller: These can be re-programmed many times, usually at least 1000. This makes it feasible to use one chip to test code changes over and over again, and avoid wastage of chips.

2.5.2.2. Data storage Data storage is known as RAM. RAM contains not only the data variables as well as stack if it is supported by hardware. And the data can be pushed and popped by using stack pointer. It also contains the area of dedicated registers for peripherals. 2.5.3. Special Function Register (SFR’s) According to Wilmshurst all the microcontroller peripherals can be configured in the software to operate in a number of different modes. Before using them certain control data must be sent to them to set them up. But for the further data flow & control there is need for some one. These needs are commonly met by means of dedicated registers, called either Special Function Registers (SFRs by Intel) or Control Registers (Motorola). One or more SFRs are used for control purposes, and one or more are used for control purposes, one or more are used for transfer of data. In practice one SFR may be used for both input and output, or be used several purposes. Each SFR can be attached with a specific peripheral for performing a specific task. See Figure 2.9. [2] 2.5.4. Input and Output Ports An I/O port is an interfaced through which data can be received & send by a microcontroller. Therefore I/O ports essentially as a primary channel of I/O data, with ports being easily connected to the other electronic devices to drive them. Usually Exploring Microcontroller Technology

20

Control SFR Microcontroller Core

Outside World

DATA BUS

Peripheral Data Transfer SFR

Interrupt

Figure 2.9: Generalized interfaced between Core & Peripherals

D Ctrl_Write

SET

Data Bus

CLR

D Pin_Write

Q

Control Register

SET

Q

Q

X

Data Register CLR

Q

Pin_Read

Figure 2.10: Standard bidirectional parallel I/O Pins

Exploring Microcontroller Technology

21

an I/O port is generally a group of up to 8 I/O lines which are addressed together as a byte. 2.5.4.1. Types& Modes of Ports There are two main port types, 1. Parallel 2. Serial And two port modes, 1. Synchronous 2. Asynchronous Parallel I/O requires a data line for each bit, while serial I/O uses a single line and transfers bits in sequence. Synchronous I/O is synchronized to a clock while asynchronous I/O is not. Microcontrollers most often have parallel I/O capability built in and serial I/O as a peripheral feature. Serial ports have a frequency of operation called their baud rate. The baud rate is the reciprocal of the transmission time for each bit. For example, if the baud rate is 9600 bits/second then the transmission time for each bit is 1/ 9600 of second. General features of each port are     

Simple Memory –mapped access, generally as an SER. Bidirectional with each bit is programmable Ability to drive LED or small load Single pin can be used for several functions Ports pins have different & alternate functionalities (like interrupt )

2.5.5. Counter /Timer Counter/ timer are crucial components of most embedded systems and included in microcontrollers. A basic computer timer is consists of a counter that can be read from or written to by the processor and driven by some constant frequency source. The counter‟s clock is typically either microcontroller‟s clock or external source. See Figure 2.11&2.12 n An n-bit binary counter can count from to (2 -1). When it reaches its maximum number, and another clock pulse is then received, it overflows back to zero.

2.5.5.1: Auto Reload feature Some counter have the feature of auto reload which means the counter value automatically reloaded to a predetermined value whenever it overflows. This reload Exploring Microcontroller Technology

22

Figure 2.11: A Simple 8-bit Counter/Timer

TC 1

2

n

3

Clock

Pulse Input

T

Figure 2.12: Pulse generation & Time interval

Exploring Microcontroller Technology

23

value is held in a presetable SFR. When ever overflow is occurred, this also causes an interrupt .This phenomenon is provide a way to generating the interrupt at a fixed frequency determined by the software engineer. If the counter is n-bit, then the overflows occur as count goes from (2n– 1) to 0.If reload value is R, it will count (2n –R) clock cycles before it overflows. With an input clock of frequency f Hz and period T, the interrupt on overflow period T int will be Tint= (2n –R) T And the interrupt frequencies will be fint = f/(2n –R)

(2:1)

(2:2)

[2]

2.5.5.2. Application of Counter/Timer 

Time Measurement: The most important application of Counter/timer is to keep the time. It does with the stable clock source of known frequency. The period of the clock forms a unit of time which can be used to measure much greater time duration. For example the time between the two pluses of the „Pulse Input‟ signal can be measured by the counting the number of clock cycles from leading edge of one pulse to the leading edge of the next. Then T=n Tc

(2:3)

TC= Known Frequency







Due to that, the counter can measure the time intervals between external events and initialize events on timed basis. Event Counting: Counters are also used for event counting. For example in object detection embedded application when ever any object is passed in between the object detecting module then an increment in the counter is occur. The real life example is automatic packing system. PWM Generation: Counters are used for generation of PWM to drive mechanical peripherals. PWM is defined as follow “A digital out put technique where a single line is used to output analog information by varying the time information by varying the length of time a pulse is active on the line.” [7] Baud Rate Generation: Counters are also used as baud rate generation for the serial port by keeping the fixed measurement of time intervals for invoking the necessary interrupts.

2.5.6. Interrupt System An embedded system which has to do a large amount of processing based on input signals. For that purposes it uses methodologies i.e. Exploring Microcontroller Technology

24

1. Interrupts: An external input to the CPU which can be used to force CPU to rapid response to the external event. [2] 2. Polling: Polling is a software technique whereby the processor continually asks a peripheral if it needs servicing. The peripheral sets a flag when it has data ready to be transfer. Interrupt sources may signal the emergency situation like temperature is beyond of limits or may indicate the periodical events like A/D conversion is completed. When an interrupt occur the CPU performs following jobs 1. 2. 3. 4. 5.

Execute the current instruction Save the context register information Process the interrupt service routine (ISR) Restore the context register Return to main program

2.5.6.1. Interrupt service routine (ISR) Software routine those is executed in response to an interrupt. It is same like subroutine but it is initiated by an interrupt and ended by return from interrupt (RETI in 8051). 2.5.6.2. Interrupt vector The starting address of an ISR is determined by the contents of a location in program memory. 2.5.6.3. Interrupt Priority A sophisticated MCU has many interrupt sources i.e. from external sources and on chip peripherals like timer & serial port. These all interrupts can be enabled or disable the mask bit in the relevant SFR. A Global interrupt enable is usually available in the microcontrollers. Each interrupt is connected to an interrupt vector which may be specified to it self and some time it may shared in between many sources. Some time many interrupts occur simultaneously, for that purpose MCUs uses the priority schemes. For example we consider the interrupt system of 8051 then it reveals it contains basically five interrupts and each one is used with respect to its priority & has an interrupt vector in control storage. 2.5.6.4. Triggered Classification of Interrupts There are two interrupt triggering methods supported for external interrupts for micro-controllers Exploring Microcontroller Technology

25

 

Level triggered interrupts Edge triggered interrupts. a) Level Triggered Interrupts: The processor merely samples the input signal every instruction cycle and if it sees a logic level 0 on the input, it fires an interrupt in the system. Thus, as long as the given input is low, the processor will keep signaling that there is an interrupt. Conversely, if you have a signal which goes low for one cycle and then returns to a logic level one the interrupt will not be cleared. The microcontroller will hold the interrupt signal until the routine can be vectored to and is completed as signaled by the execution of return from interrupt instruction. If input signal goes low and fires an interrupt, but does not return high after your ISR for that interrupt is complete, the processor will immediately request another interrupt for the same source. As long as the signal is low, the interrupt signal will be held active by the processor. Level triggered interrupts are most useful in situations where a device may be requesting interrupts very frequently. For example, if you have a device which periodically has high bursts of service requests, it may want to trigger another interrupt before you can service the previous request, and thus will not pull the request line back high b) Edge Triggered Interrupts: An edge triggered interrupt is caused by a high to low transition in the input signal. In the edge triggered method, an interrupt is caused by a sample in which the signal is a high immediately followed by a sample in which the signal is a low. Once this transition is detected, an interrupt will be signaled by the processor. As was stated above, such a method is useful for devices which will not pull the signal back to logic level one immediately upon being serviced. This is because only the falling edge of the signal will cause the interrupt, not the logic level zero state of the input signal. This means that eventually input signal must return to a logic level one if it is to ever cause another interrupt in the system. Edge triggering works well for devices that do not makes an explicit interrupt request and therefore do not typically require software service to clear their interrupt signal. The most common example of this is a system tick. Such signals are usually generated by an RTC. These devices often provide an input signal with a fixed duty cycle (such as 50%) meaning that for a certain portion of their cycle they are held high and then they are held low for the remaining portion of their cycle. The problem with using a level triggered interrupt is that the entire portion of the cycle that the signal is low will cause a big burst of interrupt activity which, if it does not mess up the timing and function of the software, will at the least prove to be a big waste of system resources.

Exploring Microcontroller Technology

26

Address Interrupt 2 8-byte data area 00001h Interrupt 1 8-byte data area 0000Bh Interrupt 0 8-byte data area 00003h Reset Vector 00000h Control Store

Figure 2.13: 8051 Interrupt priority

Exploring Microcontroller Technology

27

In an edge triggered setup, system will never receive another interrupt from this device because the request line will always be held low and thus the processor will not see any more high to low transitions in the state of the signal. 2.5.7. Buses A bus carries information in the form of signals. There are three main buses:

address, data, and control. 2.5.7.1. Address bus The address bus is unidirectional and carries the addresses of memory locations indicating where the data is stored. The number of wires in the address bus determines the total number of memory locations. With a 13 bit address bus, for example, there would be 213 or 8192 memory locations. 2.5.7. 2. Data bus The data bus is bi-directional and carries information between the CPU and memory or I/O devices. Computers are often classified according to the size of their data bus. The term “8-bit microcontroller” refers to a microcontroller with 8 lines on its data bus. The number of wires in the data bus determines the number of bits that can be stored in each memory location. 2.5.7. 3. Control bus The control bus carries data which controls system activity. Often this data includes timing signals which synchronize the movement of other information. 2.5.8. Clocking Affairs An essential part of microcontroller is the clock oscillator. This performs  

Drive the forwards all the system tasks Provide accurate measurement of time

The selection of oscillator is depends upon the type of application. There are two types of oscillators are used a) R-C Oscillator In the small level application the RC oscillator is used where the accuracy of frequency is not significant. By using Kirchoff law we can easily determine the value of R and C to require frequency as well as the oscillation period & response time . As mention above that their frequency is also unreliable but also that have disadvantage that it drift with rise of temperature and time. Exploring Microcontroller Technology

28

b) Quartz Oscillator: The quartz crystal is made of a very thin slice of crystal. The crystal is piezoelectric which means that it has property that it is subjected to mechanical strain then a voltage appears opposite surfaces & vice versa. Crystal are grown in laboratory conditions, and then cut to physical dimensions, which set the resonant frequency. In Figure 2.14 a circuit is given for crystal oscillatory function 2.5.9. Watch Dog Timer For those embedded systems that can't be constantly watched by a human, watchdog timers may be the solution. Watchdog timer can be defined as “A piece of hardware that can be used to automatically detect software anomalies and reset the processor if any occur” Most embedded systems need to be self-reliant. It's not usually possible to wait for someone to reboot them if the software hangs. Some embedded designs, such as space probes, are simply not accessible to human operators. If their software ever hangs, such systems are permanently disabled. In other cases, the speed with which a human operator might reset the system would be too slow to meet the uptime requirements of the product. Generally speaking, a watchdog timer is based on a counter that counts down from some initial value to zero. The embedded software selects the counter's initial value and periodically restarts it. If the counter ever reaches zero before the software restarts it, the software is presumed to be malfunctioning and the processor's reset signal is asserted. The processor (and the embedded software it's running) will be restarted as if a human operator had cycled the power. Figure 2.15 shows a typical arrangement. As shown, the watchdog timer is a chip external to the processor. However, it could also be included within the same chip as the CPU. This is done in many microcontrollers. In either case, the output from the watchdog timer is tied directly to the processor's reset signal. 2.5.9.1. Kicking the dog The process of restarting the watchdog timer's counter is sometimes called "kicking the dog." The appropriate visual metaphor is that of a man being attacked by a vicious dog. If he keeps kicking the dog, it can't ever bite him. But he must keep kicking the dog at regular intervals to avoid a bite. Similarly, the software must restart the watchdog timer at a regular rate, or risk being restarted. A watchdog timer is useful tool helping system recover from transient failures. Since it is so common to find watchdogs built into modern microcontrollers, the technique is effectively free. If you are working on a mission-critical system, then either Exploring Microcontroller Technology

29

Figure 2.14 Crystal oscillator circuit

Figure 2.15: Basic Watch Dog timer

Exploring Microcontroller Technology

30

common sense or a regulatory body will insist that you use a watchdog. It's always a good idea to make systems more self-reliant.

2.6. Choosing the Microcontroller There are many type of microcontroller in the market. Those vary according to their capability & peripherals. Since Microcontrollers are microprocessors with integrated general-purpose interfacing logic to facilitate the control of peripherals devices. This logic is encapsulated in I/O ports (i.e., collections of I/O pins and related interface logic) that can be written to or read from by program code. Microcontrollers are commonly used to implement digital control systems because they require minimal interfacing hardware. Peripheral devices range from user input and display units to memories and communication interfaces. According to [9] for choice of a microcontroller the following issue should be keep in mind  



Designers of microcontroller-based systems must allocate devices to ports and customize subroutines to access the devices under the specific port assignment chosen. There are several issues in performing this task. Most importantly, additional hardware must be minimized so as to maintain the benefits of using a microcontroller, namely reducing part count. If there are more device pins than port pins, then the ports need to be time-multiplexed with the corresponding de-multiplexing performed in external hardware. Another important goal is to minimize code size

A rule of 3P‟s is suggested by [10] for processor‟s desirable characteristics are what I‟ll refer to as “the three P‟s”: Price, Peripherals, and Performance Therefore if consider the opinion from different experts then we can enlist them as characteristics of a microcontroller            

Capable of direct interface to a significant no of sensor and actuators High level of integration i.e. many peripheral included on-chips Physically small Low cast , Speed Comparatively simple program and data storage requirement An optimized instruction set for generation of compact code Ability to operate in the real-time environment Ability to operate in the hostile environment i.e. high radiation Low power capability Development tools availability Size of control storage and Data storage I/O band width which affects the performance Supportive to numerical operations like multiply , division, fuzzy & complex variables [2] [4]

Exploring Microcontroller Technology

31

2.7. General Introduction to Microcontroller Families Although the model microcontroller which we will discussed in detail in the following chapter & our application is based on which is Intel 8051 but it is also necessary to give an overview to all famous families 2.7.1. 8051 First offered by Intel in the late 70s, this core is at the heart of the biggest variety of micros on Earth, from several manufacturers. Philips is the biggest player in the 8051 market, with Intel winding down their involvement to concentrate on monopolizing the PC CPU and chipset. The 8051 has Harvard architecture (code and internal data both start from 0). a) General supportive features        

Powerful bit manipulation instructions - part of RAM and many special registers are bit-addressable. Multiply and divide instructions. At least two 16-bit timers. UART capable of 500kb/s at 16MHz on all but very small parts. Plentiful internal RAM. Straightforward code addressing - always starts at zero. I/O design makes bi-directional I/O easy. Comfortable to use once learnt it

b) General drawbacks:       

Very quirky instruction set Confusing variety of internal and external memory spaces. I/O design prevents true floating inputs, and pins are always high after reset. Not very fast due to clock division. Access to external data very weak - single pointer register only. Poor compiler support - no stack-relative access. Watchdog not standard.

2.7.2. Zilog Z8 The Zilog Z8 core is not new, but a family of small OTP parts oriented at the low-cost consumer market is recent. Large ROMless parts exist, but I'm not aware of any interest in them. a) General supportive features 

Cheap true emulator available handles 18-40 pin parts.

Exploring Microcontroller Technology

32

      

Non-accumulator instruction set. Moveable register "window" into RAM. Powerful, orthogonal instruction set. Two timers in all but smallest part. Watchdog standard. Two analog comparators standard. Wide range of 18-pin parts.

b) General drawbacks     

Poor noise immunity. No A/D in small parts No RESET pin Slow Timer 8-bit only.

2.7.3. AVR A new family from Atmel touted as RISC, the AVR core promises blinding speed at one instruction per clock cycle. Although initial data promised 20MHz clock speeds, production speeds are only now reaching 8MHz. Even at 4MHz, the baseline speed, a 250ns instruction cycles isn't to be sneezed at; it's 4 times quicker than the PIC, its nearest competitor, at the same clock speed. Like their 8051-based family all AVR micros are flash-based, and free programmers are already around. Atmel claim that the AVR was designed in consultation with C compiler vendors, and it certainly includes some software features unexpected in a RISC micro. a) General supportive features              

Flash based, programming specs published. Inputs have optional pull-up and 20mA sink capability. Very high speed (almost 1MIPS/MHz) Large register space. All data processing register-to-register: no accumulator. Instruction set as powerful as possible given opcode space. Three RAM address pointers with auto increment/decrement. Zero-flag propagation for multi-byte compares. Watchdog and EEPROM standard. 1Mb/s UART on all but smallest member. No reset circuit required. Separate I/O output latch and input pin registers. Excellent C compiler support. Able to address >64K code and data.

b) General drawbacks Exploring Microcontroller Technology

33

    

Some odd restrictions on instruction usage. Apparent redundancy in instruction set. Instruction set not "clean" and orthogonal - hard to learn. Limited bit manipulation. No brown-out detector.

Like the 8051, very capable when all the instruction set and memory space quirks are understood. The non-accumulator design and zero-flag propagation make multibyte (eg 16-bit) arithmetic very compact. The separate output latch and input pin I/O registers prevent those nastily glitches that plague single-register designs. If Atmel can get the core speed up to 16MHz the AVR will get into all sorts of high-speed applications previously barred to micros. 2.7.4. PIC Microchip's RISC family has been around a few years now. It has become very popular through aggressive OTP pricing, a simple instruction set, robust hardware (e.g. brown-out detectors) and excellent support. I haven't used it, but I'll make some comments comparing it to the AVR, which is clearly designed to compete with the PIC. a) General supportive features:    

Standard brown-out detector. Wide range of sizes and peripheral choices. More language and tool choices. Running at published clock speeds.

b) General drawbacks:       

4 times slower at same clock speed. Much weaker instruction set. Limited code and data addressing. No C compiler support. No flash parts (promised). Single I/O in/out register. Accumulator-based data processing.

2.7.5. HC05 It is very popular family of MCUS from Motorola. a) General supportive features:  

Von Neumann architecture is easy to understand. Straightforward instruction set with some bit handling.

Exploring Microcontroller Technology

34



Excellent support from Motorola.

b) General drawbacks:      

Weak timers. No consistency within family - many variants specialized. No push/pop access to stack. Evaluation board (EVB) is expensive but unreliable. Not price-competitive. Slow.

2.7.6. HC11 A very popular family from Motorola, more powerful than the HC05, and it is competitive with the 8051. a) General supportive features:     

Von Neumann architecture is easy to understand. Powerful, easy-to-use instruction set. Popular parts are good value. Good support for C compilers. Good support from Motorola.

b) General drawbacks:    

Much smaller range than 8051 derivatives. Slow UART. Overall: Probably easier to learn than the 8051, and a little more powerful, but less variety of derivatives. A logical upgrade for HC05 users.

Exploring Microcontroller Technology

35

CHAPTER 3 Microcontrollers Based System Fundamentals

Exploring Microcontroller Technology

36

3.1. Embedded systems and Microcontroller By analyzing features, constraints & applications of the embedded system, it can be easily inferred that any embedded system qualities of reliability, timeliness and cost effectiveness. And microcontroller is a particular type of microprocessor, optimized to perform control functions for the lowest cost and at the smallest size possible. Generally microcontrollers are used in a recognizably „embedded system‟ environment. These facts lead us to redefine embedded systems as “An embedded system is a microcontroller-based, software-driven, reliable, realtime control system, autonomous, or human or network interactive, operating on diverse physical variables and in diverse environments, and sold into a competitive and cost conscious market.” [2] Embedded systems are divided in to two main domains  

Control Driven ( Event based) Data Driven (Real Time operating system)

Microcontrollers belong to the control driven class to perform the control the other devices which are interfaced with them. The usual reason for embedding a microcontroller is to interact with the environment, often by monitoring and controlling external machinery. In order to do this, analog inputs and outputs must be transformed to and from digital signal levels. Additionally, significant current loads may need to be switched in order to operate motors, light fixtures, and other actuators. All these requirements can lead to a large computer circuit board dominated by non-digital components. In some systems "smart" sensors and actuators (that contain their own analog interfaces, power switches, and small CPUS) may be used to off-load interface hardware from the central embedded computer. This brings the additional advantage of reducing the amount of system wiring and number of connector contacts by employing an embedded network rather than a bundle of analog wires. However, this change brings with it an additional computer design problem of partitioning the computations among distributed computers in the face of an inexpensive network with modest bandwidth capabilities. There are a variety of interfaces that enable the system to measure, manipulate, and otherwise interact with the external environment as shown in Figure 3.1. Some differences with desktop computing may be:  

The human interface may be as simple as a flashing light or as complicated as real-time robotic vision. The diagnostic port may be used for diagnosing the system that is being controlled -- not just for diagnosing the computer.

Exploring Microcontroller Technology

37

MCU

Figure 3.1: A detailed possible Embedded Microcontroller system

Output Data

Actuators

Input Data Sensor Keypad Switches Date links

MCS Buffer Data Processing

Display

Transfer Data

Figure 3.2; Data flow in Embedded Microcontroller system

Exploring Microcontroller Technology

38

 

Special-purpose field programmable (FPGA), application specific (ASIC), or even non-digital hardware may be used to increase performance or safety. Software often has a fixed function, and is specific to the application.

In addition to the emphasis on interaction with the external world, microcontroller system also provides functionality specific to their applications. Instead of executing spreadsheets, word processing and engineering analysis, embedded systems typically execute control laws, finite state machines, and signal processing algorithms. They must often detect and react to faults in both the computing and surrounding electromechanical systems, and must manipulate application-specific user interface devices. If we consider the Figure 3.2 then it reveals that microcontroller systems process the input taken from the sensor or data link according to the processing algorithm for controlling purposes or interfacing between two communication devices. So that it not only controls the devices but also control the data transfer flow.

3.2. Control system concepts Embedded systems are frequently used to control processes and devices. With embedded controllers these products can be made with a large complexity and flexibility with acceptable production costs. These processes or devices consist of physical (e.g. mechanical, electrical) components and exhibit time-continuous behavior. The controller, implemented in software, is generally some form of finitestate machine on a digital processor and is, therefore, asynchronous and timediscrete. The controller takes care of functions such as start-up, mode switching, constraint handling, safety and, using a synchronous time-discrete basic feedback controller, stability and performance. As above, it is discussed in detail that the microcontroller belongs to the control domain of embedded systems. As well some terms like sensor & actuators are used without defining & is also described at [1.3] that embedded algorithm can be based on control laws. So it is necessary to discuss some basic concepts of control systems 3.2.1. Basic definitions 3.2.1.1. Sensor A device that detects or measures real world condition heat or light and convert the physical variable into an electrical signal for use by controller into an analog or digital representation. For example photo detector converts the light energy into the proportional current.

Exploring Microcontroller Technology

39

3.2.1.2. Actuator An actuator is a device that provides the motive power to the process (i.e., a device that causes the process to provide the output). 3.2.1.3. Process/Plant The part of the system output is to be controlled is called process. The combination of process and actuator is called plant. 3.2.1.4. Controller Unit The controller is the intelligent element which computes the desired control signal by comparing the set point and error. It can be a piece of hardware or embedded software. 3.2.1.5. Set point: The input is called reference point or set point. 3.2.1.6.Error The difference between reference point and output from sensor is called is called error. 3.2.1.7. Defining the Control system Control system can be defined as follow “A control system is an interconnection of components forming a system configuration to provide a desired system response.” “Control system is collection of mechanical and electrical devices connected for the purposes of   

Commanding Directing Regulating the physical plant

3.2.2. Composition of a control system A control system comprises one or more sensors, one or more actuators & a control unit. The sensor provide input to the system, the actuators give practical effect to the output. The control unit links the sensors to actuators & exercise the control function assign to it. The control unit would be a simple switch or a powerful computer system i.e. microcontroller which is included in programmable control unit. See Figure 3.3 Exploring Microcontroller Technology

40

INPUT SET POINT

PLANT OUT PUT CONTROLLER

COMPARISON

ACTUATOR

PROCESS

SENSOR

Figure 3.3 Composition of Control System

Desire out put response

Out put Actuating Device

Process

Figure 3.4 Open-loop systems

INPUT SET POINT

OUT PUT COMPARISON

CONTROLLER

PLANT

SENSOR

Figure 3.5 Closed loop (feed back) system

Exploring Microcontroller Technology

41

3.2.3. Types of control system 3.2.3.1. Open Loop system An open-loop control system utilizes an actuating vice to control the process & the system does not measure the output and there is no correction of the actuating signal to make that output conform to the reference signal. In other words control system that is not self-correcting. The system outputs have no effect upon the signals entering the process (i.e., the control inputs are not influenced by the process outputs). For example electrical toaster 3.2.3.2. Closed loop/Feedback system In a closed loop control the system includes a sensor to measure the output and uses feedback of the sensed value to influence the control variable. For example, “self-tunable temperature system". See Figure 3.4 & 3.5 3.2.4. PID Control Strategies Generally the control strategies are used in the controller is called PID. PID stands for "proportional, integral, derivative”. Each of these performs a different task and has a different effect on the functioning of a system. And controller exercising these strategies is called PID controller. So that due to this reason the microcontroller containing the PID algorithm can be called a digital PID controller. Proportional, Integral & Differential control strategies can be used individually and in form of any combination. 3.2.4.1. Proportional ”A proportional controller is just the error signal multiplied by a constant and fed out to the drive.” Proportional control is the easiest feedback control to implement, and simple proportional control is probably the most common kind of control loop. Lets X is the set point and Y is the out put the error signal will be equal to the difference of them. It would be multiplied by constant K to for the actuator to drive the plant. Error E = X–Y Actuator Signal = K(X – Y)

(3:1) (3:2)

3.2.4.2. Integral Integral control is used to add long-term precision to a control loop. It is almost always used in conjunction with proportional control.

Exploring Microcontroller Technology

42

3.2.4.3. Differential: Proportional control deals with the present behavior of the plant, and that integral control deals with the past behavior of the plant. If we had some element that predicts the plant behavior then this might be used to stabilize the plant so that we use the differential technique for that purpose.

3.3. Interfacing issues of Microcontroller systems Although microcontroller is a digital device it can be easily interfaced with the other digital devices easily but by considering the Figure 3.1 we come to know that the sensor and actuators have an interface of Analog to digital converter and Digital to analog converters between them selves and microcontroller. So that we can dived the interfacing issue of microcontrollers in to following  

Analog matters Interfacing the with external devices

3.4. Analog matters Since microcontrollers have a lot of events to be connected with analog signals. They must be able to convert these input analog signals to digital form from a temperature sensor & also be able to convert digital signals to analog form to drive a motor. The analog matters deals with the conversion on both sides. Since the A/D conversion deals with some several individual processes therefore overall system for digitizing a signal is called “Data acquisition system”. On the other hand D/A conversion would result as PWM generation to drive a mechanical device. 3.4.1. Analog to digital conversion The usual method of bringing analog inputs into a microcontroller is to use an analog-to-digital converter (ADC). In analog-to-digital converter (ADC) accepts an analog input-a voltage or a current from a sensor or transducer and converts it to a proportional digital value that can be read by a microcontroller. The features of the ADC, some of these are shown in the Figure 3.7 are explained below 



Analog input: There is an analog input to be converted & maximum permissible input is called “input range “. The values those are beyond & below that range is treated same as maximum and minimum permissible inputs. Voltage reference: The reference voltage is the maximum value that the ADC can convert

Exploring Microcontroller Technology

43

  

Start conversion: The start of conversion is initiated by the microcontroller by setting the start conversion line. End of Conversion: ADC signals the microcontroller through End of conversion line by generating edge triggered interrupt. Output Enable: The converted output is made available on the output lines through the output enable line.

0 1 1 0 0 0 1 0 1 1 0

analog in

digital out

Figure 3.6 A/D Converter



Digital output (n-bits)

+

Voltage Reference

Analog to Digital Convertor

Start conversion

+ End of conversion

Analog Input

-

Output enable

Figure 3.7 Essential feature of ADC Bit: Volts: Output Value:

Bit 7 Bit 6 Bit 5

Bit 4 Bit 3 Bit 2 Bit 1

Bit 0

2.5 1.25 0.625 0.3125 0.156 0.078 0.039 0.0195 0

0

1

0

1

1

0

0

Table 3.1 Example conversion, on an 8-bit ADC

Exploring Microcontroller Technology

44



Quantization level/ smallest step size: The quantization level is the possible smallest step of conversion which can be measure for „n‟ bit ADC as Quantization level = 1/2n (3:2) And no of quantization levels is reciprocal of (3:2) i.e No of Quantization level = 2n

(3:3)

For an 8-bit ADC number of quantization levels are 256 

Resolution of ADC: The resolution defines the smallest voltage change that can be measured by the ADC the resolution is the same as the smallest step size, and can be calculated by dividing the reference voltage by the number of possible conversion values. Resolution can also be defined as “The number of bits those the ADC uses to represent the analog signal is the called resolution.” For example the output lines are „n‟ then resolution can be calculated as Resolution = Reference voltage/2n

(3:4)

If we are using the 8-bit ADC and reference voltage is 5 volt the resolution of ADC will be 19.5mv For example if we consider the table (3.1) where the decimal 44 is shown in the binary pattern after conversion. The most significant bit of this word indicates whether the input voltage is greater than half the reference (2.5V, with a 5V reference). Each succeeding bit represents half the range of the previous bit. The input voltage can be calculated by adding the voltages corresponding to each set bit in 0010 1100. .625 + .156 + .078 = .859 volts

(3:5)

Some microcontroller also uses the analog to digital converter as on chip peripherals. For on chip ADC there are special function registers for the manipulation of their operations. 3.4.2. Digital to analog conversion The digital to analog conversion is another important aspect of interfacing of microcontrollers. By dint to it we can control the actuators signal to drive the plant. For example, drive the dc motor for movement of robot. Similarly if consider the laser wireless communication then to we uses digital to analog converter laser driver's modulation and bias currents.

Exploring Microcontroller Technology

45

3.4.2.1 Digital to analog converter Digital to analog converter is an integrated circuit which receives the digital input in form of n-bit parallel data word or in serial manner and convert into an equivalent analog representation. The transfer & conversion of data is controllable by the control lines. Let D = n-bit digital input k = converter constant Vr = reference voltage. Vos= offset voltage Vo= output voltage The D maximum input can take (2n – 1).So the value of D/2n will also be less than 1. And the term kVr represents the output range. So the output voltage can be represents as [2] Vo= (D/2n) kVr + Vos (3:6) The resolution has same definition as for ADC, it can be determined as Resolution= (1/2n) kVr

(3:7)

In the figure3.8 the DAC is used by microcontroller to control the motor 3.4.2.2 Plus width modulation (PWM) Pulse width modulation (PWM) is another powerful technique for controlling analog circuits with a processor's digital outputs. PWM is employed in a wide variety of applications, ranging from measurement and communications to power control and conversion PWM is analog out put which is by nature repeating digital signal with a specific pulse width. Duty cycle is the fraction of the PWM cycle during which the pulse is active and measure of power being transferred in each PWM cycle. [7] By controlling analog circuits digitally, system costs and power consumption can be drastically reduced. So in the microcontrollers the PWM generation is the function of timers. To start PWM operation, software should: 1) Set the period in the timer/counter that provides the modulating square wave 2) Set the on-time in the PWM control register or memory location 3) Set the direction of the PWM output, which is one of the general-purpose I/O pins 4) Start the timer [12] Through the use of high-resolution counters, the duty cycle of a square wave is Exploring Microcontroller Technology

46

Micro Controller

Data Lines DAC

In

I/V

P Motor

Figure 3.8: Microcontroller based Motor Control using DAC

Figure 3.9: PWM Signals of Varying Duty Cycles Exploring Microcontroller Technology

47

modulated to encode a specific analog signal level. The PWM signal is still digital because, at any given instant of time, the full DC supply is either fully on or fully off. The voltage or current source is supplied to the analog load by means of a repeating series of on and off pulses. The on-time is the time during which the DC supply is applied to the load, and the off-time is the period during which it supply is switched off. Given a sufficient bandwidth, any analog value can be encoded with PWM. In the Figure 3.8 three different PWM signals, Figure 3.8 a shows a PWM output at a 10% duty cycle. That is, signal is on for 10% of the period and off the other 90%. If, the supply is 9V and the duty cycle is 10%, a 0.9V analog signal results.

3.5. Interfacing the with external devices Since system control functions were implemented using logic components and were usually large, heavy boxes. Later on, microprocessors were used and the entire controller could fit onto a small circuit board. As the process of miniaturization continued, all of the components needed for a controller were built right onto one chip. By only including the features specific to the task, cost is relatively low. A typical microcontroller has bit manipulation instructions, easy and direct access to I/O, and quick and efficient interrupt processing. One important distinction between a microcontroller and a microprocessor is that a microcontroller usually has special hardware for dealing with the outside world. These are called parallel input/output lines, or parallel I/O lines. So that to by revisiting the Figure 3.2 we can easily understand a microcontroller system would be comprise of separate modules of input (sensor or key press) and output in form of actuator (motor) or display (LED or LCD).Theses all external devices are inter faced with microcontroller via I/O ports. So it is necessary to discuss how microcontroller copes with some of these external devices. 3.5.1. Keypad Interfacing Keypads are large switch arrays. These are constructed in a matrix style & a (n x m) keypad can be read by the (n + m) port pins. As shown in the fig 3.10. The detection of key detection is done in the software. The entire row bits are initialized as output on the logic 0 and column bits as the input. After detection of key stroke the row and column bits should be returned back to output and input respectively to await the next keystroke. See Figure 3.11. [2] Some times the dedicated IC is used to save the I/O lines. There are four output lines A, B, C and D which indicates which key is pressed and DA (data available line) the key is being pressed. 3.5.2. Display Devices In many applications it is necessary for a microcontroller to display some information Exploring Microcontroller Technology

48

1

2

3

4

5

6

7

8

9

0

+ -

*

/

Microcontroller Port

.

Figure 3.10: Keypad interfacing

Set Row bits as output Set column bits as input Set Row bits to zero Save column bit pattern Set Row bits as input Set column bits s as output

Set column bits to zero

Read & Save Row bit pattern Combine Column and Row pattern to form 8 bit word

Figure 3.11: Software routine for keypad

Exploring Microcontroller Technology

49

to a user. Information can be displayed using Light Emitting Diodes (LED), segmented LED displays, dot matrix Liquid Crystal Displays (LCDs), or segmented LCDs. There two different types of display are used for microcontroller based system i.e.  Seven segment light emitting diode display  Liquid crystal display 3.5.2.1. Seven-segment light emitting diode display A display technology that uses a semiconductor diode that emits light when charged. It usually gives off a red glow, although other colors can be generated. It is used in readouts and on/off lights in a myriad of electronic appliances. [1] The seven segment display is a very popular display which can display numeric number from 0 to 9 and a limited no of letters. Every segment is associated with specific input line. By putting this line high we can glow the segment. A single seven segment can also be interfaced with the microcontroller. Then each pin of display associated with each segment will be connected separate pin of port. So to put a letter or numeric value we will use a bitmap as shown in table 3.2. Some times the seven segment display will be used in groups to display the decimal values. So to use them in the groups we multiplexed these to use to save the driver lines. See the Figure 3.13. 3.5.2.2. Liquid crystal display (Hitachi (HD44780) A display technology that uses rod-shaped molecules (liquid crystals) those flow like liquid and bend light. Non energized the crystals direct light through two polarizing filters, allowing a natural background color to show. When energized, they redirect the light to be absorbed in one of the polarizer‟s, causing the dark appearance of crossed polarizer to show. The more the molecules are twisted, the better the contrast and viewing angle. Liquid Crystal Displays are a inexpensive, low power means to display information. Unfortunately, the structure and control schemes of the displays are usually complicated. LCD control becomes even more complicated when the structure is designed to reduce the display pin count. The Hitachi HD44780 microcontroller based liquid crystal display is recognized as the standard LCD display for displaying purposes. This display is called intelligent display because it has ASCII decoders, character Generators and LCD control circuitry. The main features of LCD  

5 X 8 and 5 X10 dot matrix possible Low power operation support

Exploring Microcontroller Technology

50

g

f

Dp a

b

a f e

com e

g

b c

d

d

c

com

Figure 3.12: Seven segment display

0 1 2 3 4 5 6 7 8 9 A b C d E F

a (Pin 1)

b (Pin 10)

c (Pin 8)

d Pin 6)

e (Pin 5)

f (Pin 2)

g (Pin 9)

0 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0

0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 1

0 0 1 0 0 0 0 0 0 0 0 0 1 0 1 1

0 1 0 0 1 0 0 1 0 1 1 0 0 0 0 1

0 1 0 1 1 1 0 1 0 1 0 0 0 0 0 0

0 1 1 1 0 0 0 1 0 0 0 0 0 1 0 0

1 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0

Table 3.2: Seven segment display bitmap

Common Cathode lines

a MCU

f g

b

e

c d

a

a

f g

b

e

c d

a

f g

b

f g b

e

c

e

d

c d

Segment drivers

Figure 3.13: Multiplexed seven segment display Exploring Microcontroller Technology

51

2.7 to 5.5V Correspond to high speed microprocessor bus interface 4-bit or 8-bit interface enabled 80 X 8-bit display RAM (80 characters max.) 64 X8-bit character generator ROM  8 character fonts (5 X 8 dot)  4 character fonts (5 X 10 dot) Wide range of instruction functions:  Display clear, cursor home, display on/off, cursor on/off, display character blink, cursor shift, display shift Automatic reset circuit that initializes the controller/driver after power on Internal oscillator with external resistors Low power consumption 

       

The 44780 LCD requires 3 control lines as well as either 4 or 8 I/O lines for the data bus. The user may select whether the LCD is to operate with a 4 bit data bus or an 8-bit data bus. If a 4-bit data bus is used, the LCD will require a total of 7 data lines (3 control lines plus the 4 lines for the data bus). If an 8-bit data bus is used, the LCD will require a total of 11 data lines (3 control lines plus the 8 lines for the data bus). This LCD is available in 1X16 to 4X16 combinations. 1X16 means that 1 for line & sixteen for character. The three control lines are referred to as EN, RS, and RW & 8 data lines. 







EN: The EN line is called "Enable." This control line is used to tell the LCD that you are sending it data. To send data to the LCD, program should first set this line high (1) and then set the other two control lines and/or put data on the data bus. When the other lines are completely ready, bring EN low (0) again. The 1-0 transition tells the 44780 to take the data currently found on the other control lines and on the data bus and to treat it as a command. RS: The RS line is the "Register Select" line. When RS is low (0), the data is to be treated as a command or special instruction (such as clear screen, position cursor, etc.). When RS is high (1), the data being sent is text data which should be displayed on the screen. For example, to display the letter "T" on the screen you would set RS high. RW: The RW line is the "Read/Write" control line. When RW is low (0), the information on the data bus is being written to the LCD. When RW is high (1), the program is effectively querying (or reading) the LCD. Only one instruction ("Get LCD status") is a read command. All others are write commands--so RW will almost always be low. Data lines: It has 8 data line s which can be used as 8 bit data bus & as well as 4 bit data bus.

LCD has two different memories to perform the functions 

DDRAM (Display Data RAM): Display data RAM (DDRAM) stores display

Exploring Microcontroller Technology

52

Figure 3.14: Instruction set summary

Exploring Microcontroller Technology

53



data represented in 8-bit character codes. Its extended capacity is 80 X 8 bits, or 80 characters. The area in display data RAM (DDRAM) that is not used for display can be used as general data RAM. CGROM (Character Generator ROM): The character generator ROM generates 5 X 8 dot or 5 X 10 dot character .It can generate 208 5X8 dot character patterns and 32 5 X10 dot character patterns. User-defined character patterns are also available by mask-programmed ROM.

a) Instruction set There are four categories of instructions that:  Designate HD44780 functions, like display format, data length, etc.  Set internal RAM addresses  Perform data transfer with internal RAM  Perform miscellaneous functions

The detail of these instruction is given below & a summery of these instruction in Figure 3.15 I. Clear Display: Clear display writes space code 20H (character pattern for character code 20H must be a blank pattern) into all DDRAM addresses. It then sets DDRAM address 0 into the address counter, and returns the display to its original status if it was shifted. In other words, the display disappears and the cursor or blinking goes to the left edge of the display (in the first line if 2 lines are displayed). It also sets I/D to 1 (increment mode) in entry mode. S of entry mode does not change. II. Return Home: Return home sets DDRAM address 0 into the address counter, and returns the display to its original status. III. Entry Mode Set: I/D: Increments (I/D = 1) or decrements (I/D = 0) the DDRAM address by 1 when a character code is written into or read from DDRAM. The cursor or blinking moves to the right when increment by 1 and to the left when decremented by 1. The same applies to writing and reading of CGRAM. S: Shifts the entire display either to the right (I/D = 0) or to the left (I/D = 1) when S is 1. The display does not shift if S is 0. If S is 1, it will seem as if the cursor does not move but the display does. The display does not shift when reading from DDRAM. IV. Display On/Off Control: D: The display is on when D is 1 and off when D is 0. When off, the display data remains in DDRAM, but can be displayed instantly by setting D to 1.

Exploring Microcontroller Technology

54

C: The cursor is displayed when C is 1 and not displayed when C is 0. Even if the cursor disappears, the function of I/D or other specifications will not change during display data write. B: The character indicated by the cursor blinks when B is 1 V. Cursor or Display Shift: Cursor or display shift shifts the cursor position or display to the right or left without writing or reading display data as below S/C 0 0 1 1

R/L 0 1 0 1

Shifts the cursor position to the left. Shifts the cursor position to the right. Shifts the entire display to the left. Shifts the entire display to the right.

VI. Function Set: DL: Sets the interface data length. Data is sent or received in 8-bit lengths (DB7 to DB0) when DL is 1, and in 4-bit lengths (DB7 to DB4) when DL is 0.When 4-bit length is selected, data must be sent or received twice. N: Sets the number of display lines. F: Sets the character font. VII. Set CGRAM Address: Set CGRAM address sets the CGRAM address binary AAAAAA into the address counter. Data is then written to or read from the microcontroller for CGRAM. VIII. Set DDRAM Address: Set DDRAM address sets the DDRAM address binary AAAAAAA into the address counter. Data is then written to or read from the microcontroller for DDRAM. However, when N is 0 (1-line display), AAAAAAA can be 00H to 4FH. When N is 1 (2-line display), AAAAAAA can be 00H to 27H for the first line, and 40H to 67H for the second line. IX. Write Data to CG or DDRAM: Write data to CG or DDRAM writes 8bit binary data DDDDDDDD to CG or DDRAM. To write into CG or DDRAM is determined by the specification of the CGRAM or DDRAM address setting. After a write, the address is automatically incremented or decremented by 1 according to the entry mode. The entry mode also determines the display shift. X. Read Data from CG or DDRAM: Read data from CG or DDRAM reads 8-bit binary data DDDDDDDD from CG or DDRAM. Before entering this read instruction, either CGRAM or DDRAM address set instruction must be executed. If not executed, the first read data will be invalid. When serially executing read instructions, the next address data is normally read from the second read. [14] Exploring Microcontroller Technology

55

1 2 3 4

. Function Vss Vcc Vee RS

+5V 10 resistance H/L

5

R/W

H/L

6 7-14

E Data pins

PIN

Level

Description Ground Module power Liquid crystal drive Register select, H=data, L=instruction Read/Write, H=read (LCD->CPU) L=write (CPU->LCD Edge-sensitive Enable DB0 = LSB & DB7 = MSB

Table 3.3: LCD Pin description

Figure 3.15: LCD Interfacing

Exploring Microcontroller Technology

56

b) Pin Description In the table 3.2 the pin configuration is given. There is 8-bit data bus, 3 control lines and one pin for Vcc, Ground, and Vo (contrast). And also in fig 3.16 a LCD is interfaced with a microcontroller. Where the pins from 7-14 are connected with a parallel port to receive data & pins 3-6 are control pins are connect to the interrupts line of MCU. c) Initializing the LCD The first thing you have to do is initialize the LCD to power on and perform following steep if it is interfaced with microcontroller with 8-bit data bus 1. 2. 3. 4. 5.

Power ON; Wait more than 15ms Write 30H to LCD, Wait more than 4.1ms Write 30H to LCD, wait more than 100us Write 30H to LCD, wait more than 100us Set the operating parameters of LCD

I. Write 38H to LCD, for set interface length (8-BIT + 5x7 Dots) II. Write 0EH to LCD, “Display ON” III. Write 06H to LCD for “Entry Mode = Increment” IV. Write 01H to LCD for “ Clear Display” This is the initialization process to interface the LCD with microcontroller. After initialization other instruction are used for further operations.

3.6. Microcontroller based Serial communication There are two methods of data communication are used i.e. parallel and serial. Since parallel data communication requires more I/O lines. In the small scale embedded (microcontroller) systems there is no capacity to afford the luxury to use a lot of pins to use the data communication. There for in the embedded system the serial way of data transferring is used. Serial buses mark the landscape of embedded design. From displays to storage to peripherals, serial interfaces make communications possible. Many serial communication interfaces compete for use in embedded systems. The right serial interface for system depends on several key factors. A benefit of serial communications is low pin counts. Serial communications can be performed with just one I/O pin, compared to eight or more for parallel communications. Many common embedded system peripherals, such as analog-todigital and digital-to-analog converters, LCDs, and temperature sensors, support serial interfaces. Serial buses can also provide for inter-processor communication in a network. This allows large tasks that would normally require larger processors to be tackled with Exploring Microcontroller Technology

57

several inexpensive smaller processors. Serial interfaces allow processors to communicate without the need for shared memory and semaphores, and the problems they can create. 3.6.1. Some basic concepts    

    





 

Asynchronous: An asynchronous bus, data is sent without a timing clock. Synchronous: A synchronous bus sends data with a timing clock. Full-duplex: Full-duplex means data can be sent and received simultaneously. Arbitration: Procedure to ensure that, if more than one master simultaneously tries to control the bus, only one is allowed to do so and the message is not corrupted Half-duplex: Half-duplex is when data can be sent or received, but not at the same time. Baud rate: The signaling rate of a line, which is the number of transitions (voltage or frequency changes) that are made per second. Bit rate: The transmission speed of binary coded data. Data rate: The data transfer speed within the computer or between a peripheral and computer. Master/slave: Master/slave describes a bus where one device is the master and others are slaves. Master/slave buses are usually synchronous, as the master often supplies the timing clock for data being sent along in both directions. Multi-master: A multi-master bus is a master/slave bus that may have more than one master. These buses must have an arbitration scheme that can settle conflicts when more than one master wants to control the bus at the same time. Point-to-point: Point-to-point or peer interfaces are where two devices have a peer relation to each other; there are no masters or slaves. Peer interfaces are most often asynchronous. Multi-drop: The term multi-drop describes an interface in which there are several receivers and one transmitter. Multi-point: Multi-point describes a bus in which there are more than two peer transceivers. This is different from a multi-drop interface as it allows bidirectional communication over the same set of wires.

3.6.2. Serial communication protocols There are many serial communication protocols are used in the microcontroller systems i.e. RS-232, I2C, Serial peripheral interface etc. The selection of the communication protocols depends upon the hardware design &requirement of system. The serial communication protocols should have following capabilities    

Define the line is synchronous or asynchronous Define the permissible data rate Signal whether a device is ready to receive data Indicate the start and stop of data.

Exploring Microcontroller Technology

58

 

Detect error condition Accommodate the different speed devices

The detail of some important serial protocols are used is given below 3.6.2.1. RS-232 TIA/EIA-232-F (typically referred to as RS-232) is a common interface that can be found on almost every personal computer. RS-232 is a complete standard, not only including electrical characteristics, but physical and mechanical characteristics as well, such as connection hardware, pin-outs, and signal names. A point-to-point interface, RS-232 is capable of moderate distances at speeds up to 20Kbps. While not specifically called out in the specification, speeds of greater than 115.2Kbps are possible, provided that connections are short and proper grounding is used. a) Mechanical specification An RS-232 bus is an unbalanced bus capable of full-duplex communication between two receiver/transmitter pairs, named data terminal equipment (DTE) and data communication equipment (DCE). Each one has a transmit signal that is connected to the receive signal on the other end. b) Electrical specification Each transmitter sends data by varying the voltage on the line. A voltage higher than 3V is a binary zero, while a voltage less than --3V is a binary one. Between these voltages, the value is undefined. To convert from logic levels (0 and 5V) to these levels and back, an RS-232 conversion IC, such as the 1488, 1489, or ubiquitous MAX232, can be used. c) Format of Frame: Typical RS-232 communication frame consists of a start bit, data bits, parity bits (if any), and stop bit(s). When communicating with PCs, the typical format is eight data bits, no parity, and one stop bit (8N1). Seven data bits, even parity, and one stop bit (7E1) is also common. A start bit is often a zero and a stop bit is often a one, as shown in Figure3.17. The official specification does not delineate any communications protocol, including the use of start/stop bits. Many embedded systems that use the RS-232 bus either interface with PCs or PC peripherals such as modems. Almost every microcontroller vendor has products that include hardware support for RS-232, called Universal Asynchronous Receiver Transmitters (UARTs). UARTs are often interrupt-driven and capable of speeds up to 115.2Kbps with little software overhead, although this varies by architecture. An interfacing between personal computer and microcontroller is shown in Figure 3.18

Exploring Microcontroller Technology

59

Start bit

0

1

Stop bit

0

1

1

1

0

0

P

1

3v 0 -3v

Fig3.16: Format of RS-232 Frame (7E1)

Fig 3.17: Interfacing of MCU and personal computer

Exploring Microcontroller Technology

60

3.6.2.2. I2C The two-wire I2C-bus is used in a wide range of microcontroller-based consumer and telecommunications products. The name I2C is shorthand for a standard Inter-. IC (integrated circuit) bus Philips originally developed I2C for communication between devices inside of a TV set. Examples of simple I2C-compatible devices found in embedded systems include EEPROMs, thermal sensors, and real-time clocks. I2C is also used as a control interface to signal processing devices that have separate, application- specific data interfaces. For instance, it's commonly used in multimedia applications, where typical devices include RF tuners, video decoders and encoders, and audio processors. It is a simple, low-bandwidth, short-distance, synchronous, bidirectional & half duplex protocol. Most available I2C devices operate at speeds up to 400Kbps, with some venturing up into the low megahertz range. I 2C is easy to use to link multiple devices together since it has a built-in addressing scheme. A complete system usually consists of at least one microcontroller and other peripheral devices such as memories and I/O expanders. As shown in Figure 3.19. Here are some of the features of the I2C-bus: 

Only two bus lines are required; a serial data line (SDA) and serial clock line (SCL).  Each device connected to the bus is software addressable unique address and simple master/ slave relationships exist times; masters can operate as master-transmitters or as master-receivers.  It‟s a true multi-master bus including collision detection and arbitration to prevent data corruption if two or more masters simultaneously initiate data transfer. Serial, 8-bit oriented, bidirectional data transfers slow (under 100Kbps), fast (400Kbps), and high-speed (3.4Mbps).  On-chip filtering rejects spikes on the bus data line to preserve data integrity. The number of ICs that can be connected to the same bus limited only by a maximum bus capacitance of 400 pF. [17] The master device has following characteristics    

Initiates a transfer by generating start and stop conditions. Generates the clock. Transmits the slave address. Determines data transfer direction.

The slave device has following characteristics  

Responds only when addressed. Timing is controlled by the clock line

Exploring Microcontroller Technology

61

Fig 3.18: A complete I2C system

S

SLAVE ADDRESS W

A

DATA

A

DATA

A

P

· Master Write:

Acknowledge from slave S

SLAVE ADDRESS R

A

DATA

A

DATA

NA P

· Master Read:

Acknowledge from master No acknowledge from master

Acknowledge from slave

Fig 3.19: The I2C possible frame formats

SD A SC L

S START CONDITIO N

MS B 1

2

7

8

9 AC K

1

2

38

9 AC K

Fig 3.20: Data Transfer on the I2C Bus

Exploring Microcontroller Technology

P STOP CONDITIO N

62

The main aspects are following a) Frame Format The transmission frame may consist of a bit of start condition, an address of seven bit receiver/slave, a read & write (R/W) bit, an 8-bit data word, an acknowledge bit, followed by a stop condition. See Figure 3.20 b) Communication During communication with slave devices, the master generates all clock signals for both communications to and from the slave. Each communication begins with the master generating a start condition, an 8-bit data word, an acknowledge bit, followed by a stop condition or a repeated start. Each data bit transition takes place while SCL is low, except for the start and stop conditions. The start condition is a high-to-low transition of the SDA line while the SCL line is high. A stop condition is a low-to-high transition of the SDA line while the SCL line is high (see Figure 2). The acknowledge bit is generated by the receiver of the message by pulling the SDA line low while the master releases the line and allows it to float high. If the master reads the acknowledged bit as high, it should consider the last communication word not received and take appropriate action, including possibly resending the data. [16] 3.6.2.3. Control Area Network protocol (CAN) The CAN (Controller Area Network) is an ISO defined industrial microprocessor based serial communications bus that was originally developed for the use in motor vehicles by Robert Bosch GmbH, Germany, in the late 1980s during the late 1980's for the automotive industry. Its basic design specification called for a high bit rate, high immunity to electrical interference and an ability to detect any errors produced. Due to these features the CAN serial communications bus has become widely used throughout the automotive, manufacturing and aerospace industries. a) Development of CAN The development of CAN began when more and more electronic devices were implemented into modern motor vehicles. Examples of such devices include engine management systems, active suspension, ABS, gear control, lighting control, air conditioning, airbags and central locking. All this means more safety and more comfort for the driver and of course a reduction of fuel consumption and exhaust emissions. To improve the behavior of the vehicle even further, it was necessary for the different control systems (and their sensors) to exchange information. This was usually done by discrete interconnection of the different systems (i.e. point to point wiring). The requirement for information exchange has then Exploring Microcontroller Technology

63

grown to such an extent that a cable network with a length of up to several miles and many connectors was required. This produced growing problems concerning material cost, production time and reliability. According to [7] before the advent of CAN cars has 3 miles lengthy wires of weight 200 pound for inter connection of different devices. The solution to this problem was the connection of the control systems via a serial bus system. This bus had to fulfill some special requirements due to its usage in a vehicle. But CAN has reduced this factor to hundred feet & 10 pound. With the use of CAN, point-to-point wiring is replaced by one serial bus connecting all control systems. This is accomplished by adding some CANspecific hardware to each control unit that provides the "rules" or the protocol for transmitting and receiving information via the bus. b) Basic Concepts & Overview I. The CAN protocol uses the Data Link Layer and the Physical Layer in the ISO - OSI model. There are also a number of higher level protocols available for CAN. II. CAN is a multi-master bus with an open, linear structure with one logic bus line and equal nodes. The number of nodes is not limited by the protocol. In the CAN protocol, the bus nodes do not have a specific address. Instead, the address information is contained in the identifiers of the transmitted messages, indicating the message content and the priority of the message. III. The number of nodes may be changed dynamically without disturbing the communication of the other nodes. IV. Multicasting and Broadcasting is supported by CAN. V. CAN provides sophisticated error-detection and error handling mechanisms such as CRC check, and high immunity against electromagnetic interference. Erroneous messages are automatically retransmitted. Temporary errors are recovered. Permanent errors are followed by automatic switch-off of defective nodes. There is guaranteed system-wide data consistency. VI. The CAN protocol uses Non-Return-to-Zero or NRZ bit coding. For synchronization purposes, Bit Stuffing is used. VII. There is a high data transfer rate of 1000 kilobits per second at a maximum bus length of 40 meters or 130 feet when using a twisted wire pair which is the most common bus medium used for CAN. Message length is short with a maximum of 8 data bytes per message and there is a low latency between transmission request and start of transmission. VIII. The bus access is handled via the advanced serial communications protocol Carrier Sense Multiple Access/Collision Detection with Non Exploring Microcontroller Technology

64

Fig 3.21 Point-to-Point connection of different devices in automobiles

Fig 3.22 CAN based connection of different devices in automobiles

Exploring Microcontroller Technology

65

Destructive Arbitration. This means that collision of messages is avoided by bitwise arbitration without loss of time. IX. There are two bus states, called "dominant" and "recessive".  The bus logic uses a "Wired-AND" mechanism, that is, "dominant bits" (equivalent to the logic level "Zero") overwrite the "recessive" bits (equivalent to the logic level "One”). As shown in fig  Only if all nodes transmit recessive bits (ones), the Bus is in the recessive state.  As soon as one node transmits a dominant bit (zero), the bus is in the dominant state. [18],[19]

c) CAN Data Frame Format There are five frame formats are used in the CAN      

A DATA FRAME carries data from a transmitter to the receivers. A REMOTE FRAME is transmitted by a bus unit to request the transmission of the DATA FRAME with the same IDENTIFIER. An ERROR FRAME is transmitted by any unit on detecting a bus error. An OVERLOAD FRAME is used to provide for an extra delay between the preceding and the succeeding DATA or REMOTE FRAMEs. DATA FRAMEs and REMOTE FRAMEs are separated from preceding frames by an INTERFRAME SPACE [20]

But we will discuss only the data frame format which has following features which is shown in the Figure 3.25.  



A "Data Frame" is generated by a CAN node when the node wishes to transmit data. The frame begins with a dominant Start Of Frame bit for hard synchronization of all nodes. The Start of Frame bit is followed by the Arbitration Field consisting of 12 bits: The 11-bit Identifier, which reflects the contents and priority of the message, and the Remote Transmission Request bit. The Remote transmission request bit is used to distinguish a Data Frame (RTR = dominant) from a Remote Frame (RTR = recessive). The next field is the Control Field, consisting of 6 bits. The first bit of this field is called the IDE bit (Identifier Extension) and is at dominant state to specify that the frame is a Standard Frame. The following bit is reserved and defined as a dominant bit. The remaining 4 bits of the Control Field are the Data Length Code (DLC) and specify the number of bytes of data contained in the message (0 - 8 bytes).

Exploring Microcontroller Technology

66

Fig 3.23: CAN Bus - Wired-AND

Fig 3.24: CAN Data Frame Format:

Exploring Microcontroller Technology

67

  



The data being sent follows in the Data Field which is of the length defined by the DLC above (0, 8, 16, ...., 56 or 64 bits). The Cyclic Redundancy Field (CRC field) follows and is used to detect possible transmission errors. The CRC Field consists of a 15 bit CRC sequence, completed by the recessive CRC Delimiter bit. The next field is the Acknowledge Field. During the ACK Slot bit the transmitting node sends out a recessive bit. Any node that has received an error free frame acknowledges the correct reception of the frame by sending back a dominant bit (regardless of whether the node is configured to accept that specific message or not). From this it can be seen that CAN belongs to the "in-bit-response" group of protocols. The recessive Acknowledge Delimiter completes the Acknowledge Slot and may not be overwritten by a dominant bit. Seven recessive bits (End of Frame) end the Data Frame. [18]

d) Application of CAN I. CAN in motor vehicles (cars, trucks, buses) 



Enables communication between ECUs like engine management system, anti-skid braking, gear control, active suspension ... (power train) Used to control units like dashboard, lighting, air conditioning, windows, central locking, airbag, seat belts etc. (body control)

II.CAN in utility vehicles  

e.g. construction vehicles, forklifts, tractors etc. CAN used for power train and hydraulic control

III. CAN in trains 

High need of data exchange between the different electronic subsystem control units (i.e. acceleration, braking, door control, error messages etc. as well as diagnostics).

3.6.2.4. Other Protocols a) SPI Serial Peripheral Interface The Serial Peripheral Interface (SPI) is a synchronous serial bus developed by Motorola and present on many of their microcontrollers. The SPI bus consists of four signals: master out slave in (MOSI), master in slave out (MISO), serial clock (SCK), and active-low slave select (/SS). As a multi-master/slave protocol, communications between the master and Exploring Microcontroller Technology

68

selected slave use the unidirectional MISO and MOSI lines, to achieve data rates over 1Mbps in full duplex mode. The data is clocked simultaneously into the slave and master based on SCK pulses the master supplies. The SPI protocol allows for four different clocking types, based on the polarity and phase of the SCK signal. It is important to ensure that these are compatible between master and slave. b) Microwire Microwire is a three-wire synchronous interface developed by National Semiconductor and present on their COP8 processor family Microwire is a master/slave bus, with serial data out of the master (SO), and serial data in to the master (SI), and signal clock (SK). These correspond to SPI's MOSI, MISO, and SCK, respectively. There is also a chip select signal, which acts similarly to SPI's /SS. A full-duplex bus, Microwire is capable of speeds of 625Kbps and faster (capacitance permitting). c) 1- Wire Dallas Semiconductor's 1-Wire bus is an asynchronous, master/slave bus with no protocol for multi-master. 1-Wire is half-duplex, using an open-drain topology on a single wire for bidirectional data transfer. The 1-Wire bus also allows the data wire to transfer power to the slave devices. Though limited to a maximum speed of 16Kbps, bus length can be upwards of 1,000 feet, given the proper pull-up resistor. [21]

Exploring Microcontroller Technology

69

CHAPTER 4 A Quick view of 8051

Exploring Microcontroller Technology

70

The family of microprocessors employed in personal computers is known as Intel's x 86 families. But Intel had another family of microprocessors intended for embedded applications. To this day, Intel's 8051 family of microprocessors has been shipped in more embedded applications than any other microprocessor. If you round off the fractions, embedded systems consume 100% of the worldwide production of microprocessors. That is, all the microprocessors intended for use in desktop computers (the largest group of which are Intel's x 86 families) account for less than 1/2 % of microprocessor shipments by numbers. That is why we chose to do our project in microcontrollers and 8051 is the first step. It is employed in about half of the devices containing an embedded microcontroller. Hence, it is by far the most widespread microcontroller architecture. Since its introduction in 1980, the 8051 and its derivatives have shipped over three billion units world-wide and the production rate is still growing, which is very unusual since sales of an integrated circuit usually start to fall off after a couple of years. There are a lot of varieties of microcontrollers in the range of eight bit to 32 bit whose architecture and instruction set is based on 8051.There are thirty two vendors who have license from Intel. All these vendors are presenting different capabilities microcontrollers i.e. application specific or general purpose. Variations of the 8051 with clock speeds up to 40MHz and voltage requirements down to 1.5 volts are available. This wide range of parts based on one core makes the 8051 family an excellent choice as the base architecture for a company's entire line of products since it can perform many functions and developers will only have to learn this one platform

4.1. The Hardware The 8051 family of microcontrollers is based on an architecture, which is highly optimized for embedded control systems and its instruction set contains the fine features of both RISC and CISC. It is used in a wide variety of applications from military equipment to automobiles to the keyboard on PC. Second only to the Motorola 68HC11 in eight bit processors sales, the 8051 family of microcontrollers is available in a wide array of variations from manufacturers such as Intel, Philips, and Siemens. These manufacturers have added numerous features and peripherals to the 8051 such as I2C interfaces, analog to digital converters, watchdog timers, and pulse width modulated outputs. .4.1.1.Basic constituent of 8051 The basic architecture consists of the following features:  

8 Bit data path and ALU Easy interfacing.

Exploring Microcontroller Technology

71

        

12 to 30 MHz versions available  ( 1 µsec to 400 ns for single cycle instructions). Full instruction set including  Multiply and Divide.  Bit set, reset, and test (Boolean instructions). Variety of addressing modes. 4K X 8 ROM - Program memory. 128 x 8 RAM - Data memory. Special function registers. Serial I/O port. 32 I/O lines. Two 16-bit counter/timers.

See the block diagram of 8051 in Figure 4.1 4.1.2. Pin outs– Arrangements of pins  Pins 1-8 Pins 1 through 8 are the pins of Port 1. Port 1 is a dedicated I/O port; so these pins are available for interfacing external devices as required. No alternate function is assigned to these pins. 

Pin 9 Pin Number 9 is the system RESET (RST) of CPU of AT8051. Holding RST high for at least two machine cycles and then returning it to low resets AT8051. The Reset may be manually activated using a switch, or may be activated upon power-up using RC network. After a system reset, Program Counter is loaded with 0000H. When RST returns low, program execution begins at the first location in code memory at address 0000H. The contents of on-chip RAM are not affected by a reset operation.



Pins 10-17 The Pins 10 through 17 constitute Port 3, which is a dual-purpose port. As well as general purpose I/O, these pins are multifunctional with each having an alternate purpose related to special features of 8051.



Pins 18-19 Pins‟ numbers 18 and 19 comprise the inputs of crystal to be connected to the on-chip oscillator of 8051. Two Stabilizing capacitors of 30 pF each are also required.



Pin 20 It is the common ground of 8051 and accompanying networks.



Pins 21-28 Pins 21 through 28 are of Port 2. Port 2 is a also a dual purpose port. It can serve as a general-purpose I/O port or as the high byte of the address bus

Exploring Microcontroller Technology

72

Figure 4.1: Block diagram of 8051

Figure 4.2: Pin configuration of 8051 Exploring Microcontroller Technology

73





for designs with external code memory or more than 128 bytes of data memory. Pin 29 and Pin 31 These pins are used in conjunction with external code memory being used or else. On Pin number 29 is a control signal PSEN# (Program Store Enable) that enables external code (Program) memory. It is usually connected to Output Enable pin of an EEPROM to permit reading of program bytes. Pin 31 i.e. EA (External Access) is either tied high (+5V) or low (ground). If high, the C51 executes programs from internal ROM otherwise from external code memory and then PSEN comes into play. Pins 32 - 39 and Pin 30 Pins 32 through 39 make up Port 0. Port 0, in addition to being used as an I/O port, has the capacity to act as multiplexed data and address bus. The discrimination of data and address is provided through ALE (Address Latch Enable) which is Pin number 30.

a) Pin 40 This is where we connect positive of power supply i.e. the main power source. This in connection with pin 20 makes the power in/out pair.

4.1.3. Clock matters 8051-processor cycle consists of twelve oscillator periods. Each of the twelve oscillator periods is used for a special function by the 8051 core such as op code fetches and samples of the interrupt daisy chain for pending interrupts. The time required for any 8051 instruction can be computed by dividing the clock frequency by 12, inverting that result and multiplying it by the number of processor cycles required by the instruction in question. Therefore, if you have a system which is using an 11.059MHz clock, you can compute the number of instructions per second by dividing this value by 12. This gives an instruction frequency of 921583 instructions per second. Inverting this will provide the amount of time taken by each instruction cycle (1.085 microseconds).

4.2. Memory organization of 8051 The 8051 architecture provides the user with four physically distinct memory spaces which can be seen in Figure 4.3. Each memory space consists of contiguous addresses from 0 to the maximum size, in bytes, of the memory space. The three memory spaces function as described below.     

128 x 8 RAM - Internal data memory. 4K X 8 ROM - Internal Program memory. 64K x 8 RAM - External data memory. 64K X 8 ROM - External Program memory. 128 x 8 Special function registers (SFRs).

Exploring Microcontroller Technology

74

64k

4k 64k

Figure 4.3: Memory Architecture of 8051

END 8051 RAM

7F 30 2F 20 1F 20 17 18 0F 08 07

FF . . . . . . . . . F8 07 . . . . . . . . . 00

BIT ADDRESSABLE

REGISTER BANK 3 REGISTER BANK 2 REGISTER BANK 1 R7 R6 R5 R4 R3

REGISTER BANK 0

R2 R1 00

R0

Figure 4.4: Internal Data Memory

Exploring Microcontroller Technology

75



Bit addressing of 16 bytes RAM locations and 16 SFRs.

4.2.1. Data memory The first memory space is the 128 bytes of internal RAM on the 8051, this segment is typically referred to as the DATA segment. Data memory can be address in following ways    

Directly addressable range (general purpose)  00 to 7F hexadecimal. Indirectly addressable range  00 to FF hexadecimal. Bit addressable space  20 to 2F hexadecimal. Four register banks  00 to 1F hexadecimal

4.2.1.1. Register banks The DATA memory contains two smaller segments of interest. The first sub segment consists of the four sets of register banks which compose the first 32 bytes of RAM. The 8051 can use any of these four groups of eight bytes as its default register bank. The selection of register banks is changeable at any time via the RS1 and the RS0 bits in the Program Status Word (PSW). These two bits combine into a number from 0 to 3 (with RS1 being the most significant bit) which indicates the register bank to be used. Register bank switching allows not only for quick parameter passing, but also opens the door for simplifying task switching on the 8051. Variables stored in the DATA segment can also be accessed indirectly via R0 or R1. The register being used as the memory pointer must contain the address of the byte to be retrieved or altered. These instructions can take one or two processor cycles depending on the source/destination data byte. See lower part of Figure 4.4 4.2.1.2. BDATA The second sub-segment in the DATA space is a bit addressable segment in which each bit can be individually accessed. This segment is referred to as the BDATA segment. The bit addressable segment consists of 16 bytes (128 bits) above the four register banks in memory. The 8051 contains several single bit instructions which are often very useful in control applications and aid in replacing external combinatorial logic with software in the 8051 thus reducing parts count on the target system. It should be noted that these 16 bytes can also be accessed on a "bytewide" basis just like any other byte in the DATA space. 4.2.1.3. General purpose RAM The general purpose RAM is also called scratch pad Ram which can be utilizing for Exploring Microcontroller Technology

76

reserving the variables. 4.2.1. Internal Program memory The CODE segment is that area in which the executable program resides. This segment can be up to 4K. The processor treats this segment as read only and will generate signals appropriate to access a memory device such as an EPROM. However, this does not mean that the CODE segment must be implemented using an EPROM. Many embedded systems these days are using EEPROM which allows the memory to be overwritten either by the 8051 itself or by an external device. This makes upgrades to the product easy to do since new software can be downloaded into the EEPROM rather than having to disassemble it and install a new EPROM. In addition to executable code, it is common practice with the 8051 to store fixed lookup tables in the CODE segment. To facilitate this, the 8051 provides instructions which allow rapid access to tables via the data pointer (DPTR) or the program counter with an offset into the table optionally provided by the accumulator. This means that oftentimes, a table's base address can be loaded in DPTR and the element of the table to access can be held in the accumulator. The addition is performed by the 8051 during the execution of the instruction which can save many cycles depending on the situation. 4.2.3. External Program memory & Data memory The 64 KB external ROM can also be used for larger program which can be indirectly addressable via R0 and R1 in 256 byte segments. And entire space is indirectly addressable via the data pointer DPTR. The external ROM is also called XCODE .The external ROM is interfaced with the 8051 via Port 0 and Port 2 by using a D-flip flop as shown in the Figure 4.5. Similarly an external RAM of 64 KB can also be used as XDATA memory area. Entire XDATA space is indirectly addressable via the data pointer DPTR and indirectly addressable via R0 and R1 in 256 byte segments. The interfacing of external RAM is shown in Figure 4.6. 4.2.4. Special Function Registers memory Special Function Registers (SFRs) are areas of memory that control specific functionality of the 8051 processor. For example, four SFRs permit access to the 8051‟s 32 input/output lines. Another SFR allows a program to read or write to the 8051‟s serial port. Other SFRs allow the user to set the serial baud rate, control and access timers, and configure the 8051‟s interrupt system. When programming, SFRs have the illusion of being Internal Memory. For example, if you want to write the value "1" to Internal RAM location 50 hex you would execute the instruction: MOV 50h,#01h Exploring Microcontroller Technology

77

8051 A15 A8

PORT2 ALE PORT0

AD7 AD0

ROM(S)

ADDRESS LATCH

D7 D0

PSEN

A7 A0

ADDRESS INPUTS DATA OUTPUTS OE

Figure 4.5: External Code Memory

RAM(S) or I/O

8051 DECODE

PORT 2 ALE PORT 0

ADDRESS LATCH

WR RD

CE ADDRESS INPUTS DATA OUTPUTS R/W OE

Figure 4.6: External Data Memory

Exploring Microcontroller Technology

78

Similarly, if you want to write the value "1" to the 8051‟s serial port you would write this value to the SBUF SFR, which has an SFR address of 99 Hex. Thus, to write the value "1" to the serial port you would execute the instruction: MOV 99h,#01h As you can see, it appears that the SFR is part of Internal Memory. This is not the case. When using this method of memory access (it‟s called direct address), any instruction that has an address of 00h through 7Fh refers to an Internal RAM memory address; any instruction with an address of 80h through FFh refers to an SFR control register. The special function register memory area can not be used as general purpose register and the address map of SFR memory is shown in Figure 4.7

4.3. The Registers of 8051 8051 has two types of registers  

General Purpose register Special Function registers

4.3.1. General Purpose register 4.3.1.1 The Accumulator The Accumulator, as its name suggests, is used as a general register to accumulate the results of a large number of instructions. It can hold an 8-bit (1-byte) value and is the most versatile register the 8051 has due to the shear number of instructions that make use of the accumulator. More than half of the 8051‟s 255 instructions manipulate or use the accumulator in some way. For example, if you want to add the number 10 and 20, the resulting 30 will be stored in the Accumulator. Once you have a value in the Accumulator you may continue processing the value or you may store it in another register or in memory. The process of addition is shown below as MOV A, #31H MOV B, #2H MUL AB 4.3.1.2. B Register The "B" register is very similar to the Accumulator in the sense that it may hold an 8bit (1-byte) value. The "B" register is only used by two 8051 instructions: MUL AB and DIV AB. Thus, if you want to quickly and easily multiply or divide A by another number, you may store the other number in "B" and make use of these two instructions. Aside from the MUL and DIV instructions, the “B” register are often Exploring Microcontroller Technology

79

Figure 4.7: SFR Memory

Exploring Microcontroller Technology

80

used as yet another temporary storage register much like a ninth "R" register. As shown below the multiplication and division MOV A, #31H MOV B, #2H MUL AB And

MOV A, #24H MOV B, #5H DIV AB

4.3.1.3. R registers The "R" registers are a set of eight registers that are named R0, R1, etc. up to and including R7. These registers are used as auxiliary registers in many operations. To continue with the above example, perhaps you are adding 10 and 20. The original number 10 may be stored in the Accumulator whereas the value 20 may be stored in, say, register R4. To process the addition you would execute the command: ADD A, R4 After executing this instruction the Accumulator will contain the value 30. we can realize the "R" registers as very important auxiliary, or "helper", registers. The Accumulator alone would not be very useful if it were not for these "R" registers. The "R" registers are also used to temporarily store values. For example, let‟s say you want to add the values in R1 and R2 together and then subtract the values of R3 and R4. One way to do this would be: MOV A,R3 ;Move the value of R3 into the accumulator ADD A,R4 ;Add the value of R4 SUBB A,R5 ;Subtract the value of R5 (which now contains R3 + R4) 4.3.1.4. The Data Pointer (DPTR) The Data Pointer (DPTR) is the 8051‟s only user-accessible 16-bit (2-byte) register. DPTR, as the name suggests, is used to point to data. It is used by a number of commands which allow the 8051 to access external memory. When 8051 accesses external memory it will access external memory at the address indicated by DPTR. While DPTR is most often used to point to data in external memory, many programmers often take advantage of the fact that it‟s the only true 16-bit register available. It is often used to store 2-byte values which have nothing to do with memory locations. 4.3.1.5. The Program Counter (PC) The Program Counter (PC) is a 2-byte address which tells the 8051 where the next instruction to execute is found in memory. When the 8051 is initialized PC always starts at 0000h and is incremented each time an instruction is executed. It is Exploring Microcontroller Technology

81

important to note that PC isn‟t always incremented by one. Since some instructions require 2 or 3 bytes the PC will be incremented by 2 or 3 in these cases. 4.3.1.6. The Stack Pointer (SP) The Stack Pointer, like all registers except DPTR and PC, may hold an 8-bit (1-byte) value. The Stack Pointer is used to indicate where the next value to be removed from the stack should be taken from. When you push a value onto the stack, the 8051 first increments the value of SP and then stores the value at the resulting memory location. When you pop a value off the stack, the 8051 returns the value from the memory location indicated by SP, and then decrements the value of SP. This order of operation is important. When the 8051 is initialized SP will be initialized to 07h. If you immediately push a value onto the stack, the value will be stored in Internal RAM address 08h. This makes sense taking into account what was mentioned two paragraphs above: First the 8051 will increment the value of SP (from 07h to 08h) and then will store the pushed value at that memory address (08h). SP is modified directly by the 8051 by six instructions: PUSH, POP, ACALL, LCALL, RET, and RETI. It is also used intrinsically whenever an interrupt is triggered (more on interrupts later. Don‟t worry about them for now!). 4.4.2. Special Function Registers The 8051 is a flexible microcontroller with a relatively large number of modes of operations. Program may inspect and/or change the operating mode of the 8051 by manipulating the values of the 8051's Special Function Registers (SFRs). SFRs are accessed as if they were normal Internal RAM. The only difference is that Internal RAM is from address 00h through 7Fh whereas SFR registers exist in the address range of 80h through FFh. Each SFR has an address (80h through FFh) and a name. As it is shown in Figure 4.7, although the address range of 80h through FFh offers 128 possible addresses, there are only 21 SFRs in a standard 8051. All other addresses in the SFR range (80h through FFh) are considered invalid. Writing to or reading from these registers may produce undefined values or behavior. 4.4.2.1. P0 (Port 0, Address 80h, Bit-Addressable) This is input/output port 0. Each bit of this SFR corresponds to one of the pins on the microcontroller. For example, bit 0 of port 0 is pin P0.0, bit 7 is pin P0.7. Writing a value of 1 to a bit of this SFR will send a high level on the corresponding I/O pin whereas a value of 0 will bring it to a low level. Exploring Microcontroller Technology

82

4.4.2.2. SP (Stack Pointer, Address 81h) It is discussed earlier. 4.4.2.3. DPL/DPH (Data Pointer Low/High, Addresses 82h/83h) It is discussed earlier. 4.4.2.4. PCON (Power Control, Addresses 87h) The Power Control SFR is used to control the 8051's power control modes. Certain operation modes of the 8051 allow the 8051 to go into a type of "sleep" mode which requires much less power. These modes of operation are controlled through PCON. Additionally, one of the bits in PCON is used to double the effective baud rate of the 8051's serial port. 4.4.2.5. TCON (Timer Control, Addresses 88h, Bit-Addressable) The Timer Control SFR is used to configure and modify the way in which the 8051's two timers operate. This SFR controls whether each of the two timers is running or stopped and contains a flag to indicate that each timer has overflowed. Additionally, some non-timer related bits are located in the TCON SFR. These bits are used to configure the way in which the external interrupts are activated and also contain the external interrupt flags which are set when an external interrupt has occurred. 4.4.2.6. TMOD (Timer Mode, Addresses 89h) The Timer Mode SFR is used to configure the mode of operation of each of the two timers. Using this SFR program may configure each timer to be a 16-bit timer, an 8bit auto reload timer, a 13-bit timer, or two separate timers. Additionally, it may configurable the timers to only count when an external pin is activated or to count "events" that are indicated on an external pin. 4.4.2.7. TL0/TH0 (Timer 0 Low/High, Addresses 8Ah/8Ch) These two SFRs, taken together, represent timer 0. Their exact behavior depends on how the timer is configured in the TMOD SFR; however, these timers always count up. What is configurable is how and when they increment in value. 4.4.2.8. TL1/TH1 (Timer 1 Low/High, Addresses 8Bh/8Dh) These two SFRs, taken together, represent timer 1. Their exact behavior depends on how the timer is configured in the TMOD SFR; however, these timers always count up. What is configurable is how and when they increment in value. 4.4.2.9. P1 (Port 1, Address 90h, Bit-Addressable) This is input/output port 1. Each bit of this SFR corresponds to one of the pins on the microcontroller. For example, bit 0 of port 1 is pin P1.0, bit 7 is pin P1.7. Writing a Exploring Microcontroller Technology

83

value of 1 to a bit of this SFR will send a high level on the corresponding I/O pin whereas a value of 0 will bring it to a low level. 4.4.2.10. SCON (Serial Control, Addresses 98h, Bit-Addressable) The Serial Control SFR is used to configure the behavior of the 8051's on-board serial port. This SFR controls the baud rate of the serial port, whether the serial port is activated to receive data, and also contains flags that are set when a byte is successfully sent or received. 4.4.2.11. SBUF (Serial Control, Addresses 99h) The Serial Buffer SFR is used to send and receive data via the on-board serial port. Any value written to SBUF will be sent out the serial port's TXD pin. Likewise, any value which the 8051 receives via the serial port's RXD pin will be delivered to the user program via SBUF. In other words, SBUF serves as the output port when written to and as an input port when read from. 4.4.2.12. P2 (Port 2, Address A0h, Bit-Addressable) This is input/output port 2. Each bit of this SFR corresponds to one of the pins on the microcontroller. For example, bit 0 of port 2 is pin P2.0, bit 7 is pin P2.7. Writing a value of 1 to a bit of this SFR will send a high level on the corresponding I/O pin whereas a value of 0 will bring it to a low level. 4.4.2.13. IE (Interrupt Enable, Addresses A8h) The Interrupt Enable SFR is used to enable and disable specific interrupts. The low 7 bits of the SFR are used to enable/disable the specific interrupts, where as the highest bit is used to enable or disable ALL interrupts. Thus, if the high bit of IE is 0 all interrupts are disabled regardless of whether an individual interrupt is enabled by setting a lower bit. 4.4.2.14. P3 (Port 3, Address B0h, Bit-Addressable) This is input/output port 3. Each bit of this SFR corresponds to one of the pins on the microcontroller. For example, bit 0 of port 3 is pin P3.0, bit 7 is pin P3.7. Writing a value of 1 to a bit of this SFR will send a high level on the corresponding I/O pin whereas a value of 0 will bring it to a low level. 4.4.2.15. IP (Interrupt Priority, Addresses B8h, Bit-Addressable) The Interrupt Priority SFR is used to specify the relative priority of each interrupt. On the 8051, an interrupt may either be of low (0) priority or high (1) priority. An interrupt may only interrupt interrupts of lower priority. For example, if we configure the 8051 so that all interrupts are of low priority except the serial interrupt, the serial interrupt will always be able to interrupt the system, even if another interrupt is currently executing. Exploring Microcontroller Technology

84

Figure 4.8: PCON

Figure 4.9: PSW

Exploring Microcontroller Technology

85

4.4.2.16. PSW (Program Status Word, Addresses D0h, Bit-Addressable) The Program Status Word is used to store a number of important bits that are set and cleared by 8051 instructions. The PSW SFR contains the carry flag,the auxiliary carry flag, the overflow flag, and the parity flag. Additionally, the PSW register contains the register bank select flags which are used to select which of the "R" register banks are currently selected.

4.5. Timer operation in 8051 The 8051 comes equipped with two timers, both of which may be controlled, set, read, and configured individually. The 8051 timers have three general functions: 1) Keeping time and/or calculating the amount of time between events, 2) Counting the events themselves, or 3) Generating baud rates for the serial port. The three timer uses are distinct so we will talk about each of them separately. 4.51. TIMERS TO MEASURE TIME Obviously, one of the primary uses of timers is to measure time. We will discuss this use of timers first and will subsequently discuss the use of timers to count events. When a timer is used to measure time it is also called an "interval timer" since it is measuring the time of the interval between two events. First, it‟s worth mentioning that when a timer is in interval imer mode (as opposed to event cycle. As you will recall from the previous chapter, a single machine cycle consists of 12 crystal pulses. Thus a running timer will be incremented: 11,059,000 / 12 = 921,583

(4:1)

921,583 times per second. Unlike instructions--some of which require 1 machine cycle, others 2, and others 4--the timers are consistent: They will always be incremented once per machine cycle. Thus if a timer has counted from 0 to 50,000 you may calculate: 50,000 / 921,583 = .0542 (4:2) .0542 seconds have passed i.e. half of a tenth of a second, or one-twentieth of a second. 4.5.2. Timer SFRs As mentioned before, the 8051 has two timers which each function essentially the same way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and TCON) which control the timers, and each timer also has two SFRs dedicated solely to itself (TH0/TL0 and TH1/TL1). Exploring Microcontroller Technology

86

Osc.

÷ 12

I nt er r upt TL1 T1 (Pi n)

TH1

8- bit s 8- bit s

TF1

Cont r ol TR1

Gat e

I NT1 (Pi n)

Figure 4.9: The timer/Counter structure

Figure 4.10: TMOD SFR

Figure 4.11: TCON SFR Exploring Microcontroller Technology

87

We‟ve given SFRs names to make it easier to refer to them, but in reality an SFR has a numeric address.. The SFRs relating to timers are:      

TCON TMOD TH0 TH1 TL0 TL1

4.6. 8051 Serial Communication One of the 8051‟s many powerful features is its integrated UART, otherwise known as a serial port. The fact that the 8051 has an integrated serial port means that you may very easily read and write values to the serial port We simply need to configure the serial port‟s operation mode and baud rate. Once configured, all we have to do is write to an SFR to write a value to the serial port or read the same SFR to read a value from the serial port. The 8051 will automatically let us know when it has finished sending the character we wrote and will also let us know whenever it has received a byte so that we can process it. We do not have to worry about transmission at the bit level--which saves us quite a bit of coding and processing time. TXD and RXD are the serial output and input pins (Port 3, bits 1 and 0). 8051 serial port has following features  Full duplex UART.  Four modes of operation  Synchronous serial I/O expansion.  Asynchronous serial I/O with variable baud rate.  Nine bit mode with variable baud rate.  Nine bit mode with fixed baud rate.  10 or 11 bit frames.  Interrupt driven or polled operation.  Special function register :  SCON - Serial port control register.  SBUF - Read received data. - Write data to be transmitted.  PCON - SMOD bit. 4.6.1. Serial Interface Modes of Operation The serial port of 8051 has following mode of communication 

Mode 0: Shift Register Mode. Serial data is transmitted/received on RXD. TXD outputs shift clock. Baud Rate is 1/12 of clock frequency.

Exploring Microcontroller Technology

88

  

Mode 1: 10-bits transmitted or received. Start (0), 8 data bits (LSB first), and a stop bit (1). Baud Rate Clock is variable using Timer 1 overflow or external count input. Can go up to 104.2KHz (20MHz osc.). Mode 2: 11-bits transmitted or received. Start (0), 8 data bits (LSB first), programmable 9th bit, and stop bit (1). Baud Rate is programmable to either 1/32 or 1/64 oscillator frequency (625 KHz for 20MHz osc.). Mode 3: 11-bit mode Baud Rate variable using Timer 1 overflows or external input. 104.2 KHz max. (20 MHz osc.).

4.6.2. Setting the Serial Port Mode The first things we must do when using the 8051‟s integrated serial port is, obviously, configure it. This lets us tell the 8051 how many data bits we want, the baud rate we will be using, and how the baud rate will be determined. Let consider the "Serial Control" (SCON) SFR and define what each bit of the SFR represents. The SCON SFR allows us to configure the Serial Port. Thus, we‟ll go through each bit and review it‟s function. The first four bits (bits 4 through 7) are configuration bits. Bits SM0 and SM1 let us set the serial mode to a value between 0 and 3, inclusive. The four modes are defined in the chart immediately above. As you can see, selecting the Serial Mode selects the mode of operation (8-bit/9-bit, UART or Shift Register) and also determines how the baud rate will be calculated. In modes 0 and 2 the baud rate is fixed based on the oscillator‟s frequency. In modes 1 and 3 the baud rate is variable based on how often Timer 1 overflows. We‟ll talk more about the various Serial Modes in a moment. The next bit, SM2, is a flag for "Multiprocessor communication." Generally, whenever a byte has been received the 8051 will set the "RI" (Receive Interrupt) flag. This lets the program know that a byte has been received and that it needs to be processed. However, when SM2 is set the "RI" flag will only be triggered if the 9th bit received was a "1". That is to say, if SM2 is set and a byte is received whose 9th bit is clear, the RI flag will never be set. This can be useful in certain advanced serial applications. For now it is safe to say that you will almost always want to clear this bit so that the flag is set upon reception of any character. The next bit, REN, is "Receiver Enable." This bit is very straightforward: If you want to receive data via the serial port, set this bit. You will almost always want to set this bit. The last four bits (bits 0 through 3) are operational bits. They are used when actually sending and receiving data--they are not used to configure the serial port. The TB8 bit is used in modes 2 and 3. In modes 2 and 3, a total of nine data bits are transmitted. The first 8 data bits are the 8 bits of the main value, and the ninth bit is taken from TB8. If TB8 is set and a value is written to the serial port, the data‟s bits Exploring Microcontroller Technology

89

will be written to the serial line followed by a "set" ninth bit. If TB8 is clear the ninth bit will be "clear." The RB8 also operates in modes 2 and 3 and functions essentially the same way as TB8, but on the reception side. When a byte is received in modes 2 or 3, a total of nine bits are received. In this case, the first eight bits received are the data of the serial byte received and the value of the ninth bit received will be placed in RB8. TI means "Transmit Interrupt." When a program writes a value to the serial port, a certain amount of time will pass before the individual bits of the byte are "clocked out" the serial port. If the program were to write another byte to the serial port before the first byte was completely output, the data being sent would be garbled. Thus, the 8051 lets the program know that it has "clocked out" the last byte by setting the TI bit. When the TI bit is set, the program may assume that the serial port is "free" and ready to send the next byte. Finally, the RI bit means "Receive Interrupt." It functions similarly to the "TI" bit, but it indicates that a byte has been received. That is to say, whenever the 8051 has received a complete byte it will trigger the RI bit to let the program know that it needs to read the value quickly, before another byte is read. 4.6.3. Setting the Serial Port Baud Rate Once the Serial Port Mode has been configured, as explained above, the program must configure the serial port‟s baud rate. This only applies to Serial Port modes 1 and 3. The Baud Rate is determined based on the oscillator‟s frequency when in mode 0 and 2. In mode 0, the baud rate is always the oscillator frequency divided by 12. This means if you‟re crystal is 11.059 MHz; mode 0 baud rate will always be 921,583 baud. In mode 2 the baud rate is always the oscillator frequency divided by 64, so a 11.059Mhz crystal speed will yield a baud rate of 172,797. In modes 1 and 3, the baud rate is determined by how frequently timer 1 overflows. The more frequently timer 1 overflows, the higher the baud rate. There are many ways one can cause timer 1 to overflow at a rate that determines a baud rate, but the most common method is to put timer 1 in 8-bit auto-reload mode (timer mode 2) and set a reload value (TH1) that causes Timer 1 to overflow at a frequency appropriate to generate a baud rate. To determine the value that must be placed in TH1 to generate a given baud rate, we may use the following equation (assuming PCON.7 is clear). TH1 = 256 - ((Crystal / 384) / Baud)

(4:3)

If PCON.7 is set then the baud rate is effectively doubled, thus the equation becomes: TH1 = 256 - ((Crystal / 192) / Baud) Exploring Microcontroller Technology

(4:4) 90

For example, if we have an 11.059 MHz crystal and we want to configure the serial port to 19,200 baud we try plugging it in the first equation: TH1 = 256 - ((Crystal / 384) / Baud) TH1 = 256 - ((11059000 / 384) / 19200 ) TH1 = 256 - ((28,799) / 19200) TH1 = 256 - 1.5 = 254.5

(4:5)

To obtain 19,200 baud on a 11.059Mhz crystal we‟d have to set TH1 to 254.5. If we set it to 254 we will have achieved 14,400 baud and if we set it to 255 we will have achieved 28,800 baud. To achieve 19,200 baud we simply need to set PCON.7 (SMOD). When we do this we double the baud rate and utilize the second equation mentioned above. Thus we have: TH1 = 256 - ((Crystal / 192) / Baud) TH1 = 256 - ((11059000 / 192) / 19200) TH1 = 256 - ((57699) / 19200) TH1 = 256 - 3 = 253

(4:6)

Here we are able to calculate a nice, even TH1 value. Therefore, to obtain 19,200 baud with an 11.059MHz crystal we must: 1. 2. 3. 4.

Configure Serial Port mode 1 or 3. Configure Timer 1 to timer mode 2 (8-bit auto-reload). Set TH1 to 253 to reflect the correct frequency for 19,200 baud. Set PCON.7 (SMOD) to double the baud rate.

4.6.4. Writing to the Serial Port To write a byte to the serial port one must simply write the value to the SBUF (99h) SFR. For example, if you wanted to send the letter "A" to the serial port, it could be accomplished as easily as: MOV SBUF,#‟A‟ Upon execution of the above instruction the 8051 will begin transmitting the character via the serial port. Obviously transmission is not instantaneous--it takes a measurable amount of time to transmit. And since the 8051 does not have a serial output buffer we need to be sure that a character is completely transmitted before we try to transmit the next character. The 8051 lets us know when it is done transmitting a character by setting the TI bit in SCON. When this bit is set we know that the last character has been transmitted and that we may send the next character, if any. Consider the following code segment: CLR TI; Be sure the bit is initially clear MOV SBUF, #‟A‟ ;Send the letter „A‟ to the serial port Exploring Microcontroller Technology

91

JNB TI, $ ;Pause until the RI bit is set. The above three instructions will successfully transmit a character and wait for the TI bit to be set before continuing. The last instruction says "Jump if the TI bit is not set to $"--$, in most assemblers, means "the same address of the current instruction." Thus the 8051 will pause on the JNB instruction until the TI bit is set by the 8051 upon successful transmission of the character. 4.6.5. Reading the Serial Port Reading data received by the serial port is equally easy. To read a byte from the serial port one just needs to read the value stored in the SBUF (99h) SFR after the 8051 has automatically set the RI flag in SCON. For example, if program wants to wait for a character to be received and subsequently read it into the Accumulator, the following code segment may be used: JNB RI,$ ;Wait for the 8051 to set the RI flag MOV A,SBUF ;Read the character from the serial port

4.7. Interrupt system of 8051 The basic 8051 supports six interrupt sources: two external interrupts, two timer/counter interrupts, and a serial byte in/out interrupt. These interrupt sources force the processor to vector to one of five locations in the lowest part of the CODE address space (serial input and serial output interrupts share the same vector). The interrupt service routine must either reside there or be branched to from there. The 8051 supports two interrupt priority levels: low and high. The nature of the interrupt mechanism is very standard and thus, a low level interrupt service routine can only be interrupted by a high level interrupt and a high level interrupt service routine cannot be interrupted. Interrupt Source Power On Reset External Interrupt 0 Timer 0 Overflow External Interrupt 1 Timer 1 Overflow Serial

Symbol Vector Address RST 0000H IE0 0003H TF0 000BH IE1 0013H TF1 001BH RI/TI 0023H

Default Priority 0 (Highest) 1 2 3 4 5 (Lowest)

4.7.1. Interrupt Priority Register Each interrupt source can be individually set to one of two priority levels by altering the value of the IP (Interrupt Priority) SFR. If an interrupt source's corresponding bit Exploring Microcontroller Technology

92

----- ----- -----

    

PS

PT1

PX1

PT0

PX0

PS : Serial interface. PT1 : Timer 1. PX1 : External interrupt 1. PT0 : Timer 0. PX0 : External interrupt 0. - 0 = Low priority. - 1 = High priority.

Figure 4.11: Interrupt Priority Register

EA ---- ---- ES

EA ES ET1 EX1 ET0 EX0

ET1

EX1

ET0

EX0

: Global interrupt enable. : Serial interface. : Timer 1. : External interrupt 1. : Timer 0. : External interrupt 0. 0 = Disabled. 1 = Enabled.

Figure 4.12: Interrupt Enable Register

Exploring Microcontroller Technology

93

in this register is set, it will have high priority. Similarly, if the corresponding bit is cleared the interrupt will be of low priority and subject to being interrupted by any high priority interrupts. 4.7.2. Interrupt Enable Register All interrupts are enabled or blocked by setting or clearing the EA bit (Enable All) of the IE (Interrupt Enable) register. Each interrupt source can be individually enabled and disabled at any time by the software by altering the value of the corresponding 4.7.3. External Interrupt Signals The 8051 supports two external interrupts signals. These inputs allow external hardware devices to request interrupts and thus some sort of service from the 8051. The external interrupts on the 8051 are caused by either a low logic level on the interrupt pin (P3.2 for interrupt 0 and P3.3 for interrupt 1) or by a high to low level transition in the interrupt pin. The mode of the interrupt (level triggered or edge triggered) is selected by altering the ITx (interrupt type) bit corresponding to the interrupt in the TCON (Timer CONtrol) register. In level mode, the interrupt will be fired any time the processor samples the input signal and sees a 0. For the low to be detected, it must be held for at least one processor cycle (or 12 oscillator cycles) since the processor samples the input signal once every instruction cycle. In edge mode, the interrupt is fired when a one to zero transition is detected during back to back samples. Therefore, the zero state of the input must be held for at least one processor cycle to ensure that it is sampled

Exploring Microcontroller Technology

94

CHAPTER 5 Burning the 8051

Exploring Microcontroller Technology

95

5.1. Prerequisite for programming the Microcontroller Although in the initial chapters all of the discussion about the overall microcontroller technology but in this chapter we will discuss the programming of the 8051 which is choose as model for study. The programming of microcontroller is not a traditional job like desktop computing. It strongly co relates with the microcontroller based system design process which will be discussed in the next section. For the programming of the microcontroller a software engineer should have the clear concept of the following aspects       

Programming models Knowledge of CPU register Instruction set with function detail System memory map Initialization and use of On- chip peripherals, SFRs, Interrupt source & interrupt hierarchy Allowed Data types & directives

[2]

A good software engineer who is subjected to program a microcontroller has a good knowledge about the entire hardware feature of the respected microcontroller. Good programming of the microcontroller is also depends upon the available resources and programming tools.

5.2. Design process of Microcontroller based system Since the hardware and firmware has very close relation during the launching of a microcontroller based embedded system. So the hardware and software design go side by side. The electronic design process starts with the identification of customer requirement which may begins from the core functionalities and extend to the aesthetical pleasing. After the requirement the product specifications are determined which further leads to the conceptual design which gathers the overall the system design concept. After the conceptual process the phase of embodiment design process takes place where the concepts and ideas of previous design take the physical formation in other words the structure of hardware and software has been defined. After it the detail designs process tart where all the micro level details of hardware and software is finalized by considering the metrics of performance and cost. A flow of these processes is shown in the Figure 5.1. If we put the main features of each process with respect to the embedded system in bulleted form on micro level then we have following scenario.

Exploring Microcontroller Technology

96

Customer Requirement

Clarification of need Specification

Conceptual design Design Concept

Embodiment design Hardware and Software Layout

Detail Design

Circuit diagram Firmware Listing

Figure 5.1: Flow of MCU based system design Processes

Exploring Microcontroller Technology

97

a) Understanding the Requirement I. Enlist the requirement-Demands and wishes II. Draw the specification b) Conceptual design I. Identification of principal hardware function II. Identification of principal hardware function III. User interface & geometry IV. Cost V. Reliability and safety c) Embodiment Deign I. Determine the solution technology II. Define the hardware and software boundaries III. Choose programming language IV. Define the hardware topology V. Determine the word size and execution speed VI. And others d) Detail design I. Ensure the performance and reliability II. Ensure the manufacturability

[2]

The detailed picture of a microcontroller based system design process is shown in Figure 5.2. Since the main phase of process is the embodiment design where the structure and flow of a firmware is decided by considering the solution technology that either the dedicated microcontroller (DSP) is used or general purpose microcontroller will be used. Before choosing a microcontroller the memory size and the data types are considered to be use. The memory size determines the both size of embedded algorithms and no of variables to be used. On the other hand the word size means the size of data type which would be the most compatible with the proposed solution according to the requirement specification. Since the word size vary with the choice of microcontroller Another metric which is counted in the embodiment design i.e. processing speed, there are variety of microcontrollers whose clock speed vary in the boundaries of 4MHz to 60MHz. As well as the type of instruction set is also matters. By considering above discussed facts and hardware topology the final structure of embedded algorithm is planned i.e. what functions will be assigned to the hardware or performed by the software. At the last phase where the software and hardware are commissioned for performing the functionalities of system in a combine manner then both core components are subjected for the debugging and testing. There then the nerve breaking process takes place because any bug in the hardware and software would be crash the Exploring Microcontroller Technology

98

Figure 5.2: Detailed scenario of MCU based system design process

Exploring Microcontroller Technology

99

overall system. As in the war of Falkland, a British navel ship was wrecked by a French missile because the missile detecting system has software which had the information‟s about all the type of missile with respect to their manufacturing countries. This list was stored in the system with specification of friends and enemy specification. But the friendly French missile was fired by an enemy Argentina, so the bug in the software was resulted in a unrecoverable damage.

5.3. From source file to .HEX The compilation aspect of embedded software is different from the desktop computing software‟s, where we have an exe file as an output. The compilation process in the embedded system programming yields an ASCII text file which is called HEX file. This file is subject to download in the ROM. There it execute according to the algorithm which was designed according to the specification of the application. If we consider the Figure 5.3 there the assembler/compiler generate a .obi file for the linker which further yield the absolute object file with extension .abs. This abs file is converted in the .HEX file by a utility. For the 8051 this utility is called OH. 5.3.1. Intel Hex file format The Intel HEX file is an ASCII text file with lines of text that follow the Intel HEX file format. Each line in an Intel HEX file contains one HEX record. These records are made up of hexadecimal numbers that represent machine language code and/or constant data. Intel HEX files are often used to transfer the program and data that would be stored in a ROM or EPROM. Most EPROM programmers or emulators can use Intel HEX files. 5.3.1. 1.Record Format An Intel HEX file is composed of any number of HEX records. Each record is made up of five fields that are arranged in the following format: :llaaaatt[dd...]cc Each group of letters corresponds to a different field, and each letter represents a single hexadecimal digit. Each field is composed of at least two hexadecimal digitswhich make up a byte-as described below:    

: is the colon that starts every Intel HEX record i.e. first column. ll is the record-length field that represents the number of data bytes (dd) in the record i.e. Column 2 and 3. aaaa is the address field that represents the starting address for subsequent data in the record i.e. Column 4 and 7. tt is the field i.e. column 8 and 9 that represents the HEX record type, whic

Exploring Microcontroller Technology

100

Listing file .MAP

Assembler

.OBJ

Linker

Absolute Object file

OBJ/Hex Conversion

Hex File .HEX

Compiler

Figure 5.3: From Source to Hex

Figure 5.4: 8051 HEX file format

Exploring Microcontroller Technology

101

may be one of the following: 00 - data record 01 - end-of-file record  



02 - extended segment address record 04 - extended linear address record dd is a data field that represents first byte of data. A record may have multiple data bytes. The number of data bytes in the record must match the number specified by the ll field i.e. Column 10 and 11. cc is the checksum field that represents the checksum of the record. The checksum is calculated by summing the values of all hexadecimal digit pairs in the record modulo 256 and taking the two's complement i.e. column 14.

5.4. Programming the 8051 This section is written with the intension that reader has sufficient knowledge of Intel assembly language and ANSI C. The programming of 8051 is done in both assembly language i.e. ASM51 specific to it a subset of x86 assembly & in the higher level language like C and Basic. But the use of higher level language is costly option but more portable. Where as assembly programming is tedious work but low cost in terms of generated code.

5.5. An abridged review of ASM 51 As previously is described before starting programming a person should have knowledge of memory architecture and other prerequisites. For that purpose see the chapter four and the remaining things are going to discussed hare 5.5.1. Special Assembler Symbols The A51 assembler defines and reserves names of the x51 register set. These predefined names are used in x51 programs to access the processor registers.       

A: Accumulator. DPTR: The DPTR register is a 16-bit data pointer used to address data in XDATA or CODE memory. PC: The PC register is the 16-bit program counter. It contains the address of the next instruction to be executed. C: The Carry flag; indicates the status of operations that generate a carry bit. It is also used by operations that require a borrow bit. AB: The A and B register pair used in MUL and DIV instructions. R0 – R7: The eight 8-bit general purpose 8051 registers in the currently active register bank. A Maximum of four register banks are available. AR0 – AR7: Represent the absolute data addresses of R0 through R7 in the current register bank. The absolute address for these registers will change depending on the register bank that is currently selected. These symbols are

Exploring Microcontroller Technology

102



only available when the USING directive is given SFR: All the SFR (specials function register) name are also the assembler symbols. Like P1 for port 1 or SBUFF for serial buffer register

5.5.2. Addressing Modes An "addressing mode" refers to how you are addressing a given memory location. 5.5.2.1. Immediate Addressing Immediate addressing is so-named because the value to be stored in memory immediately follows the operation code in memory. That is to say, the instruction itself dictates what value will be stored in memory. For example, the instruction: MOV A,#20h This instruction uses Immediate Addressing because the Accumulator will be loaded with the value that immediately follows; in this case 20 (hexadecimal). Immediate addressing is very fast since the value to be loaded is included in the instruction. However, since the value to be loaded is fixed at compile-time it is not very flexible. 5.5.2.2. Direct Addressing Direct addressing is so-named because the value to be stored in memory is obtained by directly retrieving it from another memory location. For example: MOV A,30h This instruction will read the data out of Internal RAM address 30 (hexadecimal) and store it in the Accumulator. Direct addressing is generally fast since, although the value to be loaded isn‟t included in the instruction, it is quickly accessible since it is stored in the 8051internal RAM. It is also much more flexible than Immediate Addressing since the value to be loaded is whatever is found at the given address--which may be variable. Also, it is important to note that when using direct addressing any instruction which refers to an address between 00h and 7Fh is referring to Internal Memory. Any instruction which refers to an address between 80h and FFh is referring to the SFR control registers that control the 8051 microcontroller itself. 5.5.2.3. Indirect Addressing Indirect addressing is a very powerful addressing mode which in many cases Exploring Microcontroller Technology

103

provides an exceptional level of flexibility. Indirect addressing is also the only way to access the extra 128 bytes of Internal RAM found on an 8052 ( 8051‟s big brother) Indirect addressing appears as follows: MOV A,@R0 This instruction causes the 8051 to analyze the value of the R0 register. The 8051 will then load the accumulator with the value from Internal RAM which is found at the address indicated by R0. 5.5.2.4. External Direct Addressing External Memory is accessed using a suite of instructions which use what I call "External Direct" addressing. I call it this because it appears to be direct addressing, but it is used to access external memory rather than internal memory. There are only two commands that use External Direct addressing mode: MOVXA,@DPTR MOVX @DPTR,A Both commands utilise DPTR. In these instructions, DPTR must first be loaded with the address of external memory that you wish to read or write. Once DPTR holds the correct external memory address, the first command will move the contents of that external memory address into the Accumulator. The second command will do the opposite: it will allow you to write the value of the Accumulator to the external memory address pointed to by DPTR. 5.5.2.5. External Indirect Addressing External memory can also be accessed using a form of indirect addressing which I call External Indirect addressing. This form of addressing is usually only used in relatively small projects that have a very small amount of external RAM. An example of this addressing mode is: MOVX @R0, A Once again, the value of R0 is first read and the value of the Accumulator is written to that address in External RAM. Since the value of @R0 can only be 00h through FFh the project would effectively be limited to 256 bytes of External RAM. The above described addressing modes are also classified as  

Data Addressing  Above mentioned all addressing modes are covered in this domain. Bit addressing: A special feature of 8051 there are 210 bit addressable positions n BDATA and in the SFR‟s area. For example

Exploring Microcontroller Technology

104

SETB P1.3

;; set the bit number 3 in the port 3 register

5.5.3. Code Addressing Program addresses are absolute or relocatable expressions with the memory class CODE. Typically program addresses are used in jump and call instructions. For indirect jumps or calls it is required to load a program address in a register or a jump table. The following jumps and calls are possible: 5.5.3.1. Using relative jumps The relative jump method include conditional jumps (CJNE, DJNZ, JB, JBC, JC, …) and the unconditional SJMP instruction. The addressable offset is –128 to +127 bytes from the first byte of the instruction that follows the relative jump. When you use a relative jump in code, you must use an expression that evaluates to the code address of the jump destination. The assembler does all the offset computations. If the address is out of range, the assembler will issue an error message. 5.5.3.2. Using in-block jumps and calls ACALL, AJMP permits access only within a 2KByte block of program space. The low order 11 bits of the program counter are replaced when the jump or call is executed.. If ACALL or AJMP is the last instruction in a block, the high order bits of the program counter change and the jump will be within the block following the ACALL or AJMP. 5.5.3.3. Using Long jumps and calls LCALL, LJMP allows access to any address within a 64KByte segment of program space. The low order 16 bits of the program counter are replaced when the jump or call is executed. 5.5.4. Numbers, Characters Numbers can be specified in hexadecimal (base 16), decimal (base 10), octal (base 8), and binary (base 2). The base of a number is specified by the last character in the number. A number that is specified without an explicit base is interpreted as decimal number. For example MOV A, # 21H MOV A, #01010111B The Ax51 assembler allows you to use ASCII characters in an expression to generate a numeric value. Up to two characters enclosed within single quotes (') may be included in an expression. For example MOV A, #'A' Exploring Microcontroller Technology

;; 'A' evaluates to 0041h 105

MOV A,#‟AB‟

;; 'AB‟‟ evaluates to 4142h

Characters may be used anywhere in program as a immediate data operand. For example: LETTER_A

EQU

'A'

Character strings can be used in combination with the DB directive to define messages that are used in x51 assembly program. Character strings must be enclosed within single quotes ('). For example: KEYMSG: DB

'Press any key to continue.'

generates the hexadecimal data (50h, 72h, 65h, 73h, 73h, 20h, … 6Eh, 75h, 65h, 2Eh) starting at KEYMSG. 5.5.5. Arithmetic, Binary and Relational Operators 8051 offers all operators which is used for x86 like addition +, subtraction –, multiplication *, division / and remainder MOD for arithmetic, NOT, SHR, SHL, AND, OR, XOR for binary operations. For relation operation GTE >=, LTE

Suggest Documents