Top Banner

of 73

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript

Over Flux Protection Of Distribution TransformerA transformer is designed to operate at or below a maximum magnetic flux density in the transformer core. Above this design limit the eddy currents in the core and nearby conductive components cause overheating which within a very short time may cause severe damage. The magnetic flux in the core is proportional to the voltage applied to the winding divided by the impedance of the winding. The flux in the core increases with either increasing voltage or decreasing frequency. During start-up or shut down transformers, or following a load rejection, the transformer may experience an excessive ratio of volts to hertz, that is, become overexcited. In our project we can vary the voltage by using potentiometer and frequency can be increased or decreased if its occurs the load will be automatically tripped off for transformer protection.

Components Used: Transformer Microcontroller ADC Relay LOAD

Block diagram

LCD

555

Micro Controller

ADC

Relay

Current Transformer

Potential Transformer

Load

Introduction: Over flux Protection Transformer over fluxing can be a result of Overvoltage Low system frequency A transformer is designed to operate at or below a maximum magnetic flux density in the transformer core. Above this design limit the eddy currents in the core and nearby conductive components cause overheating which within a very short time may cause severe damage. The magnetic flux in the core is proportional to the voltage applied to the winding divided by the impedance of the winding. The flux in the core increases with either increasing voltage or decreasing frequency. During start up or shutdown of generatorconnected transformers, or following a load rejection, the transformer may experience an excessive ratio of volts to hertz, that is, become overexcited. When a transformer core is

overexcited, the core is operating in a non-linear magnetic region, and creates harmonic components in the exciting current.

Block Explanation: Microcontroller: Here microcontroller act as a brain to monitor the overvoltage & overflow flux maintenance. The analog parameters from the transformer are processed in the controller and then send to the LCD. Here we are using Atmel company microcontroller consists of 40 pins

Transformers: A transformer is an electrical device that transfers energy from one electrical circuit to another by magnetic coupling, where relative motion between the parts is not required to transfer energy between the circuits. It is often used to convert between high and low voltages, for impedance transformation, and to provide electrical isolation between circuits Current transformers: A current transformer is designed to provide a current in its secondary which is accurately proportional to the current flowing in its primary. Current transformers are commonly used in electricity meters to facilitate the measurement of large currents which would be difficult to measure more directly. Potential transformers: Voltage transformers (also known as potential transformers) are used in the electricity supply industry to measure accurately the voltage being supplied. They are designed to present negligible load to the voltage being measured. Analog to digital converter:

ADC are widely used device for data acquisition Here the electrical (analog)parameters are converted into digital data by the ADC and then send to the controller for further process. Here we are using ADC0808/0809 Relay: Relays are components which allow a low-power circuit to switch a relatively high current on and off, or to control signals that must be electrically isolated from the controlling circuit itself. To make a relay operate, you have to pass a suitable pull-in and holding current (DC) through its energising coil. And generally relay coils are designed to operate from a particular supply voltage often 12V or 5V

LCD:LCD is used to display the overvoltage tripping & overflow flux tripping. We are using 2*7 matrix 14 pin LCD

EMBEDDED SYSTEM Embedded System is a combination of hardware and software used to achieve a single task. It is a computer system that monitor respond to, or control an external environment. Environment are connected to systems through sensors, actuators and other I/O interfaces. Embedded system must meet timing and other constraints imposed on it by environment An Embedded system is a component within some larger system. It is contrast with general-purpose computers. The software in the embedded system is called firmware. An Embedded system is an intelligent firmware designed for a definite process to be achieved perfectly. An Embedded system in general incorporates hardware,

operating system, peripheral devices and communication software to enable to perform the predefined functions.

CHARACTERISTICS OF EMBEDDED SYSTEM In-built Intelligence. Immediate control of hardware. Uses dedicated software. Performs a specific function. Processing power and Memory limitations. Respond to external events. Timeliness, Robustness/Safety.

CLASSIFICATION OF EMBEDDED SYSTEM: REAL TIME SYSTEMS: RTS is one, which has to respond to events within a specified deadline. A right answer after the dead line is a wrong answer. RTS are sometimes classified into three categories: Hard Real Time System. Soft Real Time System. Firm Real Time System. HARD REAL TIME SYSTEMS: "Hard" real-time systems have very narrow response time The correctness of response includes a description of timeliness Deadlines are specified as points in time that occur as a fixed time interval following an event. Example: Nuclear power system, Cardiac pacemaker.

SOFT REAL TIME SYSTEM: "Soft" real-time systems have reduced constrains on "lateness" but still must operate very quickly and repeatable. Soft timeliness requirements are specified as time constraints that may be violated to some degree, without affecting the correctness of the systems behavior. Example: Railway reservation system extra seconds the data remains valid. If a single computation is late, it is not usually significant, although consistently late computation can result in system failure. Throughput may be specified as an average response time or bandwidth or as a bounded mean lateness.

FIRM REAL TIME SYSTEM: Firm deadlines are a combination of both hard and soft timeliness requirements. The computation has a short storage soft requirement and a longer hard requirement. A patient ventilator must mechanically ventilate the patient, a certain amount in the longer run. A breath could come a few seconds late without affecting patient a certain amount in the long run.

MICROCONTROLLER

A microcontroller (also MCU or C) is a functional computer system-on-a-chip. It contains a processor core, memory, and programmable input/output peripherals. Microcontrollers include an integrated CPU, memory (a small amount of RAM, program memory, or both) and peripherals capable of input and output. Microcontrollers are used in automatically controlled products and devices.

BASICS: A designer will use a Microcontroller to RAM: Random access memory. Ram is a volatile (change) memory. It general purpose memory that can store data or programs. Ex: hard disk, USB device. Gather input from various sensors Process this input into a set of actions Use the output mechanisms on the Microcontroller to do something useful.

MEMORY TYPES:

ROM: Read only memory. Rom is a non volatile memory. This is typically that is programmed at the factory to have certain values it cannot be changed. Ex: cd...

ARCHITECTURE OF AT89C51

8051 Architecture: 8051 Architecture contains the following: CPU

ALU I/O ports RAM ROM 2 Timers/Counters General Purpose registers Special Function registers Crystal Oscillators Serial ports Interrupts PSW Program Counter Stack pointer

Pin Description:

8051 contains 40 pins 32 Pins are used for I/O purpose 2 Pins for crystal oscillator to produce clock 2 Pins for Supply and ground

1 Pins for reset the controller Port 0: Port 0 occupies a total of 8 pins. It can be used for input or output. To use the pins of port 0 as both input and output ports. Each pin must be connected externally to 10K ohm pull-up resisters. This is due to the fact that P0 is an open drain. Port 1: Port 1 occupies a total of 8 pins. It can be used as input or output .In contrast to port 0, this port does not need any pull up resisters since it already has pull up resisters internally. To make port 1 an input port, it must be programmed as such by writing 1 to all its bits. Port 2: Port 2 occupies a total of 8 pins. It can be used as input or output. It already has pull-up resisters internally. To make port 2 an input, it must be programmed as such by writing 1 to all its bits. Port 3: Port 3 occupies a total of 8 pins. It can be used as input or output. Port 3 has the additional function of providing some extremely important signals such as interrupts.

Architecture: Two types of architecture are followed. I. Van-Neuman Architecture: The width of address and data bus is same. II. Haward Architecture: The bus width of address and data may not be same. Pipelinining is possible here. Microcontrollers have built-in peripherals, they are, 1) Memory a. Program memory (Eg. PROM, Flash memory) b. Data Memory (Eg. RAM, EEROM) 2. I/O Ports 3. ADC 4. Timers 5. USART 6. Interrupt controllers PWM/Capture

TIMER 1,2 I N MEMORY T E R CPU R U P T SLAVE TIMER 0 ADC PARALLEL SPI I2C UART P O R T I/ O

Peripheral Feature: The PIC 16F877A has five serial ports namely A, B, C, D and E. It has five parallel ports namely: 1. 2. 3. 4. 5. o o PSP (Parallel Slave Port 8 bit wide) SSP (Serial Synchronous Port) MSP (Master Serial Synchronous Port) I^2C (Iter Integrated Circuit) SPI (Serial Peripheral Interface) 256 8 bytes data memory 8k 14 words program memory It has three timer Timer 0 8 bit timer Timer 1 16 bit timer

o 12 bit 10 channel o o Sleep mode processor

Timer 2 8 bit timer

12 bit accuracy No external hardware multiplexer is needed

No power will be consumed during ideal condition Built in temperature sensor Built in RAM and EPROM RAM is used to control ADC.MSB is stored in RAM when LSB is outputted. PWM: Two captures PWM module. PWM used as DAC. Programmable Low voltage detection Circuitry. USART: Universal Synchronous Asynchronous Receiver and Transmitter. It converts serial data into parallel and vice versa. For instrumentation standard MAX 485 data converter should be used. This external data converter amplifies the incoming 5V (from PIC) by four times and gives 20V output i.e. -10V to +10V. Similarly, incoming 20V (from PC) is reduced as 5V by the same MAX 485 converter. MAX 485 can be replaced by MAX 232 for computer standard. This is known as Quader-Puller action. Key Features PIC micro-range Reference Manual(DS PIC 16F873 33023) Operating Frequency DC-20 MHz Resets(and Delays) POR,BOR (PWRT,OST) FLASH Program Memory 4K (14-bit words) Data Memory(bytes) 192 EEPROM Data Memory 192 Interrupts 13 I/O Ports Ports A,B,C Timers Captures/Compare/PWM modules Serial Communications 3 2 MSSP,USAR

PIC16F874 DC20 MHz POR,BOR (PWRT,OST) 4K 192 192 14 PortsA,B,C,D, E 3 2

PIC16F876 DC20 MHz POR,BOR (PWRT,OST) 8K 368 256 13 Ports A,B,C 3 2

PIC16F877 DC20 MHz POR,BOR (PWRT,OST) 8K 368 256 14 Ports A,B,C,D,E 3 2

MSSP,USART MSSP,USART MSSP,USART

T Parallel Communications -10-bit Analog-to-Digital 5 input Module channels Instruction 35 Instructions

PSP 8 input channels 35 Instructions

-5 input channels 35 Instructions

PSP 8 input channels 35 Instructions

General Features: High Performance RISC CPU Only 35 instructions are available, hence easy programming is possible which increase the processing speed. Operating speed: 9600 baud rate Power on Reset Whenever the PIC is reset, the program counter reaches the known address. Watch Dog Timer It is used to find Communication Error with its own on chip RC oscillator for reliable operation. Low Power Consumption High sink/Source Current The output of the Embedded Controller can be used to drive printer, relays, solenoid valves etc. No need of driver circuit. Compatible to all computer language No need of DLL (Dynamic Link Library) Design Features: Individual power supply for Analog and Digital circuits is required to avoid drift on analog portion. Double regulated filtered reference source is needed to ensure safest ADC operation. External clock source must be used which enables the user to design the required speed.

External CPU Synchronous circuit must be designed incase of PC requirement.Switch is used to synchronize the Embedded Controller with the PC to get COMOK signal. External RS-232 should be used for data conversion. Memory Organization: There are two memory blocks in PIC microcontroller. Each block has its own bus so that concurrent access can occur. 1. Program memory 2. Data memory Program memory Organization: PIC 87 has a 13 bit program counter capable of addressing 8k 14 program memory space. Each device has 4k 14 words of program space. The reset vector is at 000H Receiving Interrupt vector is at 0004H PIC has hardware stack with 8 bit width. It needs jump instruction to access subroutines. Push and Pop instructions cannot be used since there is no software stack is available. Program memory is organized as page 0, page 1 up to page 3 each having 2k memories. Page address should be mentioned in PC latch for executing the instructions available in some other pages. Program memory Organization:

0000H Reset Vector 000 4H 0005H 07FFH 0800H Interrupt Vector Page 0 Page 1 0FFFH 1000H 3FFFH Page 2 Page 3 Stack level 8 Program counter

Stack level 1 On-chip Program memory Stack level 2

Data Memory Organization:

RP1 0 0 1 1

RP0 0 1 0 1

Bank no 0 1 2 3

The data memory is partitioned into multiple banks which contain general purpose registers and special function registers. Each bank extends up to 7FH (128 bytes).The lower location of each bank are reserved for the special function register. Above the special function registers are general purpose registers, implemented as Static RAM. In all banks the bottom most 16 bits are called accessed irrespective of the bank number.

Data Memory Organization

00 GPR 1F 20 GPR

00 1F 20 GPR

00 1F 20 GPR

SFR 70 71 Access bank BANK 0 Status Register : 7F

SFR 70 71 Access bank BANK 1 7F

SFR 70 71 Access bank BANK 2 7F

SFR

Access bank BANK 3

The status register contains arithmetic status of ALU, Reset and bank select bits for data memory. The bits Z, DC, C are set or reset according to the device logic. IRP RP1 RP0 TO PD Z DC C

IRP 1 0 RP1.RP0 TO 1 0 PD 1 0 Z 1 0 DC 1 0

-

Register Bank Selected bit. Bank 2&3 Bank 0 &1 Bank selection bits Time Out bit After Power Up, CLRWDT instruction or SLEEP instruction A WDT time out occurred Power Down bit After power up or by the CLRWDT instruction By execution of the SLEEP instruction Zero bit The result of on arithmetic or logic operation is zero The result of on arithmetic or logic operation is not zero Digit carry / borrow bit A carry out from the 4th low order bit of the result occurred No carry out from the 4th low order bit the result.

C 1 0

-

Carry / borrow bit A carry out from the most significant bit of the result occurred No carry-out from the most significant bit of the result occurred.

INTCON REGISTER: The INTCON register is a readable and writable register which contains various enable and flag bits for the TMRO register overflow, RB port change and external RBO/INT pin interrupts. GIE PEIE TOIE INTE RBIE TOIF INTF RBIF

Bit 7

:

Bit 6 Bit 5 Bit 4

: : :

GIE 1 0 PEIE 1 0 TOIE 1 0 INTE 1 0

-

Global interrupt Enable bit Enables all un masked interrupts Disable all interrupts Peripheral interrupts Enable bit Enables all un un masked peripheral interrupts Disable all peripheral interrupts TMRO Overflow Interrupt Enable bit Enables the TMRO interrupt Disable the TMRO interrupt RBO/INT External interrupt Enable bit Enables the RBO/INT external interrupt Disable the RBO/ external Interrupt RB port change Interrupt Enable bit Enables the RB port change interrupt Disable the RB port change interrupt TMRO Overflow Interrupt Flag bit TMRO register has overflowed TMRO register did not over flow RBO/INT Enable Interrupt Flag bit The RBO/INT external Interrupt occurred The RBO/INT external interrupt did not occur RB port Change Interrupt Flag bit At least one of the RB7 : RB4 pins changed sate None of the RB7 : RB4 pins have changed state

Bit 3 Bit 2 Bit 1 Bit 0

:

RBIE 1 0 : TOIF 1 0 : INTF 1 0 : RBIF 1 0

OPTION REGISTER: RBPU INTEDG TOCS TOSE PSA PS2 PS1 PS0

RBPU INTEDG TOCS TOSE PSA 0 1

-

Weak pull up Enable bit Interrupt Edge select bit Timer0 clock source select bit Timer0 source edge select bit Pre scalar Assignment bit Timer 0 is enabled Watch dog timer is enabled Pre scalar

PS2, PS1, PS0 -

8051 Addressing Modes An "addressing mode" refers to how you are addressing a given memory location. In summary, the addressing modes are as follows, with an example of each: Immediate Addressing MOV A,#20h Direct Addressing MOV A,30h Indirect Addressing MOV A,@R0 External Direct MOVX A,@DPTR Code Indirect MOVC A,@A+DPTR Each of these addressing modes provides important flexibility. Immediate Addressing Immediate addressing is so-named because the value to be stored in memory immediately follows the operation code in memory. That is to say, the instruction itself dictates what value will be stored in memory. For example, the instruction: MOV A,#20h This instruction uses Immediate Addressing because the Accumulator will be loaded with the value that immediately follows; in this case 20 (hexidecimal).

Immediate addressing is very fast since the value to be loaded is included in the instruction. However, since the value to be loaded is fixed at compile-time it is not very flexible. Direct Addressing Direct addressing is so-named because the value to be stored in memory is obtained by directly retrieving it from another memory location. For example: MOV A,30h This instruction will read the data out of Internal RAM address 30 (hexidecimal) and store it in the Accumulator. Direct addressing is generally fast since, although the value to be loaded isnt included in the instruction, it is quickly accessable since it is stored in the 8051s Internal RAM. It is also much more flexible than Immediate Addressing since the value to be loaded is whatever is found at the given address--which may be variable. Also, it is important to note that when using direct addressing any instruction which refers to an address between 00h and 7Fh is referring to Internal Memory. Any instruction which refers to an address between 80h and FFh is referring to the SFR control registers that control the 8051 microcontroller itself. The obvious question that may arise is, "If direct addressing an address from 80h through FFh refers to SFRs, how can I access the upper 128 bytes of Internal RAM that are available on the 8052?" The answer is: You cant access them using direct addressing. As stated, if you directly refer to an address of 80h through FFh you will be referring to an SFR. However, you may access the 8052s upper 128 bytes of RAM by using the next addressing mode, "indirect addressing." Indirect Addressing Indirect addressing is a very powerful addressing mode which in many cases provides an exceptional level of flexibility. Indirect addressing is also the only way to access the extra 128 bytes of Internal RAM found on an 8052. Indirect addressing appears as follows: MOV A,@R0 This instruction causes the 8051 to analyze the value of the R0 register. The 8051 will then load the accumulator with the value from Internal RAM which is found at the address indicated by R0. For example, lets say R0 holds the value 40h and Internal RAM address 40h holds the value 67h. When the above instruction is executed the 8051 will check the value of R0.

Since R0 holds 40h the 8051 will get the value out of Internal RAM address 40h (which holds 67h) and store it in the Accumulator. Thus, the Accumulator ends up holding 67h. Indirect addressing always refers to Internal RAM; it never refers to an SFR. Thus, in a prior example we mentioned that SFR 99h can be used to write a value to the serial port. Thus one may think that the following would be a valid solution to write the value 1 to the serial port: MOV R0,#99h ;Load the address of the serial port MOV @R0,#01h ;Send 01 to the serial port -- WRONG!! This is not valid. Since indirect addressing always refers to Internal RAM these two instructions would write the value 01h to Internal RAM address 99h on an 8052. On an 8051 these two instructions would produce an undefined result since the 8051 only has 128 bytes of Internal RAM. External Direct External Memory is accessed using a suite of instructions which use what I call "External Direct" addressing. I call it this because it appears to be direct addressing, but it is used to access external memory rather than internal memory. There are only two commands that use External Direct addressing mode: MOVXA,@DPTR MOVX @DPTR,A As you can see, both commands utilize DPTR. In these instructions, DPTR must first be loaded with the address of external memory that you wish to read or write. Once DPTR holds the correct external memory address, the first command will move the contents of that external memory address into the Accumulator. The second command will do the opposite: it will allow you to write the value of the Accumulator to the external memory address pointed to by DPTR. External Indirect External memory can also be accessed using a form of indirect addressing which I call External Indirect addressing. This form of addressing is usually only used in relatively small projects that have a very small amount of external RAM. An example of this addressing mode is: MOVX @R0,A Once again, the value of R0 is first read and the value of the Accumulator is written to that address in External RAM. Since the value of @R0 can only be 00h through FFh the project would effectively be limited to 256 bytes of External RAM. There are relatively simple hardware/software tricks that can be implemented to access more than 256 bytes of memory using External Indirect addressing; however, it is usually easier to use External Direct addressing if your project has more than 256 bytes of External RAM.

8051 Program Flow When an 8051 is first initialized, it resets the PC to 0000h. The 8051 then begins to execute instructions sequentially in memory unless a program instruction causes the PC to be otherwise altered. There are various instructions that can modify the value of the PC; specifically, conditional branching instructions, direct jumps and calls, and "returns" from subroutines. Additionally, interrupts, when enabled, can cause the program flow to deviate from its otherwise sequential scheme. Conditional Branching The 8051 contains a suite of instructions which, as a group, are referred to as "conditional branching" instructions. These instructions cause program execution to follow a nonsequential path if a certain condition is true. Take, for example, the JB instruction. This instruction means "Jump if Bit Set." An example of the JB instruction might be: JB 45h,HELLO NOP HELLO: .... In this case, the 8051 will analyze the contents of bit 45h. If the bit is set program execution will jump immediately to the label HELLO, skipping the NOP instruction. If the bit is not set the conditional branch fails and program execution continues, as usual, with the NOP instruction which follows. Conditional branching is really the fundamental building block of program logic since all "decisions" are accomplished by using conditional branching. Conditional branching can be thought of as the "IF...THEN" structure in 8051 assembly language. An important note worth mentioning about conditional branching is that the program may only branch to instructions located withim 128 bytes prior to or 127 bytes following the address which follows the conditional branch instruction. This means that in the above example the label HELLO must be within +/- 128 bytes of the memory address which contains the conditional branching instruction. Direct Jumps While conditional branching is extremely important, it is often necessary to make a direct branch to a given memory location without basing it on a given logical decision. This is equivalent to saying "Goto" in BASIC. In this case you want the program flow to continue at a given memory address without considering any conditions. This is accomplished in the 8051 using "Direct Jump and Call" instructions. As illustrated in the last paragraph, this suite of instructions causes program flow to change unconditionally.

Consider the example: LJMP NEW_ADDRESS . . . NEW_ADDRESS: .... The LJMP instruction in this example means "Long Jump." When the 8051 executes this instruction the PC is loaded with the address of NEW_ADDRESS and program execution continues sequentially from there. The obvious difference between the Direct Jump and Call instructions and the conditional branching is that with Direct Jumps and Calls program flow always changes. With conditional branching program flow only changes if a certain condition is true. It is worth mentioning that, aside from LJMP, there are two other instructions which cause a direct jump to occur: the SJMP and AJMP commands. Functionally, these two commands perform the exact same function as the LJMP command--that is to say, they always cause program flow to continue at the address indicated by the command. However, SJMP and AJMP differ in the following ways:

The SJMP command, like the conditional branching instructions, can only jump to an address within +/- 128 bytes of the SJMP command. The AJMP command can only jump to an address that is in the same 2k block of memory as the AJMP command. That is to say, if the AJMP command is at code memory location 650h, it can only do a jump to addresses 0000h through 07FFh (0 through 2047, decimal).

You may be asking yourself, "Why would I want to use the SJMP or AJMP command which have restrictions as to how far they can jump if they do the same thing as the LJMP command which can jump anywhere in memory?" The answer is simple: The LJMP command requires three bytes of code memory whereas both the SJMP and AJMP commands require only two. Thus, if you are developing an application that has memory restrictions you can often save quite a bit of memory using the 2-byte AJMP/SJMP instructions instead of the 3-byte instruction. Recently, I wrote a program that required 2100 bytes of memory but I had a memory restriction of 2k (2048 bytes). I did a search/replace changing all LJMPs to AJMPs and the program shrunk downto 1950 bytes. Thus, without changing any logic whatsoever in my program I saved 150 bytes and was able to meet my 2048 byte memory restriction. NOTE: Some quality assemblers will actually do the above conversion for you automatically. That is, theyll automatically change your LJMPs to SJMPs whenever possible. This is a nifty and very powerful capability that you may want to look for in an assembler if you plan to develop many projects that have relatively tight memory restrictions.

Direct Calls Another operation that will be familiar to seasoned programmers is the LCALL instruction. This is similar to a "Gosub" command in Basic. When the 8051 executes an LCALL instruction it immediately pushes the current Program Counter onto the stack and then continues executing code at the address indicated by the LCALL instruction. Returns from Routines Another structure that can cause program flow to change is the "Return from Subroutine" instruction, known as RET in 8051 Assembly Language. The RET instruction, when executed, returns to the address following the instruction that called the given subroutine. More accurately, it returns to the address that is stored on the stack. The RET command is direct in the sense that it always changes program flow without basing it on a condition, but is variable in the sense that where program flow continues can be different each time the RET instruction is executed depending on from where the subroutine was called originally. Interrupts An interrupt is a special feature which allows the 8051 to provide the illusion of "multitasking," although in reality the 8051 is only doing one thing at a time. The word "interrupt" can often be subsituted with the word "event." An interrupt is triggered whenever a corresponding event occurs. When the event occurs, the 8051 temporarily puts "on hold" the normal execution of the program and executes a special section of code referred to as an interrupt handler. The interrupt handler performs whatever special functions are required to handle the event and then returns control to the 8051 at which point program execution continues as if it had never been interrupted. The topic of interrupts is somewhat tricky and very important. For that reason, an entire chapter will be dedicated to the topic. For now, suffice it to say that Interrupts can cause program flow to change. 8051 Tutorial: Instruction Set, Timing, and Low-Level Info In order to understand--and better make use of--the 8051, it is necessary to understand some underlying information concerning timing. The 8051 operates based on an external crystal. This is an electrical device which, when energy is applied, emits pulses at a fixed frequency. One can find crystals of virtually any

frequency depending on the application requirements. When using an 8051, the most common crystal frequencies are 12 megahertz and 11.059 megahertz--with 11.059 being much more common. Why would anyone pick such an odd-ball frequency? Theres a real reason for it--it has to do with generating baud rates and well talk more about it in the Serial Communication chapter. For the remainder of this discussion well assume that were using an 11.059Mhz crystal. Microcontrollers (and many other electrical systems) use crystals to syncrhronize operations. The 8051 uses the crystal for precisely that: to synchronize its operation. Effectively, the 8051 operates using what are called "machine cycles." A single machine cycle is the minimum amount of time in which a single 8051 instruction can be executed. although many instructions take multiple cycles. A cycle is, in reality, 12 pulses of the crystal. That is to say, if an instruction takes one machine cycle to execute, it will take 12 pulses of the crystal to execute. Since we know the crystal is pulsing 11,059,000 times per second and that one machine cycle is 12 pulses, we can calculate how many instruction cycles the 8051 can execute per second: 11,059,000 / 12 = 921,583 This means that the 8051 can execute 921,583 single-cycle instructions per second. Since a large number of 8051 instructions are single-cycle instructions it is often considered that the 8051 can execute roughly 1 million instructions per second, although in reality it is less--and, depending on the instructions being used, an estimate of about 600,000 instructions per second is more realistic. For example, if you are using exclusively 2-cycle instructions you would find that the 8051 would execute 460,791 instructions per second. The 8051 also has two really slow instructions that require a full 4 cycles to execute--if you were to execute nothing but those instructions youd find performance to be about 230,395 instructions per second. It is again important to emphasize that not all instructions execute in the same amount of time. The fastest instructions require one machine cycle (12 crystal pulses), many others require two machine cycles (24 crystal pulses), and the two very slow math operations require four machine cycles (48 crystal pulses). NOTE: Many 8051 derivative chips change instruction timing. For example, many optimized versions of the 8051 execute instructions in 4 oscillator cycles instead of 12; such a chip would be effectively 3 times faster than the 8051 when used with the same 11.059 Mhz crystal. Since all the instructions require different amounts of time to execute a very obvious question comes to mind: How can one keep track of time in a time-critical application if we have no reference to time in the outside world? Luckily, the 8051 includes timers which allow us to time events with high precision-which is the topic of the next chapter.

8051 Timers The 8051 comes equipped with two timers, both of which may be controlled, set, read, and configured individually. The 8051 timers have three general functions: 1) Keeping time and/or calculating the amount of time between events, 2) Counting the events themselves, or 3) Generating baud rates for the serial port. The three timer uses are distinct so we will talk about each of them separately. The first two uses will be discussed in this chapter while the use of timers for baud rate generation will be discussed in the chapter relating to serial ports. How does a timer count? How does a timer count? The answer to this question is very simple: A timer always counts up. It doesnt matter whether the timer is being used as a timer, a counter, or a baud rate generator: A timer is always incremented by the microcontroller. Programming Tip: Some derivative chips actually allow the program to configure whether the timers count up or down. However, since this option only exists on some derivatives it is beyond the scope of this tutorial which is aimed at the standard 8051. It is only mentioned here in the event that you absolutely need a timer to count backwards, you will know that you may be able to find an 8051compatible microcontroller that does it. USING TIMERS TO MEASURE TIME Obviously, one of the primary uses of timers is to measure time. We will discuss this use of timers first and will subsequently discuss the use of timers to count events. When a timer is used to measure time it is also called an "interval timer" since it is measuring the time of the interval between two events. How long does a timer take to count? First, its worth mentioning that when a timer is in interval timer mode (as opposed to event counter mode) and correctly configured, it will increment by 1 every machine cycle. As you will recall from the previous chapter, a single machine cycle consists of 12 crystal pulses. Thus a running timer will be incremented: 11,059,000 / 12 = 921,583 921,583 times per second. Unlike instructions--some of which require 1 machine cycle, others 2, and others 4--the timers are consistent: They will always be incremented once per machine cycle. Thus if a timer has counted from 0 to 50,000 you may calculate: 50,000 / 921,583 = .0542 .0542 seconds have passed. In plain English, about half of a tenth of a second, or onetwentieth of a second.

Obviously its not very useful to know .0542 seconds have passed. If you want to execute an event once per second youd have to wait for the timer to count from 0 to 50,000 18.45 times. How can you wait "half of a time?" You cant. So we come to another important calculation. Lets say we want to know how many times the timer will be incremented in .05 seconds. We can do simple multiplication: .05 * 921,583 = 46,079.15. This tells us that it will take .05 seconds (1/20th of a second) to count from 0 to 46,079. Actually, it will take it .049999837 seconds--so were off by .000000163 seconds-however, thats close enough for government work. Consider that if you were building a watch based on the 8051 and made the above assumption your watch would only gain about one second every 2 months. Again, I think thats accurate enough for most applications--I wish my watch only gained one second every two months! Obviously, this is a little more useful. If you know it takes 1/20th of a second to count from 0 to 46,079 and you want to execute some event every second you simply wait for the timer to count from 0 to 46,079 twenty times; then you execute your event, reset the timers, and wait for the timer to count up another 20 times. In this manner you will effectively execute your event once per second, accurate to within thousandths of a second. Thus, we now have a system with which to measure time. All we need to review is how to control the timers and initialize them to provide us with the information we need. Timer SFRs As mentioned before, the 8051 has two timers which each function essentially the same way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and TCON) which control the timers, and each timer also has two SFRs dedicated solely to itself (TH0/TL0 and TH1/TL1). Weve given SFRs names to make it easier to refer to them, but in reality an SFR has a numeric address. It is often useful to know the numeric address that corresponds to an SFR name. The SFRs relating to timers are: SFR Name TH0 TL0 TH1 TL1 TCON TMOD Description Timer 0 High Byte Timer 0 Low Byte Timer 1 High Byte Timer 1 Low Byte Timer Control Timer Mode SFR Address 8Ch 8Ah 8Dh 8Bh 88h 89h

When you enter the name of an SFR into an assembler, it internally converts it to a number. For example, the command: MOV TH0,#25h moves the value 25h into the TH0 SFR. However, since TH0 is the same as SFR address 8Ch this command is equivalent to: MOV 8Ch,#25h Now, back to the timers. First, lets talk about Timer 0. Timer 0 has two SFRs dedicated exclusively to itself: TH0 and TL0. Without making things too complicated to start off with, you may just think of this as the high and low byte of the timer. That is to say, when Timer 0 has a value of 0, both TH0 and TL0 will contain 0. When Timer 0 has the value 1000, TH0 will hold the high byte of the value (3 decimal) and TL0 will contain the low byte of the value (232 decimal). Reviewing low/high byte notation, recall that you must multiply the high byte by 256 and add the low byte to calculate the final value. That is to say: TH0 * 256 + TL0 3 * 256 + 232 = 1000 Timer 1 works the exact same way, but its SFRs are TH1 and TL1. = 1000

Since there are only two bytes devoted to the value of each timer it is apparent that the maximum value a timer may have is 65,535. If a timer contains the value 65,535 and is subsequently incremented, it will reset--or overflow--back to 0. The TMOD SFR Lets first talk about our first control SFR: TMOD (Timer Mode). The TMOD SFR is used to control the mode of operation of both timers. Each bit of the SFR gives the microcontroller specific information concerning how to run a timer. The high four bits (bits 4 through 7) relate to Timer 1 whereas the low four bits (bits 0 through 3) perform the exact same functions, but for timer 0. The individual bits of TMOD have the following functions: TMOD (89h) SFR Bit Name Explanation of Function Timer When this bit is set the timer will only run when 7 GATE1 INT1 (P3.3) is high. When this bit is clear the timer 1 will run regardless of the state of INT1. When this bit is set the timer will count events on 6 C/T1 T1 (P3.5). When this bit is clear the timer will be 1 incremented every machine cycle. 5 T1M1 Timer mode bit (see below) 1 4 T1M0 Timer mode bit (see below) 1

When this bit is set the timer will only run when 3 GATE0 INT0 (P3.2) is high. When this bit is clear the timer 0 will run regardless of the state of INT0. When this bit is set the timer will count events on 2 C/T0 T0 (P3.4). When this bit is clear the timer will be 0 incremented every machine cycle. 1 T0M1 Timer mode bit (see below) 0 0 T0M0 Timer mode bit (see below) 0 As you can see in the above chart, four bits (two for each timer) are used to specify a mode of operation. The modes of operation are: TxM1 TxM0 Timer Mode Description of Mode 0 0 0 13-bit Timer. 0 1 1 16-bit Timer 1 0 2 8-bit auto-reload 1 1 3 Split timer mode 13-bit Time Mode (mode 0) Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to maintain compatability with its predecesor, the 8048. Generally the 13-bit timer mode is not used in new development. When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is incremented from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two timer bytes are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in essence, the timer can only contain 8192 values. If you set a 13-bit timer to 0, it will overflow back to zero 8192 machine cycles later. Again, there is very little reason to use this mode and it is only mentioned so you wont be surprised if you ever end up analyzing archaeic code which has been passed down through the generations (a generation in a programming shop is often on the order of about 3 or 4 months). 16-bit Time Mode (mode 1) Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions just like 13-bit mode except that all 16 bits are used. TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and causes THx to be incremented by 1. Since this is a full 16-bit timer, the timer may contain up to 65536 distinct values. If you set a 16-bit timer to 0, it will overflow back to 0 after 65,536 machine cycles.

8-bit Time Mode (mode 2) Timer mode "2" is an 8-bit auto-reload mode. What is that, you may ask? Simple. When a timer is in mode 2, THx holds the "reload value" and TLx is the timer itself. Thus, TLx starts counting up. When TLx reaches 255 and is subsequently incremented, instead of resetting to 0 (as in the case of modes 0 and 1), it will be reset to the value stored in THx. For example, lets say TH0 holds the value FDh and TL0 holds the value FEh. If we were to watch the values of TH0 and TL0 for a few machine cycles this is what wed see: Machine Cycle 1 2 3 4 5 6 7 TH0 Value FDh FDh FDh FDh FDh FDh FDh TL0 Value FEh FFh FDh FEh FFh FDh FEh

As you can see, the value of TH0 never changed. In fact, when you use mode 2 you almost always set THx to a known value and TLx is the SFR that is constantly incremented. Whats the benefit of auto-reload mode? Perhaps you want the timer to always have a value from 200 to 255. If you use mode 0 or 1, youd have to check in code to see if the timer had overflowed and, if so, reset the timer to 200. This takes precious instructions of execution time to check the value and/or to reload it. When you use mode 2 the microcontroller takes care of this for you. Once youve configured a timer in mode 2 you dont have to worry about checking to see if the timer has overflowed nor do you have to worry about resetting the value--the microcontroller hardware will do it all for you. The auto-reload mode is very commonly used for establishing a baud rate which we will talk more about in the Serial Communications chapter. Split Timer Mode (mode 3) Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially becomes two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0. Both timers count from 0 to 255 and overflow back to 0. All the bits that are related to Timer 1 will now be tied to TH0. While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into modes 0, 1 or 2 normally--however, you may not start or stop the real timer 1 since the

bits that do that are now linked to TH0. The real timer 1, in this case, will be incremented every machine cycle no matter what. The only real use I can see of using split timer mode is if you need to have two separate timers and, additionally, a baud rate generator. In such case you can use the real Timer 1 as a baud rate generator and use TH0/TL0 as two separate timers. The TCON SFR Finally, theres one more SFR that controls the two timers and provides valuable information about them. The TCON SFR has the following structure: TCON (88h) SFR Bit Bit Name Address 7 TF1 8Fh

Explanation of Function

Timer

Timer 1 Overflow. This bit is set by the 1 microcontroller when Timer 1 overflows. Timer 1 Run. When this bit is set Timer 1 is turned 6 TR1 8Eh 1 on. When this bit is clear Timer 1 is off. Timer 0 Overflow. This bit is set by the 5 TF0 8Dh 0 microcontroller when Timer 0 overflows. Timer 0 Run. When this bit is set Timer 0 is turned 4 TR0 8Ch 0 on. When this bit is clear Timer 0 is off. As you may notice, weve only defined 4 of the 8 bits. Thats because the other 4 bits of the SFR dont have anything to do with timers--they have to do with Interrupts and they will be discussed in the chapter that addresses interrupts. A new piece of information in this chart is the column "bit address." This is because this SFR is "bit-addressable." What does this mean? It means if you want to set the bit TF1-which is the highest bit of TCON--you could execute the command: MOV TCON, #80h ... or, since the SFR is bit-addressable, you could just execute the command: SETB TF1 This has the benefit of setting the high bit of TCON without changing the value of any of the other bits of the SFR. Usually when you start or stop a timer you dont want to modify the other values in TCON, so you take advantage of the fact that the SFR is bitaddressable. Initializing a Timer Now that weve discussed the timer-related SFRs we are ready to write code that will initialize the timer and start it running.

As youll recall, we first must decide what mode we want the timer to be in. In this case we want a 16-bit timer that runs continuously; that is to say, it is not dependent on any external pins. We must first initialize the TMOD SFR. Since we are working with timer 0 we will be using the lowest 4 bits of TMOD. The first two bits, GATE0 and C/T0 are both 0 since we want the timer to be independent of the external pins. 16-bit mode is timer mode 1 so we must clear T0M1 and set T0M0. Effectively, the only bit we want to turn on is bit 0 of TMOD. Thus to initialize the timer we execute the instruction: MOV TMOD,#01h Timer 0 is now in 16-bit timer mode. However, the timer is not running. To start the timer running we must set the TR0 bit We can do that by executing the instruction: SETB TR0 Upon executing these two instructions timer 0 will immediately begin counting, being incremented once every machine cycle (every 12 crystal pulses). Reading the Timer There are two common ways of reading the value of a 16-bit timer; which you use depends on your specific application. You may either read the actual value of the timer as a 16-bit number, or you may simply detect when the timer has overflowed. Reading the value of a Timer If your timer is in an 8-bit mode--that is, either 8-bit AutoReload mode or in split timer mode--then reading the value of the timer is simple. You simply read the 1-byte value of the timer and youre done. However, if youre dealing with a 13-bit or 16-bit timer the chore is a little more complicated. Consider what would happen if you read the low byte of the timer as 255, then read the high byte of the timer as 15. In this case, what actually happened was that the timer value was 14/255 (high byte 14, low byte 255) but you read 15/255. Why? Because you read the low byte as 255. But when you executed the next instruction a small amount of time passed--but enough for the timer to increment again at which time the value rolled over from 14/255 to 15/0. But in the process youve read the timer as being 15/255. Obviously theres a problem there. The solution? Its not too tricky, really. You read the high byte of the timer, then read the low byte, then read the high byte again. If the high byte read the second time is not the same as the high byte read the first time you repeat the cycle. In code, this would appear as: REPEAT: MOV A,TH0 MOV R0,TL0 CJNE A,TH0,REPEAT

... In this case, we load the accumulator with the high byte of Timer 0. We then load R0 with the low byte of Timer 0. Finally, we check to see if the high byte we read out of Timer 0--which is now stored in the Accumulator--is the same as the current Timer 0 high byte. If it isnt it means weve just "rolled over" and must reread the timers value-which we do by going back to REPEAT. When the loop exits we will have the low byte of the timer in R0 and the high byte in the Accumulator. Another much simpler alternative is to simply turn off the timer run bit (i.e. CLR TR0), read the timer value, and then turn on the timer run bit (i.e. SETB TR0). In that case, the timer isnt running so no special tricks are necessary. Of course, this implies that your timer will be stopped for a few machine cycles. Whether or not this is tolerable depends on your specific application. Detecting Timer Overflow Often it is necessary to just know that the timer has reset to 0. That is to say, you are not particularly interest in the value of the timer but rather you are interested in knowing when the timer has overflowed back to 0. Whenever a timer overflows from its highest value back to 0, the microcontroller automatically sets the TFx bit in the TCON register. This is useful since rather than checking the exact value of the timer you can just check if the TFx bit is set. If TF0 is set it means that timer 0 has overflowed; if TF1 is set it means that timer 1 has overflowed. We can use this approach to cause the program to execute a fixed delay. As youll recall, we calculated earlier that it takes the 8051 1/20th of a second to count from 0 to 46,079. However, the TFx flag is set when the timer overflows back to 0. Thus, if we want to use the TFx flag to indicate when 1/20th of a second has passed we must set the timer initially to 65536 less 46079, or 19,457. If we set the timer to 19,457, 1/20th of a second later the timer will overflow. Thus we come up with the following code to execute a pause of 1/20th of a second: MOV TH0,#76;High byte of 19,457 (76 * 256 = 19,456) MOV TL0,#01;Low byte of 19,457 (19,456 + 1 = 19,457) MOV TMOD,#01;Put Timer 0 in 16-bit mode SETB TR0;Make Timer 0 start counting JNB TF0,$;If TF0 is not set, jump back to this same instruction In the above code the first two lines initialize the Timer 0 starting value to 19,457. The next two instructions configure timer 0 and turn it on. Finally, the last instruction JNB TF0,$, reads "Jump, if TF0 is not set, back to this same instruction." The "$" operand means, in most assemblers, the address of the current instruction. Thus as long as the timer has not overflowed and the TF0 bit has not been set the program will keep executing this same instruction. After 1/20th of a second timer 0 will overflow, set the TF0 bit, and program execution will then break out of the loop.

Timing the length of events The 8051 provides another cool toy that can be used to time the length of events. For example, let's say we're trying to save electricity in the office and we're interested in how long a light is turned on each day. When the light is turned on, we want to measure time. When the light is turned off we don't. One option would be to connect the lightswitch to one of the pins, constantly read the pin, and turn the timer on or off based on the state of that pin. While this would work fine, the 8051 provides us with an easier method of accomplishing this. Looking again at the TMOD SFR, there is a bit called GATE0. So far we've always cleared this bit because we wanted the timer to run regardless of the state of the external pins. However, now it would be nice if an external pin could control whether the timer was running or not. It can. All we need to do is connect the lightswitch to pin INT0 (P3.2) on the 8051 and set the bit GATE0. When GATE0 is set Timer 0 will only run if P3.2 is high. When P3.2 is low (i.e., the lightswitch is off) the timer will automatically be stopped. Thus, with no control code whatsoever, the external pin P3.2 can control whether or not our timer is running or not. USING TIMERS AS EVENT COUNTERS We've discussed how a timer can be used for the obvious purpose of keeping track of time. However, the 8051 also allows us to use the timers to count events. How can this be useful? Let's say you had a sensor placed across a road that would send a pulse every time a car passed over it. This could be used to determine the volume of traffic on the road. We could attach this sensor to one of the 8051's I/O lines and constantly monitor it, detecting when it pulsed high and then incrementing our counter when it went back to a low state. This is not terribly difficult, but requires some code. Let's say we hooked the sensor to P1.0; the code to count cars passing would look something like this: JNB P1.0,$ ;If a car hasn't raised the signal, keep waiting JB P1.0,$ ;The line is high which means the car is on the sensor right now INC COUNTER ;The car has passed completely, so we count it As you can see, it's only three lines of code. But what if you need to be doing other processing at the same time? You can't be stuck in the JNB P1.0,$ loop waiting for a car to pass if you need to be doing other things. Of course, there are ways to get around even this limitation but the code quickly becomes big, complex, and ugly. Luckily, since the 8051 provides us with a way to use the timers to count events we don't have to bother with it. It is actually painfully easy. We only have to configure one additional bit.

Let's say we want to use Timer 0 to count the number of cars that pass. If you look back to the bit table for the TCON SFR you will there is a bit called "C/T0"--it's bit 2 (TCON.2). Reviewing the explanation of the bit we see that if the bit is clear then timer 0 will be incremented every machine cycle. This is what we've already used to measure time. However, if we set C/T0 timer 0 will monitor the P3.4 line. Instead of being incremented every machine cycle, timer 0 will count events on the P3.4 line. So in our case we simply connect our sensor to P3.4 and let the 8051 do the work. Then, when we want to know how many cars have passed, we just read the value of timer 0--the value of timer 0 will be the number of cars that have passed. So what exactly is an event? What does timer 0 actually "count?" Speaking at the electrical level, the 8051 counts 1-0 transitions on the P3.4 line. This means that when a car first runs over our sensor it will raise the input to a high ("1") condition. At that point the 8051 will not count anything since this is a 0-1 transition. However, when the car has passed the sensor will fall back to a low ("0") state. This is a 1-0 transition and at that instant the counter will be incremented by 1. It is important to note that the 8051 checks the P3.4 line each instruction cycle (12 clock cycles). This means that if P3.4 is low, goes high, and goes back low in 6 clock cycles it will probably not be detected by the 8051. This also means the 8051 event counter is only capable of counting events that occur at a maximum of 1/24th the rate of the crystal frequency. That is to say, if the crystal frequency is 12.000 Mhz it can count a maximum of 500,000 events per second (12.000 Mhz * 1/24 = 500,000). If the event being counted occurs more than 500,000 times per second it will not be able to be accurately counted by the 8051. DESCRIPTION OF AT89C51: The AT89C51 is a low-power, high-performance CMOS 8-bit microcomputer with 4K bytes of Flash programmable and erasable read only memory (PEROM). The device is manufactured using Atmels high-density nonvolatile memory technology and is compatible with the industry-standard MCS-51 instruction set and pinout. The on-chip Flash allows the program memory to be reprogrammed in-system or by a conventional nonvolatile memory programmer. By combining a versatile 8-bit CPU with Flash on a monolithic chip, the Atmel AT89C51 is a powerful microcomputer which provides a highly-flexible and cost-effective solution to many embedded control applications. The AT89C51 provides the following standard features: 4K bytes of Flash, 128 bytes of RAM, 32 I/O lines, two 16-bit timer/counters, five vector two-level interrupt architecture, a full duplex serial port, and on-chip oscillator and clock circuitry. In

addition, the AT89C51 is designed with static logic for operation down to zero frequency and supports two software selectable power saving modes. The Idle Mode stops the CPU while allowing the RAM, timer/counters, serial port and interrupt system to continue functioning. The Power-down Mode saves the RAM contents but freezes the oscillator disabling all other chip functions until the next hardware reset.

OSCILLATOR CHARACTERISTICS: XTAL1 and XTAL2 are the input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillator; Either a quartz crystal or ceramic resonator may be used. To drive the device from an external clock source, XTAL2 should be left unconnected while XTAL1 is driven. There are no requirements on the duty cycle of the external clock signal, since the input to the internal clocking circuitry is through a divide-by-two flip-flop, but minimum and maximum voltage high and low time specifications must be observed. IDLE MODE: In idle mode, the CPU puts itself to sleep while all the on chip peripherals remain active. The mode is invoked by software. The content of the on-chip RAM and all the special functions registers remain unchanged during this mode. The idle mode can be terminated by any enabled interrupt or by a hardware reset. It should be noted that when idle is terminated by a hard ware reset, the device normally resumes program execution, from where it left off, up to two machine cycles before the internal reset algorithm takes control. On-chip hardware inhibits access to internal RAM in this event, but access to the port pins is not inhibited. To eliminate the possibility of an unexpected write to a port pin when Idle is terminated by Reset, the instruction following the one that invokes Idle should not be one that writes to a port pin or to external memory.

PIN DIAGRAM OF AT89C51

AT 89C51

PIN DESCRIPTION VCC: Supply voltage. GND: Ground. Port 0: Port 0 is an 8-bit open-drain bi-directional I/O port. As an output port, each pin can sink eight TTL inputs. When 1s are written to port 0 pins, the pins can be used as high impedance inputs. Port 0 may also be configured to be the multiplexed low order address/data bus during accesses to external program and data memory. In this mode P0 has internal pull-ups. Port 0 also receives the code bytes during Flash programming, and outputs the code bytes during program verification. External pull-ups are required during program verification. Port 1: Port 1 is an 8-bit bi-directional I/O port with internal pull-ups. The Port 1 output buffers can sink/source four TTL inputs. When 1s are written to Port 1 pins they are pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 1 pins that are externally being pulled low will source current (IIL) because of the internal pull-ups. Port 1 also receives the low-order address bytes during Flash programming and verification.

Port 2: Port 2 is an 8-bit bi-directional I/O port with internal pull-ups. The Port 2 output buffers can sink/source four TTL inputs. When 1s are written to Port 2 pins they are pulled high by the internal pull-ups and can be used as inputs. Port 2 pins that are externally being pulled low will source current (IIL) because of the internal pull-ups. RST: Reset input a high on this pin for two machine cycles while the oscillator is running resets the device. ALE/PROG: Address Latch Enable output pulse for latching the low byte of the address during accesses to external memory. This pin is also the program pulse input (PROG) during Flash programming. In normal operation ALE is emitted at a constant rate of 1/6 the oscillator frequency, and may be used for external timing or clocking purposes. Note, however, that one ALE pulse is skipped during each access to external Data Memory. PSEN: Program Store Enable is the read strobe to external program memory. When the AT89C51 is executing code from external program memory, PSEN is activated twice each machine cycle, except that two PSEN activations are skipped during each access to external data memory. EA/VPP: External Access Enable. EA must be strapped to GND in order to enable the device to fetch code from external program memory locations starting at 0000H up to FFFFH. Note, however, that if lock bit 1 is programmed, EA will be internally latched on reset. EA should be strapped to VCC for internal program executions. This pin also

receives the 12volt programming enable voltage (VPP) during Flash programming, for parts that require 12-volt VPP. XTAL1: Input to the inverting oscillator amplifier and input to the internal clock operating circuit. XTAL2: Output from the inverting oscillator amplifier. Port Pin P3.0 P3.1 P3.2 P3.3 P3.4 P3.5 P3.6 P3.7 Alternate Functions RXD (serial input port) TXD (serial output port) INT0 (external interrupt 0) INT1 (external interrupt 1) T0 (timer 0 external input) T1 (timer 1 external input) WR (external data memory write strobe) RD (external data memory read strobe)

POWER SUPPLIES The present chapter introduces the operation of power supply circuits built using filters, rectifiers and voltage regulators. Starting with an AC voltage, a steady DC voltage, is obtained by rectifying the ac voltage then filtering to a dc level and Finally Regulation is usually obtained from an IC voltage regulator unit, which takes a dc voltage and provides a some what lower dc voltage, which remains the same even if the input dc voltage varies or the output load connected to the dc voltage changes.

BLOCK DIAGRAM:

Transformer N

Rectifier

Filter

Regulator

The ac voltage, typically 230v is connected to transformer, which steps the ac voltage down to the level for desired dc output. A diode rectifier provides a full wave rectified Voltage that is initially filtered by a simple capacitive filter to produce a dc voltage. This resulting dc voltage usually has some ripple or ac voltage variation. A regulator Circuit can use this dc input to provide a regulated that not only has much ripple voltage But also remain the same dc values even if the input dc voltage changes. This voltage Regulation is usually obtained using one of a number of popular voltage regulation IC Units.

TRANSFORMER: A transformer is the static device of which electric power in one circuit is transformed into electric power of the same frequency in another circuit. It can rise or lower the voltage in a circuit but with a corresponding decrease or increase in current. It works with the principles of mutual induction. In our project we are using step down transformer for providing that necessary supply for the electronic circuits.

RECTIFIER: The full wave rectifier conducts during both positive and negative half cycles of input a.c. input; two diodes are used in this circuit. The a.c. voltage is applied through a

suitable power transformer with proper turns ratio. For the proper operation of the circuit, a center-tap on the secondary winding of the transformer is essential. During the positive half cycle of ac input voltage, the diode D1 will be forward biased and hence will conduct; while diode D2 will be reverse biased and will act as open circuit and will not conduct. In the next half cycle of ac voltage, polarity reverses and the diode D2 conducts, being forward biased, while D1 does not, being reverse biased. Hence the load current flows in both half cycles of ac voltage and in the same direction. The diode we are using here for the purpose of rectification is IN4001.

FILTER: The filter circuit used here is the capacitor filter circuit where a capacitor is connected at the rectifier output, and a DC is obtained across it. The filtered waveform is essentially a DC voltage with negligible ripples, which is ultimately fed to the load. REGULATOR: The output voltage from capacitor is more filtered and finally regulated. The voltage regulator is a device, which maintains the output voltage constant irrespective of the change in supply variations, load variations and temperature changes. Hence IC7805 is used which is a +5v regulator.

CIRCUIT DIAGRAM OF POWER SUPPLIES:

Since all electronic circuits work only with low dc voltage it needs a power supply unit to provide the appropriate voltage supply. This unit consists of a transformer, rectifier, filter and regulator. AC voltage typically 230v is connected to the transformer that steps the AC voltage down to the level to the desired AC voltage. A diode rectifier then provides a full wave rectified voltage that is initially filtered by a simple capacitive filter to produce a DC voltage. This resulting DC voltage usually has some ripple or AC voltage variations. TRANSFORMER

A transformer is an electrical device that transfers energy from one electrical circuit to another by magnetic coupling, where relative motion between the parts is not required to transfer energy between the circuits. It is often used to convert between high and low voltages, for impedance transformation, and to provide electrical isolation between circuits

Introduction The transformer is one of the simplest of electrical devices. Its basic design, materials, and principles have changed little over the last one hundred years, yet transformer designs and materials continue to be improved. Transformers are essential in high voltage power transmission providing an economical means of transmitting power over large distances. The simplicity, reliability, and economy of conversion of voltages by transformers was the principal factor in the selection of alternating current power transmission in the "War of Currents " in the late 1880's. In electronic circuitry, new methods of circuit design have replaced some of the applications of transformers, but electronic technology has also developed new transformer designs and applications. Transformers come in a range of sizes from a thumbnail-sized coupling transformer hidden inside a stage microphone to gigawatt units used to interconnect large portions of national power grids, all operating with the same basic principles and with many similarities in their parts. A current transformer is designed to provide a current in its secondary which is accurately proportional to the current flowing in its primary. Current transformers are commonly used in electricity meters to facilitate the measurement of large currents which would be difficult to measure more directly.

Care must be taken that the secondary of a current transformer is not disconnected from its load while current is flowing in the primary as in this circumstance a very high voltage would be produced across the secondary. Current transformers are often constructed with a single primary turn either as an insulated cable passing through a toroidal core, or else as a bar to which circuit conductors are connected.

Voltage transformers Voltage transformers (also known as potential transformers) are used in the electricity supply industry to measure accurately the voltage being supplied. They are designed to present negligible load to the voltage being measured.

LCD interfacing with Microcontrollers

IntroductionThe most commonly used Character based LCDs are based on Hitachi's HD44780 controller or other which are compatible with HD44580. In this tutorial, we will discuss about character based LCDs, their interfacing with various microcontrollers, various interfaces (8-bit/4-bit), programming, special stuff and tricks you can do with these simple looking LCDs which can give a new look to your application. For Specs and technical information HD44780 controller

Pin DescriptionThe most commonly used LCDs found in the market today are 1 Line, 2 Line or 4 Line LCDs which have only 1 controller and support at most of 80 charachers, whereas LCDs supporting more than 80 characters make use of 2 HD44780 controllers.

Most LCDs with 1 controller has 14 Pins and LCDs with 2 controller has 16 Pins (two pins are extra in both for back-light LED connections). Pin description is shown in the table below.

Figure 1: Character LCD type HD44780 Pin diagram (GND) Power supply (+5V) Contrast adjust 0 = Instruction input Pin no. 4 RS 1 = Data input 0 = Write to LCD module Pin no. 5 R/W 1 = Read from LCD module Pin no. 6 EN Enable signal Pin no. 7 D0 Data bus line 0 (LSB) Pin no. 8 D1 Data bus line 1 Pin no. 9 D2 Data bus line 2 Pin no. 10 D3 Data bus line 3 Pin no. 11 D4 Data bus line 4 Pin no. 12 D5 Data bus line 5 Pin no. 13 D6 Data bus line 6 Pin no. 14 D7 Data bus line 7 (MSB) Table 1: Character LCD pins with 1 ControllerPower supply

Pin No. Pin no. 1 Pin no. 2 Pin no. 3

Name VSS VCC VEE

Description

Pin No. Pin no. 1 Pin no. 2 Pin no. 3 Pin no. 4

Name D7 D6 D5 D4

Description Data bus line 7 (MSB) Data bus line 6 Data bus line 5 Data bus line 4

Pin no. 5 Pin no. 6 Pin no. 7 Pin no. 8 Pin no. 9

Data bus line 3 Data bus line 2 Data bus line 1 Data bus line 0 (LSB) Enable signal for row 0 and 1 (1stcontroller) 0 = Write to LCD module Pin no. 10 R/W 1 = Read from LCD module 0 = Instruction input Pin no. 11 RS 1 = Data input Pin no. 12 VEE Contrast adjust Pin no. 13 VSS Power supply (GND) Pin no. 14 VCC Power supply (+5V) Pin no. 15 EN2 Enable signal for row 2 and 3 (2ndcontroller) Pin no. 16 NC Not Connected Table 2: Character LCD pins with 2 Controller Usually these days you will find single controller LCD modules are used more in the market. So in the tutorial we will discuss more about the single controller LCD, the operation and everything else is same for the double controller too. Lets take a look at the basic information which is there in every LCD.

D3 D2 D1 D0 EN1

DDRAM - Display Data RAMDisplay data RAM (DDRAM) stores display data represented in 8-bit character codes. Its extended capacity is 80 X 8 bits, or 80 characters. The area in display data RAM (DDRAM) that is not used for display can be used as general data RAM. So whatever you send on the DDRAM is actually displayed on the LCD. For LCDs like 1x16, only 16 characters are visible, so whatever you write after 16 chars is written in DDRAM but is not visible to the user. Figures below will show you the DDRAM addresses of 1 Line, 2 Line and 4 Line LCDs.

Figure 2: DDRAM Address for 1 Line LCD

Figure 3: DDRAM Address for 2 Line LCD

Figure 4: DDRAM Address for 4 Line LCD

CGROM - Character Generator ROMNow you might be thinking that when you send an ascii value to DDRAM, how the character is displayed on LCD? so the answer is CGROM. The character generator ROM generates 5 x 8 dot or 5 x 10 dot character patterns from 8-bit character codes (see Figure 5 and Figure 6 for more details). It can generate 208 5 x 8 dot character patterns and 32 5 x 10 dot character patterns. Userdefined character patterns are also available by maskprogrammed ROM.

Figure 5: LCD characters code map for 5x8 dots

Figure 6: LCD characters code map for 5x10 dots As you can see in both the code maps, the character code from 0x00 to 0x07 is occupied by the CGRAM characters or the user defined characters. If user want to display the fourth custom character then the code to display it is 0x03 i.e. when user send 0x03 code to the LCD DDRAM then the fourth user created charater or patteren will be displayed on the LCD.

CGRAM - Character Generator RAMAs clear from the name, CGRAM area is used to create custom characters in LCD. In the character generator RAM, the user can rewrite character patterns by program. For 5 x 8 dots, eight character patterns can be written, and for 5 x 10 dots, four character patterns can be written. Later in this tutorial i will explain how to use CGRAM area to make custom character and also making animations to give nice effects to your application.

BF - Busy FlagBusy Flag is an status indicator flag for LCD. When we send a command or data to the LCD for processing, this flag is set (i.e BF =1) and as soon as the instruction is executed successfully this flag is cleared (BF = 0). This is helpful in producing and exact ammount of delay. for the LCD processing. To read Busy Flag, the condition RS = 0 and R/W = 1 must be met and The MSB of the LCD data bus (D7) act as busy flag. When BF = 1 means LCD is busy and will not accept next command or data and BF = 0 means LCD is ready for the next command or data to process.

Instruction Register (IR) and Data Register (DR)There are two 8-bit registers in HD44780 controller Instruction and Data register. Instruction register corresponds to the register where you send commands to LCD e.g LCD shift command, LCD clear, LCD address etc. and Data register is used for storing data which is to be displayed on LCD. when send the enable signal of the LCD is asserted, the data on the pins is latched in to the data register and data is then moved automatically to the DDRAM and hence is displayed on the LCD. Data Register is not only used for sending data to DDRAM but also for CGRAM, the address where you want to send the data, is decided by the instruction you send to LCD. We will discuss more on LCD instuction set further in this tutorial.

Commands and Instruction setOnly the instruction register (IR) and the data register (DR) of the LCD can be controlled by the MCU. Before starting the internal operation of the LCD, control information is temporarily stored into these registers to allow interfacing with various MCUs, which operate at different speeds, or various peripheral control devices. The internal operation of the LCD is determined by signals sent from the MCU. These signals, which include register selection signal (RS), read/write signal (R/W), and the data bus (DB0 to DB7), make up the LCD instructions (Table 3). There are four categories of instructions that:

Designate LCD functions, such as display format, data length, etc. Set internal RAM addresses Perform data transfer with internal RAM Perform miscellaneous functions

Table 3: Command and Instruction set for LCD type HD44780 Although looking at the table you can make your own commands and test them. Below is a breif list of useful commands which are used frequently while working on the LCD. No. 1 2 3 4 Instruction Function Set: 8-bit, 1 Line, 5x7 Dots Function Set: 8-bit, 2 Line, 5x7 Dots Function Set: 4-bit, 1 Line, 5x7 Dots Function Set: 4-bit, 2 Line, 5x7 Dots Hex 0x30 0x38 0x20 0x28 Decimal 48 56 32 40

5

Entry Mode 0x06 6 Display off Cursor off 6 (clearing display without clearing DDRAM 0x08 8 content) 7 Display on Cursor on 0x0E 14 8 Display on Cursor off 0x0C 12 9 Display on Cursor blinking 0x0F 15 10 Shift entire display left 0x18 24 12 Shift entire display right 0x1C 30 13 Move cursor left by one character 0x10 16 14 Move cursor right by one character 0x14 20 15 Clear Display (also clear DDRAM content) 0x01 1 Set DDRAM address or coursor position on 16 0x80+add* 128+add* display Set CGRAM address or set pointer to CGRAM 17 0x40+add** 64+add** location Table 4: Frequently used commands and instructions for LCD * DDRAM address given in LCD basics section see Figure 2,3,4 ** CGRAM address from 0x00 to 0x3F, 0x00 to 0x07 for char1 and so on.. The table above will help you while writing programs for LCD. But after you are done testing with the table 4, i recommend you to use table 3 to get more grip on working with LCD and trying your own commands. In the next section of the tutorial we will see the initialization with some of the coding examples in C as well as assembly.

LCD InitializationBefore using the LCD for display purpose, LCD has to be initialized either by the internal reset circuit or sending set of commands to initialize the LCD. It is the user who has to decide whether an LCD has to be initialized by instructions or by internal reset circuit. we will dicuss both ways of initialization one by one. Initialization by internal Reset Circuit An internal reset circuit automatically initializes the HD44780U when the power is turned on. The following instructions are executed during the initialization. The busy flag (BF) is kept in the busy state until the initialization ends (BF = 1). The busy state lasts for 10 ms after VCC rises to 4.5 V.

Display clear Function set: DL = 1; 8-bit interface data

N = 0; 1-line display F = 0; 5 x 8 dot character font Display on/off control: D = 0; Display off C = 0; Cursor off B = 0; Blinking off Entry mode set: I/D = 1; Increment by 1 S = 0; No shift

Note: If the electrical characteristics conditions listed under the table Power Supply Conditions Using Internal Reset Circuit are not met, the internal reset circuit will not operate normally and will fail to initialize the HD44780U. For such a case, initial-ization must be performed by the MCU as explained in the section, Initializing by Instruction.

As mentioned in the Note, there are certain condtions that has to be met, if user want to use initialization by internal reset circuit. These conditions are shown in the Table 5 below.

Table 5: Power Supply condition for Internal Reset circuit Figure 7 shows the test condition which are to be met for internal reset circuit to be active.

Figure 7: Internal Power Supply reset Now the problem with the internal reset circuit is, it is highly dependent on power supply, to meet this critical power supply conditions is not hard but are difficult to achieve when you are making a simple application. So usually the second method i.e. Initialization by instruction is used and is recommended most of the time.

Initialization by instructions Initializing LCD with instructions is really simple. Given below is a flowchart that describles the step to follow, to initialize the LCD.

Figure 8: Flow chart for LCD initialization As you can see from the flow chart, the LCD is initialized in the following sequence... 1) Send command 0x30 - Using 8-bit interface 2) Delay 20ms 3) Send command 0x30 - 8-bit interface 4) Delay 20ms 5) Send command 0x30 - 8-bit interface 6) Delay 20ms 7) Send Function set - see Table 4 for more information 8) Display Clear command 9) Set entry mode command - explained below The first 3 commands are usually not required but are recomended when you are using 4bit interface. So you can program the LCD starting from step 7 when working with 8-bit

interface. Function set command depends on what kind of LCD you are using and what kind of interface you are using (see Table 4 in LCD Command section). LCD Entry mode From Table 3 in command section, you can see that the two bits decide the entry mode for LCD, these bits are: a) I/D - Increment/Decrement bit b) S - Display shift. With these two bits we get four combinations of entry mode which are 0x04,0x05,0x06,0x07 (see table 3 in LCD Command section). So we get different results with these different entry modes. Normally entry mode 0x06 is used which is No shift and auto incremement. I recommend you to try all the possible entry modes and see the results, I am sure you will be surprised. Programming example for LCD Initialization CODE: LCD_data LCD_D7 LCD_rs LCD_rw LCD_en LCD_init: mov 5x7 dots clr LCD_rs clr LCD_rw instruction register setb LCD_en clr LCD_en acall LCD_busy command mov LCD_data,#0FH command clr LCD_rs register clr LCD_rw instruction register setb LCD_en clr LCD_en acall LCD_busy command mov LCD_data,#01H clr LCD_rs clr LCD_rw ;Selected command register ;We are writing in ;Enable H->L ;Wait for LCD to process the ;Display on, Curson blinking ;Selected instruction ;We are writing in ;Enable H->L ;Wait for LCD to process the ;Clear LCD ;Selected command register ;We are writing in LCD_data,#38H ;Function set: 2 Line, 8-bit, equ equ equ equ equ P2 P2.7 P1.0 P1.1 P1.2 ;LCD ;LCD ;LCD ;LCD ;LCDData port

D7/Busy Flag Register Select Read/Write Enable

instruction register setb LCD_en clr LCD_en acall LCD_busy command mov LCD_data,#06H with no shift clr LCD_rs clr LCD_rw instruction register setb LCD_en clr LCD_en acall LCD_busy command ret

;Enable H->L ;Wait for LCD to process the ;Entry mode, auto increment ;Selected command register ;We are writing in ;Enable H->L ;Wait for LCD to process the ;Return from routine

Now we can do the same thing in C, I am giving example using Keil C. Similar code can be written for SDCC.

CODE: #include . #define LCD_data P2 #define LCD_D7 P2_7 #define LCD_rs P1_0 #define LCD_rw P1_1 #define LCD_en P1_2 void LCD_init() { LCD_data = 0x38; 8-bit, 5x7 dots LCD_rs = 0; register LCD_rw = 0; register LCD_en = 1; LCD_en = 0; LCD_busy(); the command LCD_data = 0x0F; blinking command LCD_rs = 0; register LCD_rw = 0;

//Function set: 2 Line, //Selected command //We are writing in data //Enable H->L //Wait for LCD to process //Display on, Curson //Selected command //We are writing in data

register LCD_en = 1; LCD_en = 0; LCD_busy(); the command LCD_data = 0x01; LCD_rs = 0; register LCD_rw = 0; register LCD_en = 1; LCD_en = 0; LCD_busy(); the command LCD_data = 0x06; increment with no shift LCD_rs = 0; register LCD_rw = 0; register LCD_en = 1; LCD_busy(); }

//Enable H->L //Wait for LCD to process //Clear LCD //Selected command //We are writing in data //Enable H->L //Wait for LCD to process //Entry mode, auto //Selected command //We are writing in data //Enable H->L

With the help of the above code, you are able to initialize the LCD. Now there is a function/subroutine coming in the code i.e. LCD_busy, which is used to put delay for LCD so that there should not be any command or data sent to the LCD untill it finish executing the command. More on this delay routine is explained in the next section.

ANALOG TO DIGITAL CONVERTER:

Basics Of Analog-To-Digital Converter(ADC): An analog-to-digital converter (abbreviated ADC, A/D or A to D) is a device that converts a continuous quantity to a discrete time digital representation. An ADC may also provide an isolated measurement. The reverse operation is performed by a digital-toanalog converter (DAC). Typically, an ADC is an electronic device that converts an input analog voltage or current to a digital number proportional to the magnitude of the voltage or current. However, some non-electronic or only partially electronic devices, such as rotary encoders, can also be considered ADCs. The digital output may use different coding schemes. Typically the digital output will be a two's complement binary number that is proportional to the input, but there are other possibilities. An encoder, for example, might output a Gray code.

Resolution

An 8-level ADC coding scheme. The resolution of the converter indicates the number of discrete values it can produce over the range of analog values. The values are usually stored electronically in binary form, so the resolution is usually expressed in bits. In consequence, the number of discrete values available, or "levels", is a power of two. For example, an ADC with a resolution of 8 bits can encode an analog input to one in 256 different levels, since 28 = 256. The values can represent the ranges from 0 to 255 (i.e. unsigned integer) or from 128 to 127 (i.e. signed integer), depending on the application. Resolution can also be defined electrically, and expressed in volts. The minimum change in voltage required to guarantee a change in the output code level is called the least significant bit (LSB) voltage. The resolution Q of the ADC is equal to the LSB voltage. The voltage resolution of an ADC is equal to its overall voltage measurement range divided by the number of discrete voltage intervals:

where N is the number of voltage intervals and EFSR is the full scale voltage range. EFSR is given by

where VRefHi and VRefLow are the upper and lower extremes, respectively, of the voltages that can be coded. Normally, the number of voltage intervals is given by

where M is the ADC's resolution in bits. That is, one voltage interval is assigned per code level. Example: Coding scheme as in figure 1 Full scale measurement range = 0 to 10 volts ADC resolution is 12 bits: 212 = 4096 quantization levels (codes) ADC voltage resolution, Q = (10 V 0 V) / 4096 = 10 V / 4096 0.00244 V 2.44 mV.

In practice, the useful resolution of a converter is limited by the best signalto-noise ratio (SNR) that can be achieved for a digitized signal. An ADC can resolve a signal to only a certain number of bits of resolution, called the effective number of bits (ENOB). One effective bit of resolution changes the signal-to-noise ratio of the digitized signal by 6 dB, if the resolution is limited by the ADC. If a preamplifier has been used prior to A/D conversion, the noise introduced by the amplifier can be an important contributing factor towards the overall SNR. Response type Most ADCs are linear types. The term linear implies that the range of input values has a linear relationship with the output value. Some early converters had a logarithmic response to directly implement Alaw or -law coding. These encodings are now achieved by using a higherresolution linear ADC (e.g. 12 or 16 bits) and mapping its output to the 8-bit coded values.

Accuracy An ADC has several sources of errors. Quantization error and (assuming the ADC is intended to be linear) non-linearity are intrinsic to any analog-todigital conversion. There is also a so-called aperture error which is due to a clock jitter and is revealed when digitizing a time-variant signal (not a constant value). These errors are measured in a unit called the least significant bit (LSB). In the above example of an eight-bit ADC, an error of one LSB is 1/256 of the full signal range, or about 0.4%. Quantization error Main article: Quantization error Quantization error (or quantization noise) is the difference between the original signal and the digitized signal. Hence, The magnitude of the quantization error at the sampling instant is between zero and half of one LSB. Quantization error is due to the finite resolution of the digital representation of the signal, and is an unavoidable imperfection in all types of ADCs. Non-linearity All ADCs suffer from non-linearity errors caused by their physical imperfections, causing their output to deviate from a linear function (or some other function, in the case of a deliberately non-linear ADC) of their input. These errors can sometimes be mitigated by calibration, or prevented by testing. Important parameters for linearity are integral non-linearity (INL) and differential non-linearity (DNL). These non-linearity reduce the dynamic range of the signals that can be digitized by the ADC, also reducing the effective resolution of the ADC.

Sampling rate The analog signal is continuous in time and it is necessary to convert this to a flow of digital values. It is therefore required to define the rate at which new digital values are sampled from the analog signal. The rate of new values is called the sampling rate or sampling frequency of the converter.

A continuously varying bandlimited signal can be sampled (that is, the signal values at intervals of time T, the sampling time, are measured and stored) and then the original signal can be exactly reproduced from the discrete-time values by an interpolation formula. The accuracy is limited by quantization error. However, this faithful reproduction is only possible if the sampling rate is higher than twice the highest frequency of the signal. This is essentially what is embodied in the Shannon-Nyquist sampling theorem. Since a practical ADC cannot make an instantaneous conversion, the input value must necessarily be held constant during the time that the converter performs a conversion (called the conversion time). An input circuit called a sample and hold performs this task in most cases by using a capacitor to store the analog voltage at the input, and using an electronic switch or gate to disconnect the capacitor from the input. Many ADC integrated circuits include the sample and hold subsystem internally. Aliasing All ADCs work by sampling their input at discrete intervals of time. Their output is therefore an incomplete picture of the behavior of the input. There is no way of knowing, by looking at the output, what the input was doing between one sampling instant and the next. If the input is known to be changing slowly compared to the sampling rate, then it can be assumed that the value of the signal between two sample instants was somewhere between the two sampled values. If, however, the input signal is changing rapidly compared to the sample rate, then this assumption is not valid. If the digital values produced by the ADC are, at some later stage in the system, converted back to analog values by a digital to analog converter or DAC, it is desirable that the output of the DAC be a faithful representation of the original signal. If the input signal is changing much faster than the sample rate, then this will not be the case, and spurious signals called aliases will be produced at the output of the DAC. The frequency of the aliased sig