In industrial process, Speed as a variable refers to the revolution per minute of some piece of rotating equipment. Speed is a scalar quantity equal to the magnitude of velocity. There is various method of measurement, of which the tachometer is the most frequently used device. They are used for the measurement of angular speed, usually in revolution per minute (rpm). Most of industrial machine operated with one or more motor & many types of fans are used in industries as well as in domestic. So that speed of motor, fan etc. is very important factor. So here we describe an Easy & very accurate RPM indicator using new technology of micro controller. This RPM INDICATOR measures up to 100000 RPM & it is very useful for industries & domestic appliances. This project ‘micro controller based contact less tachometer’ design makes use of 8051 micro controller for interfacing to various hardware peripherals. Technology today is seeing its heights in all the areas, especially in the area of Embedded Systems. It is true that every electronic gadget that is used in daily life right from a PC keyboard to a refrigerator is an Embedded System. This it shows how vastly the technology is expanding.









The block diagram of wireless tachometer is shown, it consists of power supply unit, display unit, TSOP 555 timer, IR transmitter & micro controller. This project based on micro controller, the power was passed to the micro controller through the help of power supply unit. The data passed to the IR transmitter through the help of 555 timer, then IR transmitter send the data through wireless, TSOP will receive the data and move towards to the micro controller unit. The micro controller unit will send the data into display unit, display unit will display the message of received data from micro controller.



Fig: IR transmitter circuit


Fig: IR receiver circuit The microcontroller ATMEL (8051) consists of 4 ports. They are port0, port1, port2, and port3.Port1 have 8 pins. Each pin is connected to LCD data lines. The controller resistor (i.e) rs, rw, en Pins are connected to Port 3.5 to Port 3.7. Connect 10 K Ohm pull up resistor to the Port 0. P0.0 are connected to Push button. Port 3.4 are connected to TSOP. 40th and 31st pins are connected to (+5V) VCC ,20th pin to GND. Pin 18th and 19th are connected to crystal oscillator (11.0592 MHz).8.2k ohm resistor are connected to 9th Pin of microcontroller and another end is GND.10uf capacitor +ve terminal is connected to +VCC(+5V),-ve terminal is GND. The 1st pin of the LCD connected to the ground. 2nd pin is power supply which is connected to +Vcc (+5V) the 3rd pin for variable resistor which is used to adjust the contrast of the LCD. 4th pin for reset then (7- 14) pins are data bus lines which is used for data and command transfer. If the LCD has a backlight it will be powered by pin 15 & pin 16. When RS = 0 instruction code data (command) is given to the LCD. If RS = 1 the data is given to LCD through the data bus line. Pin 5 for R/W if R/W = 1 then read operation take place then R/W = 0 write operation take place. Pin 6th used for enable the LCD. RS is connected to the port 3.5,R/W is connected to the port 3.6, EN is connected to the port 3.7. 555 IC it is a timer IC. It consists of 8 pins. 1st pin is given to ground. 8th pin are VCC. 2nd pin are connected to 6th pin. 10uf capacitor are connected to 6th and GND. 6th pin are connected to 10k variable resistor 1st pin. 2nd pin are connected to 150 OHM resistor the other end are connected to VCC. 3rd pin are connected to 120 ohm resistor the other end connected to +VE IR transmitter the other end are connected to GND.



Power supply unit: As we all know any invention of latest technology cannot be activated without the source of power. So it this fast moving world we deliberately need a proper power source which will be apt for a particular requirement. All the electronic components starting from diode to Intel IC’s only work with a DC supply ranging from _+5v to _+12. we are utilizing for the same, the most cheapest and commonly available energy source of 230v-50Hz and stepping down , rectifying, filtering and regulating the voltage. This will be dealt briefly in the forth-coming sections. Step down transformer: When AC is applied to the primary winding of the power transformer it can either be stepped down or up depending on the value of DC needed. In our circuit the transformer of 230v/15-015v is used to perform the step down operation where a 230V AC appears as 15V AC across the secondary winding. One alteration of input causes the top of the transformer to be positive and the bottom negative. The next alteration will temporarily cause the reverse. The current rating of the


transformer used in our project is 2A. Apart from stepping down AC voltages , it gives isolation between the power source and power supply circuitries. Rectifier unit: In the power supply unit, rectification is normally achieved using a solid state diode. Diode has the property that will let the electron flow easily in one direction at proper biasing condition . As AC is applied to the diode, electrons only flow when the anode and cathode is negative. Reversing the polarity of voltage will not permit electron flow. A commonly used circuit for supplying large amounts of DC power is the bridge rectifier. A bridge rectifier of four diodes (4*IN4007) are used to achieve full wave rectification. Two diodes will conduct during the negative cycle and the other two will conduct during the positive half cycle. The DC voltage appearing across the output terminals of the bridge rectifier will be somewhat lass than 90% of the applied rms value. Normally one alteration of the input voltage will reverse the polarities. Opposite ends of the transformer will therefore always be 180 deg out of phase with each other. For a positive cycle, two diodes are connected to the positive voltage at the top winding and only one diode conducts. At the same time one of the other two diodes conducts for the negative voltage that is applied from the bottom winding due to the forward bias for that diode. In this circuit due to positive half cycleD1 & D2 will conduct to give 10.8v pulsating DC. The DC output has a ripple frequency of 100Hz. Since each altercation produces a resulting output pulse, frequency = 2*50 Hz. The output obtained is not a pure DC and therefore filtration has to be done. Filtering unit Filter circuits which usually capacitor is acting as a surge arrester always follow the rectifier unit. This capacitor is also called as a decoupling capacitor or a bypassing capacitor, is used not only to ‘short’ the ripple with frequency of 120Hz to ground but also to leave the frequency of the DC to appear at the output. A load resistor R1 is connected so that a reference to the ground is maintained. C1R1 is for bypassing ripples. C2R2 is used as a low pass filter, i.e. it passes only low frequency signals and bypasses high frequency signals. The load resistor should be 1% to 2.5% of the load.






Introduction: Despite it’s relatively old age, the 8051 is one of the most popular microcontrollers in use today. Many derivative microcontrollers have since been developed that are based on and compatible with--the 8051. Thus, the ability to program an 8051 is an important skill for anyone who plans to develop products that will take advantage of microcontrollers. Many web pages, books, and tools are available for the 051 developer. I hope the information contained in this document/web page will assist you in mastering 8051 programming. While it is not my intention that this document replaces a hardcopy book purchased at your local book store, it is entirely possible that this may be the case. It is likely that this document contains everything you will need to learn 8051 assembly language programming. Of course, this document is free and you get what you pay for so if, after reading this document, you still is lost you may find it necessary to buy a book. This document is both a tutorial and a reference tool. The various chapters of the document will explain the 8051 step by step. The chapters are targeted at people who are attempting to learn 8051 assembly language programming. The appendices are a useful reference tool that will assist both the novice programmer as well as the experienced professional developer. This document assumes the following: • • • A general knowledge of programming. An understanding of decimal, hexadecimal, and binary number systems. A general knowledge of hardware.

That is to say, no knowledge of the 8051 is assumed--however, it is assumed you’ve done some amount of programming before, have a basic understanding of hardware, and a firm grasp on the three numbering systems mentioned above. The concept of converting a number from decimal to hexadecimal and/or to binary is not within the scope of this document--and if you can’t do those types of conversions there are probably some concepts that will not be completely understandable. This document attempts to address the need of the typical programmer. For example, there are certain features that are nifty and in some cases very useful--but 95% of the programmers will never use these features. Types of Memory: 10

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.

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. Programming Tip: 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 Hard ware, programs are limited to 64K. 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 the 8051 supports External RAM up to 64K. Programming Tip: 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 (SFR) memories. 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 it’s 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 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 8051’s stack since, as illustrated in the memory map, the area reserved for the stack is only 80 bytes--and usually it is less since these 80 bytes has to be shared between the stack and user variables. 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 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 synonymous 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. Programming Tip:


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. 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 FF h to Internal RAM address 20h you’ve effectively set bits 00h through 07h. 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. Programming Tip: 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 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 || SETB 80h Both these instructions accomplish the same thing. However, using the SETB command will turn on the P0.0 line without affecting 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. Programming Tip: By default, the 8051 initializes the Stack Pointer (SP) to 08h 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 8051’s 32 input/output lines. Another SFR allows a program to read or write to the 8051’s serial port. Other SFRs allow the user to set the serial baud rate, control and access timers, and configure the 8051’s interrupt system. When programming, SFRs have the illusion of being Internal Memory. For example, if you want to write the value "1" to Internal RAM location 50 hex you would execute the instruction: MOV 50h, #01h Similarly, if you want to write the value "1" to the 8051’s serial port you would write this value to the SBUF SFR, which has an SFR address of 99 Hex. Thus, to write the value "1" to the serial port you would execute the instruction: MOV 99h, #01h As you can see, it appears that the SFR is part of Internal Memory. This is not the case. When using this method of memory access (it’s called direct address), any instruction that has an address of 00h through 7Fh refers to an Internal RAM memory address; any instruction with an address of 80h through FFh refers to an SFR control register. Programming Tip: 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.


SFR’s: What Are SFR’s? 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.


As you can see, although the address range of 80h through FFh offers 128 possible addresses, there are only 21 SFRs in a standard 8051. All other addresses in the SFR range (80h through FFh) are considered invalid. Writing to or reading from these registers may produce undefined values or behavior. Programming Tip: 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 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 background 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 auxiliary 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 using SCON, the program may read or write to the serial port using the SBUF register. Programming Tip: 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 Description 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. Programming Tip: 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.

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, and LCALL, RET, RETI, and whenever interrupts are provoked by the microcontroller. Programming Tip: 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). Programming Tip:


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 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 occurred. 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/8Bh): 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 8Ch/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. Programming Tip: 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. Programming Tip: 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, and 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. IP (Interrupt Priority, Addresses B8h, and 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, and 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. Programming Tip:


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 erratically and unpredictably--and it will be tricky to debug since the behavior will tend not to make any sense. ACC (Accumulator, Addresses E0h, and 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 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 compatibility 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.


Programming Tip: 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.

Basic Registers: The Accumulator If you’ve worked with any other assembly languages you will be familiar with the concept of an Accumulator register. The Accumulator, as it’s name suggests, is used as a general register to accumulate the results of a large number of instructions. It can hold an 8-bit (1-byte) value and is the most versatile register the 8051 has due to the shear number of instructions that make use of the accumulator. More than half of the 8051’s 255 instructions manipulate or use the accumulator in some way. For example, if you want to add the number 10 and 20, the resulting 30 will be stored in the Accumulator. Once you have a value in the Accumulator you may continue processing the value or you may store it in another register or in memory. The "R" registers The "R" registers are a set of eight registers that are named R0, R1, etc. up to and including R7. These registers are used as auxiliary registers in many operations. To continue with the above example, perhaps you are adding 10 and 20. The original number 10 may be stored in the Accumulator whereas the value 20 may be stored in, say, register R4. To process the addition you would execute the command: ADD A, R4


After executing this instruction the Accumulator will contain the value 30. You may think of the "R" registers as very important auxiliary, or "helper", registers. The Accumulator alone would not be very useful if it were not for these "R" registers. The "R" registers are also used to temporarily store values. For example, let’s say you want to add the values in R1 and R2 together and then subtract the values of R3 and R4. One way to do this would be: MOV A, R3; Move the value of R3 into the accumulator ADD A, R4; add the value of R4 MOV R5, A; Store the resulting value temporarily in R5 MOV A, R1; Move the value of R1 into the accumulator ADD A, R2; add the value of 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 isn’t 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. 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 and DIV an instruction, the “B” register is often used as yet another temporary storage register much like a ninth "R" register. The Data Pointer (DPTR) The Data Pointer (DPTR) is the 8051’s only user-accessible 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 it’s the only true 16-bit register available. It is often used to store 2- byte values which have nothing to do with memory locations.


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 isn’t always incremented by one. Since some instructions require 2 or 3 bytes the PC will be incremented by 2 or 3 in these cases. The Program Counter is special in that there is no way to directly modify it’s value. That is to say, you can’t do something like PC=2430h. On the other hand, if you execute LJMP 2340h you’ve effectively accomplished the same thing. It is also interesting to note that while you may change the value of PC (by executing a jump instruction, etc.) there is no way to read the value of PC. That is to say, there is no way to ask the 8051 "What address are you about to execute?" As it turns out, this is not completely true: There is one trick that may be used to determine the current value of PC. This trick will be covered in a later chapter. The Stack Pointer (SP) The Stack Pointer, like all registers except DPTR and PC, may hold an 8-bit (1-byte) value. The Stack Pointer is used to indicate where the next value to be removed from the stack should be taken from. When you push a value onto the stack, the 8051 first increments the value of SP and then stores the value at the resulting memory location. When you pop a value off the stack, the 8051 returns the value from the memory location indicated by SP and then decrements the value of SP. This order of operation is important. When the 8051 is initialized SP will be initialized to 07h. If you immediately push a value onto the stack, the value will be stored in Internal RAM address 08h. This makes sense taking into account what was mentioned two paragraphs above: First the 8051 will increment the value of SP (from 07h to 08h) and then will store the pushed value at that memory address (08h). SP is modified directly by the 8051 by six instructions: PUSH, POP, ACALL, LCALL, RET, and RETI. It is also used intrinsically whenever an interrupt is triggered (more on interrupts later. Don’t worry about them for now!).


The infrared LED emitter produces a light beam across the bottom of the coil. We chose IR (infrared) because there's less noise and ambient light than at normal optical wavelengths. Later, I found plenty of ambient light sources that interfered with the light beam, most noticeably indirect sunshine from a nearby window made a big difference to the optodetector. It would probably work fine to use a visible LED instead, such as high-intensity red. It would even work with a flashlight bulb, which also make it much easier to see everything working inside the levitator's box. Mount the whole assembly in a five-sided box type of frame, to eliminate ambient light from most directions. We want the LED to be the brightest light seen by the optodetector. You will probably see an improvement if you put black paper around the emitter side of the box to reduce reflected light. Choose a bias resistor for the LED to produce a healthy signal. I used 500 ohms, which yields a 30 mA current through the LED. That is, current is voltage divided by resistance, or approximately 15 volts divided by 500 ohms will yield about 30 mA. You want the LED bright enough to be well above "noise" sources. You don't want it too bright, or it will drive the optodetector into "on" saturation. (Though that's not likely to be a problem with a couple inches of separation to the detector.) You also don't want it too bright or it wastes power and produces heat, which may shorten its lifetime. Check the specifications for your own infrared LED and run it fairly hot, but don't overdrive it. Note the photo detectors from Radio Shack are quite sensitive, and you can probably use a 1K-ohm resistor successfully in place of the 500-ohm.


LED Characteristics Light Emitting Diodes are silicon devices that produce light. The light is produced only when current passes through in the forward direction. To produce light, the forward voltage must be higher than the diode's internal barrier voltage. This point is labelled +VF ("voltage forward") on the graph. Like any other diode, LEDs pass current in the forward direction, but block current in the reverse direction. This means the LED will only light up if connected with its cathode on the negative side of the circuit, and its anode on the positive side. Too much reverse voltage will destroy LEDs and diodes. It is important to note that once the voltage across the LED reaches +VF, the diode conducts current extremely well.

3.1.3 TSOP:
The TSOP17... – Series are miniaturized receivers for infrared remote control systems. PIN diode and preamplifier are assembled on lead frame, the epoxy package is designed as IR filter. The demodulated output signal can directly be decoded by a microprocessor. TSOP17.. is the standard IR remote control receiver series, supporting all major transmission codes.

Features _ Photo detector and preamplifier in one package


_ internal filter for PCM frequency _ Improved shielding against electrical field disturbance _ TTL and CMOS compatibility _ Output active low _ Low power consumption _ High immunity against ambient light _ Continuous data transmission possible (1200 bit/s) _ Suitable burst length 10 cycles/burst

Block Diagram

Application Circuit


3.3.4 LCD:
In recent years the LCD is finding widespread use replacing LED's.This is due to 1) The declining prices of LCD's. 2) The ability to display numbers, characters, and graphics. This is in contrast to LED's which are limited to numbers and a few characters. 3) Incorporation of a refreshing controller in to the LCD, thereby relieving the CPU of the task of refreshing the LCD.In contrast, the LED must be refreshed by the CPU to keep displaying the data. 4) Ease of programming for characters and graphics. LCD PIN DESCRITION:


Vcc, Vss, Vee: While Vcc and Vss provide +5V and ground, respectively, Vee is used for controlling LCD contrast. RS, register select: There are two very important registers inside the LCD.The RS pin is used for their selection as follows. 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. E, enable: 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 LCD to latch in the data present at the data pins. This pulse must be a minimum of 450ns wide. D0---D7: The 8--bit data pins, D0-D7 are used to send information to the LCD or read the contents of the LCD's 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. We also use RS = 0 to check the busy flag bit to see if LCD is ready to receive the information. The busy flag is D7 and can be read when R/W = 1 and RS = 0, as follows, if R/W = 1,RS = 0.When D7 = 1 (busy flag bit=1), the LCD is busy taking care of internal operations and will not accept any new information.



You probably use items containing an LCD (liquid crystal display) every day. They are all around us -- in laptop computers, digital clocks and watches, microwave ovens, CD players and many other electronic devices. LCDs are common because they offer some real advantages over other display technologies. They are thinner and lighter and draw much less power than cathode ray tubes (CRTs).

Figure 5.4 LCD display A general purpose alphanumeric LCD display, with two lines of 16 characters is shown in the figure. A liquid crystal display (LCD) is a thin, flat display device made up of any number of color or monochrome pixels arrayed in front of a light source or reflector. It is prized by engineers because it uses very small amounts of electric power, and is therefore suitable for use in battery-powered electronic devices. Each pixel (picture element) consists of a column of liquid crystal molecules suspended between two transparent electrodes, and two polarizing filters, the axes of polarity of which are perpendicular to each other. Without the liquid crystals between them, light passing through one would be blocked by the other. The liquid crystal twists the polarization of light entering one filter to allow it to pass through the other. The molecules of the liquid crystal have electric charges on them. By applying small electrical charges to transparent electrodes over each pixel or sub pixel, the molecules are twisted by electrostatic forces. This changes the twist of the light passing through the molecules, and allows varying degrees of light to pass (or not to pass) through the polarizing filters. Before applying an electrical charge, the liquid crystal molecules are in a relaxed state. Charges on the molecules cause these molecules to align themselves in a helical structure, or


twist (the "crystal"). In some LCDs, the electrode may have a chemical surface that seeds the crystal, so it crystallizes at the needed angle. Light passing through one filter is rotated as it passes through the liquid crystal, allowing it to pass through the second polarized filter. A small amount of light is absorbed by the polarizing filters, but otherwise the entire assembly is transparent. When an electrical charge is applied to the electrodes, the molecules of the liquid crystal align themselves parallel to the electric field, thus limiting the rotation of entering light. If the liquid crystals are completely untwisted, light passing through them will be polarized perpendicular to the second filter, and thus be completely blocked. The pixel will appear unlit. By controlling the twist of the liquid crystals in each pixel, light can be allowed to pass though in varying amounts, correspondingly illuminating the pixel. Many LCDs are driven to darkness by an alternating current, which disrupts the twisting effect, and become faint or transparent when no current is applied. To save cost in the electronics, LCDs are often multiplexed. In a multiplexed display, electrodes on one side of the display are grouped and wired together, and each group gets its own voltage source. On the other side, the electrodes are also grouped, 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. Important factors to consider when evaluating an LCD monitor include resolution, viewable size, response time (sync rate), viewing angle, color support, brightness and contrast ratio, aspect ratio, and input ports


A voltage regulator is an electrical regulator designed to automatically maintain a constant voltage level. It may use an electromechanical mechanism, or passive or active electronic components. Depending on the design, it may be used to regulate one or more AC or DC voltages. With the exception of shunt regulators, all voltage regulators operate by comparing the actual output voltage to some internal fixed reference voltage. Any difference is amplified and used to control the regulation element. This forms a negative feedback servo control loop. If the output voltage is too low, the regulation element is commanded to produce a higher voltage. If the output voltage is too high, the regulation element is commanded to produce a lower voltage. In this way, the output voltage is held roughly constant. The control loop must be carefully designed to produce the desired tradeoff between stability and speed of response. Contents· 1 Electromechanical regulators · 2 Mains regulators · 3 AC voltage stabilizers · 4 DC voltage stabilizers · 5 Active regulators. 5.1 Linear regulators. 5.2 Switching regulators. 5.3 Comparing linear vs. switching regulators. 5.4 SCR regulators. 5.5 Combination (hybrid) regulators.


Electromechanical regulators Early automobile generators and alternators had a mechanical voltage regulator using two or three relays and various resistors to stabilize the generator's output at slightly more than 6 or 12 V, independent of the engine's rpm or the varying load on the vehicle's electrical system. More modern designs use solid state technology (transistors) to do the same. These regulators operate by controlling the field current reaching the generator (or alternator) and in this way controlling the output voltage produced by the generator. Mains regulators Electromechanical regulators have also been used to regulate the voltage on AC power distribution lines. These regulators generally operate by selecting the appropriate tap on a transformer with multiple taps. If the output voltage is too low, the tap changer switches connections to produce a higher voltage. If the output voltage is too high, the tap changer switches connections to produce a lower voltage. The controls provide a dead band wherein the controller will not act, preventing the controller from constantly hunting (constantly adjusting the voltage) to reach the desired target voltage. AC voltage stabilizers A voltage stabilizer is a type of household mains regulator which uses a continuously variable autotransformer to maintain an AC output that is as close to the standard or normal mains voltage as possible, under conditions of fluctuation. It uses a servomechanism (or negative feedback) to control the position of the tap (or wiper) of the autotransformer, usually with a motor. An increase in the mains voltage causes the output to increase, which in turn causes the tap (or wiper) to move in the direction that reduces the output towards the nominal voltage. An alternative method is the use of a type of saturating transformer called a Ferro resonant transformer. These transformers use a tank circuit composed of a high-voltage resonant winding and a capacitor to produce a nearly constant average output with a varying input. The Ferro resonant approach is attractive due to its lack of active components, relying on the square loop saturation characteristics of the tank circuit to absorb variations in average input voltage. The Ferro resonant output has a high harmonic content, leading to a distorted output waveform. The Ferro resonant action is a flux limiter rather than a voltage regulator, but with a fixed supply frequency it can maintain an almost constant average output voltage even as the input voltage varies.


DC voltage stabilizers Many simple DC power supplies regulate the voltage using a shunt regulator such as a zener diode, avalanche breakdown diode, or voltage regulator tube. Each of these devices begins conducting at a specified voltage and will conduct as much current as required to hold its terminal voltage to that specified voltage. The power supply is designed to only supply a maximum amount of current that is within the safe operating capability of the shunt regulating device (commonly, by using a series resistor). In shunt regulators, the voltage reference is also the regulating device. If the stabilizer must provide more power, the shunt regulator output is only used to provide the standard voltage reference for the electronic device, known as the voltage stabilizer. The voltage stabilizer is the electronic device, able to deliver much larger currents on demand. Active regulators Because they (essentially) dump the excess current not needed by the load, shunt regulators are inefficient and only used for low-power loads. When more power must be supplied, more sophisticated circuits are used. In general, these can be divided into several classes: · · · Linear regulators Switching regulators SCR regulators

Linear regulators Linear regulators insert a variable resistance in series with the load current. In the past, one or more vacuum tubes were commonly used as the variable resistance. Modern designs use one or more transistors instead. Linear designs have the advantage of very "clean" output with little noise introduced into their DC output. Entire linear regulators are available as integrated circuits. These chips come in either fixed or variable voltage types. Switching regulators Instead of controlling a variable resistance, the output of a switching regulator is controlled by rapidly switching a series device on and off. The duty cycle of the switch sets how much charge is transferred to the load. This is controlled by a similar feedback mechanism as in a linear regulator. 38

Because the series element is either fully conducting, or switched off, it dissipates almost no power; this is what gives the switching design its efficiency. Switching regulators are also able to generate output voltages which are higher than the input, or of opposite polarity - something not possible with a linear design. Like linear regulators, nearly-complete switching regulators are also available as integrated circuits. Unlike linear regulators, these usually require one external component: an inductor that acts as the energy storage element. (Unfortunately, the inductor must be external because large-valued inductors tend to be physically large relative to almost all other kinds of component; because of this, they are impossible to fabricate within integrated circuits.) Comparing linear vs. switching regulators Sometimes only one or the other will work: · · required. · computers). · Switching regulators are required when the only power supply is a DC voltage, and a Switching regulators are best when power efficiency is critical (such as in portable Linear regulators are best when low output noise is required Linear regulators are best when a fast response to input and output disturbances is

higher output voltage is required. In many cases either one would work. So the choice comes down to which costs less. At high levels of power (above a few watts), switching regulators are cheaper. At low levels of power, linear regulators are cheaper. SCR regulators Regulators powered from AC power circuits can use silicon controlled rectifiers (SCRs) as the series device. Whenever the output voltage is below the desired value, the SCR is triggered, allowing electricity to flow into the load until the AC mains voltage passes through zero (ending the half cycle). SCR regulators have the advantages of being both very efficient and very simple, but because they can not terminate an on-going half cycle of conduction, they are not capable of very accurate voltage regulation in response to rapidly-changing loads.


Combination (hybrid) regulators Many power supplies use more than one regulation method in series. For example, the output from a switching regulator can be further regulated by a linear regulator. The switching regulator accepts a wide range of input voltages and efficiently generates a (somewhat noisy) voltage slightly above the ultimately desired output. That is followed by a linear regulator that generates exactly the desired voltage and eliminates nearly all the noise generated by the switching regulator. Other designs may use an SCR regulator as the "pre-regulator", followed by another type of regulator Regulator (automatic control) In automatic control, a regulator is a device which has the function of maintaining a designated characteristic. It performs the activity of managing or maintaining a range of values, in a machine. The measurable property of a device is managed closely by specified conditions or an advance set value; or it can be a variable according to a predetermined arrangement scheme. It can be used generally to connote any set of various controls or devices for regulating or controlling items or objects. Examples are a voltage regulator (which can be a transformer whose voltage ratio of transformation can be adjusted, or an electronic circuit that produces a defined voltage), a gas regulator, such as a diving regulator, which maintains its output at a fixed pressure lower than its input, and a fuel regulator (which controls the supply of fuel). Regulators can be designed to control anything from gasses or fluids, to light or electricity. Speed can be regulated by; electronic, mechanical, or electro-mechanical means. Such instances include; · Electronic regulators as used in model railway sets where the voltage is raised or lowered

to control the speed of the engine · Mechanical systems such as valves as used in fluid control systems. Purely mechanical

pre-automotive systems included synch designs as the Watt centrifugal governor whereas modern systems may have electronic fluid speed sensing components directing solenoids to set the valve to the desired rate.



Complex electro-mechanical speed control systems used to maintain speeds in modern

cars (cruise control) - often including hydraulic components

A crystal oscillator (sometimes abbreviated to XTAL on schematic diagrams) is an electronic circuit that uses the mechanical resonance of a physical crystal of piezoelectric material along with an amplifier and feedback to create an electrical signal with a very precise frequency. It is an especially accurate form of an electronic oscillator. This frequency is used to keep track of time (as in quartz wristwatches), to provide a stable clock signal for digital integrated circuits, and to stabilize frequencies for radio transmitters. Crystal oscillators are a common source of time and frequency signals. The crystal used therein is sometimes called a "timing crystal". Contents· • • • • • Crystals for timing purposes Crystals and frequency Series or parallel resonance Spurious frequencies Notation

Crystals for timing purposes


A miniature 4.000 MHz quartz timing crystal enclosed in a hermetically sealed package. A crystal is a solid in which the constituent atoms, molecules, or ions are packed in a regularly ordered, repeating pattern extending in all three spatial dimensions. Almost any object made of an elastic material could be used like a crystal, with appropriate transducers, since all objects have natural resonant frequencies of vibration. For example, steel is very elastic and has a high speed of sound. It was often used in mechanical filters before quartz. The resonant frequency depends on size, shape, elasticity and the speed of sound in the material. High-frequency crystals are typically cut in the shape of a simple, rectangular plate. Low-frequency crystals, such as those used in digital watches, are typically cut in the shape of a tuning fork. For applications not needing very precise timing, a low-cost ceramic resonator is often used in place of a quartz crystal. When a crystal of quartz is properly cut and mounted, it can be made to bend in an electric field, by applying a voltage to an electrode near or on the crystal. This property is known as piezoelectricity. When the field is removed, the quartz will generate an electric field as it returns to its previous shape, and this can generate a voltage. The result is that a quartz crystal behaves like a circuit composed of an inductor, capacitor and resistor, with a precise resonant frequency. Quartz has the further advantage that its size changes very little with temperature. Therefore, the resonant frequency of the plate, which depends on its size, will not change much, either. This means that a quartz clock, filter or oscillator will remain accurate. For critical applications the quartz oscillator is mounted in a temperature-controlled container, called an crystal oven, and can also be mounted on shock absorbers to prevent perturbation by external mechanical vibrations. Quartz timing crystals are manufactured for frequencies from a few tens of kilohertz to tens of megahertz. More than two billion (2 × 109) crystals are manufactured annually. Most are


small devices for wristwatches, clocks, and electronic circuits. However, quartz crystals are also found inside test and measurement equipment, such as counters, signal generators, and oscilloscopes. Crystals and frequency

Fig: Schematic symbol and equivalent circuit for a quartz crystal in an oscillator The crystal oscillator circuit sustains oscillation by taking a voltage signal from the quartz resonator, amplifying it, and feeding it back to the resonator. The rate of expansion and contraction of the quartz is the resonant frequency, and is determined by the cut and size of the crystal. A regular timing crystal contains two electrically conductive plates, with a slice or tuning fork of quartz crystal sandwiched between them. During startup, the circuit around the crystal applies a random noise AC signal to it, and purely by chance, a tiny fraction of the noise will be at the resonant frequency of the crystal. The crystal will therefore start oscillating in synchrony with that signal. As the oscillator amplifies the signals coming out of the crystal, the crystal's frequency will become stronger, eventually dominating the output of the oscillator. Natural resistance in the circuit and in the quartz crystal filter out all the unwanted frequencies. One of the most important traits of quartz crystal oscillators is that they can exhibit very low phase noise. In other words, the signal they produce is a pure tone. This makes them particularly useful in telecommunications where stable signals are needed and in scientific equipment where very precise time references are needed.


The output frequency of a quartz oscillator is either the fundamental resonance or a multiple of the resonance, called an overtone frequency. A typical Q for a quartz oscillator ranges from 104 to 106. The maximum Q for a high stability quartz oscillator can be estimated as Q = 1.6 × 107/f, where f is the resonance frequency in MHz. Environmental changes of temperature, humidity, pressure, and vibration can change the resonant frequency of a quartz crystal, but there are several designs that reduce these environmental effects. These include the TCXO, MCXO, and OCXO (defined below). These designs (particularly the OCXO) often produce devices with excellent short-term stability. The limitations in short-term stability are due mainly to noise from electronic components in the oscillator circuits. Long term stability is limited by aging of the crystal. Due to aging and environmental factors such as temperature and vibration, it is hard to keep even the best quartz oscillators within one part in 10-10 of their nominal frequency without constant adjustment. For this reason, atomic oscillators are used for applications that require better long-term stability and accuracy. Although crystals can be fabricated for any desired resonant frequency, within technological limits, in actual practice today engineers design crystal oscillator circuits around relatively few standard frequencies, such as 10 MHz, 20 MHz and 40 MHz. Using frequency dividers, frequency multipliers and phase locked loop circuits, it is possible to synthesize any desired frequency from the reference frequency. Care must be taken to use only one crystal oscillator source when designing circuits to avoid subtle failure modes of met stability in electronics. If this is not possible, the number of distinct crystal oscillators, PLLs, and their associated clock domains should be rigorously minimized, through techniques such as using a subdivision of an existing clock instead of a new crystal source. Each new distinct crystal source needs to be rigorously justified since each one introduces new difficult to debug probabilistic failure modes, due to multiple crystal interactions, into equipment.


Series or parallel resonance A Quartz crystal provides both series and parallel resonance. The series resonance is a few kHz lower than the parallel one. Crystals below 30 MHz are generally operated at parallel resonance, which means that the crystal impedance appears infinite. Any additional circuit capacitance will thus pull the frequency down. For a parallel resonance crystal to operate at its specified frequency, the electronic circuit has to provide a total parallel capacitance as specified by the crystal manufacturer. Crystals above 30 MHz (up to >200 MHz) are generally operated at series resonance where the impedance appears at its minimum and equal to the series resistance. For this reason the series resistance is specified (<100 Ω) instead of the parallel capacitance. For the upper frequencies, the crystals are operated at one of its overtones, presented as being a fundamental, 3rd, 5th, or even 7th overtone crystal. The oscillator electronic circuits usually provides additional LC circuits to select the wanted overtone of a crystal. Spurious frequencies For crystals operated in series resonance, significant (and temperature-dependent) spurious responses may be experienced. These responses typically appear some tens of kHz above the wanted series resonance. Even if the series resistances at the spurious resonances appear higher than the one at wanted frequency, the oscillator may lock at a spurious frequency (at some temperatures). This is generally avoided by using low impedance oscillator circuits to enhance the series resistance difference. Notation On electrical schematic diagrams, crystals are designated with the class letter "Y" (Y1, Y2, etc.) Oscillators, whether they are crystal oscillators or other, are designated with the class letter "G" (G1, G2, etc.) (See IEEE Std 315-1975, or ANSI Y32.2-1975) On occasion, one may see a crystal designated on a schematic with "X" or "XTAL", or a crystal oscillator with "XO", but these forms are deprecated.


Crystal oscillator types and their abbreviations: · · · · · · · MCXO - microcomputer-compensated crystal oscillator OCVCXO - oven-controlled voltage-controlled crystal oscillator OCXO - oven-controlled crystal oscillator RBXO - rubidium crystal oscillators (RBXO). TCVCXO - temperature-compensated-voltage controlled crystal oscillator TCXO - temperature-compensated crystal oscillator VCXO - voltage-controlled crystal oscillator

What are crystal oscillators? Crystal oscillators are oscillators where the primary frequency determining element is a quartz crystal. Because of the inherent characteristics of the quartz crystal the crystal oscillator may be held to extreme accuracy of frequency stability. Temperature compensation may be applied to crystal oscillators to improve thermal stability of the crystal oscillator. Crystal oscillators are usually, fixed frequency oscillators where stability and accuracy are the primary considerations. For example it is almost impossible to design a stable and accurate LC oscillator for the upper HF and higher frequencies without resorting to some sort of crystal control. Hence the reason for crystal oscillators. The frequency of older FT-243 crystals can be moved upward by crystal grinding. A practical example of a Crystal Oscillator


This is a typical example of the type of crystal oscillators which may be used for say converters. Some points of interest on crystal oscillators in relation to figure 1. The transistor could be a general purpose type with an Ft of at least 150 Mhz for HF use. A typical example would be a 2N2222A. The turn’s ratio on the tuned circuit depicts an anticipated nominal load of 50 ohms. This allows a theoretical 2K5 ohm on the collector. If it is followed by a buffer amplifier (highly recommended) I would simply maintain the typical 7:1 turn’s ratio. I have included a formula for determining L and C in the tuned circuits of crystal oscillators in case you have forgotten earlier tutorials. Personally I would make L a reactance of around 250 ohms. In this case I'd make C a smaller trimmer in parallel with a standard fixed value. You can use an overtone crystal for the crystal and set L * C for the odd particular multiple of overtone wanted in your crystal oscillators. Of particular interest to those people wanting to develop a variable crystal oscillator is the Super VXO. Worth a look oscillation is the periodic variation, typically in time, of some measure as seen, for example, in a swinging pendulum. The term vibration is sometimes used more narrowly to mean a mechanical oscillation but sometimes is used to be synonymous with oscillation. Oscillations occur not only in physical systems but also in biological systems and in human society. Oscillations are the origin of the sensation of musical tone An electronic oscillator is an electronic circuit that produces a repetitive electronic signal, often a sine wave or a square wave.


A low-frequency oscillator (or LFO) is an electronic oscillator that generates an AC waveform between 0.1 Hz and 10 Hz. This term is typically used in the field of audio synthesizers, to distinguish it from an audio frequency oscillator. Types of electronic oscillator: 1. Harmonic oscillator. 2. Relaxation oscillator.

Harmonic oscillator The harmonic oscillator produces a sinusoidal output. The basic form of an harmonic oscillator is an electronic amplifier with the output attached to a narrow-band electronic filter, and the output of the filter attached to the input of the amplifier. When the power supply to the amplifier is first switched on, the amplifier's output consists only of noise. The noise travels around the loop, being filtered and re-amplified until it increasingly resembles the desired signal. A piezoelectric crystal (commonly quartz) may be coupled to the filter to stabilise the frequency of oscillation, resulting in a crystal oscillator. There are many ways to implement harmonic oscillators, because there are different ways to amplify and filter. For example: · · · · · · Hartley oscillator Colpitts oscillator Clapp oscillator Pierce crystal oscillator Phase-shift oscillator RC oscillator (Wien Bridge and "Twin-T")

Relaxation oscillator


The relaxation oscillator is often used to produce a non-sinusoidal output, such as a square wave or saw tooth. The oscillator contains a nonlinear component such as a transistor that periodically discharges the energy stored in a capacitor or inductor, causing abrupt changes in the output waveform. Square-wave relaxation oscillators can be used to provide the clock signal for sequential logic circuits such as timers and counters, although crystal oscillators are often preferred for their greater stability. Triangle-wave or saw tooth oscillators are used in the time base circuits that generate the horizontal deflection signals for cathode ray tubes in analogue oscilloscopes and television sets. In function generators, this triangle wave may then be further shaped into a close approximation of a sine wave. The multivibrator and the rotary traveling wave oscillator are other types of relaxation oscillators Variable-frequency oscillator VFO is an acronym for Variable Frequency Oscillator. A variable frequency oscillator is needed in any radio receiver or transmitter that works by the super heterodyne principle, and which can be tuned across various frequencies. Altering the frequency of the VFO will control the frequency to which the radio is tuned. 1. Why do radios need a VFO? 2. Analogue VFO 2.1 Tuning Capacitor 2.2 Varactor 3. Digital VFO 3.1 Digital Frequency Synthesis · 4. Performance 4.1 Accuracy 4.1.1 Stability 4.1.2 Repeatability 4.2 Purity 4.2.1 Spurii 4.2.2 Phase noise


4.3 Crystal control Why do radios need a VFO? In a simple superhet radio receiver, incoming radio frequencies from the antenna are made to mix (or multiply) with an internally generated radio frequency from the VFO in a process called mixing. The mixing process can produce a range of output signals: · · · · At all the original frequencies, At frequencies that are the sum of each two mixed frequencies At frequencies that equal the difference between two of the mixed frequencies At other, usually higher, frequencies. If the required incoming radio frequency and the VFO frequency were both rather high (RF) but quite similar, then by far the lowest frequency produced from the mixer will be their difference. In very simple radios, it is relatively straightforward to separate this from all the other spurious signals using a filter, to amplify it and then further to process it into an audible signal. In more complex situations, many enhancements and complications get added to this simple process, but this mixing or heterodyning principle remains at the heart of it. There are two main types of VFO in use: analogue and digital. Analogue VFO An analogue VFO could be an electronic oscillator where the value of at least one of the active components is adjustable under user control so as to alter its output frequency. The active component whose value is adjustable is usually a capacitor, but could be a variable inductor. Tuning Capacitor The variable capacitor is a mechanical device in which the separation of a series of interleaved metal plates is physically altered to vary its capacitance. Adjustment of this capacitor is sometimes facilitated by a mechanical step-down gearbox to achieve fine tuning. Varactor


A reversed-biased semiconductor diode exhibits capacitance. Since the width of its nonconducting depletion region depends on the magnitude of the reverse bias voltage, this voltage can be used to control the junction capacitance. The varactor bias voltage may be generated in a number of ways and there may need to be no significant moving parts in the final design. Varactor have a number of disadvantages including temperature drift and ageing , electronic noise, low Q factor and non-linearity. Digital VFO Modern radio receivers and transmitters usually use some from of digital frequency synthesis to generate their VFO signal. The advantages of this are manifold, including smaller designs, lack of moving parts, and the ease with which preset frequencies can be stored and manipulated in the digital computer that is usually embedded in the design for other purposes anyway. It is also possible for the radio to become extremely frequency-agile in that the control computer could alter the radio's tuned frequency many tens, thousands or even millions of times a second. This capability allows communications receivers effectively to monitor many channels at once, perhaps using digital selective calling (DSC) techniques to decide when to open an audio output channel and alert users to incoming communications. Pre-programmed frequency agility also forms the basis of some military radio encryption and stealth techniques. Extreme frequency agility lies at the heart of spread spectrum techniques that are currently gaining mainstream acceptance in computer wireless networking such as Wi-Fi. There are disadvantages to digital synthesis such as the inability of a digital synthesizer to tune smoothly through all frequencies, but with the channelisation of many radio bands, this can also be seen as an advantage in that it prevents radios from operating in between two recognized channels. Digital frequency synthesis almost always relies on crystal controlled frequency sources. Crystal controlled oscillators have enormous advantages over inductive and capacitively controlled ones in terms of stability and repeatability as well as low noise and high Q factor. The disadvantage comes when you try to alter the resonant frequency to tune the radio, but a wide range of digital techniques have made this unnecessary in modern practice.


Digital Frequency Synthesis The electronic and digital techniques involved in this include: · Direct Digital Synthesis (DDS): Enough data points for a mathematical sine

function are stored in digital memory. These are recalled at the right speed and fed to a digital to analogue converter where the required sine wave is built up. · Direct Frequency Synthesis: Early channelised communication radios had multiple

crystals - one for each channel on which they could operate. After a while this thinking was combined with the basic ideas of heterodyning and mixing described under #Why do radios need a VFO? Above. Multiple crystals can be mixed in various combinations to produce various output frequencies. · Phase Locked Loop (PLL): Using a Varactor-controlled or voltage-controlled

oscillator (VCO) (described above in Varactor under #Analogue VFO techniques) and a phase detector, a control-loop can be set up so that the VCO's output is frequency-locked to a crystal controlled reference oscillator. This would not be much use unless the phase detector's comparisons were made not between the actual outputs of the two oscillators, but between the outputs of each after frequency division by two slightly different divisors. Then by altering the frequency-division divisor(s) under computer control, a variety of actual (undivided) VCO output frequencies can be generated. It is this last, the PLL technique, that dominates most radio VFO design thinking today. Performance The performance of a radio's VFO strongly influences the performance of the radio itself. Accuracy It is useful if the frequency produced by the VFO is both stable and repeatable. Stability An unstable VFO's output frequency will drift with time. The root cause of this can often be traced to temperature dependency in some of the voltages and component values involved. Often as radios warm up it is necessary slightly to re-tune them to remain on frequency. Repeatability 52

Ideally, for the same selected radio channel, the VFO in your radio is generating exactly the same frequency today as it was on the day the radio was first assembled and tested. This will mean that any built-in errors seen that day during the manufacture will have been calibrated out, and this calibration will not have changed through to today. If this is not the case, then you will not be able entirely to trust your tuning dial. This would be a source of irritation on a receiver, where you may have to tune slightly off the known frequency to receive a certain station. The problem can be more serious in a transmitter as you could unwittingly and illegally be transmitting on a frequency for which you are not authorized or licensed. If you do so, it is your responsibility, and trying to blame your badly calibrated circuitry will be no defense. Purity You can imagine the shape of the VFO's frequency vs. amplitude graph to be the shape of the 'window' through which the radio receives (and in the case of a transmitter, through which it transmits when you ask it to transmit a pure sine-wave tone). In the ideal case, this frequency/amplitude plot is very simple, i.e. there is absolutely no output at any frequency except one, and plenty of pure output at exactly that frequency. In this ideal case, of course, the 'window' is unique and infinitely narrow. The ideal radio will receive and transmit only exactly what is expected. Spurii A VFO's frequency vs. amplitude graph (or Fourier analysis) may exhibit not one but several narrow peaks, probably harmonically related. Each of these other peaks can potentially mix with some other incoming signal and produce a spurious response. This spurii (sometimes spelt spuriae) result in you hearing two stations at once, even though the other is nowhere near this one on the band. The extra peaks may be many hundreds or thousands of times lower in value than the main one, but don't forget that the other, interfering station may be hundreds or thousands of times more powerful at the antenna than the one you are after.


In a transmitter, these spurious signals are actually generated along with the one you expect. If they are not completely filtered out before they are transmitted, then the licenseholder may again be in breach of the terms of his or her license. Phase noise When examined with very sensitive equipment, the pure sine-wave peak in a VFO's frequency graph will most likely turn out not to be sitting on a flat noise-floor. Slight random 'jitters' in the signal's timing will mean that the peak is sitting on 'skirts' of phase-noise at frequencies either side of the desired one, These are also troublesome in crowded bands. They allow through unwanted signals that are fairly close to the one we expect, but because of the random quality of these phase-noise 'skirts', the signals are usually unintelligible, appearing just as extra noise in the signal we are after. The effect is that what should be a clean signal in a crowded band can appear to be a very noisy signal, because of the effects of all the strong signals nearby. The effect of VFO phase noise on a transmitter is that random noise is actually transmitted either side of the required signal. Again, this must be avoided at all costs for legal reasons in many cases. Crystal control In all performances cases, crystal controlled oscillators are better behaved than the semiconductor- and LC-based alternatives. They tend to be more stable, more repeatable, have fewer and lower harmonics and lower noise than all the alternatives in their cost-band. This in part explains their huge popularity in low-cost and computer-controlled (i.e. PPL and synthesizer-based) VFOs Crystal oven A crystal oven is a temperature-controlled chamber used to maintain constant temperature of electronic crystals, in order to ensure stability of operation of an oscillator known as an Oven Controlled Crystal Oscillator or OCXO. It is typically used in broadcast and measurement applications where precise frequency of oscillation is critical to proper circuit operation.


The crystal is mounted within a thermally-insulated enclosure; the enclosure also contains one or more electric (resistive) heaters. Closed-loop control is used to modulate the heater and ensure that the crystal is heated to the specific temperature desired. Because the oven operates above ambient temperature, the crystal or oscillator within usually requires a warm-up period after power has been applied. During this warm-up period, the frequency may not be fully stable. Because of the power required power to run the heater, oscillators using crystal ovens require more power than oscillators that run at ambient temperature and the requirement for the heater, thermal mass, and thermal insulation means that oscillators using ovens are physically larger than their ambient counterparts. However, in return, the oven-controlled oscillator achieves the best frequency stability possible from a crystal. Achieving better performance requires switching to an atomically-stabilized technique such as a rubidium standard, cesium standard, or hydrogen maser.

4.1 Source Code:
#include<AT89X51.h> void lcd_cmd(unsigned char); void lcd_data(unsigned char); void lcd_convert(unsigned long); unsigned long count=0; unsigned int val=0; unsigned long sol; sbit rs sbit rw sbit en void main() { lcd_cmd(0x38); lcd_cmd(0x01); =P2^4; =P2^5; =P2^6;


lcd_cmd(0x84); lcd_cmd(0x0f); lcd_data ('0'); lcd_data ('0'); lcd_data ('0'); lcd_data ('0'); lcd_data ('0'); lcd_data ('0'); lcd_data ('0'); lcd_data ('0'); lcd_data ('0'); lcd_data ('0'); TMOD=0x16; IE=0x8A; IP = 0x02; TH0 = 0xff; TL0 = 0xff; TH1=TL1 =0; TR0=1; While (1); }

Void timer1 (void) interrupt 3 { Count++; }

Void counter0 (void) interrupt 1 {


EA=0; TR1=TR0=0; Val=TL1; Val = (TH1<<8); Sol=60000000/ (((65536*count) +Val)*1.085); lcd_convert (sol); Count=0; Val=0; TH1=TL1=0; TR1=TR0=1; EA=1; }

Void lcd_cmd (unsigned char dat) { Unsigned int c; P0=dat; rs =0; rw=0; en=1; for(c=0;c<2000;c++); en=0; }

void lcd_data(unsigned char dat) { unsigned int c; P0=dat; rw=0;


rs=en=1; for(c=0;c<2000;c++); en=0; }

void lcd_convert(unsigned long da) { unsigned long a,b,c,d,e,f,g,h,i,j,k,l,m,n; a=da/10; b=da%10; c=a/10; d=a%10; e=c/10; f=c%10; g=e/10; h=e%10; i=g/10; j=g%10; k=i/10; l=i%10; m=k%10; n=k/10; lcd_cmd(0x01); lcd_cmd(0x84); lcd_data(n|0x30); lcd_data(m|0x30); lcd_data(l|0x30); lcd_data(j|0x30); lcd_data(h|0x30);


lcd_data(f|0x30); lcd_data(d|0x30); lcd_data(b|0x30); }





APPENDIX: Kiel Compiler:
Kiel is an IDE(Integrated Development Environment) which is used to develop an application program , compile and run it Even the code can be debugged .It is a simulator where we can check the application code even in the absence of the hardware board. Kiel is also a cross compiler The process of development of the soft code on a processor for a particular application and which can be implemented on the target processor is known as Cross Development. In our design the main heart of the hardware module is the micro controller which is the programmable IC .The programming language used for developing the software to the micro controller is Embedded C /Assembly. The KEIL cross compiler is used to edit ,compile and debug this program Micro Flash programmer is used for burning the developed code on Kiel in to the micro controller Chip.


Software Development Cycle When you use the Kiel Software tools, the project development cycle is roughly the same as it is for any other software development project.

1. Create a project, select the target chip from the device database, and configure the tool settings. 2. Create source files in C or assembly. 3. Build your application with the project manager. 4. Correct errors in source files. 5. Test the linked application. µVision2 IDE: The µVision2 IDE combines project management, a rich-featured editor with interactive error correction, option setup, make facility, and on-line help. Use µVision2 to create your source files and organize them into a project that defines your target application. µVision2 automatically compiles, assembles, and links your embedded application and provides a single focal point for your development efforts. C51 Compiler & A51 Assembler: 62

Source files are created by the µVision2 IDE and are passed to the C51 Compiler or A51 assembler. The compiler and assembler process source files and create relocatable object files. The Keil C51 Compiler is a full ANSI implementation of the C programming language that supports all standard features of the C language. In addition, numerous features for direct support of the 8051 architecture have been added. The Keil A51 macro assembler supports the complete instruction set of the 8051 and all derivatives. µVision2 Debugger The µVision2 symbolic, source-level debugger is ideally suited for fast, reliable program debugging. The debugger includes a high-speed simulator that let you simulate an entire 8051 system including on-chip peripherals and external hardware. The attributes of the chip you use are automatically configured when you select the device from the Device Database. The µVision2 Debugger provides several ways for you to test your programs on real target hardware. _ Install the MON51 Target Monitor on your target system and download your program using the Monitor-51 interface built-in to the µVision2 Debugger. _ Use the Advanced GDI interface to attach use the µVision2 Debugger front end with your target system. _µVision2 Integrated Development Environment The µVision2 IDE is a Windows-based software development platform that combines a robust editor, project manager, and make facility. µVision2 supports all of the Kiel tools for the 8051 including the C compiler, macro assembler, linker/locator, and object-HEX converter. µVision2 helps expedite the development process of your embedded applications by providing the following: _ Full-featured source code editor, _ Device database for configuring the development tool setting, _ Project manager for creating and maintaining your projects, _ Integrated make facility for assembling, compiling, and linking your embedded applications, _ dialogs for all development tool settings, _ True integrated source-level Debugger with high-speed CPU and peripheral simulator, _ Advanced GDI interface for software debugging in the target hardware and for connection to Monitor51, _ Links to development tools manuals, device datasheets & user’s guides.


C51 Optimizing C Cross Compiler The Keil C51 Cross Compiler is an ANSI C Compiler that was written specifically to generate fast, compact code for the 8051 microcontroller family. The C51 Compiler generates object code that matches the efficiency and speed of assembly programming. Using a high-level language like C has many advantages over assembly language programming: _ Knowledge of the processor instruction set is not required. Rudimentary knowledge of the memory structure of the 8051 CPU is desirable (but not necessary). _ Details like register allocation and addressing of the various memory types and data types is managed by the compiler. _ Programs get a formal structure (which is imposed by the C programming language) and can be divided into separate functions. This contributes to source code reusability as well as better overall application structure. _ The ability to combine variable selection with specific operations improves program readability. _ Keywords and operational functions that more nearly resemble the human thought process may be used. _ Programming and program test time is drastically reduced. _ The C run-time library contains many standard routines such as: formatted output, numeric conversions, and floating-point arithmetic. _ Existing program parts can be more easily included into new programs because of modular program construction techniques. _ The language C is a very portable language (based on the ANSI standard) that enjoys wide popular support and is easily obtained for most systems. Existing program investments can be quickly adapted to other processors as needed. C51 Language Extensions Even though the C51 Compiler is ANSI-compliant, some extensions were added to support the facilities of the 8051 microprocessor. The C51 Compiler includes extensions for: _ Data Types, _ Memory Types, _ Memory Models,


_ Pointers, _ Reentrant Functions, _ Interrupt Functions, _ Real-Time Operating Systems, _ Interfacing to PL/M and A51 source files. Code Optimizations The C51 Compiler is an aggressive optimizing compiler that takes numerous steps to ensure that the code generated and output to the object file is the most efficient (smallest and/or fastest) code possible. The compiler analyzes the generated code to produce the most efficient instruction sequences. This ensures that your C program runs as quickly and effectively as possible in the least amount of code space. The C51 Compiler provides nine different levels of optimizing. Each increasing level includes the optimizations of levels below it. The following is a list of all optimizations currently performed by the C51 Compiler. General Optimizations _ Constant Folding: Constant values occurring in an expression or address calculation are combined as a single constant. _ Jump Optimizing: Jumps are inverted or extended to the final target address when the program efficiency is thereby increased. _ Dead Code Elimination: Code that cannot be reached (dead code) is removed from the program. _ Register Variables: Automatic variables and function arguments are located in registers whenever possible. No data memory space is reserved for these variables. _ Parameter Passing Via Registers: A maximum of three function arguments may be passed in registers. _ Global Common Sub expression Elimination: Identical sub expressions or address calculations that occur multiple times in a function are recognized and calculated only once whenever possible. _ Common Tail Merging: Common instruction blocks are merged together using jump instructions. _ Re-use Common Entry Code: Common instruction sequences are moved in front of a function to reduce code size.


_ Common Block Subroutines: Multiple instruction sequences are packed into subroutines. Instructions are rearranged to maximize the block size. 8051-Specific Optimizations _ Peephole Optimization: Complex operations are replaced by simplified operations when memory space or execution time can be saved as a result. _ Access Optimizing: Constants and variables are computed and included directly in operations. _ Extended Access Optimizing: The DPTR register is used as a register variable for memory specific pointers to improve code density. _ Data Overlaying: Function data and bit segments are OVERLAYABLE and are overlaid with other data and bit segments by the BL51 linker. _ Case/Switch Optimizing: Depending upon their number, sequence, and location, switch and case statements may be optimized using a jump table or string of jumps.

Options for Code Generation _ OPTIMIZE (SIZE): Common C operations are replaced by subprograms. Program code size is reduced at the expense of program speed. _ OPTIMIZE (SPEED): Common C operations are expanded in-line. Program speed is increased at the expense of code size. _ NOAREGS: Absolute register access is not used. Program code is independent of the register bank. _ NOREGPARMS: Parameter passing is performed in local data segments rather than dedicated registers. This is compatible with earlier versions of the C51 Compiler, the PL/M-51 compiler, and the ASM-51 assembler. Debugging: The C51 Compiler uses the Intel Object Format (OMF51) for object files and generates complete symbol information. Additionally, the compiler can include all the necessary information such


as; variable names, function names, line numbers, and so on to allow detailed and thorough debugging and analysis with the µVision2 Debugger or any Intel-compatible emulators. In addition, the OBJECTEXTEND control directive embeds additional variable type information in the object file that allows type-specific display of variables and structures when using certain emulators.You should check with your emulator vendor to determine if it is compatible with the Intel OMF51 object module format and if it can accept Keil object modules. A51 Macro Assembler The A51 Assembler is a macro assembler for the 8051 microcontroller family. It translates symbolic assembler language mnemonics into executable machine code. The A51 Assembler allows you to define each instruction in an 8051 program and is used where utmost speed, small code size, and exact hardware control is essential. The assembler’s macro facility saves development and maintenance time since common sequences need only be developed once. Source-Level Debugging The A51 Assembler generates complete line number, symbol, and type information in the object file created. This allows exact display of program variables in your debugger. Line numbers are used for source-level debugging of your assembler programs with the µVision2 Debugger or third-party emulator. Functional Overview The A51 Assembler translates an assembler source file into a relocatable object module. It generates a listing file optionally with symbol table and cross reference. The A51 Assembler supports two different macro processors: _ The Standard Macro Processor is the easier macro processor to use. It allows you to define and use macros in your 8051 assembly programs. The standard macro syntax is compatible with that used in many other assemblers. _ The Macro Processing Language (MPL) is a string replacement facility that is fully compatible with the Intel ASM51 macro processor. MPL has several predefined macro processor functions that perform many useful operations like string manipulation or number processing. Another powerful feature of the A51 Assembler macro processors is conditional assembly depending on command line directives or


assembler symbols. Conditional assembly of sections of code can help you achieve the most compact code possible. It also allows you to generate different applications from one assembly source file. ASSEMBLY VS C: • The assembly code is difficult to read and maintain. • The amount of code reusable from assembly code is very low. •C programs are easy to read, understand, maintain , because it possesses greater structure. • With C the programmer need not know the architecture of the processor. • Code developed in C will be more portable to other systems rather than in assembly.

Difference between Conventional C and Embedded C: • Compliers for conventional C are TC, BC • Compilers for Embedded C are keil µvision - 2 & 3, PIC C etc. • Conventional C programs needs complier to compile the program & run it. • The embedded C program needs a cross compiler to compile & generate HEX code. • The programs in C are basically processor dependent whereas Embedded C programs are micro controller dependent. •The C program is used for developing an application and not suitable for embedded systems. • The embedded C is an extension of the conventional C. i.e Embedded C has all the features of normal C, but has some extra added features which are not available in C. • Many functions in C do not support Reentrant concept of functions. •C is not memory specific. i.e variables cannot be put in the desired memory location but the location of variable can be found out. • In embedded C this can be done using specific inbuilt instructions. •C depends on particular processor or application. • Embedded C is Controller or target specific. • Embedded C allows direct communication with memory. Why C for Micro controllers:


• Compatibility • Direct access to hardware address • Direct connection to interrupts • Optimization consideration • Development environment • Reentrancy Rules for developing Embedded C Program: • Code Optimization. 1. Minimize local variables If the number of local variables in a function is less, the compiler will be able to fit them into registers. Hence, it will be avoiding frame pointer operations on local variables that are kept on stack. This can result in considerable improvement due to two reasons: •All local variables are in registers so this improves performance over accessing them from memory. •If no local variables need to be saved on the stack, the compiler will not incur the overhead of setting up and restoring the frame pointer. 1. Declare local variables in the inner most scope • Do not declare all the local variables in the outermost function scope. • If local variables are declared in the inner most scope. • If the parameter was declared in the outermost scope, all function calls would have incurred the overhead of object. • Place case labels in narrow range • If the case labels are in a narrow range, the compiler does not generate a if-else-if cascade for the switch statement. • Instead, it generates a jump table of case labels along with manipulating the value of the switch to index the table. • This code generated is faster than if-else-if cascade code that is generated in cases where the case labels are far apart. • Also, performance of a jump table based switch statement is independent of the number of case entries in switch statement.


Reduce the number of parameters Function calls with large number of parameters may be expensive due to large number of parameter pushes on stack on each call. For the same reason, avoid passing complete structures as parameters. Use pointers and references in such cases. Use references for parameter passing and return value for types bigger than 4 bytes Passing parameters by value results in the complete parameter being copied on to the stack. This is fine for regular types like integer, pointer etc. These types are generally restricted to four bytes. When passing bigger types, the cost of copying the object on the stack can be prohibitive. When the function exits the destructor will also be invoked. Thus it is efficient to pass references as parameters. This way you save on the overhead of a temporary object creation, copying and destruction. This optimization can be performed easily without a major impact to the code by Replacing pass by value parameters by const references. (It is important to pass const references so that a bug in the called function does not change the actual value of the parameter. Passing bigger objects as return values also has the same performance issues. A temporary return object is created in this case too. •Use All the SFR’s in capital letters only. •Reduce the warnings in the program. •Make use of MACRO definitions in the program. •Always define the variables in the code memory by using the keyword code in declaration. •Eg unsigned int code a[] = { }; •Always define as unsigned type of declaration. •Make use of sbit definition for single bit declaration. •Eg sbit rs = P3^6; •Since these are not floating point co-processor, no decimal values can be given as input to them. • So we cannot define the above declaration as sbit rs = P3.6. • The declaration like this below are invalid. P3^6 = 0; • P3^6 is bit addressable type & 0 is a 8 bit data which cannot be


stored in single bit. • Permanent termination of the program is got by using while(1);