You are on page 1of 78

CONTENTS

1. SYNOPSIS............................................2 2. THEORY..............................................5 2.1 EMBEDDED SYSTEMS.............................6 2.2 MICROCONTROLLERS.............................7 2.3 8051 MICROCONTROLLERS........................9 2.4 8051 MEMORY ARCHITECTURE....................15 2.5 LIGHT EMITTING DIODES.......................25 2.6 ALPHANUMERIC LCD............................28 2.7 ANALOG-TO-DIGITAL CONVERTERS................35 2.8 ZERO CROSSING DETECTORS.....................42 2.9 OPTOCOUPLERS................................44 2.10 TRIAC.......................................48 3. DESIGN AND IMPLEMENTATION..........................54 3.1 CIRCUIT DIAGRAM.............................55 3.2 CIRCUIT EXPLANATION.........................56 3.3 SOURCE CODE.................................62 4. RESULT & CONCLUSION................................68 5. BIBLIOGRAPHY.......................................70

1. SYNOPSIS
This project is a standalone temperature based fan speed controller that controls the speed of the fan according to the room temperature. The microcontroller is the heart of the circuit as it controls all the functions. The microcontroller allows dynamic and faster control and liquid crystal display (LCD) makes the system user-friendly. It is very compact using few components and can be implemented for several applications including air-conditioners, water-heaters, ovens, heat-exchangers, mixers, furnaces, incubators, thermal baths and veterinary operating tables. The temperature sensor LM35 senses the temperature and converts it into an electrical (analog) signal, which is applied to the micro controller through an ADC. The analog signal is converted into digital format by the analog-to-digital converter (ADC). The sensed temperature and fan status (including speed levels) are displayed on the LCD. The system also indicates the fan speed through LEDS. The microcontroller interfaces with a TRIAC for varying the fan speed. The main advantage of using a TRIAC to vary the speed of an AC motor is the TRIAC reduces the energy flow to the motor and TRIAC works very well for alternating currents. A zero crossing detector circuit is used to interrupt the microcontroller. After getting an interrupt, the microcontroller will fire TRIAC after some delay. This will cut the current supplied to motor and so the speed of motor will vary. Thus by varying the delay after which the TRIAC is triggered we can change the speed of fan. The system is built with AT89S52, LM35, ADC0804, Alphanumeric LCD, LEDs, ZCD, and a TRIAC. The software part of the system is designed using C language. The Keil IDE is used as a development tool. This project uses regulated 5V, 500mA power supply. The AC mains supply is applied to a 9V step-down transformer. The transformer output is 9V AC which is rectified using a bridge rectifier. The output of bridge rectifier is DC 9V which is filtered by a capacitor, and then regulated using 7805 voltage regulator. The output of 7805 is +5V DC which is the required

voltage for microcontroller operation. Also an LED in series with 470 Ohms resistor is used for power on indication.

BLOCK DIAGRAM

MCU LM35 ALPHANUMERIC LCD

ADC

SPEED INDICATOR LEDS

DRIVER ZCD

TRIAC

2. THEORY 2.1 EMBEDDED SYSTEMS


2.1.0 INTRODUCTION
An embedded system is one that has computer hardware with software embedded in it as one of its most important component. It is a dedicated computer-based system for an application or product. It may be either an independent system or a larger part of a system. As its software usually embeds in ROM (read only memory) it does not need secondary memories as in a computer. An embedded system has three main components: 1. It has hardware. 2. It has main application software. The application software may perform concurrently the series of tasks or multiple tasks. 3. It has a real time operating system (RTOS) that supervises the application software and provides the mechanism to let the processor to run a process as per scheduling and do the context-switch between the various processes. An embedded system has software designed to keep in view three constraints: 1. Available system memory. 2. Available processor speed. 3. The need to limit power dissipation when running the system continuously in cycle of wait for events, run, stop and wake-up.

2.1.1 CHARACTERISTICS OF AN EMBEDDED SYSTEM


The following are the basic characteristics of an embedded system:
1. Embedded systems are designed to do some specific task, rather than be a general-purpose

computer for multiple tasks. Some also have real-time performance constraints that must be

met, for reasons such as safety and usability; others may have low or no performance requirements, allowing the system hardware to be simplified to reduce costs.
2. Embedded systems are not always standalone devices. Many embedded systems consist of

small, computerized parts within a larger device that serves a more general purpose. For example, an embedded system in an automobile provides a specific function as a subsystem of the car itself.
3. The program instructions written for embedded systems are referred to as firmware, and are

stored in read-only memory or Flash memory chips. They run with limited computer hardware resources: little memory, small or non-existent keyboard and/or screen.

2.1.2 EXAMPLES OF EMBEDDED SYSTEMS


Embedded systems span all aspects of modern life and there are many examples of their use. Virtually every electronic device designed and manufactured today is an embedded system, and virtually no first-world person is untouched by this technology. In fact, once you start looking for them, we're sure you can quickly find a few dozen embedded systems in your home. Physically, embedded systems range from portable devices such as digital watches and MP3 players, to large stationary installations like traffic lights, factory controllers, navigation systems, or the systems controlling nuclear power plants. Complexity varies from low, with a single microcontroller chip, to very high with multiple units, peripherals and networks mounted inside a large chassis or enclosure.

2.2 MICROCONTROLLERS
2.2.0 INTRODCUTION
A microcontroller is a small computer on a single integrated circuit containing a processor core, memory, and programmable input/output peripherals. A microcontroller can be considered a self-contained system with a processor, memory and peripherals and can be used as an embedded system. The majority of microcontrollers in use today are embedded in other machinery, such as automobiles, telephones, appliances, and peripherals for computer systems. These are called embedded systems. While some embedded systems are very sophisticated, many have minimal requirements for memory and program length, with no operating system, and low software

complexity. Embedded systems usually have no keyboard, screen, disks, printers, or other recognizable I/O devices of a personal computer, and may lack human interaction devices of any kind. Microcontrollers are designed for embedded applications, in contrast to the microprocessors used in personal computers or other general purpose applications. By reducing the size and cost compared to a design that uses a separate microprocessor, memory, and input/output devices, microcontrollers make it economical to digitally control even more devices and processes. Thus, a microcontroller is a single integrated circuit, commonly with the following features: central processing unit - ranging from small and simple 4-bit processors to complex 32bit or 64-bit processors discrete input and output bits, allowing control or detection of the logic state of an individual package pin serial input/output such as serial ports (UARTs) other serial communications interfaces like IC, Serial Peripheral Interface and Controller Area Network for system interconnect peripherals such as timers, event counters, PWM generators, and watchdog volatile memory (RAM) for data storage ROM, EPROM, EEPROM or Flash memory for program and operating parameter storage clock generator - often an oscillator for a quartz timing crystal, resonator or RC circuit many include analog-to-digital converters in-circuit programming and debugging support

2.2.1 HISTORY
The first computer system on a chip optimized for control applications - microcontroller was the Intel 8048 released in 1975, with both RAM and ROM on the same chip. This chip would find its way into over one billion PC keyboards, and other numerous applications. Most microcontrollers at this time had two variants. One had an erasable EEPROM program memory, which was significantly more expensive than the PROM variant which was only programmable once.

In 1993, the introduction of EEPROM memory allowed microcontrollers (beginning with the Microchip PIC16x84) to be electrically erased quickly without an expensive package as required for EPROM, allowing both rapid prototyping, and In System Programming. The same year, Atmel introduced the first microcontroller using Flash memory. Other companies rapidly followed suit, with both memory types.

2.3 8051 MICROCONTROLLERS


2.3.0 INTRODUCTION
The Intel 8051 is a Harvard architecture, single chip microcontroller (C) which was developed by Intel in 1980 for use in embedded systems. The Intel 8051 microcontroller is one of the most popular general purpose microcontrollers in use today. The success of the Intel 8051 spawned a number of clones which are collectively referred to as the MCS-51 family of microcontrollers, which includes chips from vendors such as Atmel, Philips, Infineon, and Texas Instruments. The Intel 8051 is an 8-bit microcontroller which means that most available operations are limited to 8 bits. There are 3 basic sizes of the 8051: Short, Standard, and Extended. The Short and Standard chips are often available in DIP form, but the Extended 8051 models often have a different form factor, and are not "drop-in compatible". All these things are called 8051 because they can all be programmed using 8051 assembly language, and they all share certain features (although the different models all have their own special features). Some of the features that have made the 8051 popular are: 8-bit data bus 16-bit address bus 32 general purpose registers each of 8 bits 16 bit timers (usually 2, but may have more, or less) 3 internal and 2 external interrupts Bit as well as byte addressable RAM area of 16 bytes Four 8-bit bidirectional I/O ports (short models have two 8-bit ports) 16-bit program counter and data pointer Programmable Serial Channel

The 8051 models may also have a number of special, model-specific features, such as UARTs, ADC, DAC, etc. The common features included in modern 8051 based microcontrollers include built-in reset timers with brown-out detection, on-chip oscillators, self-programmable Flash ROM program memory, boot loader code in ROM, EEPROM non-volatile data storage, IC, SPI, and USB host interfaces, CAN or LIN bus, PWM generators, analog comparators, A/D and D/A converters, RTCs, extra counters and timers, in-circuit debugging facilities, more interrupt sources, and extra power saving modes. A particularly useful feature of the 8051 core is the inclusion of a boolean processing engine which allows bit-level boolean logic operations to be carried out directly and efficiently on internal registers and RAM. Another valued feature is that it has four separate register sets, which can be used to greatly reduce interrupt latency compared to the more common method of storing interrupt context on a stack.

2.3.1 RELATED PROCESSORS


The 8051's predecessor, the 8048, was used in the keyboard of the first IBM PC, where it converts key presses into the serial data stream which is sent to the main unit of the computer. The 8048 and derivatives are still used today for basic model keyboards. The 8031 was a cut down version of the original Intel 8051 that did not contain any internal program memory (ROM). To use this chip, external ROM had to be added containing the program that the 8031 would fetch and execute. The 8052 was an enhanced version of the original 8051 that featured 256 bytes of internal RAM instead of 128 bytes, 8 KB of ROM instead of 4 KB, and a third 16-bit timer. The 8032 had these same features except for the internal ROM program memory. The 8052 and 8032 are largely considered to be obsolete because these features and more are included in nearly all modern 8051 based microcontrollers.

2.3.2 ATMEL 89 SERIES


The Atmel AT89 series is an Intel 8051-compatible family of 8 bit

microcontrollers manufactured by the Atmel Corporation. Based on the Intel 8051 core, the

AT89 series remains very popular as general purpose microcontrollers, due to their industry standard instruction set, and low unit cost. The following table gives a list of popular AT89 series microcontrollers:
Device Name AT89C1051 AT89C2051 AT89C51 AT89C52 AT89C55 AT89S51 AT89S52 AT89S53 Program Memory 1K Flash 2K Flash 4K Flash 8K Flash 20K Flash 4K Flash 8K Flash 12K Flash Data Memory 64 Bytes RAM 128 Bytes RAM 128 Bytes RAM 256 Bytes RAM 256 Bytes RAM 128 Bytes RAM 256 Bytes RAM 256 Bytes RAM

While considerably less powerful than the newer AT90 series of AVR microcontrollers, new product development has continued with the AT89 series for the aforementioned advantages. Of more recent times, the AT89 series has been augmented with 8051-cored special function microcontrollers, specifically in the areas of USB, IC, SPI and CAN bus controllers, MP3 decoders and hardware PWM.

2.3.3 AT89C51 DESCRIPTION 2.3.3.0 INTRODUCTION


The AT89C51 is a low-power, high-performance CMOS 8-bit microcomputer with 4K bytes of Flash programmable and erasable read only memory (EPROM). The device is manufactured using Atmels high-density nonvolatile memory technology and is compatible with the industrystandard MCS-51 instruction set and pin out. 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, a five vector two-level interrupt architecture, a full duplex serial port, on-chip oscillator and clock circuitry.

2.3.3.1 PIN DIAGRAM OF AT89C51

2.3.3.2 AT89C51 FEATURES


The following are the major features of AT89C51: Compatible with MCS-51 Products 4K Bytes of In-System Reprogrammable Flash Memory (Endurance: 1,000 Write/Erase Cycles) Fully Static Operation: 0 Hz to 24 MHz Three-level Program Memory Lock 128 x 8-bit Internal RAM 32 Programmable I/O Lines Two 16-bit Timer/Counters

Six Interrupt Sources Programmable Serial Channel Low-power Idle and Power-down Modes

2.3.3.3 DESCRIPTION OF BASIC PINS


PIN 9: PIN 9 is the reset pin which is used to reset the microcontrollers internal registers and ports upon starting up. A high on this pin for two machine cycles while the oscillator is running resets the device. PINS 18 & 19: The 8051 has a built-in oscillator hence we need to only connect a crystal at these pins to provide clock pulses to the circuit. PINS 40 and 20: Pins 40 and 20 are VCC and GND respectively. The 8051 chip needs +5V 500mA to function properly, although there are lower powered versions like the Atmel 2051 which is a scaled down version of the 8051 which runs on +3V. PINS 29, 30 & 31: As described in the features of the 8051, this chip contains a built-in flash memory. In order to program this we need to supply a voltage of +12V at pin 31. If external memory is connected then PIN 31, also called EA (external access), and should be connected to ground to indicate the presence of external memory. PIN 30 is called ALE (address latch enable), which is used when multiple memory chips are connected to the controller and only one of them needs to be selected. PIN 29 is called PSEN (program store enable). In order to use the external memory it is required to provide the low voltage (0) on both PSEN and EA pins.

2.3.3.4 I/O PORTS


All 8051 microcontrollers have 4 I/O ports each comprising 8 bits which can be configured as inputs or outputs. Accordingly, in total of 32 input/output pins enabling the microcontroller to be connected to peripheral devices are available for use. Pin configuration, i.e. whether it is to be configured as an input (1) or an output (0), depends on its logic state. In order to configure a microcontroller pin as an output, it is necessary to apply a logic zero (0) to appropriate I/O port bit. In this case, voltage level on appropriate pin will be 0.

Similarly, in order to configure a microcontroller pin as an input, it is necessary to apply a logic one (1) to appropriate port. In this case, voltage level on appropriate pin will be +5V (as is the case with any TTL input). PORT P1 (Pins 1 to 8): The port P1 is a general purpose input/output port which can be used for a variety of interfacing tasks. The other ports P0, P2 and P3 have dual roles or additional functions associated with them based upon the context of their usage. PORT P3 (Pins 10 to 17): PORT P3 acts as a normal I/O port, but port P3 has additional functions such as, serial transmit and receive pins, 2 external interrupt pins, 2 external counter inputs, read and write pins for memory access. PORT P2 (pins 21 to 28): PORT P2 can also be used as a general purpose 8 bit port when no external memory is present, but if external memory access is required then port P2 will act as an address bus in conjunction with port P0 to access external memory. PORT P2 acts as A8-A15, as can be seen from pin diagram. PORT P0 (pins 32 to 39): PORT P0 can be used as a general purpose 8 bit port when no external memory is present, but if external memory access is required then port P0 acts as a multiplexed address and data bus that can be used to access external memory in conjunction with PORT P2. P0 acts as AD0-AD7, as can be seen from pin diagram. When we are using PORT P0 for input/output, an external pull-up resistor is needed, depending on the characteristics of the device driven by the port pin.

2.3.3.5 BASIC CONFIGURATION OF 8051


In order to use 8051 microcontroller we need the basic connections like RESET (Pin 9), Crystal (Pins 18 and 19), GND (Pin 20), EA (Pin 31), and VCC (Pin 40). The PIN 9 is the reset pin which is used reset the microcontrollers internal registers and ports upon starting up. A high on this pin for two machine cycles while the oscillator is running resets the device. Depending on purpose of device, the reset pin is usually connected to a power-on reset push button or circuit or to both of them. The PINS 18 and 19 are the crystal pins. The 8051 has a built-in oscillator hence we need to only connect a crystal at these pins to provide clock pulses to the circuit. The PINS 20 and 40 are GND and VCC respectively. The 8051 chip needs +5V 500mA to function properly.

The PIN 31 is the external access pin. If EA = 1, the microcontroller executes the program code from its internal program memory. If EA = 0, the microcontroller executes the program code from external program memory. Often, the program code is present in the internal program memory of 8051. So, this pin is connected to VCC. The following diagram shows the essential configuration of any 8051 based microcontroller:

2.4 8051 MEMORY ARCHITECTURE


2.4.0 INTRODUCTION
The 8051 has two types of memory and these are Program Memory and Data Memory. Program Memory (ROM) is used to permanently save the program being executed, while Data Memory (RAM) is used for temporarily storing data and intermediate results created and used during the operation of the microcontroller. Depending on the model in use (we are still talking about the 8051 microcontroller family in general) at most a few KB of ROM and 128 or 256 bytes of RAM

is used. However, all 8051 microcontrollers have a 16-bit addressing bus and are capable of addressing 64 KB memory.

2.4.1 PROGRAM MEMORY


The first models of the 8051 microcontroller family did not have internal program memory. It was added as an external separate chip. These models are recognizable by their label beginning with 803 (for example 8031 or 8032). All later models have a few KB ROM embedded. Even though such an amount of memory is sufficient for writing most of the programs, there are situations when it is necessary to use additional memory as well. How does the microcontroller handle external memory depend on the EA pin logic state:

If EA = 0 then the microcontroller completely ignores internal program memory and executes only the program stored in external memory. If EA = 1 then the microcontroller executes first the program from built-in ROM, then the program stored in external memory. In both cases, P0 and

P2 are not available for use since being used for data and address transmission. Besides, the ALE and PSEN pins are also used.

2.4.2 DATA MEMORY


As already mentioned, Data Memory is used for temporarily storing data and intermediate results created and used during the operation of the microcontroller. Besides, RAM memory built in the 8051 family includes many registers such as counters and timers, input/output ports, serial data buffers etc. The previous models had 256 RAM locations, while for the later models this number was incremented by additional 128 registers. However, the first 256 memory locations (addresses 0-FFh) are the heart of memory common to all the models belonging to the 8051 family. Locations available to the user occupy memory space with addresses 0-7Fh, i.e. first 128 registers. This part of RAM is divided in several blocks. The first block consists of 4 banks each including 8 registers denoted by R0-R7. Prior to accessing any of these registers, it is necessary to select the bank containing it. The next memory block (address 20h-2Fh) is bit- addressable, which means that each bit has its own address (0-7Fh). Since there are 16 such registers, this block contains in total of 128 bits with separate addresses (address of bit 0 of the 20h byte is 0, while address of bit 7 of the 2Fh byte is 7Fh). The third group of registers occupies addresses 2Fh-7Fh, i.e. 80 locations, and does not have any special functions or features.

2.4.3 SPECIAL FUNCTION REGISTERS (SFRS)


Special Function Registers (SFRs) are a sort of control table used for running and monitoring the operation of the microcontroller. Each of these registers as well as each bit they include, has its name, address in the scope of RAM and precisely defined purpose such as timer control, interrupt control, serial communication control etc. Even though there are 128 memory locations intended to be occupied by them, the basic core, shared by all types of 8051 microcontrollers, has only 21 such registers. The rest of locations are intentionally left unoccupied in order to enable the manufacturers to further develop

microcontrollers keeping them compatible with the previous versions. It also enables programs written a long time ago for microcontrollers which are out of production now to be used today.

2.4.4 ADDITIONAL RAM


In order to satisfy the programmers constant hunger for Data Memory, the manufacturers decided to embed an additional memory block of 128 locations into the latest versions of the 8051 microcontrollers. However, its not as simple as it seems to be The problem is that electronics performing addressing has 1 byte (8 bits) on disposal and is capable of reaching only the first 256 locations, therefore. In order to keep already existing 8-bit architecture and compatibility with other existing models a small trick was done.

What does it mean? It means that additional memory block shares the same addresses with locations intended for the SFRs (80h- FFh). In order to differentiate between these two physically separated memory spaces, different ways of addressing are used. The SFRs memory locations are accessed by direct addressing, while additional RAM memory locations are accessed by indirect addressing.

2.4.5 8051 BASIC REGISTERS


2.4.5.1 A Register (Accumulator) A register is a general-purpose register used for storing intermediate results obtained during operation. All results obtained from arithmetical operations performed by the ALU are stored in the accumulator. Data to be moved from one register to another must go through the accumulator. In other words, the A register is the most commonly used register and it is impossible to imagine a microcontroller without it. More than half instructions used by the 8051 microcontroller use somehow the accumulator.

2.4.5.2 B Register Multiplication and division can be performed only upon numbers stored in the A and B registers. All other instructions in the program can use this register as a spare accumulator (A).

Note: During the process of writing a program, each register is called by its name so that their exact addresses are not of importance for the user. During compilation, their names will be automatically replaced by appropriate addresses. 2.4.5.3 R Registers (R0-R7) This is a common name for 8 general-purpose registers (R0, R1, R2 ...R7). Even though they are not true SFRs, they deserve to be discussed here because of their purpose. They occupy 4 banks within RAM. Similar to the accumulator, they are used for temporary storing variables and intermediate results during operation. Which one of these banks is to be active depends on two bits of the PSW Register. Active bank is a bank the registers of which are currently used.

The following example best illustrates the purpose of these registers. Suppose it is necessary to perform some arithmetical operations upon numbers previously stored in the R registers: (R1+R2) - (R3+R4). Obviously, a register for temporary storing results of addition is needed. This is how it looks in the program: MOV A,R3; ADD A,R4; MOV R5,A; MOV A,R1; ADD A,R2; SUBB A,R5; Means: move number from R3 into accumulator Means: add number from R4 to accumulator Means: temporarily move the result from accumulator into R5 Means: move number from R1 to accumulator Means: add number from R2 to accumulator Means: subtract number from R5 (there are R3+R4)

2.4.5.4 Program Status Word (PSW) Register PSW register is one of the most important SFRs. It contains several status bits that reflect the current state of the CPU. Besides, this register contains Carry bit, Auxiliary Carry, two register bank select bits, Overflow flag, parity bit and user-definable status flag.

P - Parity - If a number stored in the accumulator is even then this bit will be automatically set (1), otherwise it will be cleared (0). It is mainly used during data transmit and receive via serial communication. Bit 1 - This bit is intended to be used in the future versions of microcontrollers. OV Overflow - Overflow occurs when the result of an arithmetical operation is larger than 255 and cannot be stored in one register. Overflow condition causes the OV bit to be set (1). Otherwise, it will be cleared (0).

RS0, RS1 - Register bank select bits. These two bits are used to select one of four register banks of RAM. By setting and clearing these bits, registers R0-R7 are stored in one of four banks of RAM. RS1 0 0 1 1 RS0 0 1 0 1 SPACE IN RAM Bank 0 (00h-07h) Bank 1 (08h-0Fh) Bank 2 (10h-17h) Bank 3 (18h-1Fh)

F0 - Flag 0 - This is a general-purpose bit available for use. AC Auxiliary Carry - Auxiliary Carry Flag is used for BCD operations only. CY Carry - Carry Flag is the (ninth) auxiliary bit used for all arithmetical operations and shift instructions. 2.4.5.5 Data Pointer Register (DPTR) DPTR register is not a true one because it doesn't physically exist. It consists of two separate registers: DPH (Data Pointer High) and (Data Pointer Low). For this reason it may be treated as a 16-bit register or as two independent 8-bit registers. Their 16 bits are primarily used for external memory addressing. Besides, the DPTR Register is usually used for storing data and intermediate results.

2.4.5.6 Stack Pointer (SP) Register A value stored in the Stack Pointer points to the first free stack address and permits stack availability. Stack pushes increment the value in the Stack Pointer by 1. Likewise, stack pops decrement its value by 1. Upon any reset and power-on, the value 7 is stored in the Stack Pointer, which means that the space of RAM reserved for the stack starts at this location. If another value is written to this register, the entire Stack is moved to the new memory location.

2.4.5.7 P0, P1, P2, P3 - Input/output Registers If neither external memory nor serial communication system are used then 4 ports within total of 32 input/output pins are available for connection to peripheral environment. Each bit within these ports affects the state and performance of appropriate pin of the microcontroller. Thus, bit logic state is reflected on appropriate pin as a voltage (0 or 5 V) and vice versa, voltage on a pin reflects the state of appropriate port bit. As mentioned, port bit state affects performance of port pins, i.e. whether they will be configured as inputs or outputs. If a bit is cleared (0), the appropriate pin will be configured as an output, while if it is set (1), the appropriate pin will be configured as an input. Upon reset and power-on, all port bits are set (1), which means that all appropriate pins will be configured as inputs.

2.4.5.8 PCON register

The purpose of the Register PCON bits is: SMOD Baud rate is twice as much higher by setting this bit. GF1 General-purpose bit (available for use). GF0 General-purpose bit (available for use). PD By setting this bit the microcontroller enters the power down mode. IDL By setting this bit the microcontroller enters the idle mode.

Power Down Mode By setting the PD bit of the PCON register from within the program, the microcontroller is set to Power down mode, thus turning off its internal oscillator and reduces power consumption enormously. The microcontroller can operate using only 2V power supply in power- down mode, while a total power consumption is less than 40uA. The only way to get the microcontroller back to normal mode is by reset. While the microcontroller is in Power Down mode, the state of all SFR registers and I/O ports remains unchanged. By setting it back into the normal mode, the contents of the SFR register is lost, but the content of internal RAM is saved. Reset signal must be long enough, approximately 10mS, to enable stable operation of the quartz oscillator. Idle Mode Upon the IDL bit of the PCON register is set, the microcontroller turns off the greatest power consumer- CPU unit while peripheral units such as serial port, timers and interrupt system continue operating normally consuming 6.5mA. In Idle mode, the state of all registers and I/O ports remains unchanged. In order to exit the Idle mode and make the microcontroller operate normally, it is necessary to enable and execute any interrupt or reset. It will cause the IDL bit to be automatically cleared and the program resumes operation from instruction having set the IDL bit. It is recommended that first three instructions to execute now are NOP instructions. They don't perform any operation but provide some time for the microcontroller to stabilize and prevents undesired changes on the I/O ports.

2.4.5.9 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 is not always incremented by one. Since some instructions require 2 or 3 bytes then the PC will be incremented by 2 or 3 in these cases. The Program Counter is special in that there is no way to directly modify its value. That is to say, you cant do something like PC=2430h. On the other hand, if you execute LJMP 2430h youve effectively accomplished the same thing.

2.5 LIGHT EMITTING DIODES


2.5.0 INTRODUCTION
Light Emitting Diodes or LEDs, are among the most widely used of all the types of diodes available. They are the most visible type of diodes that emits a fairly narrow bandwidth of either visible colored light, invisible infra-red or laser type light when a forward current is passed through them. A "Light Emitting Diode" or LED as it is more commonly called, is basically just a specialized type of PN-junction diode, made from a very thin layer of fairly heavily doped semiconductor material. When the diode is Forward Biased, electrons from the semiconductors conduction band combine with holes from the valence band, releasing sufficient energy to produce photons of light. Because of this thin layer a reasonable number of these photons can leave the junction and radiate away producing a colored light output. Unlike normal diodes which are made for detection or power rectification, and which are generally made from either Germanium or Silicon semiconductor material, Light Emitting Diodes are made from compound type semiconductor materials such as Gallium Arsenide (GaAs), Gallium Phosphide (GaP), Gallium Arsenide Phosphide (GaAsP), Silicon Carbide (SiC) or Gallium Indium Nitride (GaInN). The exact choice of the semiconductor material used will determine the overall wavelength of the photon light emissions and therefore the resulting color of the light emitted, as in the case of the visible light colored LEDs, (RED, AMBER, GREEN etc).

Typical LED Characteristics Semiconductor Material GaAs GaAsP GaAsP GaAsP:N GaP SiC GaInN Wavelength 850-940nm 630-660nm 605-620nm 585-595nm 550-570nm 430-505nm 450nm Color Infra-Red Red Amber Yellow Green Blue White VF @ 20mA 1.2v 1.8v 2.0v 2.2v 3.5v 3.6v 4.0v

From the table above we can see that the main P-type dopant used in the manufacture of Light Emitting Diodes is Gallium (Ga, atomic number 31) and the main N-type dopant used is Arsenic (As, atomic number 31) giving the resulting Gallium Arsenide (GaAs) crystal structure, which has the characteristics of radiating significant amounts of infrared radiation from its junction when a forward current is flowing through it. By also adding Phosphorus (P, atomic number 15), as a third dopant the overall wavelength of the emitted radiation is reduced to give visible red light to the human eye. Further refinements in the doping process of the PN-junction have resulted in a range of colors available from red, orange and amber through to yellow, and the recently developed blue LED which is achieved by injecting nitrogen atoms into the crystal structure during the doping process.

2.5.1 LED SERIES RESISTANCE


The series resistor value RS is calculated by simply using Ohms Law, knowing the required forward current IF, the supply voltage VS and the expected forward voltage drop of the LED, VF at this current level as shown below:

2.5.2 LIGHT EMITTING DIODES I-V CHARACTERISTICS


Before a light emitting diode can "emit" any form of light it needs a current to flow through it, as it is a current dependant device. As the LED is to be connected in a forward bias condition across a power supply it should be Current Limited using a series resistor to protect it from excessive current flow. From the table above we can see that each LED has its own forward voltage drop across the PN-junction and this parameter which is determined by the semiconductor material used is the forward voltage drop for a given amount of forward conduction current, typically for a forward current of 20mA. In most cases LEDs are operated from a low voltage DC supply, with a series resistor to limit the forward current to a suitable value from say 5mA for a simple LED indicator to 30mA or more where a high brightness light output is needed.

2.5.3 LED TYPICAL APPLICATIONS


The following figure shows how to interface the LED to microcontroller. As you can see the anode is connected through a resistor to Vcc and the cathode is connected to the microcontroller pin. So when the Port Pin is HIGH the LED is OFF and when the Port Pin is LOW the LED is turned ON.

2.6 ALPHANUMERIC LCD


2.6.0 INTRODUCTION

Liquid Crystal Display also called as LCD is very helpful in providing user interface as well as for debugging purpose. The most commonly used character based LCDs are based on Hitachi's HD44780 controller or other which are compatible with HD44780. The 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 characters, whereas LCDs supporting more than 80 characters make use of 2 HD44780 controllers.

2.6.1 PIN DESCRIPTION

Pin No. 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Name VSS VCC VEE RS R/W EN D0 D1 D2 D3 D4 D5 D6 D7

Description Power supply (GND) Power supply (+5V) Contrast adjust 0 = Instruction input 1 = Data input 0 = Write to LCD module 1 = Read from LCD module Enable signal Data bus line 0 (LSB) Data bus line 1 Data bus line 2 Data bus line 3 Data bus line 4 Data bus line 5 Data bus line 6 Data bus line 7 (MSB)

15 16

LED+ LED-

Back Light VCC Back Light GND

2.6.2 LCD MEMORY


The LCD display contains three memory blocks: DDRAM Display Data RAM CGROM Character Generator ROM CGRAM Character Generator RAM

2.6.2.0 DDRAM - DISPLAY DATA RAM


Display 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 characters is written in DDRAM but is not visible to the user.

2.6.2.1 CGROM - CHARACTER GENERATOR ROM


Now 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. It can generate 208 5 x 8 dot character patterns and 32 5 x 10 dot character patterns.

2.6.2.2 CGRAM - CHARACTER GENERATOR RAM


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

2.6.3 BF - BUSY FLAG


Busy Flag is a 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 amount 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.

2.6.4 INSTRUCTION REGISTER (IR) & DATA REGISTER (DR)


There are two 8-bit registers in HD44780 controller: Instruction Register and Data register. The IR (Instruction Register) stores instruction codes, such as display clear and cursor shift, and address information for display data RAM (DDRAM) and character generator RAM (CGRAM). The IR can only be written from the MCU. The DR (Data Register) temporarily stores data to be written into DDRAM or CGRAM and temporarily stores data to be read from DDRAM or CGRAM. Data written into the DR from the MCU is automatically written into DDRAM or CGRAM by an internal operation. The DR is also used for data storage when reading data from DDRAM or CGRAM. When address information is written into the IR, data is read and then stored into the DR from DDRAM or CGRAM by an internal operation. Data transfer between the MCU is then completed when the MCU reads the DR. After the read, data in DDRAM or CGRAM at the next address is sent to the DR for the next read from the MCU. By the register selector (RS) signal, these two registers can be selected.

2.6.5 COMMANDS AND INSTRUCTION SET

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

Although looking at the table you can make your own commands and test them. Below is a brief list of useful commands which are used frequently while working on the LCD. NO 1 2 3 4 5 6 7 8 9 10 12 13 14 15 16 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 Entry Mode Display off Cursor off Display on Cursor on Display on Cursor off Display on Cursor blinking Shift entire display left Shift entire display right Move cursor left by one character Move cursor right by one character Clear Display (also clear DDRAM content) Set DDRAM address or cursor position on display HEX 0x30 0x38 0x20 0x28 0x06 0x08 0x0E 0x0C 0x0F 0x18 0x1C 0x10 0x14 0x01 0x80+add

17

Set CGRAM address or set pointer to CGRAM location

0x40+add

2.6.6 SENDING COMMANDS TO LCD


To send commands we simply need to select the command register. The common steps are: Move data to LCD port Select command register Select write operation Send enable signal Wait for LCD to process the command

2.6.7 SENDING DATA TO LCD


To send data we simply need to select the data register. Everything is same as the command routine. Following are the steps: Move data to LCD port Select data register Select write operation Send enable signal Wait for LCD to process the data

2.6.8 LCD 4-BIT MODE PROGRAMMING 2.6.8.0 INTRODUCTION


There are many reasons why sometime we prefer to use LCD in 4-bit mode instead of 8-bit. One basic reason is lesser number of pins is needed to interface LCD. In 4-bit mode the data is sent in nibbles, first we send the higher nibble and then the lower nibble. To enable the 4-bit mode of LCD, we need to follow special sequence of initialization that tells the LCD controller that user has selected 4-bit mode of operation. We call this special sequence as resetting the LCD. Following is the reset sequence of LCD: Wait for about 20mS

Send first init value (0x30) Wait for about 10mS Send second init value (0x30) Wait for about 1mS Send third init value (0x30) Wait for about 1mS Select bus width (0x30 - for 8-bit and 0x20 for 4-bit) Wait for about 1mS

2.6.8.1 LCD CONNECTIONS IN 4-BIT MODE

2.6.8.2 SENDING DATA/COMMAND IN 4-BIT MODE


We will now look into the common steps to send data/command to LCD when working in 4-bit mode. In 4-bit mode data is sent nibble by nibble; first we send higher nibble and then lower nibble. This means in both command and data sending function we need to separate the higher 4bits and lower 4-bits. The common steps are: Mask lower 4-bits Send to the LCD port

Send enable signal Mask higher 4-bits Send to LCD port Send enable signal

2.7 ANALOG-TO-DIGITAL CONVERTERS


2.7.0 INTRODUCTION
Analog-to-digital converters are among the most widely used devices for data acquisition. Digital computers use binary (discrete) values, but in the physical world everything is analog (continuous). Temperature, pressure, humidity, and velocity are a few examples of physical quantities that we deal with every day. A physical quantity is converted to electrical signals using a device called a transducer. Transducers are also referred to as sensors. Sensors for temperature, velocity, pressure, light, and many other natural quantities produce an output that is voltage. Therefore, we need analog-to-digital converter to translate the analog signals to digital numbers so that the microcontroller can read and process them. An ADC has n-bit resolution where n can be 4, 8, 10, 12, 16 or even 24 bits. The higher resolution ADC provides a smaller step size, where step size is the smallest change that can be discerned by an ADC. In addition to resolution, conversion time is another major factor in judging an ADC. Conversion time is defined as the time it takes the ADC to convert the analog input to a digital number. The ADC chips are either parallel or serial. The basic principle of analog-to-digital conversion is to use the comparator principle to determine whether or not to turn on a particular bit of the binary number output. It is typical for an ADC to use a digital-to-analog converter (DAC) to determine one of the inputs to the comparator. Following are the most used conversion methods: Digital-Ramp ADC Successive Approximation ADC Flash ADC

2.7.1 DIGITAL-RAMP ADC

Conversion from analog to digital form inherently involves comparator action where the value of the analog voltage at some point in time is compared with some standard. A common way to do that is to apply the analog voltage to one terminal of a comparator and trigger a binary counter which drives a DAC. The output of the DAC is applied to the other terminal of the comparator. Since the output of the DAC is increasing with the counter, it will trigger the comparator at some point when its voltage exceeds the analog input. The transition of the comparator stops the binary counter, which at that point holds the digital value corresponding to the analog voltage.

2.7.2 SUCCESSIVE APPROXIMATION ADC


The following diagram illustrates 4-bit SAC with 1 volt step size:

The successive approximation ADC is much faster than the digital ramp ADC because it uses digital logic to converge on the value closest to the input voltage. A comparator and a DAC are used in the process. A flowchart explaining the working is shown in the figure below.

2.7.3 FLASH ADC


Illustrated is a 3-bit flash ADC with resolution 1 volt. The resistor net and comparators provide an input to the combinational logic circuit, so the conversion time is just the propagation delay through the network - it is not limited by the clock rate or some convergence sequence. It is the fastest type of ADC available, but requires a comparator for each value of output (63 for 6-bit, 255 for 8-bit, etc.) Such ADCs are available in IC form up to 8-bit and 10-bit flash ADCs (1023 comparators) are planned. The encoder logic executes a truth table to convert the ladder of inputs to the binary number output.

2.7.4 ADC0804 IC
The ADC0804 IC is an 8-bit parallel ADC in the family of the ADC0800 series from National Semiconductor. It is also available from many other manufacturers. It works with +5V and has a resolution of 8 bits. In the ADC0804, the conversion time varies depending on the clocking signals applied to the CLK IN pin, but it cannot be faster than 100 us.

2.7.4.0 ADC0804 PIN DIAGRAM

2.7.4.1 ADC0804 PIN DESCRIPTION


CS: An active low input pin used to activate the ADC. RD: An active low input pin used to get the converted data out of the ADC. WR: An active low input pin used to start the conversion process. CLK IN and CLK R: CLK IN is an input pin connected to an external clock source when an external clock is used for timing. However, the ADC0804 has an internal clock generator. To use the internal clock generator of the ADC0804, the CLK IN and CLK R pins are connected to a capacitor and a resistor. In that case the clock frequency is determined by the equation: f = 1 / (1.1 * R * C) Typical values are R = 10K and C = 150pF. Substituting in the above equation, we get f = 606 KHz. In that case, the conversion time is 110 us. INTR: An active low output pin used to indicate end of conversion. It is a normally high pin and when the conversion is finished, it goes low to signal the microcontroller that the converted data is ready to be picked up.

Vin(+) and Vin(-): These are the differential analog inputs where Vin = Vin(+) Vin(-). Often the Vin(-) pin is connected to ground and the Vin(+) pin is used as the analog input to be converted to digital. AGND and DGND: These are the input pins providing the ground for both the analog and the digital signals. Analog ground is connected to the ground of the analog Vin while digital ground is connected to the ground of the Vcc pin. Vref/2: An input voltage used for the reference voltage. If this pin is open (not connected), the analog input voltage for the ADC0804 is in the range of 0 to +5 volts. However, there are many applications where the analog input applied to Vin needs to be other than the 0 to +5V range. Vref/2 is used to implement analog input voltages other than 0 to +5V. DB0 DB7: These are the digital data output pins. To calculate the output value, we can use the following formula: Dout = Vin / StepSize where Dout = digital data output, Vin = analog input voltage, and Stepsize is the smallest change, which is (2xVref/2)/255 for ADC0804. Vcc: This is the +5V power supply. It is also used as a reference voltage when the Vref/2 is open (not connected).

2.7.4.2 ADC0804 TYPICAL APPLICATIONS

As shown in the typical circuit, ADC0804 can be interfaced with any microcontroller. You need a minimum of 11 pins to interface ADC0804, eight for data pins and 3 for control pins. As shown in the typical circuit the chip select pin can be made low if you are not using the microcontroller port for any other peripheral.

2.7.4.3 TIMING DIAGRAMS

The above timing diagrams are from ADC0804 datasheet. The first diagram shows how to start a conversion. Also you can see which signals are to be asserted and at what time to start a conversion. So looking into the timing diagram FIGURE 1, we note down the steps or say the order in which signals are to be asserted to start a conversion of ADC. As we have decided to make Chip select pin as low so we need not to bother about the CS signal in the timing diagram. Below steps are for starting an ADC conversion. I am also including CS signal to give you a clear picture. While programming we will not use this signal. 1. Make chip select (CS) signal low. 2. Make write (WR) signal low.

3. Make chip select (CS) high. 4. Wait for INTR pin to go low (means conversion ends). Once the conversion in ADC is done, the data is available in the output latch of the ADC. Look at the FIGURE 2 that shows the timing diagram of how to read the converted value from the output latch of the ADC. Data of the new conversion is only available for reading after ADC0804 made INTR pin low or say when the conversion is over. Below are the steps to read output from the ADC0804. 1. Make chip select (CS) pin low. 2. Make read (RD) signal low. 3. Read the data from port where ADC is connected. 4. Make read (RD) signal high. 5. Make chip select (CS) high.

2.7.5 LM35 TEMPERATURE SENSOR


The LM35 is a popular and low cost temperature sensor. It has three pins. The Vcc can be from 4V to 20V as specified by the datasheet. To use the sensor simply connect the Vcc to +5V, GND to ground and the OUT to one of the ADC (analog to digital converter) channel. The output linearly varies with temperature. The output is 10 mV per degree centigrade So if the output is 310 mV then temperature is 31 degree C.

2.7.5.0 LM35 PIN DIAGRAM

2.8 ZERO CROSSING DETECTORS


A zero crossing detector literally detects the transition of a signal waveform from positive and negative, ideally providing a narrow pulse that coincides exactly with the zero voltage condition. The zero-crossing circuit/power supply is quite simple. It starts as a standard 5V power supply using a 7805 regulator and a 9V AC transformer. This will provide power for the microcontroller. The following figure shows this basic power supply circuit:

To generate the zero-crossing signal, we need to tap into the power supply after the bridge rectifier, so we get the pulsating DC at this point. The initial filter capacitors job is to get rid of this signal, so we need to insert a diode in between the bridge rectifier and the capacitor. Now that we have this signal, we want to generate a pulse when the signal is zero. We add a transistor with pull-up resistor and a voltage divider to the circuit. The following figure shows this basic zero crossing detection circuit:

The following figure shows the pulsating DC and zero crossing signals. As long as the base voltage is greater than the turn-on voltage of the transistor, the transistor will pull the output to ground. When the voltage drops below the turn-on voltage, the transistor will turn off, and the output will be pulled high by the resistor. Since the pull-up is to the 5V supply, we get a nice pulse that is nearly symmetrical around the zero cross point. This signal is connected to an input pin on the microcontroller. The width of the pulse is determined by the input voltage, the resistors used in the voltage divider, the diode drops in the rectifier, and the voltage at which the transistor turns on.

2.9 OPTOCOUPLERS
2.9.0 INTRODUCTION
A transformer isolate the primary input voltage from the secondary output voltage using electromagnetic coupling by means of a magnetic flux circulating within the iron laminated core. But we can also provide electrical isolation between an input source and an output load using just light by using a very common and valuable electronic component called an optocoupler. An Optocoupler, also known as an Opto-isolator or Photo-coupler, is an electronic component that interconnects two electrical circuits by means of an optical interface. The point is that an optocoupler uses a short optical transmission path to transfer a signal between the elements of circuit, while keeping them electrically isolated. This isolation makes sense only if diodes and photo-sensitive elements are separately powered. In this way, the microcontroller and expensive additional electronics are completely protected from high voltage and noises which are the most common cause of destroying, damaging or unstable operation of electronic devices in practice.

The basic design of an optocoupler consists of an LED that produces infra-red light and a semiconductor photo-sensitive device that is used to detect this emitted infra-red light. Both the LED and photo-sensitive device are enclosed in a light-tight body or package with metal legs for the electrical connections as shown. An optocoupler or opto-isolator consists of a light emitter, the LED and a light sensitive receiver which can be a single photo-diode, photo-transistor, photo-resistor, photo-SCR, or a photoTRIAC and the basic operation of an optocoupler is very simple to understand.

Figure: Photo-transistor Optocoupler Assume a photo-transistor device as shown. Current from the source signal passes through the input LED which emits an infra-red light whose intensity is proportional to the electrical signal. This emitted light falls upon the base of the photo-transistor, causing it to switch-ON and conduct in a similar way to a normal bipolar transistor. The base connection of the phototransistor can be left open for maximum sensitivity or connected to ground via a suitable external resistor to control the switching sensitivity making it more stable. When the current flowing through the LED is interrupted, the infra-red emitted light is cut-off, causing the photo-transistor to cease conducting. The photo-transistor can be used to switch current in the output circuit. The spectral response of the LED and the photo-sensitive device are closely matched being separated by a transparent medium such as glass, plastic or air. Since there is no direct electrical connection between the input and output of an optocoupler, electrical isolation up to 10kV is achieved.

Optocouplers are available in four general types, each one having an infra-red LED source but with different photo-sensitive devices. The four optocouplers are: photo-transistor, photodarlington, photo-SCR and photo-triac as shown below:

Figure: Optocoupler Types The photo-transistor and photo-darlington devices are mainly for use in DC circuits while the photo-SCR and photo-triac allow AC powered circuits to be controlled. There are many other kinds of source-sensor combinations, such as LED-photodiode, LED-LASER, lampphotoresistor pairs, reflective and slotted optocouplers. Simple homemade optocouplers can be constructed by using individual components. An LED and a photo-transistor are inserted into a rigid plastic tube or encased in heat-shrinkable tubing as shown. The tubing can be of any length.

2.9.1 OPTOCOUPLER APPLICATIONS

Optocouplers and opto-isolators can be used on their own, or to switch a range of other larger electronic devices such as transistors and triacs providing the required electrical isolation between a lower voltage control signal and the higher voltage or current output signal. Common applications for optocouplers include microprocessor input/output switching, DC and AC power control, PC communications, signal isolation and power supply regulation which suffer from current ground loops, etc. The electrical signal being transmitted can be either analogue (linear) or digital (pulses). In the following application, the optocoupler is used to detect the operation of the switch or another type of digital input signal. This is useful if the switch or signal being detected is within an electrically noisy environment. The output can be used to operate an external circuit, light or as an input to a PC or microprocessor.

Figure: Optocoupler Switch Apart from detecting DC signals and data, Opto-triac isolators are also available which allow AC powered equipment and mains lamps to be controlled. Opto-coupled triacs such as the MOC 3020, have voltage ratings of about 400 volts making them ideal for direct mains connection and a maximum current of about 100mA. For higher powered loads, the opto-triac may be used to provide the gate pulse to another larger triac via a current limiting resistor as shown.

Figure: Optocoupler Triac Control This type of optocoupler configuration forms the basis of a very simple solid state relay application which can be used to control any AC mains powered load such as lamps and motors. Optocouplers and Opto-isolators are great electronic devices that allow devices such as transistors and triacs to be controlled from an output port, switch or low voltage data signal. Their main advantage is the high electrical isolation between the input and output. Optocouplers utilizing a SCR or triac as the photo-detector are designed for AC power-control applications. The main advantage in this configuration is the complete isolation from any noise or voltage spikes present on the AC line as well as zero-crossing detection which reduces the generation of electrical noise.

2.10 TRIAC
2.10.0 INTRODUCTION
A triac is a three terminal semiconductor device for controlling current. Triacs are widely used in AC power control applications. They are able to switch high voltages and high levels of current, and over both parts of an AC waveform. This makes triac circuits ideal for use in a variety of applications where power switching is needed. One particular use of triac circuits is in light dimmers for domestic lighting, and they are also used in many other power control situations including motor control.

A triac is effectively the development of a SCR or thyristor, but unlike the thyristor which is only able to conduct in one direction, the triac is a bidirectional device. As such the triac is an ideal device to use for AC switching applications because it can control the current flow over both halves of an alternating cycle. A thyristor is only able to control them over one half of a cycle; during the remaining half no conduction occurs and accordingly only half the waveform can be utilized.

2.10.1 TRIAC SYMBOL


The basic triac symbol used on circuit diagram indicates its bi-directional properties. The triac symbol can be seen to be a couple of thyristor symbols in opposite senses merged together. This is what the triac symbol indicates.

TRIAC Symbol for Circuit Diagrams Like a thyristor, a triac has three terminals. However the names of these are a little more difficult to assign, because the main current carrying terminals are connected to what is effectively a cathode of one thyristor, and the anode of another within the overall device. There is a gate which acts as a trigger to turn the device on. In addition to this the other terminals are either called Anodes, or Main Terminals. These are usually designated Anode 1 and Anode 2 or Main Terminal 1 and Main Terminal 2 (MT1 and MT2). When using triacs it is both MT1 and MT2 have very similar properties.

2.10.2 TRIAC STRUCTURE

The TRIAC structure is very different to that of the ordinary thyristor. Having the ability to switch signals on both halves of a cycle requires the TRIAC structure to be considerably more complicated than other similar devices. Nevertheless the TRIAC fabrication is well established and TRIACs are widely and cheaply available. As can be seen, the TRIAC structure consists of a number of different areas - typically four n-type areas as shown and two p-type areas. The structure of a TRIAC may be considered to be a DIAC with an additional gate contact provided to enable control of the device. Like other power devices, the TRIAC is normally made of silicon. Using a silicon fabrication process further enables the devices to be produced very cheaply. The market would not tolerate the devices if they were made using more expensive technologies.

The Structure of a TRIAC The gate contact is made to the p-base region, although there is an additional n-type diffusion layer placed under much of the gate.

2.10.3 TRIAC OPERATION


It is possible to view the operation of a triac in terms of two thyristors in parallel but around different ways. The operation of the triac can be looked on in this fashion, although the actual operation at the semiconductor level is rather more complicated.

TRIAC Equivalent as Two Thyristors When the voltage on the MT1 is positive with regard to MT2 and a positive gate voltage is applied, one of the thyristors conducts. When the voltage is reversed and a negative voltage is applied to the gate, the other thyristor conducts. This is provided that there is sufficient voltage across the device to enable a minimum holding current to flow. One of the drawbacks of the triac is that it does not switch symmetrically because of its internal construction and the slight differences between the two halves. It will often have an offset, switching at different gate voltages for each half of the cycle. This results in harmonics being generated: the less symmetrical the triac fires, the greater the level of harmonics that are produced. It is not normally desirable to have high levels of harmonics in a power system and as a result triacs are not favored for high power systems. Instead for these systems two thyristors may be used as it is easier to control their firing. To help in overcoming the problem of non-symmetrical firing and the resulting harmonics, a device known as a diac (diode AC switch) is often placed in series with the gate of the triac. The inclusion of this device helps make the switching more even for both halves of the cycle. This results from the fact that the diac switching characteristic is far more even than that of the triac. Since the diac prevents any gate current flowing until the trigger voltage has reached a certain voltage in either direction, this makes the firing point of the triac more even in both directions.

DIAC and TRIAC Connected Together

2.10.4 TRIAC ADVANTAGES AND DISADVANTAGES


When switching of both halves of an AC waveform is needed then there are two options that are normally considered. One is to use a TRIAC, and the other is to use two thyristors connected back to back - one thyristor is used to switch one half of the cycle and the second connected in the reverse direction operates on the other half cycle. As there are two options the advantages and disadvantages of using a TRIAC must be weighed up. TRIAC Advantages Can switch both halves of an AC waveform Single component can be used for full AC switching TRIAC Disadvantages A TRIAC does not fire symmetrically on both sides of the waveform Switching gives rise to high level of harmonics due to non-symmetrical switching More susceptible to EMI problems as a result of the non-symmetrical switching Care must be taken to ensure the TRIAC turns off fully when used with inductive loads

2.10.5 TRIAC APPLICATIONS


TRIACs are used in a number of applications. However they tend not to be used in high power switching applications - one of the reasons for this is the non-symmetrical switching characteristics. For high power applications this creates a number of difficulties, especially with electromagnetic interference. However TRIACs are still used for many electrical switching applications:

Domestic light dimmers Electric fan speed controls Small motor controls Control of small AC powered domestic appliances

The TRIAC is easy to use and provides cost advantages over the use of two thyristors for many low power applications. Where higher powers are needed, two thyristors placed in "anti-parallel" are almost always used.

3. DESIGN AND IMPLEMENTATION 3.1 CIRCUIT DIAGRAMS

3.2 CIRCUIT EXPLANATION


The complete project circuit can be divided into the following modules: 1. 8051 Minimal Configuration Module 2. LCD Display Module 3. ADC and LM35 Module 4. LEDs Module 5. ZCD and TRIAC Module 1. 8051 MINIMAL CONFIGURATION MODULE In order to use 8051 microcontroller we need the basic connections like RESET (Pin 9), Crystal (Pins 18 and 19), GND (Pin 20), EA (Pin 31), and VCC (Pin 40) as shown in the following diagram:

The PIN 9 is the reset pin which is used reset the microcontrollers internal registers and ports upon starting up. A high on this pin for two machine cycles while the oscillator is running resets the device. The PINS 18 and 19 are the crystal pins. The 8051 has a built-in oscillator amplifier hence we need to only connect a crystal at these pins to provide clock pulses to the circuit. The PINS 20 and 40 are GND and VCC respectively. The 8051 chip needs +5V 500mA to function properly. The PIN 31 is the external access pin. If EA = 1, the microcontroller executes the program code from its internal program memory. If EA = 0, the microcontroller executes the program code from external program memory. In our project, the program code is present in the internal program memory of 8051. So, this pin is connected to VCC. 2. LCD DISPLAY MODULE The project uses a 16x2 alphanumeric LCD to display various messages like current temperature and fan status (including speed levels). The microcontroller interfaces with this alphanumeric

LCD in 4-bit mode. The alphanumeric LCD contains totally 16 pins and these are connected as follows:

The above diagram indicates the following configuration: Pins 1 (VSS) and 16 (LED-) are connected to GND. Pins 2 (VDD) and 15 (LED+) are connected to VCC. Pin 3 (VEE) is connected to 10k POT. Pin 4 (RS) is connected to microcontroller (P0.5). Pin 5 (R/W) is connected to GND. Pin 6 (E) is connected to microcontroller (P0.7). Pins 11 to 14 (DB0 DB7 i.e., 4 data pins) are connected to microcontroller port P0 (P0.0, P0.1, P0.2, and P0.3).

The R/W pin of LCD is connected to GND, which indicates that we are only writing to LCD. We are not reading anything from the LCD. The 4 data pins of LCD are connected to port P0. The port P0 doesnt have internal pull up resistors. So, we are connecting external pull up resistors to port P0. For this, we are using a 10K resistor pack available in SIL package. 1. ADC AND LM35 MODULE The temperature sensor LM35 gives the output in analog form. So, we are converting this analog value to digital value with the help of analog-to-digital converter. The ADC IC used in this project is ADC0804. The ADC0804 is an 8-bit parallel ADC i.e., its resolution is 8 bits. It is available in 20-pin DIP package and we did the configuration as follows: Pin 1 (CS) is connected to GND. Pin 2 (RD) is connected to microcontroller (P3.5). Pin 3 (WR) is connected to microcontroller (P3.6). Pins 4 (CLK IN) and 19 (CLK R) are connected to a capacitor (150pF) and a resistor (10k). Pin 5 (INTR) is connected to microcontroller (P3.7). Pin 6 (Vin(+)) is connected to the output pin of LM35. Pin 7 (Vin(-)) is connected to GND. Pin 8 (AGND) is connected to GND. Pin 9 (Vref/2) is connected to 10k POT. Pin 10 (DGND) is connected to GND. Pins 18 to 11 (DB0 DB7 i.e., data pins) are connected to microcontroller port P1. Pin 20 (VCC) is connected to VCC.

The temperature sensor LM35 has 3 pins and we did its configuration as follows: Pin 1 (+Vs) is connected to VCC (+5V).

Pin 2 (Vout) is connected to Vin(+) of ADC0804. Pin 3 (GND) is connected to GND.

The ADC0804 has an internal clock generator. To use the internal clock generator of the ADC0804, the CLK IN and CLK R pins are connected to a capacitor and a resistor. The output of LM35 linearly varies with temperature. The output range of LM35 is 0 to 1.50V and scaling is 10 mV per degree centigrade. So, we need to set the reference voltage of ADC to 1.50V. For this, we are using a 10k POT and Vref/2 is set to 0.75V. 1. LEDS MODULE The project uses six LEDs to display the fan speed levels. If the temperature is less than 35oC, all LEDs are turned OFF. If the temperature is greater than or equal to 35oC and less than 40oC, the first LED will be turned ON to indicate the speed level as 1. If the temperature is greater than or equal to 40oC and less than 45oC, the first two LEDS will be turned ON to indicate the speed

level as 2, and so on. The following figure shows how to interface the LEDs to microcontroller. As you can see the Anode is connected through a resistor to Vcc and the Cathode is connected to the microcontroller pin. So, when the port pin is HIGH the LED is OFF and when the port pin is LOW the LED is turned ON.

2. ZCD AND TRIAC MODULE The microcontroller interfaces with a TRIAC (BT136) via an optocoupler (MOC3021) for varying the fan speed. The main advantage of using a TRIAC to vary the speed of an AC motor is the TRIAC reduces the energy flow to the motor and TRIAC works very well for alternating currents. An optocoupler uses a short optical transmission path to transfer a signal between the elements of circuit, while keeping them electrically isolated. This isolation makes sense only if diodes and photo-sensitive elements are separately powered. In this way, the microcontroller and expensive additional electronics are completely protected from high voltage and noises which are the most common cause of destroying, damaging or unstable operation of electronic devices in practice. A zero crossing detector circuit is used to interrupt the microcontroller. After getting an interrupt, the microcontroller will fire TRIAC after some delay. This will cut the current supplied to motor and so the speed of motor will vary. Thus by varying the delay after which the TRIAC

is triggered we can change the speed of fan. The following diagram will show zero crossing detector and TRIAC interfacing with microcontroller:

3.5 SOURCE CODE


/* PROGRAM FOR AUTOMATIC SPEED CONTROLLER FOR FANS */ #include <reg51.h> #define LCD_RS 0x20 #define LCD_EN 0x80 #define LCD_PORT P0 #define ADC_DATA P1 sbit LED1 = P2^0; sbit LED2 = P2^1; sbit LED3 = P2^2;

sbit sbit sbit sbit sbit sbit sbit

LED4 = P2^3; LED5 = P2^4; LED6 = P2^5; FAN = P3^4; ADC_RD = P3^5; ADC_WR = P3^6; ADC_INTR = P3^7;

/* Global Variables */ unsigned char speedLevel; /* General Routines */ void Initialize(void); void LCD_Reset(void); void LCD_Initialize(void); void LCD_SendCommand(unsigned char val); void LCD_SendCharacter(unsigned char val); void LCD_SendMessage(unsigned char *p); unsigned char ADC_Convert(void); void Delay(unsigned int n); void TRIAC_Delay(unsigned char n); /* Interrupt Routines */ void ExternalInterrupt1(void) interrupt 2 { switch (speedLevel) { case 0: FAN = 1; break; case 1: TRIAC_Delay(10); FAN = 0; TRIAC_Delay(3); FAN = 1; break; TRIAC_Delay(9); FAN = 0; TRIAC_Delay(3); FAN = 1; break; TRIAC_Delay(8); FAN = 0; TRIAC_Delay(3); FAN = 1; break; TRIAC_Delay(6);

case 2:

case 3:

case 4:

FAN = 0; TRIAC_Delay(3); FAN = 1; break; case 5: TRIAC_Delay(4); FAN = 0; TRIAC_Delay(3); FAN = 1; break; TRIAC_Delay(1); FAN = 0; TRIAC_Delay(3); FAN = 1; break;

case 6:

} } /* Main Routine */ void main(void) { unsigned char previousTemperature,currentTemperature,adcVal,i; Initialize(); previousTemperature = 0; while (1) { adcVal = ADC_Convert(); currentTemperature = ((1.50 / 255.0) * adcVal) * 100; LCD_SendCommand(0x80); LCD_SendMessage("TEMPERATURE:"); LCD_SendCharacter((currentTemperature/100) + '0'); LCD_SendCharacter(((currentTemperature/10) % 10) + '0'); LCD_SendCharacter((currentTemperature%10) + '0'); LCD_SendCharacter('C'); LCD_SendCommand(0xC0); if (currentTemperature != previousTemperature) { if (currentTemperature < 35) { speedLevel = 0; LED1 = LED2 = LED3 = LED4 = LED5 = LED6 = 1; LCD_SendMessage("FAN OFF "); }

else if (currentTemperature < 40) { speedLevel = 1; LED2 = LED3 = LED4 = LED5 = LED6 LED1 = 0; LCD_SendMessage("SPEED LEVEL: 1 } else if (currentTemperature < 45) { speedLevel = 2; LED3 = LED4 = LED5 = LED6 = 1; LED1 = LED2 = 0; LCD_SendMessage("SPEED LEVEL: 2 } else if (currentTemperature < 50) { speedLevel = 3; LED4 = LED5 = LED6 = 1; LED1 = LED2 = LED3 = 0; LCD_SendMessage("SPEED LEVEL: 3 } else if (currentTemperature < 55) { speedLevel = 4; LED5 = LED6 = 1; LED1 = LED2 = LED3 = LED4 = 0; LCD_SendMessage("SPEED LEVEL: 4 } else if (currentTemperature < 60) { speedLevel = 5; LED6 = 1; LED1 = LED2 = LED3 = LED4 = LED5 LCD_SendMessage("SPEED LEVEL: 5 } else { speedLevel = 6; LED1 = LED2 = LED3 = LED4 = LED5 LCD_SendMessage("SPEED LEVEL: 6 }

= 1; ");

");

");

");

= 0; ");

= LED6 = 0; ");

previousTemperature = currentTemperature; for ( i = 0; i < 10; i++) Delay(65000); } } }

void Initialize(void) { FAN = 1; LED1 = LED2 = LED3 = LED4= LED5 = LED6 = 1; LCD_Initialize(); speedLevel = 0; IT1 = 1; IE = 0x84; } void LCD_Reset(void) { LCD_PORT = 0xFF; Delay(20000); LCD_PORT LCD_PORT LCD_PORT LCD_PORT = = = = 0x03 + LCD_EN; 0x03; 0x00 + LCD_EN; 0x00;

Delay(10000); LCD_PORT LCD_PORT LCD_PORT LCD_PORT = = = = 0x03 + LCD_EN; 0x03; 0x00 + LCD_EN; 0x00;

Delay(1000); LCD_PORT LCD_PORT LCD_PORT LCD_PORT = = = = 0x03 + LCD_EN; 0x03; 0x00 + LCD_EN; 0x00;

Delay(1000); LCD_PORT LCD_PORT LCD_PORT LCD_PORT = = = = 0x02 + LCD_EN; 0x02; 0x00 + LCD_EN; 0x00;

Delay(1000); } void LCD_Initialize(void)

{ LCD_Reset(); LCD_SendCommand(0x28); LCD_SendCommand(0x0C); LCD_SendCommand(0x01); LCD_SendCommand(0x06); LCD_SendCommand(0x80); } void LCD_SendCommand(unsigned char val) { LCD_PORT = ((val >> 4) & 0x0F) | LCD_EN; LCD_PORT = (val >> 4) & 0x0F; LCD_PORT = (val & 0x0F) | LCD_EN; LCD_PORT = val & 0x0F; Delay(1000); } void LCD_SendCharacter(unsigned char val) { LCD_PORT = ((val >> 4) & 0x0F) | LCD_EN | LCD_RS; LCD_PORT = ((val >> 4) & 0x0F) | LCD_RS; LCD_PORT = (val & 0x0F) | LCD_EN | LCD_RS; LCD_PORT = (val & 0x0F) | LCD_RS; Delay(1000); } void LCD_SendMessage(unsigned char *p) { while (*p) LCD_SendCharacter(*p++); } unsigned char ADC_Convert(void) { unsigned char adcVal; ADC_DATA = 0xFF; ADC_INTR = 1; ADC_RD = 1; ADC_WR = 1; ADC_WR = 0; ADC_WR = 1; while (ADC_INTR == 1); ADC_RD = 0;

adcVal = ADC_DATA; ADC_RD = 1; return adcVal; } void Delay(unsigned int n) { while (n--) ; } void TRIAC_Delay(unsigned char n) { TMOD = 0x01; while(n--) { TH0 = TL0 = TR0 = while

0xFE; 0x0C; 1; (TF0 == 0) ; TR0 = 0; TF0 = 0;

} }

4. RESULT & CONCLUSION


The Automatic Speed Controller for Fans project was finally completed. A lot of effort was put into the design, implementation and days of toil in front of the computer, writing and debugging the code. The project was finally completed with 100% expected results. We earned a lot of knowledge on microcontrollers. A deeper and clearer view of the architecture, ports & all other functional blocks was achieved. We had a peek look at all simple functional parts of the project like the crystal oscillator, logic gates and the works. Well, these were the topics that we have already dealt with, but we must be honest and admit that there were various practical issues which one would learn only during a project. Theres a lot of learning & yet not the end, learning is a continuous never ending process but is definitely fun.

5. BIBLIOGRAPHY

BOOKS MCS-51 Microcontroller Family Users Manual The 8051 Microcontroller and Embedded Systems by Muhammad A Mazidi, Janice Mazidi, Rolin Mc Kinlay

WEBSITES

www.8051projects.net www.8052.com en.wikipedia.org

You might also like