Você está na página 1de 86

PROJECT REPORT ON EMBEDDED SYSTEMS AND DESIGN

ADVANCE TECHNOLOGY,CHANDIGARH

SU BMITTED TO: COORDINATOR(P.T) Rajeshwar Dass Assistant Professor ECE Department


1

SUBMITTED BY: Rohit Gulati ECE(Vth semester) 0803043

LIST OF CONTENTS

Introduction to Advance Technology 1. Introduction to Microcontroller 2. 8051 Microcontroller 3. Memory concepts in 8051 4. 8051- I/O Ports Programming 5. 8051 Timers and Counters 6. Serial Communication 7. Interrupts in 8051 8. L.E.D , 7 Segment and L.C.D 9. ADC interfacing 10. Relay , Buzzer and DC motor Summary References Appendix 80 83 84 76

1 2 13 21 42 47 50 60 65

78

LIST OF FIGURES
FIGURE NO.
1.1
1.2 1.3 1.4 1.5 2.1 2.2 3.1 4.1

DESCRIPTION
A MICROPROCESSOR A MICROCONTROLLER

PAGE NO.
5 8 9 11 12 17 19 24 43 44 46 50 52 53 59 66 67 70 8.1 8.2 8.3 6.4 6.3 4.3 6.1 6.2 4.2

BLOCK DIAGRAM OF A MICROCONTROLLER INTEL MICROCONTROLLER 8051 INSIDE THE MICROCONTROLLER 8051 PIN DIAGRAM CRYSTAL CONNECTIONS BIT REGISTER 8051 PIN DESCRIPTION

PORT 0 WITH PULL- UP RESISTORS PORT 3 ALTERNATE FUNCTIONS SERIAL VERSUS PARALLEL DATA TRANSFER SIMPLE, HALF AND FULL DUPLEX FRAMING ASCII "A" (41H) DS89C4X0 PIN DIAGRAM STRUCTURE OF L.E.D. 7 SEGMENT PIN DIAGRAM OF LCD

LIST OF TABLES
TABLE NO.
1.1 2.1 2.2 3.1 5.1 6.1 6.2 6.3 6.4 7.1 7.2 8.1 8.2

DESCRIPTION
8051 MEMBERS 8051 FAMILY ALTERNATE FUNCTIONS OF PORT 3 OF 8051 SFRs TIMERS PC BAUD RATES SCON REGISTER MODE SELECTION BITS PCON REGISTER AND INSTRUCTOIN SET INTERRUPT VECTOR TABLE INTERRUPT REGISTER INPUT COMMANDS FOR 7 SEGMENT PIN DESCRIPTION AF AN LCD

PAGE NO.
12 14 18 31 48 54 55 55 58 61 64 68 71

INTRODUCTION TO ADVANCE TECHNOLOGY


The company cum institute where I did my training Is Advance Technolgy(ATECH). Advance Technology is a company founded in 1999 specializing in Embedded System ,Test & Measuring service utility operations and maintenance support services. The company was started solely for providing R&D solutions in the area of Embedded Systems, VLSI, DSP and Embedded Wireless. The company providesSolutions including Manufacturing to the Indian Industry and Defense in demanding fields like Instrumentation, Communication, Noise/ Vibration analyzers.The company has its head office in Chandigarh.The company also has its regional offices in Haryana,Punjab,Himachal and northern India. The company provides training in Embedded Systems, VLSI, FPGA, CPLD etc. the duration of the

programmes wary from 6 weeks to 6 months. The company had an M.o.U. signed with Deenbandhu Chhotu Ram University of Science and Technology.The company provided a 6 weeks training in the college premises in Embedded Systems from 15 June to 21 July. Atech Labs is fully focused for High-End Specialized Training Programs. It is an innovative concept of Imparting Hi-Technology Training to Customers and Young Professional in Embedded Microcontroller, VLSI Design, Digital Signal Processing Design, Wireless & Communication and Industrial Training. Atech Labs dedicated to provide niche & highly qualified technologies which are value based and operates at a Highly Technical Education Sector. It dedicated itself to the training and development of outstanding professionals in order to meet the ever-growing challenges of Technology Industry. Our Mission is to provide Current and Comprehensive Educational Programs that enhance Individual Performance and Corporate Productivity in the Higher End Technology with a Knowledge based. We provide the most convenient and cost effective delivery of Course Contents by World Experts in Academia and Industry.

CHAPTER 1 INTRODUCTION TO MICROCONTROLLER

INTRODUCTION:Circumstances that we find ourselves in today in the field of

microcontrollers had their beginnings in the development of technology of integrated circuits. This development has made it possible to store hundreds of thousands of transistors into one chip. That was a

prerequisite for production of microprocessors, and the first computers were made by adding external peripherals such as memory, input-output lines, timers and other. Further increasing of the volume of the

package resulted in creation of integrated circuits. These integrated circuits contained both processor and peripherals. That is how the

first chip containing a microcomputer, or what would later be known as a microcontroller came about.

DEFINITION OF A MICROCONTROLLER:-

Microcontroller, as the name suggests, are small controllers. They are like single chip computers that are often embedded into other systems to function as processing/controlling unit. For example, the remote control decoding you and are using probably has microcontrollers They are inside also that used do in

other

controlling

functions.

automobiles, washing machines, microwave ovens, toys ... etc, where automation is needed. The key features of microcontrollers include:

High Integration of Functionality

Microcontrollers
because they have that

sometimes on-chip enable

are memory to

called and

single-chip circuitry as small

computers and other

I/O

circuitries

them

function

standalone

computers without other supporting circuitry.

Field Programmability, Flexibility Microcontrollers often use EEPROM or EPROM as their storage
device to allow field programmability so they are flexible to use. Once the program is tested to be correct then large

quantities of microcontrollers can be programmed to be used in embedded systems.

Easy to use.

MICROCONTROLLER FOR EMBEDDED SYSTEM:Microprocessors and Microcontroller are widely used in embedded systems products. An Embedded product uses a microprocessor (or micro controller to do one task only. A printer is an example of embedded system since the processor inside it performs only one task, namely, getting the data printing it.

A PC can be used for any number of applications such as Word processor, print server, bank teller terminal, video game player, network server or internet terminal software for variety of applications can be loaded and run. Of course, the reason a PC can perform a myriad tasks is that it has a RAM memory and a operating system that loads Applications software and let CPU run it. In an Embedded system there is only one application software that is typically burned into ROM. And x86 PC or is connected to various embedded products such as keyboard, printer, sound card etc. Each one of these peripherals has a Microcontroller inside it that performs only one task for example Inside every mouse there is a microcontroller that performs the task of finding mouse position and sending it to the PC.

VARIOUS APPLICATIONS OF EMBEDDED SYSTEMS:-

Embedded systems span all aspects of modern life and there are many examples

of

their

use.Telecommunications systems employ numerous embedded systems from telephone switches for the network to mobile phones at the end-user. Computer networking uses dedicated routers and network bridges to route data.Consumer electronics include personal digital assistants (PDAs), mp3 players, mobile phones, videogame consoles, digital cameras, DVD players, GPS receivers, and printers. Many household appliances, such as microwave ovens, washing machines and dishwashers, are including embedded systems to provide flexibility, efficiency and features. Advanced HVAC systems use networked thermostats to more accurately and efficiently control temperature that can change by time of day and season. Home automation uses wired- and wireless-networking that can be used to control lights, climate, security, audio/visual, surveillance, etc., all of which use embedded devices for sensing and controlling. Transportation systems from flight to automobiles increasingly use embedded systems. New airplanes contain advanced avionics such as inertial guidance systems and GPS receivers that also have considerable safety requirements. Various electric motors brushless DC motors, induction motors and DC motors are using electric/electronic motor controllers. Automobiles, electric vehicles, and hybrid vehicles are

increasingly using embedded systems to maximize efficiency and reduce pollution. Other automotive safety systems include anti-lock braking system (ABS), Electronic Stability Control (ESC/ESP), traction control (TCS) and automatic four-wheel drive. Medical equipment is continuing to advance with more embedded systems for vital signs monitoring, electronic stethoscopes for amplifying sounds, and various medical imaging (PET, SPECT, CT, MRI) for non-invasive internal inspections. In addition to commonly described embedded systems based on small computers, a new class of miniature wireless devices called motes are quickly gaining popularity as the field of wireless sensor networking rises. Wireless sensor networking, WSN, makes use of miniaturization made possible by advanced IC design to couple full wireless subsystems to sophisticated sensors, enabling people and companies to measure a myriad of things in the physical world and act on this information through IT monitoring and control systems. These motes are completely self contained, and will typically run off a battery source for many years before the batteries need to be changed or charged.

MICROPROCESSORS AND MICROCONTROLLERS :-

A microprocessor is multipurpose ,programmable ,clock driven ,register based electronic device that reads binary instructions from a storage device called memory ,accepts binary data as input and processes data according to those instructions and provides results as output. A typical programmable machine can be represented with four components : microprocessor ,input ,output and memory. These four components work together or interact with each other to perform a given task.

Figure 1.1- A MICROPROCESSOR

The fact that it is programmable means that it can be instructed to perform given tasks with its capability. The microprocessor is a click driven semiconductor device consisting of electronic logic circuits

manufactured by using either a large scale integration(LSI) or very large scale integration (VLSI).The microprocessor is capable of performing various computing functions and making decisions to cahnge the sequence of program execution . In large computers ,a C.P.U. implemented on one or more circuit boards performs these computing functions .The microprocessor is in many ways similar to a C.P.U. ,but includes all the logic circuitry ,including the control unit on one chip. A good example of a microprocessor is the INTELs 8085 and 8086. The present microprocessors used in computers are the i-3 ,i-5 and i-7 processors again from INTEL.A microprocessor does not have RAM , ROM, OR I/O PORTS ,these are provided by the system designer externally.Though it makes it more expensive and bulky, it also enables the designer to provide RAM,ROM and I/O PORTS as required at hand . Microprocessors are widely used in personal computers. A microcontroller (C) is a small computer on a single integrated circuit containing a processor core, memory, and programmable input/output peripherals. Program memory in the form of ROM is also often included on chip, as well as a typically small amount of RAM. A microcontroller can be considered a selfcontained system with a processor, memory and peripherals and can be used as an embedded system. The majority of microcontrollers in use today are embedded in other machinery, such as automobiles, telephones, appliances, and peripherals for computer systems. While some embedded systems are very sophisticated, many have minimal requirements for memory and program length, with no operating system, and low software complexity. Typical input and output devices include switches, relays, solenoids, LEDs,

10

small or custom LCD displays, radio frequency devices, and sensors for data such as temperature, humidity, light level etc. Embedded systems usually have no keyboard, screen, disks, printers, or other recognizable I/O devices of a personal computer, and may lack human interaction devices of any kind. In contrast to general-purpose CPUs, micro-controllers may not implement an external address or data bus as they integrate RAM and non-volatile memory on the same chip as the CPU. Using fewer pins, the chip can be placed in a much smaller, cheaper package. Integrating the memory and other peripherals on a single chip and testing them as a unit increases the cost of that chip, but often results in decreased net cost of the embedded system as a whole. Even if the cost of a CPU that has integrated peripherals is slightly more than the cost of a CPU and external peripherals, having fewer chips typically allows a smaller and cheaper circuit board, and reduces the labor required to assemble and test the circuit board. A micro-controller is a single integrated circuit, commonly with the following features: * central processing unit - ranging from small and simple 4-bit processors to complex 32- or 64-bit processors * discrete input and output bits, allowing control or detection of the logic state of an individual package pin * serial input/output such as serial ports (UARTs) * other serial communications interfaces like IC, Serial Peripheral Interface and Controller Area Network for system interconnect * peripherals such as timers, event counters, PWM generators, and watchdog * volatile memory (RAM) for data storage * ROM, EPROM, EEPROM or Flash memory for program and operating parameter storage * clock generator - often an oscillator for a quartz timing crystal, resonator or RC circuit * many include analog-to-digital converters * in-circuit programming and debugging support

This integration drastically reduces the number of chips and the amount of wiring and circuit board space that would be needed to produce equivalent systems using separate chips. Furthermore, and on low pin count devices in particular, each pin may interface to several internal peripherals, with the pin function selected by software. This allows a part to be used in a wider variety of applications than if pins had

11

dedicated functions. Micro-controllers have proved to be highly popular in embedded systems since their introduction in the 1970s. The decision of which peripheral to integrate is often difficult. The microcontroller vendors often trade operating frequencies and system design flexibility against time-to-market requirements from their customers and overall lower system cost. Manufacturers have to balance the need to minimize the chip size against additional functionality.

Microcontroller architectures vary widely. Some designs include general-purpose microprocessor cores, with one or more ROM, RAM, or I/O functions integrated onto the package. Other designs are purpose built for control applications. A micro-controller instruction set usually has many instructions intended for bit-wise operations to make control programs more compact. For example, a general purpose processor might require several instructions to test a bit in a register and branch if the bit is set, where a microcontroller could have a single instruction to provide that commonly-required function.

FIG. 1.2

A MICROCONTROLLER

12

FIG. 1.3

BLOCK DIAGRAM OF A MICROCONTROLLER

Criteria for choosing a Microcontoller:1. The first and foremost criterioin in choosing a microcontroller is that it must meet the task at hand efficeintly and cost effectively. In analyzing the needs of a microcontroller-based project, we must first see whether an 8 bit ,16 bit,or 32 bit micro controller can best handle the computing needs of the task most effectively.Among other considreatoins in this category are:

A. Speed- what the highest speed that a microcontroller supports? B. Packaging-does it come in a 40-pin DIP(DUAL IN LINE PACKAGE) or a QFP(QUAD FLAT PACKAGE) or some other packaging format? This is important in terms of space, assembling and prototyping the end product. C. Power consumption.This is especially critical for battery powered products. D. The amount of RAM and ROM on chip. E. The no.of I/O pins and the TIMER on the chip. F. How easy it is to upgrade to higher- performance or lower power consumption versions.

13

G. Cost per unit .This is important in terms of the final cost of the product in which a microcontroller
is used. For example ,there are microcontrollers that cost 50 percents per unit when purchased 100, 000 units at a time.

2.

The second criterion is in choosing the microcontroller in how easy is to develop product around it.key considerstion include the availibilty of an assembler, debuger ,a code-efficient C language compiler , emulater, technical support ,and both in-house and outside expertise. In many cases , thirdparty vendor(that is,a supplier other than the chip manufacture) support for the chip is as good as, if not better than, support from the chip manufacturer .

3.

The third critrion in chooosing a microcontroller is its ready availability in needed quantities both now and I the future. For some reason designers this even more important that the first two criteria.currently, of the leading 8-bit microcontrollers, the 8051 family has the largest number of diversified (multiple source) suppliers. By supplier is meant a procedcure besides the originator of the microcontroller. In the case of the 8051, which has originated by intel.

SOME OF THE COMPANIES PRODUCING A MEMBER OF THE 8051 FAMILY:1. 2. 3. 4. 5. 6. 7. Intel (original) Atmel Philips/Signetics AMD Infineon (formerly Siemens) Matra Dallas Semiconductor/Maxim

14

Figure 1.4-INTEL MICROCONTROLLER 8051

CHARACTERSTICS OF 8051 MICROCONTROLLER:1. 8-bit data bus - It can access 8 bits of data in one operation (hence it is an 8-bit microcontroller).

2. 16-bit address bus - It can access 216 memory locations 64 kb each of RAM and ROM.
3. 4. 5. 6. 7. 8. 9. On-chip RAM - 128 bytes ("Data Memory"). On-chip ROM - 4 kb ("Program Memory"). Four bi-directional input/output port . I/O Pins 32. Two 16-bit timers. Serial port 1 (UART). Interrupt Sources 6.

15

Figure 1.5-INSIDE THE MICROCONTROLLER BLOCK DIAGRAM

VARIOUS 8051 FAMILY MEMBERS:

Table 1.1- 8051 MEMBERS

16

CHAPTER 2 8051 MICROCONTROLLER


Microcontroller 8051 or the INTELs 8051 as it was originated by INTEL, is one of the very popular microcontrollers. INTEL introduced this 8 bit microcontroller in 1981. The microcontroller had 128 bytes of RAM,4K bytes of on chip ROM, two timers ,one serial port and four I/O ports. The 8051 became very popular after Intel allowed other manufacturers to make and market any flavours of 8051 though they pleased the condition that they remain code compatible with 8051.Nowadays a large number of companies are making 8051 , these are Atmel, Infineon Technologies (formerly Siemens AG), Maxim Integrated Products (via its Dallas Semiconductor subsidiary), NXP (formerly Philips Semiconductor), Nuvoton (formerly Winbond), ST Microelectronics, Silicon Laboratories (formerly Cygnal), Texas Instruments and Cypress Semiconductor.

8051 FAMILY:The 8051 is just one of the MCS-51 family of microcontrollers developed by Intel. The design of each of the MCS-51 microcontrollers are more or less the same. The differences between each member of the family is the amount of on-chip memory and the number of timers is

Microcontroller 8051 8031 8751 8052 8032

On-chip Memory 4K ROM 0 4K EPROM 8K ROM 0

Code On-chip Memory 128 bytes 128 bytes 128 bytes 256 bytes 256 bytes 17

Data

Timers 2 2 2 3 3

8752

8K EPROM

256 bytes

TABLE 2.1 8051 FAMILY

FEATURES:Some of the important features of the 8051 microcontrollers are :# 8-bit ALU, Accumulator and 8-bit Registers; hence it is an 8-bit microcontroller # 8-bit data bus - It can access 8 bits of data in one operation # 16-bit address bus - It can access 216 memory locations - 64 KB of ROM # On-chip RAM - 128 bytes (data memory) # On-chip ROM - 4 kByte (program memory) # Four byte bi-directional input/output port # UART (serial port) # Two 16-bit Counter/timers # Two-level interrupt priority A particularly useful feature of the 8051 core is the inclusion of a boolean processing engine which allows bit-level boolean logic operations to be carried out directly and efficiently on internal registers and RAM. This feature helped cement the 8051's popularity in industrial control applications. Another valued feature is that it has four separate register sets, which can be used to greatly reduce interrupt latency compared to the more common method of storing interrupt context on a stack. The 8051 UARTs make it simple to use the chip as a serial communications interface. External pins can be configured to connect to internal shift registers in a variety of ways, and the internal timers can also be used, allowing serial communications in a number of modes, both synchronous and asynchronous. Some modes allow communications with no external components. A mode compatible with an RS-485 multipoint communications environment is achievable, but the 8051' s real strength is fitting in with existing adhoc protocols (e.g., when controlling serial-controlled devices).Once a UART, and a timer if necessary, have been configured, the programmer needs only to write a simple interrupt routine to refill the send shift register whenever the last bit is shifted out by the UART and/or empty the full receive shift register (copy the data somewhere else). The main program then performs serial reads and writes simply by reading and writing 8-bit data to stacks.

18

8051 based microcontrollers typically include one or two UARTs, two or three timers, 128 or 256 bytes of internal data RAM (16 bytes of which are bit-addressable), up to 128 bytes of I/O, 512 bytes to 64 kB of internal program memory, and sometimes a quantity of extended data RAM (ERAM) located in the external data space. The original 8051 core ran at 12 clock cycles per machine cycle, with most instructions executing in one or two machine cycles. With a 12 MHz clock frequency, the 8051 could thus execute 1 million one-cycle instructions per second or 500,000 two-cycle instructions per second. Enhanced 8051 cores are now commonly used which run at six, four, two, or even one clock per machine cycle, and have clock frequencies of up to 100 MHz, and are thus capable of an even greater number of instructions per second. All SILabs, some Dallas and a few Atmel devices have single cycle cores.Common features included in modern 8051 based microcontrollers include built-in reset timers with brown-out detection, onchip oscillators, self-programmable Flash ROM program memory, bootloader code in ROM, EEPROM non-volatile data storage, IC, SPI, and USB host interfaces, CAN or LIN bus, PWM generators, analog comparators, A/D and D/A converters, RTCs, extra counters and timers, in-circuit debugging facilities, more interrupt sources, and extra power saving modes.

PIN CONFIGURATION :In the 8051 there are four ports for I/O operations. It has 40 pins, out of which a total of 32 pins are set aside for the four ports P0 , P1, P2 and P3. The rest of the pins are designated as Vcc, GND, XTAL1 , XTAL2, EA ,ALE The four ports P0, P1, P2, and P3 each use 8 pins making them 8 bit ports.All the ports upon RESET are configured as inputs, ready to be used as input ports. Port 0 - pins 32 to 39 make up the 8-bit I/O port 0. However, if external memory is used, these lines are as a multiplexed address and data bus. Port 1 - pins 1 to 8 make up the 8-bit I/O port 1. Port 2 - pins 21 to 28 make up the 8-bit I/O port 2. However, if external memory is used, these lines make up the high-byte of the external address (A8 to A15). Port 3 - pins 10 to 17 make up the 8-bit I/O port 3.

19

Figure 2.1- 8051 PIN DIAGRAM The following are the special functions and repective pins:RST - the reset input is on pin 9. This pin is used for resetting the 8051 EA-bar - the external access, on pin 31, is used for enabling or disabling the on-chip ROM. When tied high (5V), the 8051 executes instructions in internal ROM when executing in the lower 4K (8K for the 8052) of memory. If tied low the 8051 will always execute instructions in external memory. The 8031 and 8032 should always have pin 31 tied low as there is no internal code memory. ALE - the address latch enable is on pin 30. The ALE is used for latching the low byte of the address into an external register. We will deal with this at a later date. PSEN-bar - the program store enable is an output signal on pin 29. This signal is used for fetching instructions from external code memory. Port 3 also does some additional alternate functions.It is a multipurpose port.

Pin P3.0 P3.1 P3.2 P3.3 P3.4 P3.5

Name RXD TXD INT0-bar INT1-bar T0 T1

Bit Address B0H B1H B2H B3H B4H B5H

Function Receive data for serial port Transmit data for serial port External interrupt 0 External interrupt 1 Timer/counter 0 external input Timer/counter 1 external input

20

P3.6 P3.7

WR-bar RD-bar

B6H B7H

External data memory write strobe External data memory read strobe

Table 2.2 - ALTERNATE FUNCTIONS OF PORT 3 OF 8051

`The 8051 has an on chip oscillator but requires an external clock to run it. Most often a quartz crystal
oscillator is connected to inputs XTAL1( pin 19) and XTAL2( pin 18). The quartz crystal oscillator also needs two capacitors of 30pF . On side of each capacitor is connected to ground.It must be noted that there are various speeds of the 8051 family. Speed refers to the maximum oscillator frequency connected crystal.For example a 12 MHz crystal must be connected to a crystal of frequency 12 MHz or less.

Figure. 2.2 - CRYSTAL CONNECTIONS

INTERRUPTS:Microcontrollers must provide real time (predictable, though not necessarily fast) response to events in the embedded system they are controlling. When certain events occur, an interrupt system can signal the processor to suspend processing the current instruction sequence and to begin an interrupt service routine (ISR, or "interrupt handler"). The ISR will perform any processing required based on the source of the interrupt before returning to the original instruction sequence. Possible interrupt sources are device

21

dependent, and often include events such as an internal timer overflow, completing an analog to digital conversion, a logic level change on an input such as from a button being pressed, and data received on a communication link.

PROGRAMS :Microcontroller programs must fit in the available on-chip program memory, since it would be costly to provide a system with external, expandable, memory. Compilers and assemblers are used to convert highlevel language and assembler language codes into a compact machine code for storage in the microcontroller's memory. Depending on the device, the program memory may be permanent, read-only memory that can only be programmed at the factory, or program memory may be field-alterable flash or erasable read-only memory

8051 TIMERS:The basic 8051 has two on-chip timers that can be used for timing durations or for counting external events.Interval timing allows the programmer to perform operations at specific instants in time .We achieve this through the use of time delays . Since the microcontroller operates at a specific frequency, we could work out exactly how many iterations of the time delay was needed to give us the desired delay. However, this is cumbersome and prone to error. And there is another disadvantage; the CPU is occupied, stepping through the loops. If we use the on-chip timers, the CPU could be off doing something more useful while the timers take on the menial task of keeping track of

CHAPTER 3 MEMORY CONCEPTS IN 8051


22

TYPES OF MEMORY:
The 8051 has three very general types of memory. To effectively program the 8051 it is necessary to have a basic understanding of these memory types. The memory types are illustrated in the following graphic. They are: On-Chip Memory, External Code Memory, and External RAM.

On-Chip Memory refers to any memory (Code, RAM, or other) that physically exists on the microcontroller itself. On-chip memory can be of several types, but we'll get into that shortly.

External Code Memory is code (or program) memory that resides off-chip. This is often in the form of an external EPROM.

External RAM is RAM memory that resides off-chip. This is often in the form of standard static RAM or flash RAM.

Code Memory:
Code memory is the memory that holds the actual 8051 program that is to be run. This memory is limited to 64K and comes in many shapes and sizes: Code memory may be found on-chip, either burned into the microcontroller as ROM or EPROM. Code may also be stored completely off-chip in an external ROM or, more commonly, an external EPROM. Flash RAM is also another popular method of storing a program. Various combinations of these memory types may also be used--that is to say, it is possible to have 4K of code memory on-chip and 64k of code memory off-chip in an EPROM. When the program is stored on-chip the 64K maximum is often reduced to 4k, 8k, or 16k. This varies depending on the version of the chip that is being used. Each version offers specific capabilities and one of the distinguishing factors from chip to chip is how much ROM/EPROM space the chip has. However, code memory is most commonly implemented as off-chip EPROM. This is especially true in low-cost development systems and in systems developed by students.

Since code memory is restricted to 64K, 8051 programs are limited to 64K. Some assemblers and compilers offer ways to get around this limit when used with specially wired hardware. However, without such special compilers and hardware, programs are limited to 64K.

23

External RAM:
As an obvious opposite of Internal RAM, the 8051 also supports what is called External RAM. As the name suggests, External RAM is any random access memory which is found off-chip. Since the memory is off-chip it is not as flexible in terms of accessing, and is also slower. For example, to increment an Internal RAM location by 1 requires only 1 instruction and 1 instruction cycle. To increment a 1-byte value stored in External RAM requires 4 instructions and 7 instruction cycles. In this case, external memory is 7 times slower. What External RAM loses in speed and flexibility it gains in quantity. While Internal RAM is limited to 128 bytes (256 bytes with an 8052), the 8051 supports External RAM up to 64K.

The 8051 may only address 64k of RAM. To expand RAM beyond this limit requires programming and hardware tricks. You may have to do this "by hand" since many compilers and assemblers, while providing support for programs in excess of 64k, do not support more than 64k of RAM. This is rather strange since it has been my experience that programs can usually fit in 64k but often RAM is what is lacking. Thus if you need more than 64k of RAM, check to see if your compiler supports it-- but if it doesn't, be prepared to do it by hand.

On Chip Memory:
As mentioned at the beginning of this chapter, the 8051 includes a certain amount of on-chip memory. On-chip memory is really one of two types: Internal RAM and Special Function Register (SFR) memory. The layout of the 8051's internal memory is presented in the following memory map:

As is illustrated in this map, the 8051 has a bank of 128 bytes of Internal RAM. This Internal RAM is found on-chip on the 8051 so it is the fastest RAM available, and it is also the most flexible in terms of reading, writing, and modifying its contents. Internal RAM is volatile, so when the 8051 is reset this memory is cleared.The 128 bytes of internal ram is subdivided as shown on the memory map. The first 8 bytes (00h - 07h) are "register bank 0". By manipulating certain SFRs, a program may choose to use register banks 1, 2, or 3. These alternative register banks are located in internal RAM in addresses 08h through 1Fh. We'll discuss "register banks" more in a later chapter. For now it is sufficient to know that

24

they "live" and are part of internal RAM. Bit Memory also lives and is part of internal RAM. We'll talk more about bit memory very shortly, but for now just keep in mind that bit memory actually resides in internal RAM, from addresses 20h through 2Fh. The 80 bytes remaining of Internal RAM, from addresses 30h through 7Fh, may be used by user variables that need to be accessed frequently or at high-speed. This area is also utilized by the microcontroller as a storage area for the operating stack. This fact severely limits the 8051s stack since, as illustrated in the memory map, the area reserved for the stack is only 80 bytes-and usually it is less since this 80 bytes has to be shared between the stack and user variables.

REGISTERS:
Register are used to store information temporarily, while the information could be a byte of data to be processed, or an address pointing to the data to be fetched. The 8 bits of a register are shown from MSB D7 to the LSB D0.With an 8-bit data type, any data larger than 8 bits must be broken into 8-bit chunks before it is processed.

Figure 3.1 -8 BIT REGISTER

Basic Registers:

1. The Accumulator: If you have worked with any other assembly languages you will be familiar
with the concept of an Accumulator register.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 (1byte) value and is the most versatile register the 8051 has due to the shear number of instructions

25

that make use of the accumulator. More than half of the 8051s 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.

2. The "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 auxillary 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.You may think of the "R" registers as very important auxillary, 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, lets 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 ADD MOV MOV ADD

A,R3

;Move A,R4

the ;Add

value

of the

R3

into value

the of

accumulator R4 in R5

R5,A A,R1

;Store ;Move

the the ;Add

resulting value of the

value R1

temporarily into value the of

accumulator R2

A,R2

SUBB A,R5 ;Subtract the value of R5 (which now contains R3 + R4) As you can see, we used R5 to temporarily hold the sum of R3 and R4. Of course, this isnt the most efficient way to calculate (R1+R2) - (R3 +R4) but it does illustrate the use of the "R" registers as a way to store values temporarily.

3. The "B" Register: The "B" register is very similar to the Accumulator in the sense that it may
hold an 8-bit (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

26

may store the other number in "B" and make use of these two instructions. Aside from the MUL and DIV instructions, the "B" register is often used as yet another temporary storage register much like a ninth "R" register.

4. The Data Pointer (DPTR):The Data Pointer (DPTR) is the 8051s only user-accessable 16-bit (2byte) register. The Accumulator, "R" registers, and "B" register are all 1-byte values. 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 the 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 its the only true 16-bit register available. It is often used to store 2-byte values which have nothing to do with memory locations.

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 important to note that PC isnt always incremented by one. Since some instructions require 2 or 3 bytes the PC will be incremented by 2 or 3 in these cases.

The Program Counter is special in that there is no way to directly modify its value. That is to say, you cant do something like PC=2430h. On the other hand, if you execute LJMP 2430h you have effectively accomplished the same thing.

6. The Stack Pointer (SP): The Stack Pointer, like all registers except DPTR and PC, may hold an 8bit (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

27

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.

Register Banks:
The 8051 uses 8 "R" registers which are used in many of its instructions. These "R" registers are numbered from 0 through 7 (R0, R1, R2, R3, R4, R5, R6, and R7). These registers are generally used to assist in manipulating values and moving data from one memory location to another. For example, to add the value of R4 to the Accumulator, we would execute the following instruction: ADD A, R4

Thus if the Accumulator (A) contained the value 6 and R4 contained the value 3, the Accumulator would contain the value 9 after this instruction was executed.However, as the memory map shows, the "R" Register R4 is really part of Internal RAM. Specifically, R4 is address 04h. This can be see in the bright green section of the memory map. Thus the above instruction accomplishes the same thing as the following operation:

ADD A, 04h This instruction adds the value found in Internal RAM address 04h to the value of the Accumulator, leaving the result in the Accumulator. Since R4 is really Internal RAM 04h, the above instruction effectively accomplished the same thing. But watch out! As the memory map shows, the 8051 has four distinct register banks. When the 8051 is first booted up, register bank 0 (addresses 00h through 07h) is used by default. However, your program may instruct the 8051 to use one of the alternate register banks; i.e., register banks 1, 2, or 3. In this case, R4 will no longer be the same as Internal RAM address 04h. For example, if your program instructs the 8051 to use register bank 3, "R" register R4 will now be synonomous with Internal RAM address 1Ch.The concept of register banks adds a great level of flexibility to the 8051, especially when dealing with interrupts (we'll talk about interrupts later). However, always remember that the register banks really reside in the first 32 bytes of Internal RAM.

28

If you only use the first register bank (i.e. bank 0), you may use Internal RAM locations 08h through 1Fh for your own use. But if you plan to use register banks 1, 2, or 3, be very careful about using addresses below 20h as you may end up overwriting the value of your "R" registers!

Bit Memory:
The 8051, being a communications-oriented microcontroller gives the user the ability to access a number of bit variables. These variables may be either 1 or 0. There are 128 bit variables available to the user, numbered 00h through 7Fh. The user may make use of these variables with commands such as SETB and CLR. For example, to set bit number 24 (hex) to 1 you would execute the instruction: SETB 24h It is important to note that Bit Memory is really a part of Internal RAM. In fact, the 128 bit variables occupy the 16 bytes of Internal RAM from 20h through 2Fh. Thus, if you write the value FFh to Internal RAM address 20h you have effectively set bits 00h through 07h. That is to say that: MOV 20h, #0FFh is equivalent to: SETB SETB SETB SETB SETB SETB SETB SETB 07h As illustrated above, bit memory isnt really a new type of memory. Its really just a subset of Internal RAM. But since the 8051 provides special instructions to access these 16 bytes of memory on a bit by bit basis it is useful to think of it as a separate type of memory. However, always keep in mind that it is just a subset of Internal RAM--and that operations performed on Internal RAM can change the values of the bit variables. 00h 01h 02h 03h 04h 05h 06h

If your program does not use bit variables, you may use Internal RAM locations 20h through 2Fh for your own use. But if you plan to use bit variables, be very careful about

29

using addresses from 20h through 2Fh as you may end up overwriting the value of your bits!

Bit variables 00h through 7Fh are for user-defined functions in their programs. However, bit variables 80h and above are actually used to access certain SFRs on a bit-by-bit basis. For example, if output lines P0.0 through P0.7 are all clear (0) and you want to turn on the P0.0 output line you may either execute: MOV P0, #01h or you may execute: SETB 80h

Both these instructions accomplish the same thing. However, using the SETB command will turn on the P0.0 line without effecting the status of any of the other P0 output lines. The MOV command effectively turns off all the other output lines which, in some cases, may not be acceptable.

By default, the 8051 initializes the Stack Pointer (SP) to 07h when the microcontroller is booted. This means that the stack will start at address 08h and expand upwards. If you will be using the alternate register banks (banks 1, 2 or 3) you must initialize the stack pointer to an address above the highest register bank you will be using, otherwise the stack will overwrite your alternate register banks. Similarly, if you will be using bit variables it is usually a good idea to initialize the stack pointer to some value greater than 2Fh to guarantee that your bit variables are protected from the stack.

Special Function Register (SFR) 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 8051s 32 input/output lines. Another SFR allows a program to read or write to the 8051s serial port. Other SFRs allow the user to set the serial baud rate, control and access timers, and configure the 8051s 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

30

Similarly, if you want to write the value "1" to the 8051s 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 ( its 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.

SFRs are used to control the way the 8051 functions. Each SFR has a specific purpose and format which will be discussed later. Not all addresses above 80h are assigned to SFRs. However, this area may NOT be used as additional RAM memory even if a given address has not been assigned to an SFR.

What Are SFRs?

The 8051 is a flexible microcontroller with a relatively large number of modes of operations. Your 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. The following chart provides a graphical presentation of the 8051's SFRs, their names, and their address.

31

Table 3.1- SFRs

As you can see, although the address range of 80h through FFh offer 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.

It is recommended that you not read or write to SFR addresses that have not been assigned to an SFR. Doing so may provoke undefined behavior and may cause your program to be incompatible with other 8051-derivatives that use the given SFR for some other purpose.

SFR Types

32

As mentioned in the chart itself, the SFRs that have a blue background are SFRs related to the I/O ports. The 8051 has four I/O ports of 8 bits, for a total of 32 I/O lines. Whether a given I/O line is high or low and the value read from the line are controlled by the SFRs in green.

The SFRs with yellow backgrounds are SFRs which in some way control the operation or the configuration of some aspect of the 8051. For example, TCON controls the timers, SCON controls the serial port.

The remaining SFRs, with green backgrounds, are "other SFRs." These SFRs can be thought of as auxillary SFRs in the sense that they don't directly configure the 8051 but obviously the 8051 cannot operate without them. For example, once the serial port has been configured usingSCON, the program may read or write to the serial port using the SBUF register.

The SFRs whose names appear in red in the chart above are SFRs that may be accessed via bit operations (i.e., using the SETB and CLR instructions). The other SFRs cannot be accessed using bit operations. As you can see, all SFRs that whose addresses are divisible by 8 can be accessed with bit operations.

SFR Descriptions This section will endeavor to quickly overview each of the standard SFRs found in the above SFR chart map. It is not the intention of this section to fully explain the functionality of each SFR--this information will be covered in separate chapters of the tutorial. This section is to just give you a general idea of what each SFR does.

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.

While the 8051 has four I/O port (P0, P1, P2, and P3), if your hardware uses external RAM or external code memory (i.e., your program is stored in an external ROM or EPROM chip or if you are using external RAM chips) you may not use P0 or P2. This is because the 8051 uses ports P0 and P2 to address the external memory. Thus if you are using external RAM or code memory you may only use ports P1 and P3 for your own use.

33

SP (Stack Pointer, Address 81h): This is the stack pointer of the microcontroller. This SFR indicates where the next value to be taken from the stack will be read from in Internal RAM. If you push a value onto the stack, the value will be written to the address of SP + 1. That is to say, if SP holds the value 07h, a PUSH instruction will push the value onto the stack at address 08h. This SFR is modified by all instructions which modify the stack, such as PUSH, POP, LCALL, RET, RETI, and whenever interrupts are provoked by the microcontroller.

The SP SFR, on startup, is initialized to 07h. This means the stack will start at 08h and start expanding upward in internal RAM. Since alternate register banks 1, 2, and 3 as well as the user bit variables occupy internal RAM from addresses 08h through 2Fh, it is necessary to initialize SP in your program to some other value if you will be using the alternate register banks and/or bit memory. It's not a bad idea to initialize SP to 2Fh as the first instruction of every one of your programs unless you are 100% sure you will not be using the register banks and bit variables.

DPL/DPH (Data Pointer Low/High, Addresses 82h/83h): The SFRs DPL and DPH work together to represent a 16-bit value called the Data Pointer. The data pointer is used in operations regarding external RAM and some instructions involving code memory. Since it is an unsigned two-byte integer value, it can represent values from 0000h to FFFFh (0 through 65,535 decimal).

DPTR is really DPH and DPL taken together as a 16-bit value. In reality, you almost always have to deal with DPTR one byte at a time. For example, to push DPTR onto the stack you must first push DPL and then DPH. You can't simply plush DPTR onto the stack. Additionally, there is an instruction to "increment DPTR." When you execute this instruction, the two bytes are operated upon as a 16-bit value. However, there is no instruction that decrements DPTR. If you wish to decrement the value of DPTR, you must write your own code to do so.

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

34

PCON. Additionally, one of the bits in PCON is used to double the effective baud rate of the 8051's serial port.

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 occured.

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 your program may configure each timer to be a 16-bit timer, an 8-bit auto reload timer, a 13-bit timer, or two separate timers. Additionally, you may configure the timers to only count when an external pin is activated or to count "events" that are indicated on an external pin.

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.

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.

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 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.

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.

35

To use the 8051's on-board serial port, it is generally necessary to initialize the following SFRs: SCON, TCON, and TMOD. This is because SCON controls the serial port. However, in most cases the program will wish to use one of the timers to establish the serial port's baud rate. In this case, it is necessary to configure timer 1 by initializing TCON and TMOD.

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.

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.

While the 8051 has four I/O port (P0, P1, P2, and P3), if your hardware uses external RAM or external code memory (i.e., your program is stored in an external ROM or EPROM chip or if you are using external RAM chips) you may not use P0 or P2. This is because the 8051 uses ports P0 and P2 to address the external memory. Thus if you are using external RAM or code memory you may only use ports P1 and P3 for your own use.

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.

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.

36

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. However, if a serial interrupt is executing no other interrupt will be able to interrupt the serial interrupt routine since the serial interrupt routine has the highest priority.

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.

If you write an interrupt handler routine, it is a very good idea to always save the PSW SFR on the stack and restore it when your interrupt is complete. Many 8051 instructions modify the bits of PSW. If your interrupt routine does not guarantee that PSW is the same upon exit as it was upon entry, your program is bound to behave rather radically and unpredictably--and it will be tricky to debug since the behavior will tend not to make any sense.

ACC (Accumulator, Addresses E0h, Bit-Addressable): The Accumulator is one of the most-used SFRs on the 8051 since it is involved in so many instructions. The Accumulator resides as an SFR at E0h, which means the instruction MOV A, #20h is really the same as MOV E0h, #20h. However, it is a good idea to use the first method since it only requires two bytes whereas the second option requires three bytes.

B (B Register, Addresses F0h, Bit-Addressable): The "B" register is used in two instructions: the multiply and divide operations. The B register is also commonly used by programmers as an auxiliary register to temporarily store values.

Other SFRs

37

The chart above is a summary of all the SFRs that exist in a standard 8051. All derivative microcontrollers of the 8051 must support these basic SFRs in order to maintain compatability with the underlying MSCS51 standard.

A common practice when semiconductor firms wish to develop a new 8051 derivative is to add additional SFRs to support new functions that exist in the new chip. For example, the Dallas Semiconductor DS80C320 is upwards compatible with the 8051. This means that any program that runs on a standard 8051 should run without modification on the DS80C320. This means that all the SFRs defined above also apply to the Dallas component.

However, since the DS80C320 provides many new features that the standard 8051 does not, there must be some way to control and configure these new features. This is accomplished by adding additional SFRs to those listed here. For example, since the DS80C320 supports two serial ports (as opposed to just one on the 8051), the SFRs SBUF2 and SCON2 have been added. In addition to all the SFRs listed above, the DS80C320 also recognizes these two new SFRs as valid and uses their values to determine the mode of operation of the secondary serial port. Obviously, these new SFRs have been assigned to SFR addresses that were unused in the original 8051. In this manner, new 8051 derivative chips may be developed which will run existing 8051 programs.

If you write a program that utilizes new SFRs that are specific to a given derivative chip and not included in the above SFR list, your program will not run properly on a standard 8051 where that SFR does not exist. Thus, only use non-standard SFRs if you are sure that your program wil only have to run on that specific microcontroller. Likewise, if you write code that uses non-standard SFRs and subsequently share it with a third-party, be sure to let that party know that your code is using non-standard SFRs to save them the headache of realizing that due to strange behavior at run-time.

7. The Accumulator: If you have worked with any other assembly languages you will be familiar
with the concept of an Accumulator register.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 (1byte) value and is the most versatile register the 8051 has due to the shear number of instructions

38

that make use of the accumulator. More than half of the 8051s 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.

8. The "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 auxillary 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.You may think of the "R" registers as very important auxillary, 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, lets 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 ADD MOV MOV ADD A,R3 ;Move A,R4 R5,A A,R1 ;Store ;Move A,R2 the ;Add the the ;Add value of the resulting value of the value R1 R3 into value temporarily into value the of the of in accumulator R4 R5

accumulator R2

SUBB A,R5 ;Subtract the value of R5 (which now contains R3 + R4) As you can see, we used R5 to temporarily hold the sum of R3 and R4. Of course, this isnt the most efficient way to calculate (R1+R2) - (R3 +R4) but it does illustrate the use of the "R" registers as a way to store values temporarily.

9. The "B" Register: The "B" register is very similar to the Accumulator in the sense that it may
hold an 8-bit (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

39

and DIV instructions, the "B" register is often used as yet another temporary storage register much like a ninth "R" register.

10.

The Data Pointer (DPTR): The Data Pointer (DPTR) is the 8051s only user-accessable

16-bit (2-byte) register. The Accumulator, "R" registers, and "B" register are all 1-byte values. 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 the 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 its the only true 16-bit register available. It is often used to store 2-byte values which have nothing to do with memory locations.

11.

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 important to note that PC isnt always incremented by one. Since some instructions require 2 or 3 bytes the PC will be incremented by 2 or 3 in these cases.

The Program Counter is special in that there is no way to directly modify its value. That is to say, you cannot do something like PC=2430h. On the other hand, if you execute LJMP 2430h you have effectively accomplished the same thing.

12.

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

40

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.

41

CHAPTER 4

8051- I/0 PORTS PROGRAMMING

I/O PORTS:
In the 8051 there are a total of four ports for I/O operations. Examining pin out confirmation shown below, note that of the 40 pins , a total of 32 pins are set aside for the four ports P0, P1, P2 and P3, where each port takes 8 pins. The rest of the pins are designated as Vcc, GND, XTAL1, XTAL2, RST, EA, ALE/PROG and PSEN.

I/O PORT PINS AND THEIR FUNCTIONS:


The four ports P0, P1, P2 & P3 each use 8 pins, making them 8-bits ports. All the ports upon RESET are configured as inputs, ready to be used as input ports. When the first 0 is written to a port, it becomes an output. To reconfigure it as an input, a 1 must be sent to the port. To use any of these ports as a input ports, it must be programmed.

Port 0:
Port 0 occupies a total of 8 pins (pins 32-39).It can be used for input or output. To use the pins of port 0 as both input & output ports, each pin must be connected externally to a 10k-ohm pull-up resistor. This is due to the fact that P0 is an open drain, unlike P1, P2 and P3.'Open drain' is term used for MOS chips in the same way that 'open collector' is 14 used for TTL chips. In any system using the 8051/52 chip, we normally connect P0 to pull-up resistor. See Figure 4-2.in this way we can have advantage of both input and output. For example, following code will continuously send out to port 0 the alternative values of 55H and AAH.

BACK: MOV A, #55H MOV P0, A ACALL DELAY

42

MOV A, #AAH MOV P0, A ACALL DELAY SJMP BACK

It must be noted that complementing 55H (01010101) turns it into AAH (10101010).By sending 55H and AAH to a given port continuously, we toggle all bits of that port.

Figure 4.1-8051 PIN DESCRIPTION

Port 0 as Input: 43

With resistors connected to a port 0, in order to make it an input, the port must be programmed by writing 1 to all the bits. In the following code, the port 0 is configured first as an input port by writing 1s to it, and then data is received from that port and sent to P1. ; Get a byte from P0 and sent it to P1 Mov A, #0FFH ; 0A = FF hex MOV P0, A ; make P0 an input port ; by writing all 1s to it BACK: MOV A, P0 ; get data from P0 MOV P1,A ; send it to port 1 SJMP BACK ; keep doing it.

Dual Role of Port 0:


As shown in Figure 4-1, port 0 is also designated as AD0-AD7, allowing it to be used for both address and data. When connecting an 8051/31 to an external memory, port 0 provides both address and data. The 8051 multiplexes addresses and data through port 0 to save pins.

Figure 4.2- PORT 0 WITH PULL- UP RESISTORS

Port 2:
Port 2 occupies a total of 8 pins (pins 21 through 28).it can be used as input or output. Just like P1, port 2 is configured as an input port. The following code will send out continuously to port 2 and the alternating values 55H and AAH. That is, all the bits of P2 toggle continuously.

44

MOV A, #55H BACK: MOV P2, A ACALL DELAY CPL A ; complement reg. A SJMP BACK

Port 2 as input:
To make port 2 an input, it must programmed as such by writing 1 to all its bits. In the following code, port 2 is configured first as an input port by writing 1s to it. Then data is received from that port and is sent to P1 continuously.

MOV A, #OFH ; A=FF hex MOV P2,A ;make P2 an input port by ; writing all 1s to it. BACK: MOV A,P2 ; get data from P2 MOV P1,A ;send it to port 1 SJMP BACK ; keep doing that

Dual Role of Port 2:


In many systems based on the 8051, P2 is used as simple I/O. However in 8031- based systems, port 2 must be used along with P0 to provide the 16-bit address for external memory. As shown in Figure 4-1, port 2 is also designated as path for 16 bits; of address. While P0 provides the lower 8 bits via A0-A7, it is the job of P2 to provide bits A8 to A-15 of the address. When the 8051/31 is capable of accessing 64 K bytes of external memory, it needs a path for 16 bit of address. While P0 provides the lower 8 bits via A0 to A7, it is job of P2 is used for the upper 8 bits of the 16 bits address, and it cannot be used for I/O. We conclude that in systems based on 8751, 89C51, or DS 589C4x0microcontrollers, we have three ports P0, P1 and P2, for I/O operations. This should be enough for microcontroller applications. That leaves P3 for interrupts as well other signals.

45

Port 3:
Port 3 occupies a total of 8 pins, pin 10 to 17. it can be used as input or output. P3 does not need any pull up registers, just as P1.Port 3 is configured as input port upon reset; this is not the way it is most commonly used. Port 3 has additional function of providing some extremely important functions such as interrupts.

Figure 4.3- PORT 3 ALTERNATE FUNCTIONS

46

CHAPTER 5 8051 TIMERS AND COUNTERS

The 8051 has two timers: Timer 0 and Timer 1. They can be used either as timers or as event counters.

Basic registers of the timer:


Both Timer 0 and Timer 1 are 16 bits wide. Since the 8051 has an 8-bit architecture, each 16-bit timer is accessed as two separate registers of low byte and high byte.

TH0 (8 bit)
D15 D14 D13 D12 D11 D10 D9 D8 D7

TL0 (8 bit)
D6 D5 D4 D3 D2 D1 D0

TH1 (8 bit)
D15 D14 D13 D12 D11 D10 D9 D8 D7

TL1 (8 bit)
D6 D5 D4 D3 D2 D1 D0

TMOD (timer mode) register:


Both timers 0 and 1 use the same register, called TMOD, to set the various timer operation modes. TMOD is an 8-bit register in which the lower 4 bits are aside for Timer 0 and the upper 4 bits for Timer 1.

Timer 1
GATE C/T M1 M0 GATE

Timer 0
C/T M1 M0

TMOD register 47

GATE decides whether hardware (INTx pin) or software (TRx) approach is used for starting or stopping the timer. For hardware approach, gate is set. C/T when set, Timer is used as counter, otherwise as timer M1, M0 these are used to select timer mode.

Mode 0 1 2 3

M1 0 0 1 1

M0 0 1 0 1 13-bit timer mode 16-bit timer mode 8-bit auto-reload Split timer mode

Description

Table 5.1 TIMERS

Hardware approach:
Timer (used as timer) runs only when there is high signal on INT0 (for timer 0) or INT1 ( for timer 1) pins. These are available at pin 2 and pin 3 of Port 3 respectively. Timer (used as counter) counts only when there is high signal on T0 (for timer 0) or T1 ( for timer 1) pins. These are available at pin 4 and pin 5 of Port 3 respectively.

Software approach:

48

For software triggering of timer, TCON special function register is used. TCON is an 8-bit, bitaddressable register.

Timer/Counter
TF1 TR1 TF0 TR0 IE1

Timer Interrupts
IT1 IE0 IT0

TCON register

TF timer overflow flag. If timer is being used in mode 0 or 1, TF is set when upper limit is reached. In order to repeat the process, the registers TH and TL must be reloaded and TF must be reset to 0. TR to start the timer, this bit must be set. Similarly, to stop the timer, this bit must be cleared.

49

CHAPTER 6 SERIAL COMMUNICATION

BASIC OF SERIAL COMMUNICATION:


Computers transfer data in two ways:

1. Parallel: Often 8 or more lines (wire conductors) are used to transfer data to a device that is only
a few feet away.

2. Serial: To transfer to a device located many meters away, the serial method is used.
The data is sent one bit at a time.

Figure 6.1-SERIAL VERSUS PARALLEL DATA TRANSFER

At the transmitting end, the byte of data must be converted to serial bits using parallel-in-serial-out shift register. At the receiving end, there is a serial in-parallel-out shift register to receive the serial data and pack them into byte. When the distance is short, the digital signal can be transferred as it is on a simple wire and requires no modulation. If data is to be transferred on the telephone line, it must be converted

50

from 0s and 1s to audio tones. This conversion is performed by a device called a modem, Modulator/demodulator.

TYPES OF SERIAL COMMUNICATION:

Serial data communication uses two methods. 1. 2. Synchronous method transfers a block of data at a time. Asynchronous method transfers a single byte at a time.

It is possible to write software to use either of these methods, but the programs can be tedious and long. There are special IC chips made by many manufacturers for serial communications knows as UART (universal asynchronous Receiver transmitter) and USART (universal synchronous-asynchronous Receiver-transmitter).

HALF AND FULL DUPLEX TRANSMISSION:


If data can be transmitted and received, it is a duplex transmission. If data transmitted one way a time, it is referred to as half duplex. If data can go both ways at a time, it is full Duplex. This is in contrast to simplex transmission.

51

Figure 6.2- SIMPLE, HALF AND FULL DUPLEX

The data is coming in at the receiving end of the data line in the serial data transfer is all 0s and 1s; it is difficult to make sense of the data unless the sender and receiver agree on a set of rules, a protocol, on How the data is packed How many bits constitute a character When the data begins and ends

ASYNCHRONOUS SERIAL COMMUNICATION:


Asynchronous serial data communication is widely used for character-oriented transmissions. Each character is placed in between start and stop bits, this is called framing. Block-oriented data transfers use the synchronous method. The start bit is always one bit, but the stop bit can be one or two bits. The start bit is always a 0 (low) and the stop bit(s) is 1 (high).

52

Figure 6.3- FRAMING ASCII "A" (41H)

Due to the extended ASCII characters, 8-bit ASCII data is common. In older systems, ASCII characters were 7-bit. In modern PCs the use of one stop bit is standard. In older systems, due to the slowness of the receiving mechanical device, two stop bits were used to give the device sufficient time to organize itself before transmission of the next byte. Assuming that we are transferring a text file of ASCII characters using 1 stop bit, we have a total of 10 bits for each character. This gives 25% overhead, i.e. each 8-bit character with an extra 2 bits. In some systems in order to maintain data integrity, the parity bit of the character byte is included in the data frame. UART chips allow programming of the parity bit for odd-, even-, and noparity options.

BAUD RATE:
The rate of data transfer in serial data communication is stated in bps (bits per second). Another widely used terminology for bps is baud rate. It is modem terminology and is defined as the number of signal changes per second. In modems, there are occasions when a single change of signal transfers several bits of data.

53

As far as the conductor wire is concerned, the baud rate and bps are the same, and we use the terms interchangeably. The data transfer rate of given computer system depends on communication ports incorporated into that system. IBM PC/XT could transfer data at the rate of 100 to 9600 bps. Pentium-based PCs transfer data at rates as high as 56K bps .In asynchronous serial data communication, the baud rate is limited to 100K bps. To allow data transfer between the PC and an 8051 system without any error, we must make sure that the baud rate of 8051 system matches the baud rate of the PCs COM port. Hyper terminal function supports baud rates much higher than listed below.

Table 6.1-PC BAUD RATES

SBUF (SERIAL BUFFER) REGISTER:


SBUF is an 8-bit register used solely for serial communication. For a byte data to be transferred via the TxD line, it must be placed in the SBUF register. The moment a byte is written into SBUF, it is framed with the start and stop bits and transferred serially via the TxD line. SBUF holds the byte of data when it is received by 8051 RxD line. When the bits are received serially via RxD , the 8051 de frames it by eliminating the stop and start bits, making a byte out of the data received, and then placing it in SBUF.

SCON (SERIAL CONTROL) REGISTER:


SCON is an 8-bit register used to program the start bit, stop bit, and data bits of data framing, among other things.

54

Table 6.2 SCON REGISTER

1. SM0, SM1- They determine the framing of data by specifying the number of bits per character,
and the start and stop bits.

Table 6.3-MODE SELECTION BITS

2. SM2 - This enables the multiprocessing capability of the 8051. 3. REN (receive enable) - It is a bit-addressable register. When it is high, it allows 8051 to
receive data on RxD pin, If low, the receiver is disable.

4. TI (transmit interrupt) When 8051 finishes the transfer of 8-bit character It raises TI flag
to indicate that it is ready the transfer another byte TI bit is raised at the beginning of the stop bit.

5. RI (receive interrupt) - When 8051 receives data serially via RxD, it gets rid of the start and
stop bits and places the byte in SBUF register. It raises the RI flag bit to indicate that a byte has been received and should be picked up before it is lost . RI is raised halfway through the stop bit.

55

PROGRAMMING THE 8051 TO TRANSFER DATA SERIALLY:


In programming the 8051 to transfer character bytes serially, the following steps must be taken. 1. TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2 (8-bit auto-reload) to set baud rate. 2. 3. The TH1 is loaded with one of the values to set baud rate for serial data transfer. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-bit data is framed with start and stop bits. 4. 5. 6. 7. TR1 is set to 1 to start timer 1. TI is cleared by CLR TI instruction. The character byte to be transferred serially is written into SBUF register. The TI flag bit is monitored with the use of instruction JNB TI, xx to see if the character has been transferred completely. 8. To transfer the next byte, go to step 5.

PROGRAMMING THE 8051 TO RECEIVE DATA SERIALLY:


In the programming of the 8051 to receive character bytes serially, the following steps must be taken. 1. TMOD register is loaded with the value 20H, indicating the use of timer 1 in mode 2 (8-bit auto reload) to set baud rate. 2. 3. TH1 is loaded to set baud rate. The SCON register is loaded with the value 50H, indicating serial mode 1, where an 8-bit data is framed with start and stop bits. 4. 5. 6. TR1 is set to 1 to start timer 1. RI is cleared by CLR RI instruction. The RI flag bit is monitored with the use of instruction JNB RI, xx to see if an entire character has been received yet. 7. 8. When RI is raised, SBUF has the byte , its contents are moved into a safe place. To receive the next character, go to step.

56

DOUBLING THE BAUD RATES:


There are two ways to increase the baud rate of data transfer in the 8051.

To use a higher frequency crystal. To change a bit in the PCON register.

PCON register is an 8-bit register. Of the 8-bits, some are unused, and some are used for the power control capability of the 8051. The bit that is used for the serial communication is D7, the SMOD (serial mode) bit.When the 8051 is powered up, D7 (SMOD bit) of the PCON register. We can set it to high by software and thereby double the baud rate.

Table 6.4-PCON REGISTER AND INSTRUCTOIN SET TO SET HIGH D7 OF PCON

DS89C4x0 and DS80C320:


Many new generations of 8051 microcontroller come with two serial ports, like DS89C4x0 and DS80C320. The second serial port of DS89C4x0 uses pins P1.2 and P1.3 for the Rx and Tx lines. The second serial port uses some reserved SFR addresses for the SCON and SBUF.There is no universal agreement among the makers as to which addresses should be used. The SFR addresses of C0H and C1H are set aside for SBUF and SCON of DS89C4x0. The DS89C4x0 technical documentation refers to these registers as SCON1 and SBUF1.The first ones are designated as SCON0 and SBUF0.

57

Figure 6.4- DS89C4X0 PIN DIAGRAM

Upon reset, DS89c4x0 uses Timer 1 for setting baud rate of both serial ports, While each serial port has its own SCON and SBUF registers, both ports can use Timer1 for setting the baud rate. SBUF and SCON refer to the SFR registers of the first serial port, Since the older 8051 assemblers do not support this new second serial port, we need to define them in program .To avoid confusion, in DS89C4x0 programs we use SCON0 and SBUF0 for the first and SCON1 and SBUF1for the second serial ports.

58

CHAPTER 7 INTERRUPTS IN 8051

INTERRUPTS VS. POLLING:


59

A single microcontroller can serve several devices. There are two ways to do that: INTERRUPT OR POLLING. In the interrupt method whenever any device needs its service, the device notifies the microcontroller by sending it an interrupt signal. Upon receiving an interrupt signal, the microcontroller interrupts whatever it is doing and serves the device.

The program which is associated with the interrupt is called the interrupt service routine (ISR) or
interrupt handler.

i.e. An INTERRUPT is an external or internal event that interrupts the microcontroller to inform it that a device needs its service. Or in the polling method The microcontroller continuously monitors the status of a given device. When the conditions met, it performs the service. After that, it moves on to monitor the next device until everyone is serviced.

ie. Polling can monitor the status of several devices and serve each of them as certain conditions are met. The advantage of interrupts is that the microcontroller can serve many devices (not all at the same time).Each devices can get the attention of the microcontroller based on the assigned priority. For the polling method, it is not possible to assign priority since it checks all devices in a round-robin fashion. The microcontroller can also ignore (mask) a device request for service. This is not possible for the polling method. The most important reason that the interrupt is preferable is that the polling method wastes much of the microcontrollers time by polling devices that do not need service. So in order to avoid tying down the microcontroller, interrupts are used. For example. we use the instruction JNB TF, target and waited until the timer rolled over, and while we were waiting we could not do anything else.

INTERRUPT SERVICE ROUTINE:

60

For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler. When an interrupt is invoked, the microcontroller runs the interrupt service routine .For every interrupt, there is a fixed location in memory that holds the address of its ISR. The group of memory locations set aside to hold the addresses of ISRs is called interrupt vector table.

Table 7.1 Interrupt Vector Table

STEP IN EXECUTING AN INTERRUPT:


Upon activation of an interrupt, the microcontroller goes through the following steps. 1. It finishes the instruction it is executing and saves the address of the next instruction (PC) on the stack. 2. It also saves the current status of all the interrupts internally (ie. not on the stack). 3. It jumps to a fixed location in memory, called the interrupt vector table, that holds the address of the ISR. 4. The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it. It starts to execute the interrupt service subroutine until it reaches the last instruction of the subroutine which is RETI (return from interrupt).

61

5. Upon executing the RETI instruction, the microcontroller returns to the place where it was interrupted first, it gets the program counter (PC) address from the stack by popping the top two bytes of the stack into the PC Then it starts to execute from that address.

SIX INTERRUPTS IN THE 8051:


In reality, only five interrupts are available to the user in the 8051, but many manufacturers data sheets state that there are six interrupts since they include reset. The six interrupts in thr 8051 are allocated as follows. 1. Reset power-up reset. 2. Two interrupts are set aside for the timers. one for timer 0 and one for timer 1. 3. Two interrupts are set aside for hardware external interrupts. P3.2 and P3.3 are for the external hardware interrupts INT0 (or EX1), and INT1 (or EX2). 4. Serial communication has a single interrupt that belongs to both receive and transfer.

ENABLING AND DISABLING AN INTERRUPT:


Upon reset, all interrupts are disabled (masked), meaning that none will be responded to the microcontroller if they are activated. The interrupt must be enabled by software in order for the microcontroller to respond to them. There is a register called IE ( interrupts enabled) that is responsible for enabling(unmasking) and disabling(masking) the interrupts. Figure-2 shows the IE register. Note that IE is a bit-addressable register. From figure -2 notice that bit D7 in the IE register is called EA(enable all).This must be set to 1 in the order for the rest of the register to take effect.D6 is unused.D5 is used by the 8052.D4 bit is for the serial interrupts, and so on.

STEPS IN ENABLING AN INTERRUPT:


To enable an interrupt, we take the following steps:

62

1) Bit D7 of the IE register (EA) must be set to high to allow the rest of register to take effect. 2) If EA = 1, interrupts are enabled and will be responded to if their corresponding bits in IE are high. 3) If EA = 0, no interrupt will be responded to, even if the associated bit in the IE register is high.

63

64

Table 7.2 INTERRUPT REGISTER

65

CHAPTER 8 L.E.D. , 7 SEGMENT & L.C.D.


L.E.D.:A light-emitting diode (LED) is a semiconductor light source. LEDs are used as indicator lamps in many devices, and are increasingly used for lighting. When a light-emitting diode is forward biased (switched on), electrons are able to recombine with holes within the device, releasing energy in the form of photons. This effect is called electroluminescence and the color of the light (corresponding to the energy of the photon) is determined by the energy gap of the semiconductor.. LEDs present many advantages over incandescent light sources including lower energy consumption, longer lifetime, improved robustness, smaller size, faster switching, and greater durability and reliability. Light-emitting diodes are used in applications as diverse as automotive lighting (particularly indicators) and in traffic signals. The compact size of LEDs has allowed new text and video displays and sensors to be developed, while their high switching rates are useful in advanced communications technology. Infrared LEDs are also used in the remote control units of many commercial products including televisions, DVD players, and other domestic appliances.

WORKING
Like a normal diode, the LED consists of a chip of semiconducting material doped with impurities to create a p-n junction. As in other diodes, current flows easily from the p-side, or anode, to the n-side, or cathode, but not in the reverse direction. Charge-carrierselectrons and holesflow into the junction from electrodes with different voltages. When an electron meets a hole, it falls into a lower energy level, and releases energy in the form of a photon. The wavelength of the light emitted, and therefore its color, depends on the band gap energy of the materials forming the p-n junction. In silicon or germanium diodes, the electrons and holes recombine by a non-radiative transition which produces no optical emission, because these are indirect band gap materialsLED development began with infrared and red devices made with gallium arsenide. Advances in materials science have made possible the production of devices with ever-shorter wavelengths, producing light in a variety of colors.

66

FIG. 8.1- STRUCTURE OF L.E.D. L.E.D.s can also be controlled by the use of a microcontroller . The positive side of the L.E.D. is connected to a pin of a microcontroller and the negative side is connected to ground. When a higher (1) signal is given to that pin, the L.E.D. gets 5 V , and it gets forward biased so it glows. The reverse happens when the negative end is coonected to microcontroller and positive end to Vcc. A lower (0) signal would then glow the L.E.D. Usually L.E.D.s are used in clusters to form a certain pattern . This may be a character , a logo or a symbol which may be stationary , moving flashing etc. This is done by programming the microcontroller to glow the L.E.D.s in a certain predetermined manner. Some of these are the cluster of L.E.D.s used at traffic signals to display the time remaining, those used by shopkeepers outside their shops displaying offers or their item names. One such cluster is a seven segment.It can be used to display any number from 0 to F. When more than one of these are used they can display bigger numbers.

7 SEGMENT
A seven segment display, as its name indicates, is composed of seven elements. Individually on or off, they can be combined to produce simplified representations of the arabic numerals. Often the seven segments are arranged in an oblique (slanted) arrangement, which aids readability. The seven segments are arranged as a rectangle of two vertical segments on each side with one horizontal segment on the top, middle, and bottom. Additionally, the seventh segment bisects the rectangle horizontally. There are also fourteensegment displays and sixteen-segment displays (for full alphanumerics); however, these have mostly been replaced by dot-matrix displays. Seven-segment displays may use an array of light-emitting diodes (LEDs), or other light-generating or controlling techniques such as cold cathode gas discharge, vacuum fluorescent, incandescent filaments, and others. In a simple LED package, typically all of the cathodes (negative terminals) or all of the anodes (positive terminals) of the segment LEDs are connected together and brought

67

out to a common pin; this is referred to as a "common cathode" or "common anode" device. Hence a 7 segment plus decimal point package will only require nine pins (though commercial products typically contain more pins, and/or spaces where pins would go, in order to match industry standard pinouts). Multiple-digit LED displays as used in pocket calculators and similar devices used multiplexed displays to reduce the number of IC pins required to control the display. For example, all the anodes of the A segments of each digit position would be connected together and to a driver pin, while the cathodes of all segments for each digit would be connected. To operate any particular segment of any digit, the controlling integrated circuit would turn on the cathode driver for the selected digit, and the anode drivers for the desired segments; then after a short blanking interval the next digit would be selected and new segments lit, in a sequential fashion. In this manner an eight digit display with seven segments and a decimal point would require only 8 cathode drivers and 8 anode drivers, instead of sixty-four drivers and IC pins. Often in pocket calculators the digit drive lines would be used to scan the keyboard as well, providing further savings; however, pressing multiple keys at once would produce odd results on the multiplexed display.

Figure 8.2- 7 SEGMENT

A single byte can encode the full state of a 7-segment-display

h 1 1 1 1 1 1 1 1 1 1

g 0 0 1 1 1 1 1 0 1 1

f 1 0 0 0 1 1 1 0 1 1

e 1 0 1 0 1 0 1 0 1 0

d 1 0 1 1 0 1 1 0 1 0

c 1 1 0 1 0 1 1 1 1 1

b 1 1 1 1 1 0 0 1 1 1

a 1 0 1 1 0 1 0 1 1 1

Number 0 1 2 3 4 5 6 7 8 9

Input 0xBF 0x86 0xDB 0xCF 0xE6 0xED 0xFC 0x87 0xFF 0xE7

Table 8.1 INPUT COMMANDS FOR 7 SEGMENT

68

To display numbers greater than 10, we use more than one 7 segments placing them side by side. Though they can be commanded individually but that requires a large no. of pins. For eg. For displaying a no. of 4 digits, we would require 32 pins, 8 for each. An intelligent way of reducing the number of pins is to connect their common anode or cathode to microcontroller and giving them command at the same time from the same pins. Whichever is getting ground at its common cathode would glow and all others would be off. Lets just discuss a program to display numbers from 0000 to 1000. To do that we send the signal 0xbf to all of them which have their data inputs common and we send 0 only to the 1 st 7 segment rest all are 1. So this would glow. Then in a very short time we send 0 to the 2 nd 7 segment and rest all 1. Now the second one glows. Same we do for the 3rd and 4th 7 segment. Now the important thing is that this is happening very fast . Thus we would see all of them glowing together . Now we required only 8 + 4 pins i.e. 12 pins . So we have saved a number of pins.To display the number 0001 we send 0x86 to the data pins and 0 to the first 7 segment, then we send 0xbf to the data pins and 0 to the 2nd 7 segment .We do the same for the 3rd and 4th 7 segment. We observe 0001 in the four 7 segments. In the same way numbers from 0002 to 1000 are written A program showing the code for this is written:Void main() { A[10]={0xBF,0x86, 0xDB,0xCF,0xE6,0xED,0xFC,0x87,0xFF,0xE7} For(k=0 to 9) { For(l=0 to 9) { For(m=0 to 9) { For(n=0 to 9) { For(o=0 to 1000) { P[0]=0x01; P[2]=A[n]; P[0]=0x02; P[2]=A[m]; P[0]=0x04; P[2]=A[l]; P[0]=0x08; P[2]=A[k]; }}}}}}

L.C.D ( Liquid Crystal Display):69

A liquid crystal display (LCD) is a thin, flat electronic visual display that uses the light modulating properties of liquid crystals (LCs). When a large number of pixels are needed in a display, it is not technically possible to drive each directly since then each pixel would require independent electrodes. Instead, the display is multiplexed. In a multiplexed display, electrodes on one side of the display are grouped and wired together (typically in columns), and each group gets its own voltage source. On the other side, the electrodes are also grouped (typically in rows), with each group getting a voltage sink. The groups are designed so each pixel has a unique, unshared combination of source and sink. The electronics, or the software driving the electronics then turns on sinks in sequence, and drives sources for the pixels of each sink.

Figure 8.3- PIN DIAGRAM OF LCD

70

Table 8.2 PIN DESCRIPTION AF AN LCD

LCD PIN DESCRIPTION:Vcc ,Vee and Ground


Pin no. 1 provides ground while pin no. 2 provides Vcc i.e. +5V . Vee is used for controlling LCD contrast.

RS,Register Select
There are two very important registers inside LCD. The RS pin is used for their selection . If RS=0, the instruction command code register is selected, allowing the user to send a command such as clear display ,cursor at home , etc. If RS= 1 , the data register is selected, allowing the user to send data to be displayed on the LCD.

R/W , read/write
R/W input allows the user to write information from it. R/W=1 when reading , R/W=0 when writing.

E ,enable

71

The enable pin is used by the LCD to latch information presented to its data pins. When data is supplied to data pins, a high to low pulse must be applied to this pin in order for the LCD to latch in the data present in the data pins. This pulse must be a minimum of 450 ns.

D0 - D7
The 8 bit data pins, D0 D7 , are used to send information to the LCD or read the contents of the LCDs internal registers. To display letters and numbers , we send ASCII codes for the letters A-Z ,a-z and numbers 0-9 to these pins while making RS=1. There are also instruction command codes that can be sent to the LCD to clear the display or force the cursor to the home position or blink the cursor. To send any of the commands to the LCD , make pin RS = 0 .For data, make RS = 1. Then send a high to low pulse to the E pin to enable the internal latch of the LCD. Various command codes are given in the following table.

72

LCD COMMAND CODES:

73

74

Table 8.5 LCD COMMAND CODES

Program to display characters RK in the LCD :void cmddisplay()\ { RS=0; E=1; E=0; } Void datadisplay() { RS=1; E=1; E=0; } Void delay() { For(i=0;i<=100;i++); }

75

Void main() { While(1) { P2=0x38; Cmddisplay(); Delay(); P2=0x0E; Cmddisplay(); Delay(); P2=0x06; Cmddisplay(); Delay(); P2=0x01; Cmddisplay(); Delay(); P2=0x80; Cmddisplay(); Delay(); P2=A; Datadisplay; Delay(); P2=T; Datadisplay(); Delay(); }}

// to specify the function set // for display on and cursor on // for cursor in increment position and shift is invisible // to clear display

76

CHAPTER 9 ADC INTERFACING

ADC DEVICES:
Digital computers use binary (discrete) values, but in the physical world everything is analog. Temperature, pressure (wind or liquid, humidity) and velocity are the few examples of physical quantities that we deal with everyday.

A physical quantity is converted to electrical (voltage, current) signals using a device called TRANSDUCER. Also known as to be SENSORS.

We need analog-to-digital converter to translate the analog signal to digital numbers so that the microcontrollers can read and process them

An ADC has an n bit- resolution where n can be 8, 10, 12, 16 or even 24 bits. The higher resolution ADC provides a smaller step size, where step size is the smallest change that can be discerned by an ADC.

CONVERSION TIME is defined as the time it takes the ADC to convert the analog input to a digital (binary).

ADC0804 CHIP
The ADC0804 is an 8-bit parallel ADC in the family of the ADC0800 series from national semiconductor .It is also available from many other manufacturers. It works with +5V volts and has a resolution of 8 bits. In the ADC0804, the conversion time varies depending on the clocking signals applied to the CLK IN pin, but it cannot be faster than 110 micro-second. The following is the ADC0804 pin description:

CS (CHIP SELECT) - Chip select is an active low input used to activate the ADC0804 chip. To access the ADC0804, this pin must be low.

77

RD (READ) - This is an input signal and is active low. The ADC converts the analog input to its binary equivalent and holds it in an internal register. RD is used to get converted data out of the ADC0804 chip. When CS=0, if a high-to-low pulse is applied to the RD pin, the 8-bit digital output shows up at the D0-D7 data pins. This RD pins is also referred to as output enable (OE).

CLK IN CLK R- CLK IN is an input pin connected to an external clock is used for timing.

INTR (interrupt; a better might be end of conversion)-This is an output pin and is active low. It is normally high pin and when the conversion is finished, it goes to low to signal the CPU that the converted data is already to be picked up. After INTR goes low, we makes CS= 0 and send a high-to low pulse to the RD pin to get the data out of the ADC0804 chip.

V.IN(+) AND V.IN (-)- These are the differential analog inputs where: V.IN = V. IN (+) - V.IN (-) Often the V.IN (-) pin is connected to ground and the V.IN (+) pin is used as the analog to be converted to be digital.

Vcc This is the +5volt power supply. It is also used as a reference voltage when Vref / 2input(pin9) is open (not connected).

Vref/2- Pin 9 is an input voltage for the reference voltage. If this is open, the analog input voltage for the AD0804 is in the range of 0 to 5 volts. However, there are many applications where the analog input applied to Vin needs to be other than the 0 to +5V range.

D0-D7 D0-D7(D7 is the MSB ) are the digital output pins since ADC0804 ia a parallel ADC chip .These are tri-state buffered and the converted data only when CS=0 AND RD is forced low.

78

CHAPTER 10 RELAY, BUZZER AND D.C. MOTOR

RELAY:Relay is a device used to control a high voltage device with the microcontroller. Normal household appliances run on 220V. So they cannot be connected directly to the microcontroller. A relay has its input on the side of the microcontroller. On its output it has 2 modes, normally open and normally closed. When given 5 V on input it shorts the normally closed mode , otherwise normally open mode is short. This helps the microcontroller to control devices such as fan , lights etc. Also there is no contact between the output and input so the microcontroller is totally safe. Relays are electromechanical devices. A magnetic field is produced when a voltage is provided to the input which is 5V . This voltage attracts the armature and the relay is in normally closed mode. A springing action brings it back to normally open mode when power supply is removed.

BUZZER:Buzzer is a device used to produce sound. It is attached directly to the microcontroller. One pin of it is grounded and the other pin is connected to the microcontroller. Thus when 5V is given it produces a sound. The reverse can also be done. One pin of it can be given Vcc directly and the other to controller. On giving gorund i.e. 0 , it produces sound. It is used mainly in washing machines, microwave ovens etc.

D.C. MOTOR:-

79

An interfacing method for turning on and off a DC motor via a microcontroller is to directly connect it through a transistor. The transistor would be switched ON by giving 5V from the controller. However, the above circuit will only work for a 5 V motor. If the supply voltage is changed (for example, if the supply is changed to 12 V to run a 12 V motor) then the motor will be on all the time because 5 V applied to the base of the p-n-p transistor is not enough to turn it off. To run the motor with higher voltage it is connected via a H bridge I.C. which is L293D. L293D is a dual H-Bridge motor driver, with only one IC we can interface two DC motors which can be controlled in both clockwise and counter clockwise direction and if you have motor with fix direction of motion the you can make use of all the four I/Os to connect up to four DC motors. L293D has output current of 600mA and peak output current of 1.2A per channel. Moreover for protection of circuit from back EMF ouput diodes are included within the IC. The output supply (VCC2) has a wide range from 4.5V to 36V, which has made L293D a best choice for DC motor driver.

80

SUMMARY

An embedded system is a system designed to perform one or a few dedicated functions often with realtime computing constraints. It is embedded as part of a complete device often including hardware and mechanical parts. Embedded systems are designed to do some specific task, rather than be a generalpurpose computer for multiple tasks. Some also have real-time performance constraints that must be met, for reasons such as safety and usability; others may have low or no performance requirements, allowing the system hardware to be simplified to reduce A microprocessor is multipurpose ,programmable ,clock driven ,register based electronic device that reads binary instructions from a storage device called memory ,accepts binary data as input and processes data according to those instructions and provides results as output. A typical programmable machine can be represented with four components : microprocessor ,input ,output and memory. These four components work together or interact with each other to perform a given task. A microcontroller (C) is a small computer on a single integrated circuit containing a processor core, memory, and programmable input/output peripherals. Program memory in the form of ROM is also often included on chip, as well as a typically small amount of RAM. A microcontroller can be considered a selfcontained system with a processor, memory and peripherals and can be used as an embedded system. The majority of microcontrollers in use today are embedded in other machinery, such as automobiles, telephones, appliances, and peripherals for computer systems. In the 8051 microcontroller there are four ports for I/O operations. It has 40 pins, out of which a total of 32 pins are set aside for the four ports P0 , P1, P2 and P3. The rest of the pins are designated as Vcc, GND, XTAL1 , XTAL2, EA ,ALE The four ports P0, P1, P2, and P3 each use 8 pins making them 8 bit ports. Microcontrollers were originally programmed only in assembly language, but various high-level programming languages are now also in common use to target microcontrollers. These languages are either designed specially for the purpose, or versions of general purpose languages such as the C programming language. Compilers produce hex file that we download into the ROM of the microcontroller.

81

Various data types are available in 8051 C . The main objective of the programmer is to create as small hex file as possible as the memory space is limited. This makes the study of data types very important . A judicial and accurate use of these can help limit the code size to a large extent. A light-emitting diode (LED) is a semiconductor light source. LEDs are used as indicator lamps in many devices, and are increasingly used for lighting. L.E.D.s can also be controlled by the use of a microcontroller . The positive side of the L.E.D. is connected to a pin of a microcontroller and the negative side is connected to ground. When a higher (1) signal is given to that pin, the L.E.D. gets 5 V , and it gets forward biased so it glows. The reverse happens when the negative end is coonected to microcontroller and positive end to Vcc. A lower (0) signal would then glow the L.E.D. A seven segment display, as its name indicates, is composed of seven elements. Individually on or off, they can be combined to produce simplified representations of the arabic numerals. Often the seven segments are arranged in an oblique (slanted) arrangement, which aids readability. The seven segments are arranged as a rectangle of two vertical segments on each side with one horizontal segment on the top, middle, and bottom. Additionally, the seventh segment bisects the rectangle horizontally. A liquid crystal display (LCD) is a thin, flat electronic visual display that uses the light modulating properties of liquid crystals (LCs). When a large number of pixels are needed in a display, it is not technically possible to drive each directly since then each pixel would require independent electrodes. Instead, the display is multiplexed. In a multiplexed display, electrodes on one side of the display are grouped and wired together (typically in columns), and each group gets its own voltage source. The basic 8051 has two on-chip timers that can be used for timing durations or for counting external events.Interval timing allows the programmer to perform operations at specific instants in time . . If we use the on-chip timers, the CPU could be off doing something more useful while the timers take on the menial task of keeping track of time. Microcontrollers must provide real time (predictable, though not necessarily fast) response to events in the embedded system they are controlling. When certain events occur, an interrupt system can signal the processor to suspend processing the current instruction sequence and to begin an interrupt service routine (ISR, or "interrupt handler"). The ISR will perform any processing required based on the source of the interrupt before returning to the original instruction sequence. Possible interrupt sources are device dependent, and often include events such as an internal timer overflow, completing an analog to digital conversion, a logic level change on an input such as from a button being pressed, and data received on a communication link.

82

In serial communication only one line is required to transmit and receive data , unlike parallel communication in which eight lines are required. Though an additional line for ground and possibly a third line for clock is also required. The advantage that serial communication has is that it requires lesser lines and so is ideal for long distance communication. The obvious disadvantage of serial communication, compared with parallel, is the reduction in the data transfer rate.

83

REFERENCES

The 8051 Microcontroller And Embedded System By MAZIDI Data Sheet of PC89C51 Data Sheet of L293D Data Sheet of RELAY

Internet, website www.wikipedia.org ATECHs Compact Disk 8085 by Ramesh Gaonkar

84

APPENDICES

Interrupt Priority
In most systems, some events are more important than others. For example, imagine a microwave oven in operation (ie; heating food). Let's also imagine a user presses a key on the keypad and opens the oven door at the same time. The interrupt caused by opening the door is more important than the interrupt caused by the key press (when the oven door is opened the microwave must immediately shut down, regardless of what's being pressed on the keypad) and it should be serviced first. Therefore, microcontrollers are designed so that interrupts can be prioritized. The 8051 has only two interrupt priority levels, 0 and 1, with 1 being the high priority. On reset, all interrupts are set at the low priority. To set an interrupt to high priority we set the appropriate bit in the interrupt priority (IP) SFR

External Interrupts
External interrupts occur as a result of a low-level or negative edge on the INT0-bar or INT1-bar pins on the 8051 (INT0-bar is at P3.2 while INT1-bar is at P3.3). The flags that generate these interrupts are IE0 and IE1 in the TCON register. As stated above, the interrupt may be caused by either a low-level or a negative edge on the INTx-bar pin. The choice of low-level activation or edge activation can be programmed through the IT0 and IT1 bits in the TCON register.

Setting the Baud Rate in Mode 1


The serial port in mode 1 can be operated over a range of baud rates (ie; bits/sec). There are a number of standard baud rates that many device serial ports operate at. These are listed in the table at the end of the document. If the designer of an 8051 system is required to transmit data from the serial port to a device (eg; a monitor) he/she needs to discover what baud rate the device's serial port operates at and configure the 8051 serial port to operate at the same baud rate. In mode 1, the baud rate is determined by the overflow of timer 1. However, since the timer operates at a relatively high frequency (compared to serial port baud rates) the timer 1 overflow frequency is divided by either 32 or 16

85

PROGRAM STATUS WORD Bit PSW.7 PSW.6 PSW.5 PSW.4 PSW.3 PSW.2 PSW.1 PSW.0 Symbol CY AC F0 RS1 RS0 OV -P Address D7H D6H D5H D4H D3H D2H D1H D0H Description Carry flag Auxiliary carry flag Flag 0 Register bank select 1 Register bank select 0 Overflow flag Reserved Even parity flag

86

Você também pode gostar