INTRODUCTION
This project gives a home security system with GSM interface. So you can get SMS alert
from your home when the security fails. The system has 1 LPG gas sensor and 1 temperature
sensor. The whole system is controlled by atmega8 microcontroller. It continuously reads the
sensors and if any of the sensors fails then it will send an SMS to the house owner.This
project mainly focuses on providing security of home from LPG leakage and from fire when
the user is away from or on the place. The system is MOBILE based and uses wireless
technology to secure the house from unpredictable phenomenon. This system provides ideal
solution to the problems faced by home owners. The system is wireless therefore more
adaptable and cost-effective. The system uses GSM technology thus providing ubiquitous
access to the system for security. This system will be a powerful and flexible tool that will
offer this service at any time, and from anywhere with the constraints of the technologies
being applied. The proposed approach for designing this system is to implement a
microcontroller-based control module that receives its instructions to a cellular phone over
the GSM network.
2. BLOCK DIAGRAM
3. CIRCUIT DIAGRAM
The power supply unit is used to provide constant 5 V dc supply to the peripherals. The 230
V ac is converted into 9 V ac by using a transformer and then a bridge rectifier rectifies it to a
9 V dc with ac ripples. This is then filtered by electrolytic capacitors used across the rectifier
output. LM7805 regulator is employed to obtain a constant 5 V dc at the output. The LM7805
is simple to use. You simply connect the positive lead of your unregulated DC power supply
(anything from 9VDC to 24VDC) to the Input pin, connect the negative lead to the Common
pin and then when you turn on the power, you get a 5 volt supply from the Output pin.
Circuit Features:
Brief description of operation: Gives out well regulated +5V output, output current
capabilityof 100 mA
Circuit protection: Built-in overheating protection shuts down output when regulator
IC getstoo hot
Availability of components: Easy to get, uses only very common basic components
Design testing: Based on datasheet example circuit, I have used this circuit
successfully aspart of many electronics projects
Component costs: Few dollars for the electronics components + the input transformer
cost.
4.2 7805 IC
7805 is a voltage regulator integrated circuit. It is a member of 78xx series of fixed linear
voltage regulator ICs. The voltage source in a circuit may have fluctuations and would not
give the fixed voltage output. The voltage regulator IC maintains the output voltage at a
constant value. The xx in 78xx indicates the fixed output voltage it is designed to provide.
7805 provides +5V regulated power supply. Capacitors of suitable values can be connected at
input and output pins depending upon the respective voltage levels.
4.3 RESISTOR
A resistor is a passive two-terminal electrical component that implements electrical
resistance as a circuit element. Resistors act to reduce current flow, and, at the same time, act
to lower voltage levels within circuits. Resistors may have fixed resistances or variable
resistances, such as those found in thermistors, varistors, trimmers, photo resistors, and
potentiometers.
The currents through a resistor are in direct proportions to the voltage across the resistor's
terminals. This relationship is represented by Ohm'slaw:
where I is the current through the conductor in units of amperes, V is the potential difference
measured across the conductor in units of volts, and R is the resistance of the conductor in
units of ohms (symbol: ).
The ratio of the voltage applied across a resistor's terminals to the intensity of current in the
circuit is called its resistance, and this can be assumed to be a constant (independent of the
voltage) for ordinary resistors working within their ratings.
Resistors are common elements of electricalnetworks and electroniccircuits and are
ubiquitous in electronicequipment. Practical resistors can be composed of various compounds
and films, as well as resistancewires (wire made of a high-resistivity alloy, such as nickelchrome). Resistors are also implemented within integratedcircuits, particularly analog
devices, and can also be integrated into hybrid and printedcircuits.
The electrical functionality of a resistor is specified by its resistance: common commercial
resistors are manufactured over a range of more than nine orders of magnitude. When
specifying that resistance in an electronic design, the required precision of the resistance may
require attention to the manufacturing tolerance of the chosen resistor, according to its
specific application. The temperature coefficient of the resistance may also be of concern in
some precision applications. Practical resistors are also specified as having a maximum
power rating which must exceed the anticipated power dissipation of that resistor in a
particular circuit: this is mainly of concern in power electronics applications. Resistors with
7
higher power ratings are physically larger and may require heat sinks. In a high-voltage
circuit, attention must sometimes be paid to the rated maximum working voltage of the
resistor. While there is no minimum working voltage for a given resistor, failure to account
for a resistor's maximum rating may cause the resistor to incinerate when current is run
through it.
Practical resistors have a series inductance and a small parallel capacitance; these
specifications can be important in high-frequency applications. In a low-noise amplifier or
pre-amp, the noise characteristics of a resistor may be an issue. The unwanted inductance,
excess noise, and temperature coefficient are mainly dependent on the technology used in
manufacturing the resistor. They are not normally specified individually for a particular
family of resistors manufactured using a particular technology. A family of discrete resistors
is also characterized according to its form factor, that is, the size of the device and the
position of its leads (or terminals) which is relevant in the practical manufacturing of circuits
using them. The ohm (symbol: ) is the SI unit of electrical resistance, named after Georg
Simon Ohm. An ohm is equivalent to a volt per ampere. Since resistors are specified and
manufactured over a very large range of values, the derived units of milliohm (1 m = 103
), kiloohm (1 k = 103 ), and megaohm (1 M = 106 ) are also in common usage.
Electronic symbols and notation
The symbol used for a resistor in a circuit diagram varies
4.4 CAPACITORS
A capacitor (originally known as a condenser) is a passivetwo-terminalelectrical component
used to store energyelectrostatically in an electric field. The forms of practical capacitors vary
widely, but all contain at least two electrical conductors (plates) separated by a dielectric (i.e.,
insulator). The conductors can be thin films of metal, aluminium foil or disks, etc. The
'nonconducting' dielectric acts to increase the capacitor's charge capacity. A dielectric can be
glass, ceramic, plastic film, air, paper, mica, etc. Capacitors are widely used as parts of
electrical circuits in many common electrical devices. Unlike a resistor, a capacitor does not
dissipate energy. Instead, a capacitor stores energy in the form of an electrostatic field
between its plates.
When there is a potential difference across the conductors (e.g., when a capacitor is attached
across a battery), an electric field develops across the dielectric, causing positive charge (+Q)
to collect on one plate and negative charge (-Q) to collect on the other plate. If a battery has
been attached to a capacitor for a sufficient amount of time, no current can flow through the
capacitor. However, if an accelerating or alternating voltage is applied across the leads of the
capacitor, a displacement current can flow.
An ideal capacitor is characterized by a single constant value for its capacitance. Capacitance
is expressed as the ratio of the electric charge (Q) on each conductor to the potential
difference (V) between them. The SI unit of capacitance is the farad (F), which is equal to
one coulomb per volt (1 C/V). Typical capacitance values range from about 1 pF (1012 F) to
about 1 mF (103 F).
The capacitance is greater when there is a narrower separation between conductors and when
the conductors have a larger surface area. In practice, the dielectric between the plates passes
a small amount of leakage current and also has an electric field strength limit, known as the
breakdown voltage. The conductors and leads introduce an undesired inductance and
resistance.
Capacitors are widely used in electronic circuits for blocking direct current while allowing
alternating current to pass. In analog filter networks, they smooth the output of power
supplies. In resonant circuits they tune radios to particular frequencies. In electric power
transmission systems they stabilize voltage and power flow.[1]
9
Theory of operation
A capacitor consists of two conductors separated by a non-conductive region.The nonconductive region is called the dielectric. In simpler terms, the dielectric is just an electrical
insulator. Examples of dielectric media are glass, air, paper, vacuum, and even a
semiconductordepletion region chemically identical to the conductors. A capacitor is
assumed to be self-contained and isolated, with no net electric charge and no influence from
any external electric field. The conductors thus hold equal and opposite charges on their
facing surfaces, and the dielectric develops an electric field. In SI units, a capacitance of one
farad means that one coulomb of charge on each conductor causes a voltage of one volt
across the device.
An ideal capacitor is wholly characterized by a constant capacitanceC, defined as the ratio of
charge Q on each conductor to the voltage V between them:[10]
Because the conductors (or plates) are close together, the opposite charges on the conductors
attract one another due to their electric fields, allowing the capacitor to store more charge for
a given voltage than if the conductors were separated, giving the capacitor a large
capacitance.
Sometimes charge build-up affects the capacitor mechanically, causing its capacitance to
vary. In this case, capacitance is defined in terms of incremental changes:
10
4.5 DC CONNECTOR
A DC connector (or DC plug, for one common type of connector) is an electrical
connector for supplying direct current (DC) power.
Compared to domestic AC power plugs and sockets, DC connectors have many more
standard types that are not interchangeable. The dimensions and arrangement of DC
connectors can be chosen to prevent accidental interconnection of incompatible sources and
loads. Types vary from small coaxial connectors used to power portable electronic devices
from AC adapters, to connectors used for automotive accessories and for battery packs in
portable equipment.
11
4.6 LED
A light-emitting diode (LED) is a two-lead semiconductor light source that resembles a
basic p-n junction diode, except that an LED also emits light. When an LED's anode lead has
a voltage that is more positive than its cathode lead by at least the LED's forward voltage
drop, current flows. Electrons are able to recombine with holes within the device, releasing
energy in the form of photons. This effect is called electroluminescence, and the color of the
light (corresponding to the energy of the photon) is determined by the energy band gap of the
semiconductor.
An LED is often small in area (less than 1 mm2), and integrated optical components may be
used to shape its radiation pattern.[8]
Appearing as practical electronic components in 1962, the earliest LEDs emitted lowintensity infrared light. Infrared LEDs are still frequently used as transmitting elements in
remote-control circuits, such as those in remote controls for a wide variety of consumer
electronics. The first visible-light LEDs were also of low intensity, and limited to red.
Modern LEDs are available across the visible, ultraviolet, and infrared wavelengths, with
very high brightness.
Early LEDs were often used as indicator lamps for electronic devices, replacing small
incandescent bulbs. They were soon packaged into numeric readouts in the form of sevensegment displays, and were commonly seen in digital clocks.
Recent developments in LEDs permit them to be used in environmental and task lighting.
LEDs have many advantages over incandescent light sources including lower energy
consumption, longer lifetime, improved physical robustness, smaller size, and faster
switching. Light-emitting diodes are now used in applications as diverse as aviation lighting,
automotive headlamps, advertising, general lighting, traffic signals, and camera flashes.
However, LEDs powerful enough for room lighting are still relatively expensive, and require
more precise current and heat management than compact fluorescent lamp sources of
comparable output.
LEDs have allowed new text, video displays, and sensors to be developed, while their high
switching rates are also useful in advanced communications technology.
12
13
5. MIROCONTROLLER UNIT
5.1 ATMEGA16
OVERVIEW
The ATmega16 is a low-power CMOS 8-bit microcontroller based on the AVR enhanced
RISC architecture. By executing powerful instructions in a single clock cycle, the ATmega16
achieves throughputs approaching 1 MIPS per MHz allowing the system designed to
optimize power consumption versus processing speed.
The AVR core combines a rich instruction set with 32 general purpose working registers. All
the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two
independent registers to be accessed in one single instruction executed in one clock cycle.
The resulting architecture is more code efficient while achieving throughputs up to ten times
faster than conventional CISC microcontrollers.
The ATmega16 provides the following features: 16 Kbytes of In-System Programmable
Flash Program memory with Read-While-Write capabilities, 512 bytes EEPROM, 1 Kbyte
SRAM, 32general purpose I/O lines, 32 general purpose working registers, a JTAG interface
for Boundary-scan, On-chip Debugging support and programming, three flexible
Timer/Counters with compare modes, Internal and External Interrupts, a serial programmable
USART, a byte oriented Two-wire Serial Interface, an 8-channel, 10-bit ADC with optional
differential input stage with programmable gain (TQFP package only), a programmable
Watchdog Timer with Internal Oscillator, an SPI serial port, and six software selectable
power saving modes. The Idle mode stops the CPU while allowing the USART, Two-wire
interface, A/D Converter, SRAM, Timer/Counters, SPI port, and interrupt system to continue
functioning. The Power-down mode saves the register contents but freezes the Oscillator,
disabling all other chip functions until the next External Interrupt or Hardware Reset. In
Power-save mode, the Asynchronous Timer continues to run, allowing the user to maintain a
timer base while the rest of the device is sleeping. The ADC Noise Reduction mode stops the
CPU and all I/O modules except Asynchronous Timer and ADC, to minimize switching noise
during ADC conversions. In Standby mode, the crystal/resonator Oscillator is running while
the rest of the device is sleeping. This allows very fast start-up combined with low-power
14
consumption. In Extended Standby mode, both the main Oscillator and the Asynchronous
Timer continue to run.
The device is manufactured using Atmels high density nonvolatile memory technology. The
On chip ISP Flash allows the program memory to be reprogrammed in-system through an SPI
serial interface, by a conventional nonvolatile memory programmer, or by an On-chip Boot
program running on the AVR core. The boot program can use any interface to download the
application program in the Application Flash memory. Software in the Boot Flash section
will continue to run while the Application Flash section is updated, providing true ReadWhile-Write operation. By combining an 8-bit RISC CPU with In-System SelfProgrammable Flash on a monolithic chip, the Atmel ATmega16 is a powerful
microcontroller that provides a highly-flexible and cost-effective solution to many embedded
control applications.
The ATmega16 AVR is supported with a full suite of program and system development tools
including: C compilers, macro assemblers, program debugger/simulators, in-circuit
emulators, and evaluation kits.
15
Pin Configurations
Pin Descriptions
VCC:Digital supply voltage.
GND:Ground.
Port A (PA7..PA0):Port A serves as the analog inputs to the A/D Converter.
Port A also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used. Port
pins can provide internal pull-up resistors (selected for each bit). The Port A output buffers
have symmetrical drive characteristics with both high sink and source capability. When pins
PA0 to PA7are used as inputs and are externally pulled low, they will source current if the
internal pull-upresistors are activated. The Port A pins are tri-stated when a reset condition
becomes active, even if the clock is not running.
16
Port B (PB7..PB0):Port B is an 8-bit bi-directional I/O port with internal pull-up resistors
(selected for each bit). The Port B output buffers have symmetrical drive characteristics with
both high sink and source capability. As inputs, Port B pins that are externally pulled low will
source current if the pull-up resistors are activated. The Port B pins are tri-stated when a reset
condition becomes active, even if the clock is not running.
Port C (PC7..PC0): Port C is an 8-bit bi-directional I/O port with internal pull-up resistors
(selected for each bit). The Port C output buffers have symmetrical drive characteristics with
both high sink and source capability. As inputs, Port C pins that are externally pulled low will
source current if the pull-up resistors are activated. The Port C pins are tri-stated when a reset
condition becomes active, even if the clock is not running. If the JTAG interface is enabled,
the pull-up resistors on pins PC5(TDI), PC3(TMS) and PC2(TCK) will be activated even if a
reset occurs.
Port D (PD7..PD0):Port D is an 8-bit bi-directional I/O port with internal pull-up resistors
(selected for each bit). The Port D output buffers have symmetrical drive characteristics with
both high sink and source capability. As inputs, Port D pins that are externally pulled low will
source current if the pull-up resistors are activated. The Port D pins are tri-stated when a reset
condition becomes active, even if the clock is not running.
RESET: Reset Input. A low level on this pin for longer than the minimum pulse length will
generate a reset, even if the clock is not running. Shorter pulses are not guaranteed to
generate a reset.
XTAL1: Input to the inverting Oscillator amplifier and input to the internal clock operating
circuit.
XTAL2: Output from the inverting Oscillator amplifier.
AVCC:AVCC is the supply voltage pin for Port A and the A/D Converter. It should be
externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be
connected to VCC through a low-pass filter.
AREF: AREF is the analog reference pin for the A/D Converter.
17
Block Diagram
Crystal Oscillator
XTAL1 and XTAL2 are input and output, respectively, of an inverting amplifier which can
be configured for use as an On-chip Oscillator. Either a quartz crystal or aceramic resonator
may be used. The CKOPT Fuse selects between two different Oscillator amplifier modes.
When CKOPT is programmed, the Oscillator output will oscillate will a full rail-to-rail swing
on the output. This mode is suitable when operating in a very noisy environment or when the
output from XTAL2 drives a second clock buffer. This mode has a wide frequency range.
When CKOPT is unprogrammed, the Oscillator has a smaller output swing. This reduces
power consumption considerably. This mode has a limited frequency range and it cannot be
used to drive other clock buffers.
18
For resonators, the maximum frequency is 8 MHz with CKOPT unprogrammed and 16 MHz
withCKOPT programmed. C1 and C2 should always be equal for both crystals and
resonators. The optimal value of the capacitors depends on the crystal or resonator in use, the
amount of stray capacitance, and the electromagnetic noise of the environment. Some initial
guidelines forchoosing capacitors for use with crystals. For ceramic resonators, the capacitor
values given by the manufacturer should be used.
Figure : Crystal Oscillator Connections
The Oscillator can operate in three different modes, each optimized for a specific frequency
range. The operating mode is selected by the fuses CKSEL3..1
19
20
The ADC contains a Sample and Hold circuit which ensures that the input voltage to the
ADC is held at a constant level during conversion. A block diagram of the ADC is shown in
Figure
The ADC has a separate analog supply voltage pin, AVCC. AVCC must not differ more than
0.3V from VCC . See the paragraph ADC Noise Canceler on page 211 on how to connect
this pin.
Internal reference voltages of nominally 2.56V or AVCC are provided On-chip. The voltage
reference may be externally decoupled at the AREF pin by a capacitor for better noise
performance.
Figure: Analog to Digital Converter Block Schematic
21
Operation
The ADC converts an analog input voltage to a 10-bit digital value through successive
approximation. The minimum value represents GND and the maximum value represents the
voltage on the AREF pin minus 1 LSB. Optionally, AVCC or an internal 2.56V reference
voltage may be connected to the AREF pin by writing to the REFSn bits in the ADMUX
Register. The internal voltage reference may thus be decoupled by an external capacitor at the
AREF pin to improve noise immunity.
The analog input channel and differential gain are selected by writing to the MUX bits in
ADMUX. Any of the ADC input pins, as well as GND and a fixedbandgap voltage reference,
can be selected as single ended inputs to the ADC. A selection of ADC input pins can be
selected as positive and negative inputs to the differential gain amplifier.
If differential channels are selected, the differential gain stage amplifies the voltage
difference between the selected input channel pair by the selected gain factor. This amplified
value thenbecomes the analog input to the ADC. If single ended channels are used, the gain
amplifier is bypassed altogether.
The ADC is enabled by setting the ADC Enable bit, ADEN in ADCSRA. Voltage reference
and input channel selections will not go into effect until ADEN is set. The ADC does not
consume power when ADEN is cleared, so it is recommended to switch off the ADC before
entering power saving sleep modes.
The ADC generates a 10-bit result which is presented in the ADC Data Registers, ADCH and
ADCL. By default, the result is presented right adjusted, but can optionally be presented left
adjusted by setting the ADLAR bit in ADMUX.
If the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read
ADCH. Otherwise, ADCL must be read first, then ADCH, to ensure that the content of the
Data Registers belongs to the same conversion. Once ADCL is read, ADC access to Data
Register is blocked. This means that if ADCL has been read, and a conversion completes
before ADCH isread, neither register is updated and the result from the conversion is lost.
When ADCH is read, ADC access to the ADCH and ADCL Registers is re-enabled.
The ADC has its own interrupt which can be triggered when a conversion completes. When
ADC access to the Data Registers is prohibited between reading of ADCH and ADCL, the
interrupt will trigger even if the result is lost.
Starting a Conversion
A single conversion is started by writing a logical one to the ADC Start Conversion bit,
ADSC. This bit stays high as long as the conversion is in progress and will be cleared by
hardware when the conversion is completed. If a different data channel is selected while a
22
conversion is in progress, the ADC will finish the current conversion before performing the
channel change.
Alternatively, a conversion can be triggered automatically by various sources. Auto
Triggering is enabled by setting the ADC Auto Trigger Enable bit, ADATE in ADCSRA.
The trigger source is selected by setting the ADC Trigger Select bits, ADTS in SFIOR (see
description of the ADTS bits for a list of the trigger sources). When a positive edge occurs on
the selected trigger signal, the ADC prescaler is reset and a conversion is started. This
provides a method of starting conversions at fixed intervals. If the trigger signal still is set
when the conversion completes, a new conversion will not be started. If another positive edge
occurs on the trigger signal during conversion, the edge will be ignored. Note that an
Interrupt Flag will be set even if the specific interrupt is disabled or the global interrupt
enable bit in SREG is cleared. A conversion can thus be triggered without causing an
interrupt. However, the Interrupt Flag must be cleared in order to trigger a new conversion at
the next interrupt event
Using the ADC Interrupt Flag as a trigger source makes the ADC start a new conversion as
soon as the ongoing conversion has finished. The ADC then operates in Free Running mode,
constantly sampling and updating the ADC Data Register. The first conversion must be
started by writing a logical one to the ADSC bit in ADCSRA. In this mode the ADC will
perform successive conversions independently of whether the ADC Interrupt Flag, ADIF is
cleared or not.
If Auto Triggering is enabled, single conversions can be started by writing ADSC in
ADCSRA to one. ADSC can also be used to determine if a conversion is in progress. The
ADSC bit will be read as one during a conversion, independently of how the conversion was
started
23
PRESCALER ADC
By default, the successive approximation circuitry requires an input clock frequency between
50 kHz and 200 kHz to get maximum resolution. If a lower resolution than 10 bits is needed,
the input clock frequency to the ADC can be higher than 200 kHz to get a higher sample rate.
The ADC module contains a prescaler, which generates an acceptable ADC clock frequency
from any CPU frequency above 100 kHz. The prescaling is set by the ADPS bits in
ADCSRA. The prescaler starts counting from the moment the ADC is switched on by setting
the ADEN bit in ADCSRA. The prescaler keeps running for as long as the ADEN bit is set,
and is continuously reset when ADEN is low.
When initiating a single ended conversion by setting the ADSC bit in ADCSRA, the
conversion starts at the following rising edge of the ADC clock cycle.
A normal conversion takes 13 ADC clock cycles. The first conversion after the ADC is
switchedon (ADEN in ADCSRA is set) takes 25 ADC clock cycles in order to initialize the
analog circuitry.
The actual sample-and-hold takes place 1.5 ADC clock cycles after the start of a normal
conversion and 13.5 ADC clock cycles after the start of a first conversion. When a
conversion is complete, the result is written to the ADC Data Registers, and ADIF is set. In
single conversion mode, ADSC is cleared simultaneously. The software may then set ADSC
again, and a new conversion will be initiated on the first rising ADC clock edge.
When Auto Triggering is used, the prescaler is reset when the trigger event occurs. This
assures a fixed delay from the trigger event to the start of conversion. In this mode, the
sample-and-hold takes place 2 ADC clock cycles after the rising edge on the trigger source
signal. Three additional CPU clock cycles are used for synchronization logic. When using
Differential mode, along with Auto triggering from a source other than the ADC Conversion
Complete, each conversion will require 25 ADC clocks. This is because the ADC must be
disabled and re-enabled after every conversion.
24
ADC Voltage
Reference
The reference voltage for the ADC (V REF ) indicates the conversion range for the ADC.
Single ended channels that exceed V REF will result in codes close to 0x3FF. V REF can be
selected as AVCC, internal 2.56V reference, or external AREF pin.
AVCC is connected to the ADC through a passive switch. The internal 2.56V reference is
generated from the internal band gap reference (V BG ) through an internal amplifier. In
either case, the external AREF pin is directly connected to the ADC, and the reference
voltage can be made more immune to noise by connecting a capacitor between the AREF pin
and ground. V REF can also be measured at the AREF pin with a high impedant voltmeter.
Note that V REF is a high impedant source, and only a capacitive load should be connected in
a system.
If the user has a fixed voltage source connected to the AREF pin, the user may not use the
other reference voltage options in the application, as they will be shorted to the external
voltage. If no external voltage is applied to the AREF pin, the user may switch between
AVCC and 2.56V as reference selection. The first ADC conversion result after switching
reference voltage source may be inaccurate, and the user is advised to discard this result. If
differential channels are used, the selected reference should not be closer to AVCC
25
ADC Conversion
Result
After the conversion is complete (ADIF is high), the conversion result can be found in the
ADC Result Registers (ADCL, ADCH).
For single ended conversion, the result is
ADC= Vin*1024/Vref
where V IN is the voltage on the selected input pin and V REF the selected voltage reference.
0x000 represents ground, and 0x3FF represents the selected reference voltage minus one
LSB.
If differential channels are used, the result is
ADC= (Vpos Vneg )* GAIN* 512/Vref
where V POS is the voltage on the positive input pin, V NEG the voltage on the negative
input pin, GAIN the selected gain factor, and V REF the selected voltage reference. The
result is presented in twos complement form, from 0x200 (-512d) through 0x1FF (+511d).
Note that if the user wants to perform a quick polarity check of the results, it is sufficient to
read the MSB of the result (ADC9 in ADCH). If this bit is one, the result is negative, and if
this bit is zero, the result is positive.
26
SERIAL COMMUNICATION
Communication between two entities is important for the information flow to take place. In
general the information transport system can be parallel in which the complete byte of data is
sent at a time, with each bit having a separate dedicated line or it can be serial where only one
communication line is available which is shared by all the bits sequentially.
Data can be exchanged using parallel or serial techniques. Setup for parallel data transfer is
not cost effective but is a very fast method of communication. Serial communication is cost
effective because it requires only a single line of connection but on the other hand is a slow
process in comparison to parallel communication. This article explains serial communication
of AVR microcontroller (ATmega16) with PC. The data is transmitted from the controller
using RS232 standard and displayed on the PC using Hyper Terminal.
There are two methods for serial data communication (i) Synchronous and (ii) Asynchronous
communication. In Synchronous communication method complete block (characters) is sent
at a time. It doesnt require any additional bits (start, stop or parity) to be added for the
synchronization of frame. The devices are synchronized by clock. And in asynchronous
communication data transmission is done byte by byte i.e., one byte at a time. The additional
bits are added to complete a frame.
In synchronous communication the frame consists of data bits while in asynchronous
communication the total number of bits in a frame may be more than the data bits.
27
ii.
Half duplex: Transmission can be done in both the direction but one side at a
time.
iii.
Atmega16 is equipped with three different kinds of serial communication peripheral systems:
i.
Serial USART
ii.
iii.
Start bit and stop bit: These bits are use to synchronize the data frame. Start bit is one
single low bit and is always given at the starting of the frame, indicating the next bits are data
bits. Stop bit can be one or two high bits at the end of frame, indicating the completion of
frame.
Baud Rate: In simple words baud rate is the rate at which serial data is being transferred.
Atmega16 USART has following features:
Three separate interrupts for RX Complete, TX complete and TX data register empty.
USART Registers
To use the USART of Atmega16, certain registers need to be configured.
UCSR: USART control and status register. Its is basically divided into three parts UCSRA,
UCSRB and UCSRC. These registers are basically used to configure the USART.
UBRR: USART Baud Rate Registers. Basically use to set the baud rate of USART
UDR: USART data register
1. UCSRA: (USART Control and Status Register A)
RXC (USART Receive Complete): RXC flag is set to 1 if unread data exists in receive
buffer, and set to 0 if receive buffer is empty.
TXC (USART Transmit complete): TXC flag is set to 1 when data is completely
transmitted to Transmit shift register and no data is present in the buffer register UDR.
UDRE (USART Data Register Empty): This flag is set to logic 1 when the transmit buffer
is empty, indicating it is ready to receive new data. UDRE bit is cleared by writing to the
UDR register.
29
30
URSEL: USART Register select. This bit must be set due to sharing of I/O location by
UBRRH and UCSRC
UMSEL: USART Mode Select,
When 1 -> Synchronous Operation
When 0 -> Asynchronous Operation
UPM[0:1]: USART Parity Mode, Parity mode selection bits.
USBS: USART Stop Select Bit,
When 0-> 1 Stop Bit
When 1 -> 2 Stop Bits
UCSZ[0:1]: The UCSZ[1:0] bits combined with the UCSZ2 bit in UCSRB sets size of data
frame i.e., the number of data bits. The table shows the bit combinations with
respective character size.
The USART Data receive and data transmit buffer registers share the same address referred
as USART UDR register, when data is written to the register it is written in transmit data
buffer register (TXB). Received data is read from the Receive data buffer register (RXB).
31
The UBRRH register shares the same I/O address with the UCSRC register, The
differentiation is done on the basis of value of URSEL bit.
When URSEL=0; write operation is done on UBRRH register.
When URSEL=1; write operation is done on UCSRC register.
The UBRRH and UBRRL register together stores the 12-bit value of baud rate, UBRRH
contains the 4 most significant bits and UBRRL contains the other 8 least significant bits.
Baud rates of the transmitting and receiving bodies must match for successful communication
to take place.
The Connection of MAX232 and ATmega16 is shown in the circuit diagram. The
MAX232 is used for level conversion. The reader can refer the component section for
further details on MAX 232.The T1IN (pin11) of Max232 is connected to Tx (pin15) of
32
The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) is a
highly flexible serial communication device. The main features are:
Full Duplex Operation (Independent Serial Receive and Transmit Registers)
Asynchronous or Synchronous Operation
Master or Slave Clocked Synchronous Operation
High Resolution Baud Rate Generator
Supports Serial Frames with 5, 6, 7, 8, or 9 Data Bits and 1 or 2 Stop Bits
Odd or Even Parity Generation and Parity Check Supported by Hardware
Data Overrun Detection
Framing Error Detection
Noise Filtering Includes False Start Bit Detection and Digital Low Pass Filter
Three Separate Interrupts on TX Complete, TX Data Register Empty, and RX Complete
Multi-processor Communication Mode
Double Speed Asynchronous Communication Mode
Overview
A simplified block diagram of the USART transmitter is shown in Figure CPU accessible I/O
registers and I/O pins are shown in bold.
33
The dashed boxes in the block diagram separate the three main parts of the USART (listed
from the top): Clock Generator, Transmitter and Receiver. Control Registers are shared by all
units.
The clock generation logic consists of synchronization logic for external clock input used by
synchronous Slave operation, and the baud rate generator. The XCK (Transfer Clock) pin is
only used by Synchronous Transfer mode. The Transmitter consists of a single write buffer, a
serial Shift Register, parity generator and control logic for handling different serial frame
formats. The write buffer allows a continuous transfer of data without any delay between
frames. The receiver is the most complex part of the USART module due to its clock and data
recovery units. The recovery units are used for asynchronous data reception. In addition to
the recovery units, the receiver includes a parity checker, control logic, a Shift Register and a
34
two level receive buffer (UDR). The receiver supports the same frame formats as the
transmitter, and can detect frame error, data overrun and parity errors.
USART Initialization
The USART has to be initialized before any communication can take place. The initialization
process normally consists of setting the baud rate, setting frame format and enabling the
Transmitter or the Receiver depending on the usage. For interrupt driven USART operation,
the Global Interrupt Flag should be cleared (and interrupts globally disabled) when doing the
initialization. Before doing a re-initialization with changed baud rate or frame format, be sure
that there are no on-going transmissions during the period the registers are changed. The
TXC Flag can be usedto check that the Transmitter has completed all transfers, and the RXC
Flag can be used to check that there are no unread data in the receive buffer. Note that the
TXC Flag must be cleared before each transmission (before UDR is written) if it is used for
this purpose. The following simple USART initialization code examples show one assembly
and one C function that are equal in functionality. The examples assume asynchronous
operation using polling (no interrupts enabled) and a fixed frame format. The baud rate is
given as a function parameter. For the assembly code, the baud rate parameter is assumed to
be stored in the r17:r16 registers. When the function writes to the UCSRC Register, the
URSEL bit (MSB) must be set due to the sharing of I/O location by UBRRH and UCSRC.
More advanced initialization routines can be made that include frame format as parameters,
disable interrupts and so on. However, many applications use a fixed setting of the Baud and
Control Registers, and for these types of applications the initialization code can be placed
directly in the main routine, or be combined with initialization code for other I/O modules.
Data Transmission The USART Transmitter
The USART Transmitter is enabled by setting the Transmit Enable (TXEN) bit in the
UCSRB Register. When the Transmitter is enabled, the normal port operation of the TxD pin
is overridden by the USART and given the function as the transmitters serial output. The
baud rate, mode of operation and frame format must be set up once before doing any
transmissions. If synchronous operation is used, the clock on the XCK pin will be overridden
and used as transmission clock.
35
A data transmission is initiated by loading the transmit buffer with the data to be transmitted.
The CPU can load the transmit buffer by writing to the UDR I/O location. The buffered data
in the transmit buffer will be moved to the Shift Register when the Shift Register is ready to
send a new.
}
ATmega16(L)frame. The Shift Register is loaded with new data if it is in idle state (no
ongoing transmission) or immediately after the last stop bit of the previous frame is
transmitted. When the Shift Register is loaded with new data, it will transfer one complete
frame at the rate given by the Baud Register, U2X bit or by XCK depending on mode of
operation. The following code examples show a simple USART transmit function based on
polling of the Data Register Empty (UDRE) Flag. When using frames with less than eight
bits, the most significant bits written to the UDR are ignored. The USART has to be
initialized before the function can be used. For the assembly code, the data to be sent is
assumed to be stored in Register R16.
The function simply waits for the transmit buffer to be empty by checking the UDRE Flag,
before loading it with new data to be transmitted. If the Data Register Empty Interrupt is
utilized, the interrupt routine writes the data into the buffer.
Parity Generator
The parity generator calculates the parity bit for the serial frame data. When parity bit is
enabled(UPM1 = 1), the transmitter control logic inserts the parity bit between the last data
bit and the first stop bit of the frame that is sent.
Disabling the Transmitter
The disabling of the transmitter (setting the TXEN to zero) will not become effective until
ongoingand pending transmissions are completed, that is, when the transmit Shift Register
and transmit Buffer Register do not contain data to be transmitted. When disabled, the
transmitter will no longer override the TxD pin.
38
Operation
A crystal is a solid in which the constituent atoms, molecules, or ions are packed in a
regularly ordered, repeating pattern extending in all three spatial dimensions.
39
Almost any object made of an elastic material could be used like a crystal, with appropriate
transducers, since all objects have natural resonant frequencies of vibration. For example,
steel is very elastic and has a high speed of sound. It was often used in mechanical filters
before quartz. The resonant frequency depends on size, shape, elasticity, and the speed of
sound in the material. High-frequency crystals are typically cut in the shape of a simple,
rectangular plate. Low-frequency crystals, such as those used in digital watches, are typically
cut in the shape of a tuning fork. For applications not needing very precise timing, a low-cost
ceramic resonator is often used in place of a quartz crystal.
When a crystal of quartz is properly cut and mounted, it can be made to distort in an electric
field by applying a voltage to an electrode near or on the crystal. This property is known as
electrostriction or inverse piezoelectricity. When the field is removed, the quartz will
generate an electric field as it returns to its previous shape, and this can generate a voltage.
The result is that a quartz crystal behaves like a circuit composed of an inductor, capacitor
and resistor, with a precise resonant frequency.
Quartz has the further advantage that its elastic constants and its size change in such a way
that the frequency dependence on temperature can be very low. The specific characteristics
will depend on the mode of vibration and the angle at which the quartz is cut (relative to its
crystallographic axes).[10] Therefore, the resonant frequency of the plate, which depends on
its size, will not change much, either. This means that a quartz clock, filter or oscillator will
remain accurate. For critical applications the quartz oscillator is mounted in a temperaturecontrolled container, called a crystal oven, and can also be mounted on shock absorbers to
prevent perturbation by external mechanical vibrations.
40
41
6. TEMPERATURE SENSOR
Temperature sensor used in this work is LM35. LM35 is a precision IC temperature sensor
with its output proportional to the temperature (in oC). The sensor circuitry is sealed and
therefore it is not subjected to oxidation and other processes. With LM35, temperature can be
measured more accurately than with a thermistor. It also possess low self-heating and does
not cause more than 0.1oC temperature rise in still air.
The operating temperature range is from -55C to 150C. The output voltage varies by 10mV
in response to every oC rise/fall in ambient temperature, i.e., its scale factor is 0.01V/oC.
Pin Diagram:
Pin Description:
42
This sensor has a high sensitivity and fast response time. The sensor's output is an analog
resistance. The drive circuit is very simple; all you need to do is power the heater coil with
5V, add a load resistance, and connect the output to an ADC.
This LPG Gas Sensor (MQ6), ideal sensor for use to detect the presence of a dangerous LPG
leak in your Home, car or in a service station, storage tank environment. This unit can be
easily incorporated into an alarm unit, to sound an alarm or give a visual indication of the
Combustible Gas / LPG concentration. The sensor has excellent sensitivity combined with a
quick response time. The sensor can also sense iso-butane, propane, LNG and cigarette
smoke. This LPG Gas Sensor can be used to make wireless Gas leak detector in home
security system.
43
CIRCUIT DIAGRAM
44
8. GSM Module
For sending message, GSM Module named SIMCOM_300 is being used. GSM Module
SIM300with sim-card holder, RS232 interface, power supply, buzzer and audio interface.
You can connect this to PC using a USB to Serial Adaptor and use terminal programs such as
Real term to send & receive data. We can also interface GSM Module with microcontroller
directly through wires.
GSM Module works with AT COMMANDS. AT commands are used to control MODEMs.
AT is the abbreviation for Attention.
AT commands with a GSM/GPRS MODEM or mobile phone can be used to access following
information and services:
1. Information and configuration pertaining to mobile device or MODEM and SIM card.
2. SMS services.
3. MMS services.
4. Call services.
5. Data and Voice link over mobile network.
45
46
SIM300:
This is a plug and play GSM Modem with a simple to interface serial interface. Use it to send
SMS, make and receive calls, and do other GSM operations by controlling it through simple
AT commands from micro controllers and computers. It uses the highly popular SIM300
module for all its operations. It comes with a standard RS232interface which can be used to
easily interface the modem to micro controllers andcomputers. The modem consists of all the
required external circuitry required to startexperimenting with the SIM300 module like the
power regulation, external antenna, SIM Holder, etc.
Features
Provides the industry standard serial RS232 interface for easy connection tocomputers
and other devices
Provides serial TTL interface for easy and direct interface to microcontrollers
Modules operation mode can be controlled through the PWR Switch connected tothe
PWR pin (refer the SIM300 datasheet for more information)
Comes with an onboard wire antenna for better reception. Board provides anoption
for adding an external antenna through an SMA connector
The SIM300 allows an adjustable serial baud rate from 1200 to 115200 bps
(9600default)
Modem a low power consumption of 0.25 A during normal operations and around1 A
during transmission
Note: The modem consumes current of nearly 1A during transmission; please makesure that
your power supply can handle such currents.
48
Feature
Implementation
Power saving
Frequency bands
SIM300 Tri-band: EGSM 900, DCS 1800, PCS 1900. The band can be
set by
AT COMMAND, and default band is EGSM 900 and DCS 1800.
Compliant to GSM Phase 2/2
GSM class
Small MS
Transmit power
GPRS connectivity
Temperature range
DATA GPRS:
CSD:
SMS
SIM interface
External antenna
Audio features
Full Rate (ETS 06.10) Enhanced Full Rate (ETS 06.50 / 06.60 / 06.80)
Echo suppression
Two serial
interfaces
Serial Port 1 can be used for CSD FAX, GPRS service and send
AT Commands
Types of AT Commands:
There are four types of AT commands:
1. Test commands - used to check whether a command is supported or not by the MODEM.
SYNTAX: AT<command name>=?
For example: ATD=?
2. Read command - used to get mobile phone or MODEM settings for an operation.
SYNTAX: AT<command name>?
For example: AT+CBC?
3. Set commands - used to modify mobile phone or MODEM settings for an operation.
SYNTAX: AT<command name>=value1, value2, ,valueN
Some values in set commands can be optional.
For example: AT+CSCA=+919026948337, 120
4. Execution commands - used to carry out an operation.
SYNTAX: AT<command name>=parameter1, parameter2, ,parameterN
The read commands are not available to get value of last parameter assigned in
execution commands because parameters of execution commands are not stored.
For example: AT+CMSS=1,+ 9876543210, 120
50
52
An RS-232 port was once a standard feature of a personal computer for connections
tomodems, printers, mice, data storage, un-interruptible power supplies, and
otherperipheral devices.
However, the limited transmission speed, relatively large voltage swing, and
largestandard connectors motivated development of the universal serial bus which
hasdisplaced RS-232 from most of its peripheral interface roles.
Many modern personal computers have no RS-232 ports and must use an
externalconverter to connect to older peripherals. Some RS-232 devices are still
foundespecially in industrial machines or scientific instruments.
RS-232 drivers and receivers must be able to withstand indefinite short circuitto
ground or to any voltage level up to 25 volts.
The slew rate, or how fast the signal changes between levels, is alsocontrolled.
DB9 Male:
54
DB9 Female:
This USB Serial Adapter is designed to make serial port expansion quick and
simple.Connecting to a USB port on your computer or USB hub, this USB Serial
Adapterinstantly adds a serial communication port to your system with easy plug-andplayand hot-plug features.
Plugging the USB Serial Adapter into the USB port, the adapter is
automaticallydetected and installed. There are no IRQ & COM port conflicts, since
the port doesn'trequire any additional IRQ, DMA or memory on the system.
The RS-232 serial port functions as a native Windows COM port, and it is
compatiblewith Windows serial communication applications.
Compatible with all popular PDAs, modems, printers, bar code scanners, etc.
Thin cables and light weight makes it portable and easy to carry
Adds a high speed RS-232 serial port via a USB 1.1 or 2.0 connection
RS-232 data signals: DCD, RxD, TxD, DTR, GND, DSR, RTS, CTS, RI.
56
Connect bar code scanners, receipt printers and other point of sale devices
Connect and program LED and Digital signage boards with serial communication
ports
What is HyperTerminal?
Figure: HyperTerminal
In windows7 by default HyperTerminal is not there, but we can create it by simple following
method.In windows7, only option
C:\Windows\Help\HYPERTRM.CHM
C:\Windows\Help\HYPERTRM.HLP
C:\Windows\System32\hypertrm.dll
open shortcut.
HyperTerminal is ready.
58
1) Connect RS-232 port of GSM module with the serial port of the computer. Insert a SIM
card in the module.
2) Open HyperTerminal from Start> All Programs > Accessories > Communications
>HyperTerminal.
3) Enter a name for the connection and press OK.
4) Now select the communication port (COM) at which GSM module is connected.Create a
new connection set on HyperTerminal. Set parameters, like baud rate as9600, handshaking
mode as none, parity bit as none, stop bit as 1 and data bit as 8.
59
Circuit Diagram:
60
61
9. PROGRAMMING
#include<avr/io.h>
#include<util/delay.h>
#include<inttypes.h>
#define F_CPU 12000000
#define baud 9600
#define myUBRR F_CPU/16/baud-1
voidusart_init(uint16_t ubrr_value)
{
UBRRL = ubrr_value;
UBRRH = (ubrr_value>>8);
UCSRC|=(1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0);
UCSRB=(1<<RXEN)|(1<<TXEN)|(1<<RXCIE);
{
usart_send(*ptr);
ptr++;
}
}
62
usart_send_string("AT+CMGF=1");
wait(4);
usart_send('\n\r');
wait(8);
63
usart_send_string("AT+CMGD=1");
usart_send('\n\r');
wait(8);
usart_send_string("AT+CMGS=");
wait(2);
usart_send('"');
while(*no!='\0')
{
usart_send(*no);
no++;
}
usart_send('"');
_delay_ms(500);
usart_send('\n\r');
wait(4);
// start of message
while(*p!='\0')
{
usart_send(*p);
p++;
}
64
wait(6);
usart_send(26);
_delay_ms(500);
usart_send('\n\r');
wait(16);
}
intr_adc(uint8_t ch)
{
//Select ADC Channel ch must be 0-7
ADMUX&=0b11110000;
ch=ch&0b00000111;
DDRA=~(1<<ch); //make chanel number pin as input rest of the pins will be output;
// ADC_PORT=~(1<<ch); //make chanel number pin as input rest of the pins will be
output;
ADMUX|=ch;
//Start Single conversion
ADCSRA |= (1<<ADSC);
//Wait for conversion to complete
65
while(!(ADCSRA&(1<<ADIF)));
//clear the flag
ADCSRA|=(1<<ADIF);
return(ADC);
}
voidinit_adc(void)
{
ADCSRA=(1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);// 10010111
// enable ADC,prescaler % 128
ADMUX=(1<<REFS0)|(1<<REFS1)|(0<<ADLAR);
//01100000
void main()
{
inttemp_val;
init_adc();//intialize the system
usart_init(myUBRR);
DDRB = 0b00000000;//make portb as input for the switch
intswt;
int check =0;
66
int a;
while(1)
{
temp_val = r_adc(0);
temp_val = ((temp_val/2)-4);
if(temp_val>= 120)
{
send_msg("Fire in Home Be Alert","+919760365323");//to send msg
_delay_ms(5000);
}
swt = PINB & 0b00000011;
if((swt = (PINB & 0b00000010)==0))//when LPG is on it give 0v
{
_delay_ms(20);
if((swt = (PINB & 0b00000010)==0))
{
_delay_ms(20);
while((swt = (PINB & 0b00000010)==0));//wait until swt is pressed
send_msg("Leakage of LPG","+919760365323");//to send msg
}
wait(8);
}
temp_val = 0;
}//end of while
}//end of main
67
10.APPLICATIONS
This project is applicable in following fields:
1. Domestic gas leakage detector
2. Industrial Combustible gas detector
3. Portable gas detector
4. Homes
5. Factories
6. LPG storage
7. Gas cars
8. Hotels
9. Hospital etc.
68
11.CONCLUSION
We have finally succeeded in making the GSM BASED HOME SECURITY SYSTEM
USING LPG GAS DETECTOR, TEMPRATURE SENSOR FOR FIRE DETECTOR AND
GSM MODULE Satisfactorily. More knowledge is gained and more experiences are faced lot
of informations are collected ultimately, I have concluded with a great pleasure for achieving
our aim.
We have planned to fulfil my technical requirements. The knowledge I have attained with
this project really would follow till the end of our career.
69
12. REFERENCES
[1] Huang, H., Xiao, S., Meng, X., and Xiong, Y., A Remote Home Security System Based
on Wireless Sensor Network and GSM Technology, Proceedings of Second International
Conference on Networks Security, Wireless Communications and Trusted Computing, 2010.
(Conference Proceedings)
[2] Atmel Corporation, Atmega8/L Datasheet, available
http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf Command Description
ATA Answer an incoming call ATD Dial a number ATH Hang up call AT+COLP
Connected line identification presentation AT+VTS DTMF and Tone generation AT+CMGF
Select SMS message format AT+CMGS Send SMS message International Conference on
Recent Advances and Future Trends in Information Technology (iRAFIT2012) Proceedings
published in International Journal of Computer Applications (IJCA)
[3] Digi International Inc, XBee/XBee-PRO RF Modules, available
http://ftp1.digi.com/support/documentation/90000982_B.pdf
[4] Atmel Corporation, Atmega16 Datasheet, available
http://www.atmel.com/dyn/resources/prod_documents/doc2466.pdf
[5] Maxim Integrated Products, DS1307 Datasheet, available http://datasheets.maximic.com/en/ds/DS1307.pdf
[6] Texas Instruments Inc, MAX232 Datasheet, available
http://www.ti.com/lit/ds/symlink/max232.pdf
[7] Atmel Corporation, Atmega162 Datasheet, available
http://www.atmel.com/dyn/resources/prod_documents/doc2513.pdf
[8] SIMCOM Ltd, SIM300 Datasheet, available
http://wm.sim.com/sim/News/photo/2009612100507.pdf
[9] Holtek Semiconductor Inc, HT9170 Datasheet, available
http://www.holtek.com.tw/english/tech/appnote/comm/pdf/ha0038e.pdf
70