Vous êtes sur la page 1sur 84

AUTOMATED UNIFIED SYSTEM FOR LPG USING

MICROCONTROLLER
Introduction

Doing an electronic project is a creative and innovative idea for the developers,
first we have to choose the title of the project from the lot of available application
or from the developing application in research. Once the title is selected, the
developer designed the circuit from the available electronic sources. The basic
level circuit may be checked in the breadboard or using the general purpose PCB.
The advances level circuit may be simulated and may be verified using the
simulation tools.

The different components and the IC range from basic electronics device to the
very advanced ASIC. The different design and application level depends on the
requirement and cost. The design may be slowly based on the discrete circuit and
the programming chips. They may be microprocessor, microcontroller, embedded
system, VLSI, PLC.

Moreover one should construct the DC power source from the mains or can use the
batteries. The DC power required may be 5v.6v.9v.12v. etc. here we are
attempting to design and construct the project namely” AUTOMATED UNIFIED
SYSTEM FOR LPG USINGMICROCONTROLLER”
SYNOPSIS:

A cost-effective, Automated Unified System for Liquefied Petroleum Gas(LPG)


leakage detection, real time gas monitoring system and automaticcontrolling of
LPG regulator is proposed in this project. The aim of this project isto monitor for
LPG leakage to avoid fire accidents providing house safety featurewhere security
has been an important issue. The system detects the leakage of theLPG using gas
sensor MQ6 and alerts the consumer about the gas leakage byactivating the alarm
and exhaust fan. The system additionally provides theautomatically controlling of
LPG regulator. To avoid the blast this system willdisconnect the main power
supply using relay.
HARDWARE REQUIREMENTS

 Gas sensor
 Buzzer
 Motor driver
 GSM
 Relay
 Pic microcontroller
 Dc power supply
 Main switch
1.1. BLOCK DIAGRAM
BLOCK DESCRIPTION

In our project, we use a gas sensor to detect the leaked LPG. If found, then the
signal is immediately sent to the microcontroller. The controller sends a signal to
relay and motor driver .Then the signal was taken to process using relay ,in relay
whenever a coil energizes it will produce a output(i.e.. main switch will be OFF)
an the another output taken via by motor driver that is door. When signal comes to
drive a motor a door will be open automatically.
1.2. CIRCUIT DIAGRAM

Power supply gives supply to all components. It is used to convert AC voltage


into DC voltage .Transformer used to convert 230 V into 12V AC. 12V is
given to diode . Diode rangeis IN 4007, which is used to convert AC voltage
into DC voltage.AC capacitor used to chargeAC components and discharge
on ground. LM 7805 regulator is used to maintain voltage asconstant. Then
signal will be given to next capacitor , which is used to filter unwanted AC
component. Load will be LED and resistor. LED voltage is 1.75V. If
voltage isabove level beyond the limit, and then it will be dropped on
resistor.GAS SENSORis connected to controller port 2 through the PIC
circuit. IR is connected to controller port 3 through the attenuator circuit.
Relay is connectedto MAX 232 pin no 7 &8. It is connected to controller port
25 & 26. LCD is also connected tocontroller.
POWER SUPPLY:

This circuit is worn to renovate the AC to DC. It restrains of step


down transformer, bridge rectifier, ripple filter, voltage regulator and line filter.
Rationale of transformer is to step down the 230 VAC to 15VAC. This AC voltage
is auxiliary rectified using bridge rectifier, the productivity of bridge rectifier is
pulsating DC with small AC ripples. This AC ripples are then filtered using
1000uF shunt capacitor. Because the capacitor grounds AC signal and evade the
DC, so the output across the shunt capacitor is pure DC. This DC voltage is
unfettered, because change in primary of the transformer will change this DC
voltage. So it needs to regulate the voltage. Here we use series voltage regulator is
used to regulate the voltage. At last one 10uF shunt capacitor is used to filter the
fluctuation due to switching of SCR’s.
2.3.1. VOLTAGE REGULATOR

The LM7805 series of three terminal regulators is available with


several fixed output voltages making them useful in a wide range of applications.
One of these is local on card regulation, eliminating the distribution problems
associated with single point regulation. The voltages available allow these
regulators to be used in logic systems, instrumentation, HiFi, and other solid state
electronic equipment. Although designed primarily as fixed voltage regulators
these devices can be used with external components to obtain adjustable voltages
and currents .
The LM7805 series is available in an aluminum TO-3 package which
will allow over 1.0A load current if adequate heat sinking is provided. Current
limiting is included to limit the peak output current to a safe value. Safe area
protection for the output transistor is provided to limit internal power dissipation. If
internal power dissipation becomes too high for the heat sinking provided, the
thermal shutdown circuit takes over preventing the IC from overheating.
Considerable effort was expanded to make the LM7805 series of regulators easy to
use and minimize the number of external components. It is not necessary to bypass
the output, although this does improve transient response.

2.3.2. FEATURES OF VOLTAGE REGULATOR

 Output current in excess of 1A

 Internal thermal overload protection

 No external components required.

2.3.3. VOLTAGE DIVIDER

Voltage divider restricting the resistance values between 1 k- and


100 k- for the sake of obtaining accurate voltage and current readings with your
meter. With very low resistance values, the internal resistance of the ammeter has a
significant impact on measurement accuracy. Very high resistance values may
cause problems for voltage measurement, the internal resistance of the voltmeter
substantially changing circuit resistance when it is connected in parallel with a
high-value resistor.
2.3.4. SCHEMATIC DIAGRAM

Figure 2.3.3 Schematic diagram of Voltage Divider

We are purposely restricting the resistance values between 1 k- and


100 k- for the sake of obtaining accurate voltage and current readings with your
meter. With very low resistance values, the internal resistance of the ammeter has a
significant impact on measurement accuracy.

Very high resistance values may cause problems for voltage


measurement, the internal resistance of the voltmeter substantially changing circuit
resistance when it is connected in parallel with a high-value resistor. Connect the
three resistors in series, and to the 6-volt battery, as shown in the illustrations.
Measure battery voltage with a voltmeter after the resistors ,have been connected
to it, noting this voltage on paper as well. It is advisable to measure battery voltage
while it's powering the resistor circuit because this voltage may slightly from a no-
load condition. The "free-form" method where all components are connected
together with "alligator-" style jumper wire sis the least professional, but
appropriate for a simple experiment such as this.
Breadboard construction is versatile and allows for high component
density (many parts in a small space), but is quite temporary. Operations are read-
modify-write operations. Therefore, a write to a port implies that the port pins are
read, the value is modified and then written to the port data latch. Terminal strips a
much more permanent form of construction at the cost of low component density.

We saw exaggerated in the "parallel battery" experiment while powering a


high-wattage lamp: battery voltage tends to "sag" or "droop" under load. Although
this three-resistor circuit should not present a heavy enough load (not enough
current Each resistor voltage drop will be some fraction or percentage of the total
voltage, hence the name voltage divider given to this circuit. While the input
voltage may vary over some permissible voltage range, and the output load may
vary over some acceptable range, the output voltage remains constant within
specified voltage variation limits .This fractional value is determined by the
resistance of the particular resistor and the total resistance. If a resistor drops 50%
of the total battery voltage in a voltage divider circuit, that proportion of 50% will
remain the same as long as the resistor values are not altered.

2.3.5. CIRCUIT DESCRIPTION

2.3.1. POWER SUPPLY:

Here in this project most of the operations are operated in 5V and 12V. So
we use 230V/12V potential transformer and 7805 regulator for 5V. Power supply
circuit consists of bridge rectifier, ripple filter, regulator and line filter. Bridge
rectifier is constructed using 1N4007 diode. Ripple filter is build around
1000uF/25V.
POWERSUPPLY SECTION

Types of Power Supply:

There are many types of power supply. Most are designed to convert high voltage
AC mains electricity to a suitable low voltage supply for electronics circuits and
other devices. A power supply can by broken down into a series of blocks, each of
which performs a particular function.

For example a 5V regulated supply:

Each of the blocks is described in more detail below:

 Transformer - steps down high voltage AC mains to low voltage AC.


 Rectifier - converts AC to DC, but the DC output is varying.
 Smoothing - smooths the DC from varying greatly to a small ripple.
 Regulator - eliminates ripple by setting DC output to a fixed voltage.

Power supplies made from these blocks are described below with a circuit diagram and a graph
of their output:

 Transformer only
 Transformer + Rectifier
 TransforTransformer onlymer + Rectifier + Smoothing
Transformer + Rectifier + Smoothing + RegulatorTransformer only

The low voltage AC output is suitable for lamps, heaters and special AC motors. It
is not suitable for electronic circuits unless they include a rectifier and a smoothing
capacitor.

Further information: Transformer

Transformer + Rectifier

The varying DC output is suitable for lamps, heaters and standard motors. It
is not suitable for electronic circuits unless they include a smoothing
capacitor.

Further information: Transformer | Rectifier


Transformer + Rectifier + Smoothing
The smooth DC output has a small ripple. It is suitable for most electronic
circuits.
Further information: Transformer | Rectifier | Smoothing
Transformer + Rectifier + Smoothing + Regulator

The regulated DC output is very smooth with no ripple. It is suitable for all
electronic circuits.
Further information: Transformer | Rectifier | Smoothing | Regulator
2.4. RELAYS AND REED SWITCHES

1. Relays:

A relay is a switch worked by an electromagnet. It is useful if we want a small


current in one circuit to control another circuit containing a device such as a
lamp or electric motor which requires a large current, or if we wish several
different switch contacts to be operated simultaneously.

When the controlling current flows through the coil, the soft iron core is
magnetized and attracts the L-shaped soft iron armature. This rocks on its pivot
and opens, closes or changes over, the electrical contacts in the circuit being
controlled it closes the contacts.

2.4.2. . RELAY CONTROL


By using a level sensor we will get the level of feed water. This signal controls
the feed water valve for maintaining a constant level. In our project we are using
an ON-OFF control valve i.e. solenoid valve. The advantage of using ON-OFF
control valve is

1. There is no dead time


2. There is no transfer lag.
2.4.3.CIRCUIT DIAGRAM DESCRIPTION:

In this circuit transistor BC547 is used as a switch. The control signal is given
to the base terminal of the transistor. The collector is attached to the relay coil.
Relays are electromechanical devices. There are two types of relays.

1. Normally closed
2. Normally opened
We are using normally opened type relay. When the controller output from the PC
is high the transistor will be in the ON state, so relay is energized. When the

output from the PC is low the transistor will be in the OFF state, so relay is de-
energized the valve will open. When the relay is de-energized the valve will close.
So according to the controller output the valve will open or close and
thuslevelismaintained.
2.5.PIEZOELCTRICBUZZER

Figure 2.5.5 Circuit diagram of Piezoelectric Buzzer

The two series-connected diodes will drop approximately 1.4 volts, equivalent
to the combined Vbe forward voltage drops of the two transistors, resulting in a
scenario where each transistor is just on the verge of turning on when the input
signal is zero volts, eliminating the 1.4 volt "dead" signal zone that existed before.
Unfortunately, though, this solution is not perfect: as the transistors heat up from
conducting power to the load, their Vbe forward voltage drops will decrease from
0.7 volts to something less,such as 0.6 volts or 0.5 volts. The diodes, which are not
subject to the same heating effect because they do not conduct any substantial
current, will not experience the same change in forward voltage drop. Thus, the
diodes will continue to provide the same 1.4 volt bias voltage even though the
transistors require less bias voltage due to heating.
RELAY DRIVERS

Introduction:

The relay driver section gives signal to the relay and makes the relay to close
its contacts. As the relay has a small mechanical contact i.e.., a small metallic strip
the relay drier must have capacity to drive it. For this a special IC used which has
high signal carrying capacity and the IC used for this is IC ULN 2003
DARLINGTON ARRAY.

Darlington Sink Driver:

The IC ULN 2003 series are high voltage, high current Darlington drivers
comprised of seven NPN Darlington pairs.

All units feature integral clamp diodes for switching inductive loads.
Applications include relay, hammer, lamp and display (LED) drivers.

Outline pin diagram of IC ULN 2003


The above diagram shows the outline pin diagram of IC ULN 2003. it has 16
pins and each pin has some specific application and the two models of the IC are
DIP type and SOL type.

Features:

 Output current (single output) 500mA MAX.


 High sustaining voltage output 50V MIN.
 Output clamps diodes.
 Inputs compatible with various types of logic.
 Package type-AP : DIP-16 pin
 Package type-AFW : SOL-16 pin

Pin Configuration:

Pin connection of IC ULN 2003


The above diagram shows the pin diagram of IC ULN 2003 darling ton array.
It has 16 pins where the pin 8 is ground pin and pin 9 is used as common pin for all
applications which is also grounded. If we see the internal diagram of IC it has not
gates in series with diode and all are connected in parallel and their output is
connected to corresponding terminals.

The ULN2003 are high voltage, high current Darlington arrays each
containing seven open collector Darlington pairs with common emitters. Each
channel rated at 500mA and can withstand peak currents of 600mA. Suppression
diodes are included for inductive load driving and the inputs are pinned opposite
the outputs to simplify board layout.

These versatile devices are useful for driving a wide range of loads including
solenoids, relays DC motors; LED displays filament lamps, thermal print heads
and high power buffers.

ULN 2003 is supplied in 16 pin plastic DIP packages with a copper lead
frame to reduce thermal resistance. They are available also in small outline
package.

Schematic Diagram:

Schematic diagram of IC ULN 2003


The above figure shows the schematic diagram of IC ULN 2003. Here it has an input
terminal, two NPN transistors, four IN 4007 diodes. This diagram is replaced to
small size and embedded in the form of IC.

The schematic diagram consists of four diodes, two transistors and a set of
resistors. It has four terminals input, output, ground and common terminal. The three
terminals are given to three terminals of the relay and the input terminal is connected
to control logic circuit.

Maximum Ratings:

The table shows the maximum ratings of IC ULN2003 where it shows the
output voltage, maximum input voltage, operating temperature, storage temperature
etc..,

maximum ratings of IC ULN 2003


Test Circuits Of IC Uln2003:

Test circuits of IC ULN2003

The circuit shown above is the test circuit of IC ULN2003. It has a pulse
generator which generates required signal to be given to the relay. As the relay
works on DC supply this pulse generator generates pure ripple free DC.

It also has a NOT gate which makes the relay to open its contacts when the
power is off or when the fault occurs or else when the supply is on spark occurs. To
avoid this we use a NOT gate and a diode connected parallel.

Relay:

Contact Specifications:

 Configuration : 2CO, 2NO


 Contact rating : 30A at 240V AC/ 24V DC.
 Contact resistance : 100mΏ( max)
 Contact material : Silver alloy.
General Performance:

 Operating time : 30msec Max


 Fast switching version : 10msec Max
 Release time : 10maec Max
 Life expectancy
 Electrical : 5X 10^3 operations
 Mechanical : 10^3 operations
 Dielectric strength
 Between open contacts : 1000V AC
 Between coil and contact : 2000V AC
MICROCONTROLLERS

Introduction to Microcontrollers

Circumstances that we find ourselves in today in the field of


microcontrollers had their beginnings in the development of technology of
integrated circuits. This development has made it possible to store hundreds of
thousands of transistors into one chip. That was a prerequisite for production of
microprocessors, and the first computers were made by adding external peripherals
such as memory, input-output lines, timers and other. Further increasing of the
volume of the package resulted in creation of integrated circuits. These integrated
circuits contained both processor and peripherals. That is how the first chip
containing a microcomputer, or what would later be known as a microcontroller
came about.

Memory unit

Memory is part of the microcontroller whose function is to store data. For a


certain input we get the contents of a certain addressed memory location and that's
all. Two new concepts are brought to us: addressing and memory location.
Memory consists of all memory locations, and addressing is nothing but selecting
one of them. This means that we need to select the desired memory location on one
hand, and on the other hand we need to wait for the contents of that location.
Besides reading from a memory location, memory must also provide for writing
onto it. This is done by supplying an additional line called control line. We will
designate this line as R/W (read/write). Control line is used in the following way: if
r/w=1, reading is done, and if opposite is true then writing is done on the memory
location.
Block diagram of memory unit

Central Processing Unit

Let add 3 more memory locations to a specific block that will have a built in
capability to multiply, divide, subtract, and move its contents from one memory
location onto another. The part we just added in is called "central processing unit"
(CPU). Its memory locations are called registers.

Registers are therefore memory locations whose role is to help with


performing various mathematical operations or any other operations with data
wherever data can be found. Look at the current situation. We have two
independent entities (memory and CPU) which are interconnected, and thus any
exchange of data is hindered, as well as its functionality.
Bus

That "way" is called "bus". Physically, it represents a group of 8, 16, or more


wires. There are two types of buses: address and data bus. The first one consists of
as many lines as the amount of memory we wish to address and the other one is as
wide as data, in our case 8 bits or the connection line. First one serves to transmit
address from CPU memory, and the second to connect all blocks inside the
microcontroller.

Representation of Bus

Input-output unit

Those locations we've just added are called "ports". There are several types
of ports: input, output or bidirectional ports. When working with ports, first of all it
is necessary to choose which port we need to work with, and then to send data to,
or take it from the port. When working with it the port acts like a memory location.
Something is simply being written into or read from it, and it could be noticed on
the pins of the microcontroller.
Serial communication

As we have separate lines for receiving and sending, it is possible to receive


and send data (info.) at the same time. So called full-duplex mode block which
enables this way of communication is called a serial communication block. Unlike
the parallel transmission, data moves here bit by bit, or in a series of bits what
defines the term serial communication comes from. After the reception of data we
need to read it from the receiving location and store it in memory as opposed to
sending where the process is reversed. In order for this to work, we need to set the
rules of exchange of data. These rules are called protocol. Data goes from memory
through the bus to the sending location, and then to the receiving unit according to
the protocol.

Timer unit

The timer block this can give us information about time, duration, protocol
etc. The basic unit of the timer is a free-run counter which is in fact a register
whose numeric value increments by one in even intervals, so that by taking its
value during periods T1 and T2 and on the basis of their difference we can
determine how much time has elapsed. This is a very important part of the
microcontroller whose understanding requires most of our time.

Watchdog

One more thing is requiring our attention is a flawless functioning of the


microcontroller during its run-time.

Watch dog time


Suppose that as a result of some interference (which often does occur in
industry) our microcontroller stops executing the program, or worse, it starts
working incorrectly. Of course, when this happens with a computer, we simply
reset it and it will keep working. However, there is no reset button we can push on
the microcontroller and thus solve our problem. To overcome this obstacle, we
need to introduce one more block called watchdog. This block is in fact another
free-run counter where our program needs to write a zero in every time it executes
correctly. In case that program gets "stuck", zero will not be written in, and counter
alone will reset the microcontroller upon achieving its maximum value. This will
result in executing the program again, and correctly this time around.

Analog to Digital Converter

As the peripheral signals usually are substantially different from the ones
that microcontroller can understand (zero and one), they have to be converted into
a pattern which can be comprehended by a microcontroller.

Analog to Digital converter

This task is performed by a block for analog to digital conversion or by an


ADC. This block is responsible for converting an information about some analog
value to a binary number and for follow it through to a CPU block so that CPU
block can further process it.
Microcontroller with its basic elements and internal connections

Block representation of the microcontroller

CISC and RISC

Harvard architecture is a newer concept than Von-Neumann's. It rose out of


the need to speed up the work of a microcontroller. In Harvard architecture, data
bus and address bus are separate. Thus a greater flow of data is possible through
the central processing unit, and of course, a greater speed of work. Separating a
program from data memory makes it further possible for instructions not to have to
be 8-bit words. It is also typical for Harvard architecture to have fewer instructions
than von-Neumann's, and to have instructions usually executed in one cycle.
Microcontrollers with Harvard architecture are also called "RISC
microcontrollers". RISC stands for Reduced Instruction Set Computer.
Microcontrollers with von-Neumann's architecture are called 'CISC
microcontrollers'. Title CISC stands for Complex Instruction Set Computer. Since
PIC16F877 is a RISC microcontroller, that means that it has a reduced set of
instructions, more precisely 35 instructions. All of these instructions are executed
in one cycle except for jump and branch instructions. PIC16F87 usually reaches
results of 2:1 in code compression and 4:1 in speed in relation to other 8-bit
microcontrollers in its class.

PIC Microcontroller (PIC16F87X) Microcontroller Core Features:

• High-performance RISC CPU

• Only 35 single word instructions

• All single cycle instructions except for program branches which are two cycle

• Operating speed: DC - 20 MHz clock input DC - 200 ns instruction cycle

• Up to 8K x 14 words of FLASH Program Memory,

Up to 368 x 8 bytes of Data Memory (RAM)

Up to 256 x 8 bytes of EEPROM data memory


• Interrupt capability (up to 14 sources)

• Eight level deep hardware stack

• Direct, indirect and relative addressing modes

• Power-on Reset (POR)

• Power-up Timer (PWRT) and Oscillator Start-up Timer (OST)

• Watchdog Timer (WDT) with its own on-chip RC oscillator for reliable
operation

• Programmable code-protection

• Power saving SLEEP mode

• Selectable oscillator options

• Low-power, high-speed CMOS FLASH/EEPROM technology

• Fully static design

• In-Circuit Serial Programming (ICSP) via two pins

• Single 5V In-Circuit Serial Programming capability

• In-Circuit Debugging via two pins

• Processor read/write access to program memory

• Wide operating voltage range: 2.0V to 5.5V

• High Sink/Source Current: 25 mA

• Commercial and Industrial temperature ranges


• Low-power consumption:

- < 2 mA typical @ 5V, 4 MHz

- 20 mA typical @ 3V, 32 kHz

- < 1 mA typical standby current

Peripheral Features

• Timer0: 8-bit timer/counter with 8-bit prescaler

• Timer1: 16-bit timer/counter with prescaler, can be incremented during sleep via

external crystal/clock

• Timer2: 8-bit timer/counter with 8-bit period register, prescaler and postscaler

• Two Capture, Compare, PWM modules

- Capture is 16-bit, max. resolution is 12.5 ns

- Compare is 16-bit, max. resolution is 200 ns

- PWM max. resolution is 10-bit

• 10-bit multi-channel Analog-to-Digital converter

• Synchronous Serial Port (SSP) with SPI (Master Mode) and I2C (Master/Slave)

• Universal Synchronous Asynchronous Receiver Transmitter (USART/SCI) with


9-bit address detection

• Parallel Slave Port (PSP) 8-bits wide, with external RD, WR and CS controls
(40/44-pin only)
Pin layout of PIC16F877A
PIC 16F877A

Architecture of PIC16F877A
Memory organization

There are three memory blocks in each of these PICmicro MCUs. The
Program Memory and Data Memory have separate buses so that concurrent access
can occur.

Program memory organization

The PIC16F87X devices have a 13-bit program counter capable of


addressing an 8K x 14 program memory space. The PIC16F877/876 devices have
8K x 14 words of FLASH program memory and the PIC16F873/874 devices have
4K x 14. Accessing a location above the physically implemented address will
cause a wraparound. The reset vector is at 0000h and the interrupt vector is at
0004h.

Program memory and Stack memory


Data memory organization

The data memory is partitioned into multiple banks which contain the
General Purpose Registers and the Special Function Registers. Bits
RP1(STATUS<6>) and RP0 (STATUS<5>) are the bank select bits.

Table Register bank selection

Each bank extends up to 7Fh (128 bytes). The lower locations of each bank are
reserved for the Special Function Registers. Above the Special Function Registers
are General Purpose Registers, implemented as static RAM.

General purpose register file

The register file can be accessed either directly or indirectly through the File
Select Register FSR.
Special function registers

The Special Function Registers are registers used by the CPU and peripheral
modules for controlling the desired operation of the device. These registers are
implemented as static RAM. The Special Function Registers can be classified into
two sets; core (CPU) and peripheral.

Status register

The STATUS register contains the arithmetic status of the ALU, the RESET
status and the bank select bits for data memory. The STATUS register can be the
destination for any instruction, as with any other register. If the STATUS register
is the destination for an instruction that affects the Z, DC or C bits, then the write
to these three bits is disabled. These bits are set or cleared according to the device
logic. The TO and PD bits are not writable, therefore, the result of an instruction
with the STATUS register as destination may be different than intended.

OPTION_REG register

The OPTION_REG Register is a readable and writable register, which


contains various control bits to configure the TMR0 prescaler/WDT postscaler
(single assignable register known also as the prescaler), the External INT Interrupt,
TMR0 and the weak pull-ups on PORTB.

INTCON register

The INTCON Register is a readable and writable register, which contains


various enable and flag bits for the TMR0 register overflow, RB Port change and
External RB0/INT pin interrupts.
PIE1 register

The PIE1 register contains the individual enable bits for the peripheral
interrupts.

PIR1 register

The PIR1 register contains the individual flag bits for the peripheral
interrupts.

PIE2 register

The PIE2 register contains the individual enable bits for the CCP2 peripheral
interrupt, the SSP bus collision interrupt, and the EEPROM write operation
interrupt.

PIR2 register

The PIR2 register contains the flag bits for the CCP2 interrupt, the SSP bus
collision interrupt and the EEPROM write operation interrupt.

PCON register

The Power Control (PCON) Register contains flag bits to allow


differentiation between a Power-on Reset (POR), a Brown-out Reset (BOR), a
Watch-dog Reset (WDT) and an external MCLR Reset.
Addressing modes:

Direct Addressing

Direct Addressing is done through a 9-bit address. This address is obtained


by connecting 7th bit of direct address of an instruction with two bits (RP1, RP0)
from STATUS register as is shown on the following picture. Any access to SFR
registers can be an example of direct addressing.

Indirect Addressing

Indirect unlike direct addressing does not take an address from an instruction
but makes it with the help of IRP bit of STATUS and FSR registers. Addressed
location is accessed via INDF register which in fact holds the address indicated by
a FSR. In other words, any instruction which uses INDF as its register in reality
accesses data indicated by a FSR register. Let's say, for instance, that one general
purpose register (GPR) at address 0Fh contains a value of 20. By writing a value of
0Fh in FSR register we will get a register indicator at address 0Fh, and by reading
from INDF register, we will get a value of 20, which means that we have read from
the first register its value without accessing it directly (but via FSR and INDF).
It appears that this type of addressing does not have any advantages over
direct addressing, but certain needs do exist during programming which can be
solved smoothly only through indirect addressing.

Indirect addressing, INDF and FSR registers

The INDF register is not a physical register. Addressing the INDF register
will cause indirect addressing. Indirect addressing is possible by using the INDF
register. Any instruction using the INDF register actually accesses the register
pointed to by the File Select Register, FSR. Reading the INDF register itself
indirectly (FSR = ’0’) will read 00h. Writing to the INDF register indirectly results
in a no-operation (although status bits may be affected).
I/O Ports

Some pins for these I/O ports are multiplexed with an alternate function for
the peripheral features on the device. In general, when a peripheral is enabled, that
pin may not be used as a general purpose I/O pin.

PORTA and the TRISA Register

PORTA is a 6-bit wide bi-directional port. The corresponding data direction


register is TRISA. Setting a TRISA bit (=1) will make the corresponding PORTA
pin an input (i.e., put the corresponding output driver in a hi-impedance mode).
Clearing a TRISA bit (=0) will make the corresponding PORTA pin an output (i.e.,
put the contents of the output latch on the selected pin). Reading the PORTA
register reads the status of the pins, whereas writing to it will write to the port
latch. Pin RA4 is multiplexed with the Timer0 module clock input to become the
RA4/T0CKI pin. The RA4/T0CKI pin is a Schmitt Trigger input and an open drain
output. All other PORTA pins have TTL input levels and full CMOS output
drivers. Other PORTA pins are multiplexed with analog inputs and analog VREF
input. The operation of each pin is selected by clearing/setting the control bits in
the ADCON1 register (A/D Control Register1).

PORTB and the TRISB Register

PORTB is an 8-bit wide, bi-directional port. The corresponding data


direction register is TRISB. Setting a TRISB bit (=1) will make the corresponding
PORTB pin an input. Clearing a TRISB bit (=0) will make the corresponding
PORTB pin an output. Three pins of PORTB are multiplexed with the Low
Voltage Programming function; RB3/PGM, RB6/PGC and RB7/PGD.
Each of the PORTB pins has a weak internal pull-up. A single control bit
can turn on all the pull-ups. This is performed by clearing bit RBPU
(OPTION_REG<7>). The weak pull-up is automatically turned off when the port
pin is configured as an output. The pull-ups are disabled on a Power-on Reset.
Four of PORTB’s pins, RB7:RB4, have an interrupt on change feature. Only pins
configured as inputs can cause this interrupt to occur. The input pins (of RB7:RB4)
are compared with the old value latched on the last read of PORTB. The
“mismatch” outputs of RB7:RB4 are OR’ed together to generate the RB Port
Change Interrupt with flag bit RBIF (INTCON<0>).

PORTC and the TRISC Register

PORTC is an 8-bit wide, bi-directional port. The corresponding data


direction register is TRISC. Setting a TRISC bit (=1) will make the corresponding
PORTC pin an input. Clearing a TRISC bit (=0) will make the corresponding
PORTC pin an output. When the I2C module is enabled, the PORTC (3:4) pins can
be configured with normal I2C levels or with SMBUS levels by using the CKE bit
(SSPSTAT <6>).

PORTD and TRISD Registers

PORTD is an 8-bit port with Schmitt Trigger input buffers. Each pin is
individually configurable as an input or output. PORTD can be configured as an 8-
bit wide microprocessor port (parallel slave port) by setting control bit PSPMODE
(TRISE<4>). In this mode, the input buffers are TTL.
PORTE and TRISE Register

PORTE has three pins, RE0/RD/AN5, RE1/WR/AN6 and RE2/CS/AN7,


which are individually configurable as inputs or outputs. These pins have Schmitt
Trigger input buffers. I/O PORTE becomes control inputs for the microprocessor
port when bit PSPMODE (TRISE<4>) is set. In this mode, the input buffers are
TTL. PORTE pins are multiplexed with analog inputs. When selected as an analog
input, these pins will read as ’0’s. TRISE controls the direction of the RE pins,
even when they are being used as analog inputs.

Data EEPROM and FLASH Program Memory

The Data EEPROM and FLASH Program Memory are readable and writable
during normal operation over the entire VDD range. The data memory is not
directly mapped in the register file space. Instead it is indirectly addressed through
the Special Function Registers (SFR). There are six SFRs used to read and write
the program and data EEPROM memory.

These registers are: EECON1, EECON2, EEDATA, EEDATH, EEADR and


EEADRH.

The EEPROM data memory allows byte read and writes. When interfacing
to the data memory block, EEDATA holds the 8-bit data for read/write and
EEADR holds the address of the EEPROM location being accessed. The registers
EEDATH and EEADRH are not used for data EEPROM access. These devices
have up to 256 bytes of data EEPROM with an address range from 0h to FFh.
Program memory access allows for checksum calculation and calibration
table storage. A byte or word write automatically erases the location and writes the
new data (erase before write). Writing to program memory will cease operation
until the write is complete. The program memory cannot be accessed during the
write, therefore code cannot execute. During the write operation, the oscillator
continues to clock the peripherals, and therefore they continue to operate When the
write completes, the next instruction in the pipeline is executed and the branch to
the interrupt vector address will occur

Program

#include <16F877A.h>

#device *=16

#device adc=10

#use delay(clock=10000000)

#fuses HS,NOLVP,NOWDT,PUT,NOPROTECT,BROWNOUT

#use rs232(baud=9600,parity=N,xmit=PIN_C6,rcv=PIN_C7,bits=8)

#byte PORTA = 5

#byte PORTB = 6

#byte PORTC = 7

#byte PORTD = 8
#byte PORTE = 9

// variables for LCD port

#bit RS_LCD = PORTE.2 //LCD register selector

#bit RW_LCD = PORTE.1 //LCD Read/Write selector

#bit EN_LCD = PORTE.0 //LCD display eneable

#bit BF_LCD = PORTD.7 //LCD busy flag

//// Variable for Latch Enable

int dsec = 0;

int disp= 0;

int disp_bk = 0;

//////modbus variable////////

unsigned char recv_data = 0;

unsigned int recv_pos = 0;

unsigned char mod_id = 'A';


unsigned char mod_cmd = 0;

//unsigned char temp;

int sim_mode = 0;

int16 HEARTBEAT = 0;

int16 PULSEFLAG = 0;

int16 TEMP = 0; //variable declaration

int16 SPEED = 0;

int16 VBRS1 = 0;

int16 VBRS2 = 0;

int16 VBRS3 = 0;

//int16 VIBS = 60;

int msg = 0;

signed int GSM_MODE = 0;


int16 flag = 0;

#bit gsm_f0 = flag.0

#bit gsm_f1 = flag.1

#bit gsm_f2 = flag.2

#bit gsm_f3 = flag.3

#bit gsm_f4 = flag.4

//int16 in_flag = 0;

//int16 spd_cnt = 0;

//int16 spd_stp = 0;

//int16 vbs_cnt = 0;

//int16 SEN_TIMER = 0;

////variables for output load


#bit RELAY1 = PORTB.0

#bit RELAY2 = PORTB.1

#bit RELAY3 = PORTB.2

#bit RELAY4 = PORTB.3

////////Four MENU KEY Function Routine //////////////

// variables for FOUR MENU KEY Input Pins //

#bit ENTER = PORTC.0

#bit DOWN = PORTC.1

#bit UP = PORTC.2

#bit MENU = PORTC.3

////////////////// LCD PROGRAM //////////////////////////////


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

/// LCD display busy flag routine


function////////////////////////////////////////////////////////////////////////////////////////////////////////

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

void lcdready(void)

EN_LCD=0; //display disable

SET_TRIS_D( 0xff ); //PORTB input setting

RS_LCD=0; //command registor selector

RW_LCD=1; //read operation

/*while(BF_LCD==1) //while lcd busy flag set

EN_LCD=0;

EN_LCD=1;

}*/

delay_us(500);

EN_LCD =0;
}

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

///////// LCD Command


Routine////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////

void command(unsigned char lcddata)

lcdready(); // to check lcd busy flag routine

SET_TRIS_D( 0x00 ); // PORTB output setting

PORTD=lcddata; // send data to PORTB

RS_LCD=0; // command registor selector

RW_LCD=0; // write operation

EN_LCD=1; // display enable

EN_LCD=0; // display disable

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

////// LCD Character Display


routine//////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////
void display(unsigned char lcddata)

lcdready(); //to check lcd busy flag routine

SET_TRIS_D(0x00 ); //PORTB output setting

PORTD=lcddata; //send data to PORTB

RS_LCD=1; //data registor selector

RW_LCD=0; //write operation

EN_LCD=1; //display enable

EN_LCD=0; //display disable

delay_ms(dsec);

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

///////////// lcdsetting routine////////////////////////////////////////////////

void lcdsetting(void)

command(0x38); // lcd 2 line ,5x7 matrix

command(0x0c); // display on,cursor on

command(0x06); // shift cursor right


command(0x01); // clear lcd

delay_ms(1);

//////////////////// LCD END PROGRAM ///////////////

///////GSM FUNCTION //////////////

unsigned char FMR_CELL[]="9080538331"; //SUBHETHA

void crlf(int sec)

putc(0x0d);

putc(0x0a);

while(sec > 0)

delay_ms(1000);

sec = sec - 1;

}
void GSM_MSG(int msg)

lcdsetting();

dsec = 30;

command(0x80); // force cursor to beginning of 1st line

printf(display,"MESSAGE...to ");

printf("AT+CMGF=1");

crlf(2);

printf("AT+CMGS=\"");

command(0xc0);

printf(display,"CELL:%s",FMR_CELL);

printf("%s",FMR_CELL);

printf("\"");

crlf(1);

printf("LPG LEAKAGE ALERT");

crlf(0);

if(msg == 1)

{
printf("LPG LEAKAGE IS ");

crlf(0);

printf(" IDENTIFIED ");

crlf(0);

printf("KINDLY CHECK IT");

crlf(0);

printf("**THANK YOU**");

crlf(0);

// crlf(0);

else

putc(0x1a);

delay_ms(1000);
command(0x80); // force cursor to beginning of 2st line

printf(display,"SENDING........");

delay_ms(1000);

lcdsetting();

////////ADC CHANNEL VALUE/////////////

#byte ADCON_0=0X1F

#byte ADCON_1=0X9F

#bit select =ADCON_0.2

int16 AI[8];

void adcvalue(int chn)

int i;

int16 avg_tot = 0;

SET_TRIS_A( 0xff );

setup_adc_ports(AN0_AN1_AN2_AN3_AN4);
setup_adc(ADC_CLOCK_INTERNAL);

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

avg_tot = 0;

set_adc_channel(i);

select = 1;

read_adc(ADC_START_ONLY);

while(select == 1)

delay_us(1);

avg_tot = avg_tot + read_adc(ADC_READ_ONLY);

set_adc_channel(i);

select = 1;

read_adc(ADC_START_ONLY);

while(select==1)
{

delay_us(1);

avg_tot = avg_tot + read_adc(ADC_READ_ONLY);

set_adc_channel(i);

select = 1;

read_adc(ADC_START_ONLY);

while(select==1)

delay_us(1000);

avg_tot = avg_tot + read_adc(ADC_READ_ONLY);

set_adc_channel(i);

select = 1;

read_adc(ADC_START_ONLY);

while(select==1)

{
}

delay_us(1000);

avg_tot = avg_tot + read_adc(ADC_READ_ONLY);

AI[i] = avg_tot / 4 ;

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

void readAIstatus (void)

adcvalue(3); // how many channels to be used

VBRS1 = AI[0];

VBRS2 = AI[1];

VBRS3 = AI[2];
// SPEED = (int16)((float)AI[2]*0.14718);

if(VBRS1 > 300)

RELAY1 = 0;

RELAY2 = 0;

RELAY4 = 0;

GSM_MSG(1);

delay_ms(1000);

RELAY4 = 1;

else

RELAY1 = 1;

RELAY2 = 1;

RELAY4 = 1;

}
}

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

void putInt16(int16 REG1)

void TITLE (void)

lcdsetting();

dsec = 10;

command(0x80); // force cursor to beginning of 1st line

printf(display," AUTOMATIC LPG ");

command(0xc0); // force cursor to beginning of 2st line


printf(display," GAS LEAKAGE ");

delay_ms(2000);

lcdsetting();

dsec = 10;

command(0x80); // force cursor to beginning of 1st line

printf(display,"DETECTION SYSTEM");

//command(0xc0); // force cursor to beginning of 2st line

// printf(display," COMMUNICATION ");

delay_ms(2000);

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

void main(void)

SET_TRIS_A( 0xff ); //PORTA input/output setting

SET_TRIS_B( 0x00 ); //PORTB input/output setting

SET_TRIS_D( 0x00 ); //PORTD output setting

SET_TRIS_C( 0x0f ); //PORTC output setting


SET_TRIS_E( 0x00 );

sim_mode = 0;

setup_adc_ports(AN0_AN1_AN2_AN3_AN4);

setup_adc(ADC_CLOCK_INTERNAL);

setup_psp(PSP_DISABLED); /// for RS 232 serial port setting

setup_spi(FALSE);

setup_timer_0(RTCC_INTERNAL|RTCC_DIV_32);

setup_timer_1(T1_DISABLED);

setup_timer_2(T2_DISABLED,0,1);

setup_comparator(NC_NC_NC_NC);

setup_vref(FALSE);

enable_interrupts(INT_RTCC);

enable_interrupts(INT_RDA);

enable_interrupts(GLOBAL);

port_b_pullups(TRUE);

RELAY3 = 0;

RELAY4 = 0;

TITLE ();
lcdsetting();

dsec = 0;

for(;;)

RELAY1 = 1;

RELAY2 = 1;

// lcdsetting();

dsec = 10;

command(0x80); // force cursor to beginning of 1st line

printf(display," LPG DETECTION ");

command(0xc0); // force cursor to beginning of 2st line

printf(display," LPG : %04ld ",VBRS1);

delay_ms(100);

readAIstatus ();

}
INTRODUCTION TO GSM WIRELESS MODEMS

4. GSM Modem:

A GSM modem is a wireless modem that works with a GSM wireless network. A
wireless modem behaves like a dial-up modem. The main difference between them
is that a dial-up modem sends and receives data through a fixed telephone line
while a wireless modem sends and receives data through radio waves.

A GSM modem can be an external device or a PC Card / PCMCIA Card.


Typically, an external GSM modem is connected to a computer through a serial
cable or a USB cable. A GSM modem in the form of a PC Card / PCMCIA Card is
designed for use with a laptop computer. It should be inserted into one of the PC
Card / PCMCIA Card slots of a laptop computer.

Like a GSM mobile phone, a GSM modem requires a SIM card from a wireless
carrier in order to operate.

As mentioned in earlier sections of this SMS tutorial, computers use AT


commands to control modems. Both GSM modems and dial-up modems support a
common set of standard AT commands. You can use a GSM modem just like a
dial-up modem.

In addition to the standard AT commands, GSM modems support an extended set


of AT commands. These extended AT commands are defined in the GSM
standards. With the extended AT commands, you can do things like:

 Reading, writing and deleting SMS messages.


 Sending SMS messages.
 Monitoring the signal strength.
 Monitoring the charging status and charge level of the battery.
 Reading, writing and searching phone book entries.

The number of SMS messages that can be processed by a GSM modem per minute
is very low -- only about six to ten SMS messages per minute.

4.1 GSM / GPRS Modem for GSM 900 / GSM 1800 / GSM 1900
Fig 4.1 SIMCOM GSM Based Modem

SIMCOM GSM based Modem with most of the functions taken care on
board is shown on the above figure.This GSM modem is a highly flexible plug and
play GSM 900 / GSM 1800 / GSM 1900 modem for direct and easy integration
RS232, voltage range for the power supply and audio interface make this device
perfect solution for system integrators and single user. Voice, Data/Fax,
SMS,GPRS, integrated TCP/IP stack,RTC and other features like the GSM /
GPRS.

4.2 GSM MODEM CHARACTERISTICS :

 Triband GSM GPRS modem (EGSM 900/1800 / 1900 MHz )


 Designed for GPRS, data, fax, SMS and voice applications
 GPRS multi-slot class 10
 GPRS mobile station class B
 Designed for GPRS, data, fax, SMS and voice applications
 Fully compliant with GSM Phase 2/2+ specifications
 Built-in TCP/IP Protocol
 Built-in RTC in the module.
 AT Command based

4.3 SPECIFICATIONS FOR DATA :


 GPRS class 10: max 85.6 kbps (downlink)
 PBCCH Support
 Coding schemes CS 1,2,3,4
 CDS up to 14.4 kbps
 USSD
 Non transparent mode
 PPP - stack

4.3.1 SPECIFICATIONS FOR FAX :

 Group 3, Class 1

4.3.2 SPECIFICATIONS FOR SMS via GSM & GPRS :

 Point-to-point MO & MT
 SMS cell Broadcast
 Text & PDU mode

4.3.3 SPECIFICATIONS FOR VOICE :

 Tricodec
 Half rate (HR)
 Full rate (FR)
 Enhanced Full rate (EFR)
 Noise reduction

4.4 POWER SUPPLY :

Use AC DC Power Adaptor with following ratings

 Input AC Voltage : 230V


 Output DC Voltage : 12V
 Output DC Current : 2A
 Polarity : Centre +ve & Outside ve

4.5 GENERAL CHARACTERISTICS :


 Input voltage : 9V-12V
 Input current : 3mA in idle mode (only module)
 Temperature range : Operating -20 to +55 degree Celsius; Storage -40 to
+80 degree Celsius

4.6 INTERFACES :

 RS-232 through D-TYPE 9 pin connector


 Serial port baud rate 1200 to 115200 bps
 RJ11 voice connector
 Power supply through DC jacket
 SMA antenna connector
 Toggle spring/Flap Opening type SIM holder
 LED status of GSM / GPRS module
2.5. GAS SENSOR

Sensitive material of MQ-2 gas sensor is SnO2, which with lower conductivity in
clean air. When the target combustible gas exist, The sensor’s conductivity is more
higher along with the gas concentration rising. Please use simple electro circuit,
Convert change of conductivity to
correspond output signal of gas concentration.

The MQ-6 module is used in gas leakage detecting equipment in family and
industry, This module has high sensitivity to LPG, iso-butane, propane and LNG.
It can also be used to detect the presence of alcohol, cooking fumes, and cigarette
smoke.The module gives out the concentration of the gases as a analog voltage
equivalent to the concentration of the gases. The module also has an onboard
comparator for comparing against an adjustable preset value and giving out a
digital high or low. It can be easily interfaced with your Arduino or Raspberry
Pi.This is a simple-to-use MQ-6 Liquefied Petroleum, iso-butane, propane gas
Sensor module, suitable for sensing LPG (composed of mostly propane and
butane) concentrations in the air.
The MQ-6 can detect gas concentrations anywhere from 200 to
10000ppm.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.

Sensitive material of MQ-6 gas sensor is SnO2, which with lower conductivity in
clean air. When the target combustible gas exist, The sensor’s conductivity is more
higher along with the gas concentration rising. Please use simple electrocircuit,
Convert change of conductivity to correspond output signal of gas
concentration.MQ-6 gas sensor has high sensitity to Propane, Butane and LPG,
also response to Natural gas. The sensor could be used to detect different
combustible gas, especially Methane, it is with low cost and suitable for different
application.

FEATURES

 Voltage: 5V
 Detecting concentration :
 200-10000 ppm LPG
 iso-butane
 propane
 LNG
 Analog and Digital Output
 Digital Out is High or Low based on a adjustable preset threshold.
APPLICATIONS

 Domestic gas leakage detector


 Industrial Combustible gas detector
 Portable gas detector

Working
When the target combustible gas exist, The sensor’s conductivity is morehigher
along with the gas concentration rising. Please use simple electrocircuit,Convert
change of conductivity to correspond output signal of gas concentration.MQ-2 gas
sensor has high sensitivity to LPG, Propane and Hydrogen, also couldbe used to
Methane and other combustible steam, it is with low cost and suitablefor different
application. In order to make the sensor with better performance,suitable RL value
is needed:Power of Sensitivity body(Ps):Ps=Vc2×Rs/(Rs+RL)2

BUZZER

A buzzer or beeper is a signaling device, usually electronic, typically used in


automobiles, household appliances such as a microwave oven, or game shows.

It most commonly consists of a number of switches or sensors connected to


a control unit that determines if and which button was pushed or a preset time has
lapsed, and usually illuminates a light on the appropriate button or control panel,
and sounds a warning in the form of a continuous or intermittent buzzing or
beeping sound. Initially this device was based on an electromechanical system
which was identical to an electric bell without the metal gong (which makes the
ringing noise).
Often these units were anchored to a wall or ceiling and used the ceiling or
wall as a sounding board. Another implementation with some AC-connected
devices was to implement a circuit to make the AC current into a noise loud
enough to drive a loudspeaker and hook this circuit up to a cheap 8-ohm speaker.
Nowadays, it is more popular to use a ceramic-based piezoelectric sounder like a
Sonalert which makes a high-pitched tone. Usually these were hooked up to
"driver" circuits which varied the pitch of the sound or pulsed the sound on and off.

In game shows it is also known as a "lockout system," because when one


person signals ("buzzes in"), all others are locked out from signalling. Several
game shows have large buzzer buttons which are identified as "plungers".The word
"buzzer" comes from the rasping noise that buzzers made when they were
electromechanical devices, operated from stepped-down AC line voltage at 50 or
60 cycles. Other sounds commonly used to indicate that a button has been pressed
are a ring or a beep.
Specifications:

Operating frequency : 3.1 ± 0.5 KHz

Operating voltage : 3 ~ 20 V dc

Current consumption : 14 mA

Sound pressure level : 73 db

Rated voltage : 12 V dc

Tone : continuous

Operating temperature : -30 ~ +85° C

Storage temperature : -40 ~ +95° C

Dimensions : Ø23.8 x 14.5 mm

Material : ABS UL-94 1/16” high heat (black)

Weight : 4.5 g
SOFTWARE DETAILS
Introduction of MPLAB
The MPLAB X IDE is the new graphical, integrated debugging tool set for
all of Microchip’s more than 800 8-bit, 16-bit and 32-bit MCUs and digital signal
controllers, and memory devices.

It includes a feature-rich editor, source-level debugger, project manager, software


simulator, and supports Microchip’s popular hardware tools, such as the MPLAB
ICD 3 in-circuit debugger, PICkit™ 3, and MPLAB PM3 programmer.
MPLAB IDE is a Windows Operating System (OS) software program that runs on
a PC to develop applications for Microchip microcontrollers and digital signal
controllers. It is called an Integrated Development Environment, or IDE, because it
provides a single integrated "environment" to develop code for embedded
microcontrollers. Experienced embedded systems designers may want to skip
ahead to Components of MPLAB IDE.
The Object-HEX Converter creates Intel HEX files from absolute object modules.

Development Tools

The Mplab development tools for PIC offer numerous features and
advantages that help you quickly and successfully develop embedded applications.
They are easy to use and are guaranteed to help you achieve your design goals.
The MPLAB IDE and Debugger is the central part of the Microchip PIC
development tools. MPLAB offers a Build Mode and a Debug Mode.
In the MPLAB Build Mode you maintain the project files and generate the
application. MPLAB uses either the Hi-Tech or PIC ASM development tools. In
the MPLAB Debug Mode you verify your program either with a powerful CPU
and peripheral simulator that connects the debugger to the target system. The ICD2
allows you also to download your application into Flash ROM of your target
system.

Getting Started

The MPLAB IDE combines project management, make facilities, source code
editing, program debugging, and complete simulation in one powerful
environment. The MPLAB development platform is easy-to-use and helping you
quickly create embedded programs that work. The MPLAB editor and debugger
are integrated in a single application that provides a seamless embedded project
development environment. Use MPLAB to create your source files and organize
them into a project that defines your target application. MPLAB automatically
compiles, assembles, and links your embedded application and provides a single
focal point for your development efforts. When you use the MPLAB, the project
development cycle is roughly the same as it is for any other software development
project.
☞Create a project, select the target chip from the device database, and
configure the tool settings.

☞Create source files in C or assembly.

☞Build your application with the project manager.

☞Correct errors in source files.

☞Test the linked application.

☞Debug the executable logic by watching program flow with the built-in
simulator or in real time with in-circuit emulators or in-circuit debuggers.
☞Make timing measurements with the simulator or emulator.

☞View variables in Watch windows.

☞Program firmware into devices with device programmers.

Create a Project

MPLAB includes a project manager which makes it easy to design applications


for a PIC based microcontroller. You need to perform the following steps to create
a new project:
☞Start MPLAB and select the toolset

☞Create a project file and select a CPU from the device database.

☞Create a new source file and add this source file to the project.

☞Add and configure the startup code for the PIC.

☞Set tool options for target hardware.

☞Build project and create a HEX file for Flash programming.

Start MPLAB

MPLAB is a standard Windows application and started by clicking on the


program icon.
Testing Code with the Simulator

In order to test the code, software or hardware is needed that will execute the
PIC micro instructions. A debug execution tool is a hardware or software tool that
is used to inspect code as it executes a program (in this case led_delay.c).
Hardware tools such as MPLAB ICE or MPLAB ICD 2 can execute code in real
devices. If hardware is not available, the MPLAB simulator can be used to test the
code. In this tutorial we can use MPLAB SIM simulator.
The simulator is a software program that runs on the PC to simulate the
instructions of the PIC micro MCU.

It does not run in “real time,” since the simulator program is dependent upon the
speed of the PC, the complexity of the code, overhead from the operating system
and how many other tasks are running. However, the simulator accurately
measures the time it would take to execute the code if it were operating in real time
in an application.

Note: Other debug execution tools include MPLAB ICE 2000, MPLAB ICE
4000 and MPLAB ICD 2. These are optional hardware tools to test code on the
application PC board. Most of the MPLAB IDE debugging operations are the same
as the simulator, but unlike the simulator, these tools allow the target PIC micro
MCU to run at full speed in the actual target application.
Additional menu items should now appear in the Debugger menu. Additional
toolbar icons should appear in the Debug Tool Bar.

Getting Started with MPLAB SIM

MPLAB SIM is one of the debug engines that can be used with MPLAB.
The other debug engines are hardware devices, while MPLAB SIM is a software
program that runs on your PC. MPLAB SIM provides many of the same features as
in-circuit emulators and in-circuit debuggers. The difference is that both in-circuit
emulators and in-circuit debuggers allow the code to be run on actual silicon, and
also allow target application hardware to be functional while being debugged.
MPLAB SIM has features to simulate hardware interaction with other
signals and devices, and since it is running as software on the PC.
It has complete information about the internal state of the simulated chip at
each instruction. This is a little different from the hardware debuggers because,
while they are running code at full speed, they typically cannot monitor all
registers and all memory in real time.
Both MPLAB SIM and the hardware debuggers can do the traditional functions of
debuggers, but due to their differences, they can have unique features of their own.
This presentation will identify the functions and features of MPLAB SIM.
The debugger is a part of MPLAB IDE, and whether you are using MPLAB SIM,
MPLAB ICE or MPLAB ICD 2, most operations are exactly the same. This allows
you to develop code using the simulator, and then when your hardware is ready,
you can use a hardware debugger to further test your code in practice without
having to learn how to use a new tool.

These are the basic debug functions:


Reset the target, in order to restart the application.

☞Execute the code so the program can be tested to verify it functions as


designed.
☞Halt the code at breakpoints
☞While halted at breakpoints examine and modify memory and variables to
analyze and debug the application code.

☞Single Step through code to closely inspect how it executes. This allows the
engineer to go through code one instruction (or one C statement) at a time while
monitoring affected variables, registers and flags. Single stepping essentially
“zooms in” on code to ensure that it operates correctly in complex and critical
sections with ranges of variable values and under various test conditions.
Most debuggers also have additional features to help analyze and debug the
application.

Some of these are listed here:

☞Watch points group and monitor selected variables and memory locations
into a convenient, custom readout.

☞Trace buffers capture the streams of instructions executed and reveal the
contents of changing register values.

☞A Stopwatch can time a section of code. Routines can be optimized, and


critical code timing can be accurately measured and adjusted.

☞Complex breakpoints offer a method for establishing breakpoints or for


gathering data in the trace buffer based upon multiple conditions. Simple
breakpoints allow setting breakpoints in the source code or anywhere in program
memory. Complex breakpoints allow getting a breakpoint on a condition such
as, – After the main routine called “Refresh Display” executes then – wait for
subroutine “Read Temp” to execute. Then – break if the variable named
“Temperature” is greater than 20.

Complex events can be constructed to count events, so that a subroutine would


have to be executed, for example, 15 times before it starts looking for a value on a
pin or in a register. This kind of breakpoint allows you to describe the condition
where your code misbehaves, to halt at a breakpoint or to trace code when that
condition occurs. This is usually a faster way of finding bugs than simply setting
simple breakpoints and stepping through your code.

MPLAB SIM is a simulator, and as a result it has certain characteristics that make
it a unique debug engine. So the speed of the simulation is determined by,
☞How fast your PC executes,

☞The complexity of the current simulation, and

☞The number of other tasks executing on your PC.

Currently the maximum speed of MPLAB SIM is on the order of 10 MIPS, or 10


million instructions per second. This will be affected by how many other things are
being done by your PC, by the code the simulator is running, and by the other tasks
that the simulator is performing. The simulator simulates the operation of,
☞The core CPU and its internal registers,

☞Memory, and

In order to test the application on the simulator, stimulus signals can be applied to
pins and registers.

To evaluate performance, the simulator can log changing registers to files for
further analysis.

Starting Up MPLAB SIM

Select the simulator as the debug execution tool. This is done from the
Debugger>Select Tool pull down menu.

MPLAB SIM is selected as the debug engine from the Debugger menu. Note the
other functions on the debug menu, such as Run, Step, and Breakpoints.
Once a debug engine is selected, the toolbar is appended with some new icons for
running, halting, single stepping, and resetting the target.
The Status bar now shows some additional information.

☞MPLAB SIM shows as the current debug engine.

☞The simulated processor is listed, in this case the PIC16F877A,

☞Then the program counters,

☞The W register,

☞The current state of the internal CPU flags and

☞The current selected file register bank.

The toolbar icons, the menus, or the hot keys listed on the menus can be used to
execute the debug functions. Note that some are a little more complex, such as
Reset, which actually has four types of reset actions.

Once MPLAB SIM is established as the debug engine, whenever a project is built,
it is automatically loaded into the simulator’s program memory to be run and
tested.
One debug window is the source code window. This is actually the editor window,
and breakpoints can be set by clicking on a line with the right mouse button. Single
stepping with the source code window in focus will single step through the C
source lines. Since you are in the editor, changes can be done quickly, and the
project can be rebuilt.
ADVANTAGE:

Low cost
More effective
It is a safety process.
Automatically monitoring

APPLICATION:

Home based application


Human safety
Real time application

Vous aimerez peut-être aussi