You are on page 1of 53

A PROJECT REPORT ON

AUTO INTENSITY CONTROL OF STREET LIGHTS USING LDR

Submitted in partial fulfillment of the requirements

For the award of the degree

Bachelor Of Engineering

In

Electrical & Electronics Engineering

SUBMITTED BY

-------------------- (--------------)

--------------------- (---------------)

--------------------- (---------------)

DEPARTMENT OF EEE AFFILIATED TO ___________ UNIVERSITY

1
CERTIFICATE

This is to certify that the dissertation work entitled AUTO INTENSITY CONTROL OF STREET
LIGHTS USING LDR is the work done by
___________________________________________submitted in partial
fulfillment for the award of Master Of Science in Electronics
from______________ College affiliated to _________ University, Hyderabad .

________________ ____________

(Head of the Department, EEE) (Assistant Professor)

EXTERNAL EXAMINER

2
ACKNOWLEDGEMENT

The satisfaction that accompany the successful completion of any task


would be incomplete without mentioning of the people whose constant guidance
and encouragement made it possible. We take pleasure in presenting before you,
our project, which is result of studied blend of both research and knowledge.

We express our earnest gratitude to our internal guide, Assistant Professor


______________, Department of EEE, our project guide, for his constant support,
encouragement and guidance. We are grateful for his cooperation and his
valuable suggestions.

Finally, we express our gratitude to all other members who are involved either
directly or indirectly for the completion of this project.

3
DECLARATION

We, the undersigned, declare that the project entitled AUTO INTENSITY CONTROL OF
STREET LIGHTS USING LDR, being submitted in partial fulfillment for the award of

Master Of Science Degree in Electronics affiliated to _________ University, is the


work carried out by us.

4
INDEX

Contents Page No.

Abstract

Introduction to Embedded systems

Microcontroller AT89S52.

Hardware Description.

Coding..

Software Description

Conclusion

References.

5
ABSTRACT

AUTO INTENSITY CONTROL OF STREET LIGHTS USING LDR

This project consists of LDR(Light Dependent Resistor). The resistance of LDR


changes according to light illumination on its surface which in turn changes its voltage
output. The voltage from LDR is given to ADC which converts it into digital data and is
given to microcontroller. The microcontroller monitors voltage level and controls the
intensity of street light LEDs using PWM method through transistor driver circuit.

We are using 89S52 microcontroller and 16*2 LCD display to show the
status of the circuit. The regulated power supply is given to the circuit.

SOFTWARE USED

1. KEIL COMPILER
2. EMBEDDED C
3. MICRO FLASH

HARDWARE USED

1. LDR SENSOR
2. MICRO CONTROLLER AT89S52
3. TRANSISTOR DRIVER BC547
4. 7805
5. 16*2 LCD DISPLAY
6. WHITE LEDS

6
BLOCK DIAGRAM:

89S52 MCU WHITE


MCP3208 TRANSISTOR LEDs
LDR DRIVER BC547

REGULATED POWER
SUPPLY

7
INTRODUCTION TO EMBEDDED SYSEMS

Embedded systems have grown tremendously in recent years, not only in their popularity but
also in their complexity. Gadgets are increasingly becoming intelligent and autonomous. Refrigerators,
air-conditioners, automobiles, mobile phones etc are some of the common examples of devices with
built in intelligence. These devices function based on operating and environmental parameters.

The intelligence of smart devices resides in embedded systems. An embedded system, in


general, in co-operates hardware, operating systems, low-level software binding the operating system
and peripheral devices, and communication software to enable the device to perform the pre-defined
functions. An embedded system performs a single, well-defined task, is tightly constrained, is reactive
and computes results in real time.

Let us take a detailed look at these features of embedded systems:

Single functioned: An embedded system executes a specific program repeatedly. For


example, a pager is always a pager. In contrast a desktop system executes a variety of programs like
spreadsheets, word processors, etc. However there are exceptions where in an embedded systems
program is updated with newer program versions. Cell phones are examples of being updated in such a
manner.
Tightly constrained: All computing systems have constraints on design metrics but those
on embedded systems can be especially tight. A design metric is a measure of an implementations
features, such as cost, size performance and power.
Reactive and real time: Many embedded systems must continually react to changes in the
systems environment and must compute certain results in real time without delay.

8
Embedded Hardware

All embedded systems need a microprocessor, and the kinds of microprocessors used in
them are quite varied. A list of some of the common microprocessor families is the ZILOG Z8
family, Intel 805/80188/x 86 families, Motorola 68k family and the PowerPC family.

Embedded Software
The software for the embedded systems is called firmware. The firmware will be written in
assembly languages for time or resource critical operations or using higher-level languages like C or
embedded C. The software will be simulated using micro code simulators for the target processor. Since
they are supposed to perform only specific tasks these programs are stored in Read Only Memories
(ROMs).

Application areas for embedded systems

Embedded software is present in almost every electronic device you use today. There is
embedded software inside your watch, cellular phone, automobile, thermostats, Industrial control
equipment and scientific and medical equipment. Defence services use embedded software to guide
missiles and detect aircrafts. Communication satellites, medical instruments and deep space probes
would have been nearly impossible without these systems. Embedded systems cover such as broad
range of products that generalization is difficult.

Here are some broad categories.

Aerospace and Defense Electronics (ADE)


Consumer/Internet applications
Data Communications
Digital imaging
Medical electronic Mobile data infrastructures

9
Block diagram of Embedded System:

Embedded

System

Software Hardware

o ALP o Processor
o C o Peripherals
o VB o memory
Etc.,

Software deals with the languages like ALP, C, and VB etc., and Hardware deals with Processors,
Peripherals, and Memory.

Memory: It is used to store data or address.

Peripherals: These are the external devices connected

Processor: It is an IC which is used to perform some task


Processors are classified into four types like:
1. Micro Processor (p)
2. Micro controller (c)
3. Digital Signal Processor (DSP)
4. Application Specific Integrated Circuits (ASIC)

10
MICROCONTROLLER

Basically, a microcontroller is a device which integrates a number of the components of a


microprocessor system onto a single microchip. So a microcontroller combines onto the same
microchip. The following components:

CPU Core
Memory (Both RAM and ROM)
Some Parallel Digital I/Os
The microprocessor is the integration of a number of useful functions into a single IC
package. Has the ability to execute a stored set of instructions to carry out user defined tasks;
also has ability to access external memory chips to both read and write data from and to the
memory.

Essentially, a microcontroller is obtained by integrating the key components of


microprocessor, RAM, ROM, and Digital I/O onto the same chip die. Modern microcontrollers
also contain a wealth of other modules such as Serial I/O, Timers, and Analogue to Digital
Converters. There are a large number of specialized devices with additional modules for specific
needs. E.g. CAN controllers.

11
MICROCONTOLLER (AT89S52)

FEATURES

Compatible with MCS-51 Products

8K Bytes of In-System Programmable (ISP) Flash Memory

4.0V to 5.5V Operating Range

Fully Static Operation: 0 Hz to 33 MHz

256Bytes Internal RAM

32 Programmable I/O Lines

3 16-bit Timer/Counters

Full Duplex UART Serial Channel

12
DESCRIPTION OF MICROCONTROLLER AT 89S52:

The AT89S52 is a low-power, high-performance CMOS 8-bit micro


controller with 8Kbytes of in-system programmable Flash memory. The device is
manufactured

Using Atmels high-density non-volatile memory technology and is compatible


with the industry-standard 80C51 micro controller. The on-chip Flash allows the program
memory to be reprogrammed in-system or by a conventional non-volatile memory programmer.
By combining a versatile 8-bit CPU with in-system programmable flash one monolithic chip; the
Atmel AT89S52 is a powerful micro controller, which provides a highly flexible and cost-
effective solution to many embedded control applications.

13
The AT89S52 provides the following standard features: 8K bytes of Flash, 256 bytes of
RAM, 32 I/O lines, Watchdog timer, two data pointers, three 16-bit timer/counters, full
duplex serial port, on-chip oscillator, and clock circuitry. In addition, the AT89S52 is
designed with static logic for perationdown 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 interrupt or hardware reset.

14
PIN DESCRIPTION OF MICROCONTROLLER AT89S52

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 1sare written to port 0 pins, the pins can be used as high impedance
inputs. Port 0 can 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. In addition, P1.0 and P1.1 can be
configured to be the timer/counter 2 external count input

(P1.0/T2) and the timer/counter 2 trigger input P1.1/T2EX), respectively, as shown in


the following table. Port 1 also receives the low-order address bytes during Flash programming .

15
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 emits the high-order address
byte during fetches from external program memory and during accesses to external data
memory that uses 16-bit addresses (MOVX @DPTR). In this application, Port 2 uses strong
internal pull-ups when emitting 1s. During accesses to external data memory that use 8-bit
addresses (MOVX @ RI), Port 2emits the contents of the P2 Special Function Register. Port
2 also receives the high-order address bits and some control signals during Flash
programming and verification.

Port 3

Port 3 is an 8-bit bi-directional I/O port with internal pull-ups. The Port 3 output buffers
can sink/source four TTL inputs. When 1s are written to Port 3 pins, they are pulled high by the
internal pull-ups and can be used as inputs. As inputs, Port 3 pins that are externally being pulled
low will source current (IIL) because of the pull-ups. Port 3 also serves the functions of various
special features of the AT89S52, as shown in the following table.

Port 3 also receives some control signals for Flash programming and verification.

16
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 (ALE) is an 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 of1/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. If desired, ALE operation can
be disabled by setting bit 0 of SFR location

8EH. with the bit set, ALE is active only during a MOVX or MOVC
instruction. Otherwise, the pin is weakly pulled high. Setting the ALE-disable bit has no
effect if the micro controller is in external execution mode.

PSEN

Program Store Enable (PSEN) is the read strobe to external program memory. When the
AT89S52 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. A should
be strapped to VCC for internal program executions. This pin also receives the 12-
voltProgramming enables voltage (VPP) during Flash programming.

17
XTAL1

Input to the inverting oscillator amplifier and input to the internal clock operating circuit.

XTAL2

Output from the inverting oscillator amplifier.

Oscillator Characteristics

XTAL1 and XTAL2 are the input and output, respectively, of an inverting amplifier
that can be configured for use as an on-chip oscillator, as shown in Figure 1. 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,
as shown in Figure 2.

18
Hardware Description
Power supply description:

As the microcontroller operating voltage is +5V DC. Through this power


supply circuit we have to create a +5V DC which is given to the micro controller.
The below components are used to create the power supply

230V AC Step down Bridge Filter Regulator


supply transformer rectifier

Description:

230V AC supply is given to the step down transformer of 12A type. It may
be a 230V to 9V or 12V step down transformer. The output of the step down
transformer is given to bridge rectifier. The bridge rectifier is formed with 1N4007
diodes. The bridge rectifier converts the AC Voltage into DC Voltage. But the
output DC Voltage contains some AC component (ripples). So we use a capacitors-
2200uF/25V, 0.1uF/D and resistor of 10K as a filter for removing ripples. That
output DC Voltage is given to the positive voltage regulator LM7805 (i.e., 78
represents the positive series and 5 represent the output voltage it can provide).
So the output of the regulator will be the regulated +5V DC. To indicate the
condition of the circuit we place a LED at the end of the circuit.

19
( Fig 1.1 +5V Regulated Power Supply )

Voltage Regulators

Voltage regulators comprise a class of widely used ICs. Regulator IC units


contain the circuitry for reference source, comparator amplifier, control device, and
overload protection all in a single IC. IC units provide regulation of either a fixed
positive voltage, a fixed negative voltage, or an adjustably set voltage. A fixed
three-terminal voltage regulator has an unregulated dc input voltage, Vi, applied to
one input terminal, a regulated dc output voltage, Vo, from a second terminal, with
the third terminal connected to ground.

The series 78 regulators provide fixed positive regulated voltages from 5 to


24 volts. Similarly, the series 79 regulators provide fixed negative regulated
voltages from 5 to 24 volts.

20
IC Voltage Regulators

Voltage regulator ICs are available with fixed (typically 5, 12 and 15V) or
variable output voltages. They are also rated by the maximum current they can
pass. Negative voltage regulators are available, mainly for use in dual supplies.
Most regulators include some automatic protection from excessive current
('overload protection') and overheating ('thermal protection').

Many of the fixed voltage regulator ICs has 3 leads and look like power transistors,

IC Voltage Regulator

21
LIGHT SENSOR

Light Dependent Resistor (LDR) also known as photoconductor or photocell, is a


device which has a resistance which varies according to the amount of light falling on its
surface. Since LDR is extremely sensitive in visible light range, it is well suited for the
proposed application.

Features of the light sensor:

The Light Dependent Resistor (LDR) is made using the semiconductor Cadmium
Sulphide (CdS).

The light falling on the brown zigzag lines on the sensor causes the resistance of the
device to fall. This is known as a negative co-efficient. There are some LDRs that work in
the opposite way i.e. their resistance increases with light (called positive co- efficient).

The resistance of the LDR decreases as the intensity of the light falling on it increases.

Incident photons drive electrons from the valence band into the conduction band.

Cadmium
Cadmium Sulphide track
Sulphide

22
LIQUID CRYSTAL DISPLAY (LCD) OPERATION:

In recent years LCD is finding wide spread use replacing LEDs.This is due to the following reasons.

1. The declining prices of LCDs.

2. The ability to display numbers, characters, and graphics. This is in contrast to LEDs, which are limited
numbers and a few characters.

3. In corporation of a refreshing controller into the LCD, thereby relieving the CPU of the task of
refreshing the LCD. In contrast, the LED must be refreshed by the CPU to keep displaying the data.

4. Ease of programming for characters and graphics.

LCD pin descriptions:

The LCD discussed in this section has 14 pins.

VCC, VSS&VEE:

While Vcc & Vss provide +5v & ground, respectively, Vee is used for controlling LCD contrast.

RS, Register select:

There are two very important registers inside the LCD.The RS pin is used for their section as
follows:

If RS=0, the instruction command code register is selected, allowing the user to send a
command such as clear display, cursor at home etc.

If RS=1, the data register is selected, allowing the user to send data to be displayed on the
LCD.

23
R/W, read/write:

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

E, Enable:

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

D0-D7:

The 8-bit data pins, D0-D7, are used to send information to the LCD or to read the contents of
the LCDs internal register.

To display letters and numbers, we send ASCII codes for the letters A-Z, a-z, and number 0-9
to these pins while making RS=1. We also use RS=0 to check the busy flag bit to see if the LCD is ready to
receive the information.

The busy flag is D7 and can be read when R/W=1 and RS=0, as follows: if R/W=1, RS=0. When
D7=1, the LCD is busy taking care of internal operations and will not accept any new information. When
D7=0, the LCD is ready to receive information.

It is recommended to check the busy flag before writing any data to the LCD.

24
LCD COMMAND CODES:

S(HEX) Register

1 Clear the display screen

2 Return home

4 Decrement cursor

6 Increment cursor

25
BC547

The BC547 transistor is an NPN Epitaxial Silicon Transistor. The BC547 transistor is a general-
purpose transistor in small plastic packages. It is used in general-purpose switching and
amplification BC847/BC547 series 45 V, 100 mA NPN general-purpose transistors.

BC 547 TRANSISTOR PINOUTS


The BC547 transistor is an NPN bipolar transistor, in which the letters "N" and "P" refer
to the majority charge carriers inside the different regions of the transistor. Most bipolar
transistors used today are NPN, because electron mobility is higher than hole mobility in
semiconductors, allowing greater currents and faster operation. NPN transistors consist of a layer
of P-doped semiconductor (the "base") between two N-doped layers. A small current entering the
base in common-emitter mode is amplified in the collector output. In other terms, an NPN
transistor is "on" when its base is pulled high relative to the emitter. The arrow in the NPN
transistor symbol is on the emitter leg and points in the direction of the conventional current flow
when the device is in forward active mode. One mnemonic device for identifying the symbol for
the NPN transistor is "not pointing in." An NPN transistor can be considered as two diodes with
a shared anode region. In typical operation, the emitter base junction is forward biased and the
base collector junction is reverse biased. In an NPN transistor, for example, when a positive
voltage is applied to the base emitter junction, the equilibrium between thermally generated
carriers and the repelling electric field of the depletion region becomes unbalanced, allowing
thermally excited electrons to inject into the base region. These electrons wander (or "diffuse")
through the base from the region of high concentration near the emitter towards the region of low
concentration near the collector. The electrons in the base are called minority carriers because
the base is doped p-type which would make holes the majority carrier in the base.

26
Pulse Width Modulated Waveform :

The use of pulse width modulation to control dc voltage on LED or control ac voltage on ac lamp
using either fully ON or fully OFF state.

PWM
Pulse-width modulation (PWM) is a commonly used technique for controlling power to
an electrical device, made practical by modern electronic power switches. The average value of
voltage (and current) fed to the load is controlled by turning the switch between supply and load
on and off at a fast pace. The longer the switch is on compared to the off periods, the higher the
power supplied to the load is.
The PWM switching frequency has to be much faster than what would affect the load,
which is to say the device that uses the power. Typically switchings have to be done several
times a minute in an electric stove, 120 Hz in a lamp dimmer, from few kilohertz (kHz) to tens of
kHz for a motor drive and well into the tens or hundreds of kHz in audio amplifiers and
computer power supplies.
The term duty cycle describes the proportion of on time to the regular interval or period
of time; a low duty cycle corresponds to low power, because the power is off for most of the
time. Duty cycle is expressed in percent, 100% being fully on.
The main advantage of PWM is that power loss in the switching devices is very low.
When a switch is off there is practically no current, and when it is on, there is almost no voltage
drop across the switch. Power loss, being the product of voltage and current, is thus in both cases
close to zero. PWM works also well with digital controls, which, because of their on/off nature,
can easily set the needed duty cycle.

27
PWM has also been used in certain communication systems where its duty cycle has been
used to convey information over a communications channel.

Power delivery
PWM can be used to adjust the total amount of power delivered to a load without losses
normally incurred when a power transfer is limited by resistive means. The drawbacks are the
pulsations defined by the duty cycle, switching frequency and properties of the load. With a
sufficiently high switching frequency and, when necessary, using additional passive electronic
filters the pulse train can be smoothed and average analog waveform recovered.

Modern semiconductor switches such as MOSFETs or Insulated-gate bipolar transistors


(IGBTs) are quite ideal components. Thus high efficiency controllers can be built. Typically
frequency converters used to control AC motors have efficiency that is better than 98 %.
Switching power supplies have lower efficiency due to low output voltage levels (often even less
than 2 V for microprocessors are needed) but still more than 70-80 % efficiency can be achieved.

Variable-speed fan controllers for computers usually use PWM, as it is far more efficient
when compared to a potentiometer or rheostat. (Neither of the latter is practical to operate
electronically; they would require a small drive motor).

These rather simple types of dimmers can be effectively used with inert (or relatively slow
reacting) light sources such as incandescent lamps, for example, for which the additional
modulation in supplied electrical energy which is caused by the dimmer causes only negligible
additional fluctuations in the emitted light. Some other types of light sources such as light-
emitting diodes (LEDs), however, turn on and off extremely rapidly and would perceivably
flicker if supplied with low frequency drive voltages. Perceivable flicker effects from such rapid
response light sources can be reduced by increasing the PWM frequency

28
ADC

A very common external ADC is from Microchip the MCP3204. It has the following
configuration.

100K samples per second. (More than 6 times faster than AVRs inbuilt)
12 bit resolution (4 times more detailed)
4 input channels (MCP3208 has 8 channels).
SPI Bus Compatible.

Basic SPI Tutorial

These ADCs are SPI Bus based which is a serial bus. So the number of pins in IC is very low.
Total of 4 lines are required to interface it with AVR MCU.

1. MISO (Master In Slave Out)


2. MOSI (Master Out Slave In)
3. SCK (Serial Clock)
4. CS (Chip Select)

As you know in synchronous serial communication their is a clock line (SCK in case of SPI)
which synchronizes the transfer

The clock is always controlled by the MASTER. In our case the AVR MCU is the MASTER and
the MCP3204 is a slave on the bus. SPI is full duplex, that means data can be sent and
received simultaneously

The MCP3204 12 bit SPI ADC Chip.

The PIN out of MCP3204 is shown below.

MCP3204 SPI ADC Pin Configuration

29
1. CH0 : Analog Input Channel 0
2. CH1 : Analog Input Channel 1
3. CH2 : Analog Input Channel 2
4. CH3 : Analog Input Channel 3
5. N/C : Not Connected.
6. N/C : Not Connected.
7. DGND : Digital Ground.
8. CS: Chip Select.
9. Din : Connected to AVRs MOSI
10. Dout : Connected to AVRs MISO
11. CLK : Connected to AVRs SCK
12. Agnd : Analog Ground
13. Vref : Reference Voltage. (Don't know what is Vref then See: Using the Analog
To Digital Converter. )
14. Vdd : Positive supply (5v).

30
PRINTED CIRCUIT BOARD

Printed circuit boards may be covered in two topics namely

1) Technology

2) Design

Introduction to printed circuit boards:

It is called PCB in short printed circuit consists of conductive circuit pattern

Applied to one or both sides of an insulating base, depending upon that, it is called single sided
PCB or double-sided PCB.(SSB and DSB).

Conductor materials available are silver, brass, aluminium and copper. Copper is most
widely used. The thickness of conducting material depends upon the current carrying capacity
of circuit. Thus a thicker copper layer will have more current carrying capacity.

The printed circuit boards usually serves three distinct functions.

1) it provides mechanical support for the components mounted on it.


2) It provides necessary electrical interconnections.
3) It acts as heat sink that is provides a conduction path leading to removal of the heat
generated in the circuit.

31
Advantages of PCB:

1) When a number of identical assemblies are required. PCBs provide cost saving because
once a layout is approved there is no need to check the circuit every time.

2) For large equipments such as computers, the saving on checking connections or wires is
substantial.

3) PCBs have controllable and predictable electrical and mechanical properties.

4) A more uniform product is produced because wiring errors are eliminated.

5) The distributed capacitances are constant from one production to another.

6) Soldering is done in one operation instead of connecting discrete components by wires.

7) The PCB construction lands itself for automatic assembly.

8) Spiral type of inductors may be printed.

9) Weight is less.

10) It has miniaturization potential.

11) It has reproducible performance.

12) All the signals are accessible for testing at any point along conductor track.

32
CODING :

#include<reg52.h>

#include "lcd.h"

void InitTimer0(void);

void InitPWM(void);

sbit sck = P1^0;

sbit dout = P1^1;

sbit din = P1^2;

sbit cs = P1^3;

sbit PWM_Pin = P1^4;

unsigned char PWM = 0; // It can have a value from 0 (0% duty cycle) to 255 (100% duty cycle)

unsigned int temp = 0; // Used inside Timer0 ISR

unsigned char txrxbyte(unsigned char);

#define PWM_Freq_Num 1 // Highest possible PWM Frequency

unsigned char byte1,byte2,byte3;

float dcode1,dcode2,dcode3;

float vref=4.096,output,output1,output2,output3;

unsigned int i,j,k;

unsigned char str[20];

void transmit(unsigned char *);

33
void intr(void) interrupt 4

if(TI)

TI=0;

if(RI)

RI=0;

void main()

TMOD=0X20;

SCON=0X50;

IE=0X90;

TH1=0XFD;

TR1=1;

//PWM_Pin=0;

init_lcd();

display_lcd("LDR BASED LIGHT");

cmd_lcd(0xc0);

display_lcd("INTENSITY");

delay_ms(1000);

cmd_lcd(0x01);

cs=0;

34
while(1)

cs=0;

byte1=txrxbyte(0x06);

byte2=txrxbyte(0x00);

byte3=txrxbyte(0x00);

i=(byte2&0x0f);

i=(i<<8|byte3);

output1=(((vref*i)/4096));

output1=(output1*100);

cs=1;

delay_ms(10);

cs=0;

byte1=txrxbyte(0x06);

byte2=txrxbyte(0x40);

byte3=txrxbyte(0x00);

///////////////////////////////////////

i=(byte2&0x0f);

i=(i<<8|byte3);

output3=(((vref*i)/4096));

//output1=dcode1;

output3=output3*1000;

35
cs=1;

delay_ms(10);

cs=0;

byte1=txrxbyte(0x06);

byte2=txrxbyte(0xc0);

byte3=txrxbyte(0x00);

i=(byte2&0x0f);

i=(i<<8|byte3);

output=(((vref*i)/4096));

//output1=dcode1;

output=output*1000;

output=output/53;

cs=1;

delay_ms(10);

cmd_lcd(0x80);

transmit("\r\nLIGHT INTENSITY: ");

//float_lcd(output1);

delay_ms(100);

//display_lcd("% ");

/* cmd_lcd(0xc0);

transmit("\r\nGAS(PPM): ");

integer_lcd(output3);

delay_ms(100);

36
display_lcd(" PPM");

display_lcd(" ");

transmit("\r\n---------------------------- \r\n"); */

InitPWM(); // Start PWM

PWM=0; //Make 0% duty cycle

if(output1>50 && output1<=100)

PWM=255;

cmd_lcd(0x01);

display_lcd("PWM 100 %");

cmd_lcd(0xc0);

// float_lcd(output1);

//delay_ms(500);

cmd_lcd(0x01);

37
if(output1>100 && output1<=200)

PWM=180;

cmd_lcd(0x01);

display_lcd("PWM 75 %");

cmd_lcd(0xc0);

//float_lcd(output1);

//delay_ms(500);

cmd_lcd(0x01);

if(output1>200 && output1<=300)

PWM=125;

cmd_lcd(0x01);

display_lcd("PWM 50 %");

cmd_lcd(0xc0);

//float_lcd(output1);

//delay_ms(500);

cmd_lcd(0x01);

38
}

if(output1>300 && output1<400)

PWM=60;

cmd_lcd(0x01);

display_lcd("PWM 25 %");

cmd_lcd(0xc0);

//float_lcd(output1);

//delay_ms(500);

cmd_lcd(0x01);

if(output1>400 && output1<450)

PWM_Pin=1;

cmd_lcd(0x01);

display_lcd("PWM 0 %");

cmd_lcd(0xc0);

//float_lcd(output1);

39
//delay_ms(500);

cmd_lcd(0x01);

/* else

PWM_Pin=1;

cmd_lcd(0x01);

display_lcd("PWM 0 %");

cmd_lcd(0xc0);

//float_lcd(output1);

//delay_ms(500);

cmd_lcd(0x01);

} */

void transmit(unsigned char *s)

40
while(*s)

SBUF=*s++;

delay_ms(100);

unsigned char txrxbyte( unsigned char d)

char mask=0x80;

unsigned char i,c=0x00;

for(i=0;i<8;i++)

sck=1;

if(d&mask)

{din=1;}

else

{din=0;}

sck=0;

if(dout==1)

{c=c|mask;}

mask=mask>>1;

41
return c;

// Timer0 initialize

void InitTimer0(void)

TMOD &= 0xF0; // Clear 4bit field for timer0

TMOD |= 0x01; // Set timer0 in mode 1 = 16bit mode

TH0 = 0x00; // First time value

TL0 = 0x00; // Set arbitrarily zero

ET0 = 1; // Enable Timer0 interrupts

EA = 1; // Global interrupt enable

TR0 = 1; // Start Timer 0

// PWM initialize

void InitPWM(void)

InitTimer0(); // Initialize timer0 to start generating interrupts

42
// PWM generation code is written inside the Timer0 ISR

// Timer0 ISR

void Timer0_ISR (void) interrupt 1

TR0 = 0; // Stop Timer 0

if(PWM_Pin) // if PWM_Pin is high

PWM_Pin = 0;

temp = (255-PWM)*PWM_Freq_Num;

TH0 = 0xFF - (temp>>8)&0xFF;

TL0 = 0xFF - temp&0xFF;

else // if PWM_Pin is low

PWM_Pin = 1;

temp = PWM*PWM_Freq_Num;

TH0 = 0xFF - (temp>>8)&0xFF;

TL0 = 0xFF - temp&0xFF;

TF0 = 0; // Clear the interrupt flag

TR0 = 1; // Start Timer 0

43
}

Programming of Microcontroller 8051

We are using embedded C programming language to program the microcontroller.

Need of C:

Compiler produces hex file that we download into ROM of microcontroller. The size of hex file
produced by compiler is one of the main concerns of microcontroller programmers for two
reasons:

1. Microcontroller has limited on -chip ROM


2. The code space for 8051 is limited to 64 KB

Programming in assembly language is tedious and time consuming. C is a high level


programming language that is portable across many hardware architectures.

Reasons for using Embedded C:

1. It is easier and less time consuming to write in C than assembly.


2. C is easier to modify and update.
3. You can use code available in function libraries.
4. C code is portable to other microcontrollers with little or no modification.

We use reg51.h as a header file as #include <reg51.h>. These files contain all the
definitions of the 80C51 registers. This file is included in your project and will be assembled
together with the compiled output of your C program.

44
Embedded C Compiler:

ANSI C - full featured and portable

Reliable - mature, field-proven technology

Multiple C optimization levels

An optimizing assembler

Full linker, with overlaying of local variables to minimize RAM usage

Comprehensive C library with all source code provided

Includes support for 24-bit and 32-bit IEEE floating point and 32-bit long data types

Mixed C and assembler programming

Unlimited number of source files

Listings showing generated assembler

Runs on multiple platforms: Windows, Linux, UNIX, Mac OS X, Solaris

45
Embedded system tools:

Assembler:

An assembler is a computer program for translating assembly language essentially, a


mnemonic representation of machine language into object code. A cross assembler (see cross
compiler) produces code for one type of processor, but runs on another. The computational step
where an assembler is run is known as assembly time. Translating assembly instruction
mnemonics into opcodes, assemblers provide the ability to use symbolic names for memory
locations (saving tedious calculations and manually updating addresses when a program is
slightly modified), and macro facilities for performing textual substitution typically used to
encode common short sequences of instructions to run inline instead of in a subroutine.
Assemblers are far simpler to write than compilers for high-level languages.

Assembly language has several benefits:

Speed: Assembly language programs are generally the fastest programs around.

Space: Assembly language programs are often the smallest.

Capability: You can do things in assembly, which are difficult or impossible in High-

level languages.

Simulator
Simulator is a machine that simulates an environment for the purpose of training.

Compiler

46
A compiler is a program that reads a program in one language, the source language and
translates into an equivalent program in another language, the target

Language. The translation process should also report the presence of errors in the source
program.

KEIL uVision is a standard Windows application..

Create a Project File

To create a new project file select from the Vision menu Project New Project. This opens a
standard Windows dialog that asks you for the new project file name.

We suggest that you use a separate folder for each project. You can simply use the icon Create
New Folder in this dialog to get a new empty folder. Then select this folder and enter the file
name for the new project, i.e. Project1. Vision creates a new project file with the name
PROJECT1.UV2 which contains a default target and file group name. You can see these names
in the Project Workspace Files.

Select a Device

When you create a new project Vision asks you to select a CPU for your project. The Select
Device dialog box shows the Vision device database. Just select the microcontroller you use.
We are using for our examples the Philips 80C51RD+ controller. This selection sets necessary
tool options for the 80C51RD+ device and simplifies in this way the tool configuration.

47
Once you have selected a CPU from the device database you can open the user manuals for that
device in the Project Workspace Books page.

These user manuals are part of the Keil Development Tools CD-ROM that should be present in

your CD drive. .

Create New Source Files

You may create a new source file with the menu option File New. This opens an empty editor
window where you can enter your source code. Vision enables the C color syntax highlighting
when you save your file with the dialog File Save As under a filename with the extension
*.C. We are saving our example file under the name MAIN.C.

48
Add and Configure the Startup Code

The STARTUP.A51 file is the startup code for the most 8051 CPU variants. The startup code
clears the data memory and initializes hardware and reentrant stack pointers. In addition, some
8051 derivatives require a CPU initialization code that needs to match the configuration of your
hardware design. For example, the Philips 8051RD+ offers you on-chip xdata RAM that should
be enabled in the startup code. Since you need to modify that file to match your target hardware,
you should copy the STARTUP.A51 file from the folder C:\KEIL\C51\LIB to your project
folder.

Group Project Files

File group allow you to organize large projects. For the CPU startup code and other system
configuration files you may create a own file group in the Project Components, Environment,
Books dialog box. Use the New (Insert) button to create a file group named System Files. In
the project window you may drag and drop the STARTUP.A51 file to this new file group.

49
Now, the Project Workspace Files lists all items of your project. To open a file for editing,
double click on the file name in the Project Workspace. You may need to configure the startup
STARTUP.A51 in the editor.

Set Tool Options for Target

Vision lets you set options for your target hardware. The dialog Options for Target opens via
the toolbar icon or via the Project - Options for Target menu item. In the Target tab you specify

50
all relevant parameters of your target hardware and the on-chip components of the device you
have selected. The following the settings for our example are shown.

Build Project and Create a HEX File

Typical, the tool settings under Options Target are all you need to start a new application. You
may translate all source files and line the application with a click on the Build Target toolbar
icon. When you build an application with syntax errors, Vision will display errors and warning
messages in the Output Window Build page. A double click on a message line opens the source
file on the correct location in a Vision editor window.

51
Once you have successfully generated your application you can start debugging as described
under Testing Programs with the Vision Debugger.

Now you may modify existing source code or add new source files to the project. The Build
Target toolbar button translates only modified or new source files and generates the executable
file. Vision maintains a file dependency list and knows all include files used within a source
file. Even the tool options are saved in the file dependency list, so that Vision rebuilds files
only when needed. With the Rebuild Target command, all source files are translated, regardless
of modifications.

After you have tested your application, it might be required to create an Intel HEX file and to
download the application software into the physical device using a Flash programming utility.
Vision creates HEX files with each build process when Create HEX file under Options for
Target Output is enabled. The Merge32K Hexfile option is available for Code Banking
Applications when you have selected the Extended Linker LX51. You may start your Flash
programming utility after the make process when you specify the program under the option Run
User Program #1.

52
REFERENCES

BOOKS:

[1] Kenneth .J. Ayala, The 8051 Microcontroller and its applications, prentice hall, new Edition,
2006.

[2] Frank Vahid, Embedded system design, Tata Mc Graw hill, 3 Edition, 1995.

[3] Raj Kamal, Embedded Systems, JWE, 4 Edition, 2000.

[4] Jonathan Clark, Applications of Ultrasonic, Tata Mc Graw hill, new Edition, 2002.

WEBSITES:

[5] www.google.com

[6] www.howstuffworks.com

[7] www.epanorama.net

[8] www.wikipedia.org

53

You might also like