Vous êtes sur la page 1sur 64

CHAPTER 1

INTRODUCTION TO EMBEDDED SYSTEMS

Embedded system
An Embedded System is a combination of computer hardware and software, and perhaps
additional mechanical or other parts, designed to perform a specific function. An embedded
system is a microcontroller-based, software driven, reliable, real-time control system,
autonomous, or human or network interactive, operating on diverse physical variables and in
diverse environments and sold into a competitive and cost conscious market.
An embedded system is not a computer system that is used primarily for processing, not a
software system on PC or UNIX, not a traditional business or scientific application. High-end
embedded & lower end embedded systems. High-end embedded system - Generally 32, 64 Bit
Controllers used with OS. Examples Personal Digital Assistant and Mobile phones etc .Lower
end embedded systems - Generally 8,16 Bit Controllers used with an minimal operating systems
and hardware layout designed for the specific purpose. Examples Small controllers and devices
in our everyday life like Washing Machine, Microwave Ovens, where they are embedded in.

System design calls:

Figure 2(a) Embedded System design calls


1
Embedded system design cycle:

Figure. 2(b) V Diagram

Characteristics of Embedded System


An embedded system is any computer system hidden inside a product other than a
computer.
They will encounter a number of difficulties when writing embedded system software in
addition to those we encounter when we write applications
Throughput Our system may need to handle a lot of data in a short period of
time.
ResponseOur system may need to react to events quickly
TestabilitySetting up equipment to test embedded software can be difficult
DebugabilityWithout a screen or a keyboard, finding out what the software is
doing wrong (other than not working) is a troublesome problem
Reliability embedded systems must be able to handle any situation without
human intervention
Memory space Memory is limited on embedded systems, and you must make
the software and the data fit into whatever memory exists
Program installation you will need special tools to get your software into
embedded systems
Power consumption Portable systems must run on battery power, and the
software in these systems must conserve power
Processor hogs computing that requires large amounts of CPU time can
complicate the response problem
Cost Reducing the cost of the hardware is a concern in many embedded system
projects; software often operates on hardware that is barely adequate for the job.
2
Embedded systems have a microprocessor/ microcontroller and a memory. Some have a
serial port or a network connection. They usually do not have keyboards, screens or disk
drives.

Applications
1) Military and aerospace embedded software applications
2) C om m u ni c at i o n Ap p l i c at i on s
3) In d us t ri al aut om at i o n and p ro c es s co nt r ol s o ft w a r e
4) Mastering the complexity of applications.
5) Reduction of product design time.
6) Real time processing of ever increasing amounts of data.
7) Intelligent, autonomous sensors.

Classification
Real Time Systems.
RTS is one which has to respond to events within a specified deadline.
A right answer after the dead line is a wrong answer

RTS Classification
Hard Real Time Systems
Soft Real Time System

Hard Real Time System


"Hard" real-time systems have very narrow response time.
Example: Nuclear power system, Cardiac pacemaker.

Soft Real Time System


"Soft" real-time systems have reduced constrains on "lateness" but still must operate very
quickly and repeatable.
Example: Railway reservation system takes a few extra seconds the data remains valid.

3
CHAPTER 2
LITERATURE SURVEY

2.1 HISTORY
One serious road accident in the country occurs every minute and 16 die on Indian roads every
hour. 1214 road crashes occur every day in India. Two wheelers account for 25% of total road
crash deaths. 20 children under the age of 14 die every day due to road crashes in in the country.
377 people die every day, equivalent to a jumbo jet crashing every day. Two people die every
hour in Uttar Pradesh State with maximum number of road crash deaths. Tamil Nadu is the
state with the maximum number of road crash injuries.
Top 10 Cities with the highest number of Road Crash Deaths (Rank Wise).

1. Delhi (City)
2. Chennai
3. Jaipur
4. Bengaluru
5. Mumbai
6. Kanpur
7. Lucknow
8. Agra
9. Hyderabad
10. Pune

Source of Information: National Crime Records Bureau, Ministry of Road Transport & Highway,
Law commission of India, Global status report on road safety 2013
Approximately, 38% accidents are caused due to drunk and driving.

Alcohol detection system, till now was manufactured using AVR AT328 and 8051
(89c51 and 89s51) Microcontrollers.
This is larger in size and the time consumption is more.
It is very much difficult to implement the circuitry in the car due to the circuit size and
also the cost of the mass production is relatively high as compared to our system.
The accuracy is also less. Chances of failure are more in the existing system.

4
OUR PROTOTYPE:
Using an advance technology Raspberry Pi 3, Model B.
Interfacing of GSM Technology.
The size is tightly constrained.
In future, we are interfacing Camera to capture the motion object and also GPS/GPRS
technology to trace the location.

2.2 COMPARISON

Parameter Our Prototype Existing system

Yes, we can expand as the


Future compatibility No.
technology grows

Circuit complexity Simple Difficult

Maintenance Simple Difficult

Trouble shooting Easy Difficult

Cost Expensive Inexpensive

5
CHAPTER 3
PROBLEM DEFINITION

This system is one of the emerging technologies that can be used to curb the accidents related
to drunk and driving. The existing systems in the market include Breathalyzer and Smart helmet
which is not sufficient to curb the tragic reality. Hence, we introduce to you our system
automated drunk and driving system with SMS Alert [ADDA].
If any person other than the driver has consumed alcohol and if the sensor detects it, then also
the circuit won't allow the driver to start the vehicle. The sensor is sensitive, so care should be
taken while placing the sensor. If you place the raspberry Pi in a place where there is excess of
heat, the component characteristics might change. So we need to take care of that. We are
making a model of our idea. Hence, the range is limited. Every sensor is designed to work over a
specific range. The design ranges are usually fixed. We are using a basic sensor for the model
i.e. MQ-3. If the range is increased or exceeded, it will result in permanent damage of the sensor.
It is customary to use transducing elements over only the part of their range where they provide
predictable performance and often enhanced linearity. Industry level sensors with higher range
are available when implemented practically.
In practical implementation, we will directly connect the system to the ABS of the car. We
believe our system will curb the tragic reality and make a positive impact in the world. Let us
now understand the system in detail.

6
CHAPTER 4
SYSTEM REQUIREMENT AND ANALYSIS

4.1 HARDWARE REQUIREMENTS:


This system provides a unique method to curb drunken people. The system has an alcohol sensor
embedded on the steering of the car. Whenever the driver starts ignition, the sensor measures the
content of the alcohol in his breath and automatically switches off the car if he is drunken. In this
system the sensor delivers a current with a linear relationship to the alcohol molecules from zero
to very high concentration. The output of the sensor is fed to the Raspberry Pi 3 for comparison.
If the measured value reaches the threshold, relay cut off automatically and the buzzer generates
sound. Once the buzzer produces sound the system communicates with configured telecom
device unique number using the GSM Module.

Raspberry Pi: It is a mini computer that performs like a general purpose computer for daily
usage and various technology enhancement devices.

Alcohol Sensor: This is the basic gas sensor (MQ-3) that detects smoke or gas within a short
range.

DC Motor: This is basic model of DC motor with 500 Rotations per minute (RPM) used in place
of car engine in our prototype

Buzzer: This works like an indicator in our project.

LEDs: This indicates that limit is crossed or below the limit.

LCD Display: Displays information whether the limit is over or below. Also displays calling
information.

Resistors: This is current limiting device that basically implements resistance and limits the
current flow.

Capacitors: This is a component that stores charges and discharges as per need. This works as
low pass filters and high pass filters in our project.

Diodes: This is a component that basically rectifies the signal (AC to DC )

GSM MODULE (SIM900): This is a quad band modem that supports 850-900-1800-1900 MHz
frequency band. This is used as a messaging operated device in our project.

7
4.2 HARDWARE SPECIFICATIONS:

RASPBERRY PI:

The Raspberry Pi 3 is the third generation Raspberry Pi. It replaced the Raspberry Pi 2 Model B in
February 2016. Compared to the Raspberry Pi 2 it has:

A 1.2GHz 64-bit quad-core ARMv8 CPU


802.11n Wireless LAN
Bluetooth 4.1
Bluetooth Low Energy (BLE)
Like the Pi 2, it also has:
1GB RAM
4 USB ports
40 GPIO pins
Full HDMI port
Ethernet port
Combined 3.5mm audio jack and composite video
Camera interface (CSI)
Display interface (DSI)
Micro SD card slot (now push-pull rather than push-push)
Video Core IV 3D graphics core

The Raspberry Pi 3 has an identical form factor to the previous Pi 2 (and Pi 1 Model B+) and has
complete compatibility with Raspberry Pi 1 and 2.

We recommend the Raspberry Pi 3 Model B for use in schools, or for any general use. Those wishing to
embed their Pi in a project may prefer the Pi Zero or Model A+, which are more useful for embedded
projects, and projects which require very low power.

8
ALCOHOL SENSOR:

This alcohol sensor is suitable for detecting alcohol concentration on your breath, just like your
common Breathalyzer. It has a high sensitivity and fast response time. Sensor provides an analog
resistive output based on alcohol concentration. The drive circuit is very simple, all it needs is
one resistor. A simple interface could be a 0-3.3V ADC.

Features:

5V DC or AC circuit
Requires heater voltage
Operation Temperature: -10 to 70 degrees C
Heater consumption: less than 750mW

Dimensions:

16.8mm diameter
9.3 mm height without the pins

Sensitive material of MQ-3 gas sensor is SnO2, which with lower conductivity in clean air.
When the target alcohol gas exist, the sensors conductivity is higher along with the gas
concentration rising. Using simple electro circuit, Convert change of conductivity to correspond
output signal of gas concentration. MQ-3 gas sensor has high sensitivity to Alcohol, and has
good resistance to disturb of gasoline, smoke and vapour. The sensor could be used to detect
alcohol with different concentration, it is with low cost and suitable for different application.
Character Configuration

* Good sensitivity to alcohol gas

* Long life and low cost

* Simple drive circuit Application

* Vehicle alcohol detector

* Portable alcohol detector


9
DC MOTOR:

A DC motor is an electric motor that runs on direct current (DC) electricity. In any
electric motor, operation is based on simple electromagnetism. A current-carrying conductor
generates a magnetic field; when this is then placed in an external magnetic field, it will
experience a force proportional to the current in the conductor, and to the strength of the external
magnetic field. As you are well aware of from playing with magnets as a kid, opposite (North
and South) polarities attract, while like polarities (North and North, South and South) repel. The
internal configuration of a DC motor is designed to harness the magnetic interaction between a
current-carrying conductor and an external magnetic field to generate rotational motion.
Let's start by looking at a simple 2-pole DC electric motor (here red represents a magnet
or winding with a "North" polarization, while green represents a magnet or winding with a
"South" polarization).

Fig.4.8(c) DC motor

Every DC motor has six basic parts -- axle, rotor (a.k.a., armature), stator, commutator,
field magnet(s), and brushes. In most common DC motors, the external magnetic field is
produced by high-strength permanent magnets1. The stator is the stationary part of the motor --
this includes the motor casing, as well as two or more permanent magnet pole pieces. The rotor
rotates with respect to the stator. The rotor consists of windings (generally on a core), the
windings being electrically connected to the commutator. The above diagram shows a common
motor layout -- with the rotor inside the stator (field) magnets.
The geometry of the brushes, commutator contacts, and rotor windings are such that
when power is applied, the polarities of the energized winding and the stator magnet(s) are
misaligned, and the rotor will rotate until it is almost aligned with the stator's field magnets. As
the rotor reaches alignment, the brushes move to the next commutator contacts, and energize the
next winding. Given our example two-pole motor, the rotation reverses the direction of current
through the rotor winding, leading to a "flip" of the rotor's magnetic field, driving it to continue
rotating.

10
In real life, though, DC motors will always have more than two poles (three is a very
common number). In particular, this avoids "dead spots" in the commutator. You can imagine
how with our example two-pole motor, if the rotor is exactly at the middle of its rotation
(perfectly aligned with the field magnets), it will get "stuck" there. Meanwhile, with a two-pole
motor, there is a moment where the commutator shorts out the power supply (i.e., both brushes
touch both commutator contacts simultaneously). This would be bad for the power supply, waste
energy, and damage motor components as well. Yet another disadvantage of such a simple motor
is that it would exhibit a high amount of torque "ripple".
So since most small DC motors are of a three-pole design, let's tinker with the workings of one
via an interactive animation (JavaScript required):

You'll notice a few things from this -- namely, one pole is fully energized at a time (but
two others are "partially" energized). As each brush transitions from one commutator contact to
the next, one coil's field will rapidly collapse, as the next coil's field will rapidly charge up (this
occurs within a few microsecond). We'll see more about the effects of this later, but in the
meantime you can see that this is a direct result of the coil windings' series wiring.

BUZZER:
A buzzer or beeper is an audio signaling device which may be mechanical, electromechanical,
or piezoelectric. Typical uses of buzzers and beepers include alarm devices, timers, and
confirmation of user input such as a mouse click or keystroke.

Electromechanical
The electric buzzer was invented in 1831 by Joseph Henry. They were mainly used in early
doorbells until they were phased out in the early 1930s in favor of musical chimes, which had a
softer tone.

Piezoelectric
Piezoelectric buzzers, or piezo buzzers, as they are sometimes called, were invented by Japanese
manufacturers and fitted into a wide array of products during the 1970s to 1980s. This
advancement mainly came about because of cooperative efforts by Japanese manufacturing
11
companies. In 1951, they established the Barium Titanate Application Research Committee,
which allowed the companies to be "competitively cooperative" and bring about several
piezoelectric innovations and inventions.

Type of buzzers
Electromechanical
Early devices were based on an electromechanical system identical to an electric bell without the
metal gong. Similarly, a relay may be connected to interrupt its own actuating current, causing
the contacts to buzz. Often these units were anchored to a wall or ceiling to use it as a sounding
board. The word "buzzer" comes from the rasping noise that electromechanical buzzers made.

Mechanical
A joy buzzer is an example of a purely mechanical buzzer. They require drivers.

Piezoelectric

Piezoelectric disk beeper


A piezoelectric element may be driven by an oscillating electronic circuit or other audio
signal source, driven with a piezoelectric audio amplifier. Sounds commonly used to indicate
that a button has been pressed are a click, a ring or a beep.

Interior of a readymade buzzer, showing a piezoelectric-disk-beeper (With 3 electrodes ...


including 1 feedback-electrode (the central, small electrode joined with red wire in this photo),
and an oscillator to self-drive the buzzer.

12
Modern applications:
While technological advancements have caused buzzers to be impractical and undesirable, there
are still instances in which buzzers and similar circuits may be used. Present day applications
include:

Novelty uses
Judging panels
Educational purposes
Annunciator panels
Electronic metronomes
Game show lock-out device
Microwave ovens and other household appliances
Sporting events such as basketball games
Electrical alarms
Joy buzzer (mechanical buzzer used for pranks)

LED:
Light Emitting Diodes (LED) have recently become available that are white and bright,
so bright that they seriously compete with incandescent lamps in lighting applications. They are
still pretty expensive as compared to a GOW lamp but draw much less current and project a
fairly well focused beam. The diode in the photo came with a neat little reflector that tends to
sharpen the beam a little but doesn't seem to add much to the overall intensity.

When run within their ratings, they are more reliable than lamps as well. Red LEDs are now
being used in automotive and truck tail lights and in red traffic signal lights. You will be able to
detect them because they look like an array of point sources and they go on and off instantly as
compared to conventional incandescent lamps.

13
LEDs are monochromatic (one color) devices. The color is determined by the band gap of the
semiconductor used to make them. Red, green, yellow and blue LEDs are fairly common. White
light contains all colors and cannot be directly created by a single LED. The most common form
of "white" LED really isn't white. It is a Gallium Nitride blue LED coated with a phosphor that,
when excited by the blue LED light, emits a broad range spectrum that in addition to the blue
emission, makes a fairly white light.

There is a claim that these white LED's have a limited life. After 1000 hours or so of operation,
they tend to yellow and dim to some extent. Running the LEDs at more than their rated current
will certainly accelerate this process.

There are two primary ways of producing high intensity white-light using LEDS. One is to use
individual LEDS that emit three primary coloursred, green, and blueand then mix all the
colours to form white light. The other is to use a phosphor material to convert monochromatic
light from a blue or UV LED to broad-spectrum white light, much in the same way a fluorescent
light bulb works. Due to metamerism, it is possible to have quite different spectra that appear
white.

LEDs are semiconductor devices. Like transistors, and other diodes, LEDs are made out of
silicon. What makes an LED give off light are the small amounts of chemical impurities that are
added to the silicon, such as gallium, arsenide, indium, and nitride.

When current passes through the LED, it emits photons as a byproduct. Normal light bulbs
produce light by heating a metal filament until it is white hot. LEDs produce photons directly
and not via heat, they are far more efficient than incandescent bulbs.

Not long ago LEDs were only bright enough to be used as indicators on dashboards or electronic
equipment. But recent advances have made LEDs bright enough to rival traditional lighting
technologies. Modern LEDs can replace incandescent bulbs in almost any application.

LCD DISPLAY:
Liquid crystal display (LCD) has material which combines the properties of both liquid
and crystals. They have a temperature range within which the molecules are almost as mobile as
they would be in a liquid, but are grouped together in an order form similar to a crystal.

More microcontroller devices are using 'smart LCD' displays to output visual information. The
following discussion covers the connection of a Hitachi LCD display to a PIC microcontroller.
LCD displays designed around Hitachi's LCD HD44780 module, are inexpensive, easy to use,
and it is even possible to produce a readout using the 8 x 80 pixels of the display. Hitachi LCD

14
displays have a standard ASCII set of characters plus Japanese, Greek and mathematical
symbols.

For an 8-bit data bus, the display requires a +5V supply plus 11 I/O lines. For a 4-bit data bus it
only requires the supply lines plus seven extra lines. When the LCD display is not enabled, data
lines are tri-state which means they are in a state of high impedance (as though they are
disconnected) and this means they do not interfere with the operation of the microcontroller
when the display is not being addressed.

The LCD also requires 3 "control" lines from the microcontroller


Enable (E) This line allows access to the display through R/W and RS lines. When this
line is low, the LCD is disabled and ignores signals from R/W and RS. When
(E) line is high, the LCD checks the state of the two control lines and responds
accordingly.
Read/Write This line determines the direction of data between the LCD and
(R/W) microcontroller. When it is low, data is written to the LCD. When it is high,
data is read from the LCD.
Register Select With the help of this line, the LCD interprets the type of data on data lines.
(RS) When it is low, an instruction is being written to the LCD. When it is high, a
character is being written to the LCD.

Read data from data lines (if it is reading)

Reading data from the LCD is done in the same way, but control line R/W has to be high. When
we send a high to the LCD, it will reset and wait for instructions. Typical instructions sent to
LCD display after a reset are: turning on a display, turning on a cursor and writing characters
from left to right. When the LCD is initialized, it is ready to continue receiving data or

15
instructions. If it receives a character, it will write it on the display and move the cursor one
space to the right.

The Cursor marks the next location where a character will be written. When we want to write a
string of characters, first we need to set up the starting address, and then send one character at a
time. Characters that can be shown on the display are stored in data display (DD) RAM. The size
of DDRAM is 80 bytes.

The LCD display also possesses 64 bytes of Character-Generator (CG) RAM. This memory is
used for characters defined by the user. Data in CG RAM is represented as an 8-bit character bit-
map. Each character takes up 8 bytes of CG RAM, so the total number of characters, which the
user can define, is eight. In order to read in the character bit-map to the LCD display, we must
first set the CG RAM address to starting point (usually 0), and then write data to the display. The
definition of a 'special' character is given in the picture.

Before we access DD RAM after defining a special character, the program must set the DD
RAM address. Writing and reading data from any LCD memory is done from the last address
which was set up using set-address instruction. Once the address of DD RAM is set, a new
written character will be displayed at the appropriate place on the screen. Until now we discussed
the operation of writing and reading to an LCD as if it were an ordinary memory. But this is not
so. The LCD controller needs 40 to 120 microseconds (us) for writing and reading. Other
operations can take up to 5 ms. during that time, the microcontroller cannot access the LCD, and
so a program needs to know when the LCD is busy. We can solve this in two ways.
One way is to check the BUSY bit found on data line D7. This is not the best method because
LCD's can get stuck, and program will then stay forever in a loop checking the BUSY bit. The
other way is to introduce a delay in the program. The delay has to be long enough for the LCD to
finish the operation in process. Instructions for writing to and reading from an LCD memory
shown in the previous table. At the beginning we mentioned that we needed 11 I/O lines to
communicate with an LCD. However, we can communicate with an LCD through a 8-bit data
bus. The wiring for connection via a 8-bit data bus is shown in the diagram below. In this
example we use an LCD display with 2x16 characters, labeled LM16X212 by Japanese maker
SHARP.

16
RESISTORS:

A resistor is a two-terminal electronic component designed to oppose an electric current by


producing a voltage drop between its terminals in proportion to the current, that is, in accordance
with Ohm's law:

V = IR

Resistors are used as part of electrical networks and electronic circuits. They are extremely
commonplace in most electronic equipment. Practical resistors can be made of various
compounds and films, as well as resistance wire (wire made of a high-resistivity alloy, such as
nickel/chrome).

The primary characteristics of resistors are their resistance and the power they can dissipate.
Other characteristics include temperature coefficient, noise, and inductance. Less well-known is
critical resistance, the value below which power dissipation limits the maximum permitted
current flow, and above which the limit is applied voltage. Critical resistance depends upon the
materials constituting the resistor as well as its physical dimensions; it's determined by design.

Resistors can be integrated into hybrid and printed circuits, as well as integrated circuits. Size,
and position of leads (or terminals) are relevant to equipment designers; resistors must be
physically large enough not to overheat when dissipating their power.

A resistor is a two-terminal passive electronic component which implements electrical resistance


as a circuit element. When a voltage V is applied across the terminals of a resistor, a current I
will flow through the resistor in direct proportion to that voltage. The reciprocal of the constant
of proportionality is known as the resistance R, since, with a given voltage V, a larger value of R
further "resists" the flow of current I as given by Ohm's law:

Resistors are common elements of electrical networks and electronic circuits and are ubiquitous
in most electronic equipment. Practical resistors can be made of various compounds and films, as
well as resistance wire (wire made of a high-resistivity alloy, such as nickel-chrome). Resistors
are also implemented within integrated circuits, particularly analog devices, and can also be
integrated into hybrid and printed circuits.

The electrical functionality of a resistor is specified by its resistance: common commercial


resistors are manufactured over a range of more than 9 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
17
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 higher power ratings are
physically larger and may require heat sinking. In a high voltage circuit, attention must
sometimes be paid to the rated maximum working voltage of the resistor.

The series inductance of a practical resistor causes its behaviour to depart from ohms law; this
specification can be important in some high-frequency applications for smaller values of
resistance. 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 position of its leads (or terminals) which is relevant in the practical manufacturing
of circuits using them.

Units

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 milli ohm (1 m = 103 ), kilo ohm (1 k = 103
), and mega ohm (1 M = 106 ) are also in common usage.

The reciprocal of resistance R is called conductance G = 1/R and is measured in Siemens (SI
unit), sometimes referred to as a mho. Thus a Siemens is the reciprocal of an ohm: S = 1.
Although the concept of conductance is often used in circuit analysis, practical resistors are
always specified in terms of their resistance (ohms) rather than conductance.

CAPACITORS:
A capacitor or condenser is a passive electronic component consisting of a pair of conductors
separated by a dielectric. When a voltage potential difference exists between the conductors, an
electric field is present in the dielectric. This field stores energy and produces a mechanical force
between the plates. The effect is greatest between wide, flat, parallel, narrowly separated
conductors.

An ideal capacitor is characterized by a single constant value, capacitance, which is measured in


farads. This is the ratio of the electric charge on each conductor to the potential difference
between them. In practice, the dielectric between the plates passes a small amount of leakage
current. The conductors and leads introduce an equivalent series resistance and the dielectric has
an electric field strength limit resulting in a breakdown voltage.

18
The properties of capacitors in a circuit may determine the resonant frequency and quality factor
of a resonant circuit, power dissipation and operating frequency in a digital logic circuit, energy
capacity in a high-power system, and many other important aspects.

A capacitor (formerly known as condenser) is a device for storing electric charge. The forms of
practical capacitors vary widely, but all contain at least two conductors separated by a non-
conductor. Capacitors used as parts of electrical systems, for example, consist of metal foils
separated by a layer of insulating film.

Capacitors are widely used in electronic circuits for blocking direct current while allowing
alternating current to pass, in filter networks, for smoothing the output of power supplies, in the
resonant circuits that tune radios to particular frequencies and for many other purposes.

A capacitor is a passive electronic component consisting of a pair of conductors separated by a


dielectric (insulator). When there is a potential difference (voltage) across the conductors, a static
electric field develops in the dielectric that stores energy and produces a mechanical force
between the conductors. An ideal capacitor is characterized by a single constant value,
capacitance, measured in farads. This is the ratio of the electric charge on each conductor to the
potential difference between them.

The capacitance is greatest when there is a narrow separation between large areas of conductor,
hence capacitor conductors are often called "plates", referring to an early means of construction.
In practice the dielectric between the plates passes a small amount of leakage current and also
has an electric field strength limit, resulting in a breakdown voltage, while the conductors and
leads introduce an undesired inductance and resistance.

Theory of operation
Capacitance
Charge separation in a parallel-plate capacitor causes an internal electric field. A dielectric
(orange) reduces the field and increases the capacitance. A capacitor consists of two conductors
separated by a non-conductive region. The non-conductive region is called the dielectric or
sometimes the dielectric medium. In simpler terms, the dielectric is just an electrical insulator.
Examples of dielectric mediums are glass, air, paper, vacuum, and even a semiconductor
depletion 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.
The capacitor is a reasonably general model for electric fields within electric circuits. An ideal
capacitor is wholly characterized by a constant capacitance C, defined as the ratio of charge Q
on each conductor to the voltage V between them:

19
Sometimes charge build-up affects the capacitor mechanically, causing its capacitance to vary. In
this case, capacitance is defined in terms of incremental changes:

Energy storage
Work must be done by an external influence to "move" charge between the conductors in a
capacitor. When the external influence is removed the charge separation persists in the electric
field and energy is stored to be released when the charge is allowed to return to its equilibrium
position. The work done in establishing the electric field, and hence the amount of energy stored,
is given by:

Current-voltage relation
The current i(t) through any component in an electric circuit is defined as the rate of flow of a
charge q(t) passing through it, but actual charges, electrons, cannot pass through the dielectric
layer of a capacitor, rather an electron accumulates on the negative plate for each one that leaves
the positive plate, resulting in an electron depletion and consequent positive charge on one
electrode that is equal and opposite to the accumulated negative charge on the other. Thus the
charge on the electrodes is equal to the integral of the current as well as proportional to the
voltage as discussed above. As with any anti derivative, a constant of integration is added to
represent the initial voltage v (t0). This is the integral form of the capacitor equation,

Taking the derivative of this, and multiplying by C, yields the derivative form,

The dual of the capacitor is the inductor, which stores energy in the magnetic field rather than the
electric field. Its current-voltage relation is obtained by exchanging current and voltage in the
capacitor equations and replacing C with the inductance L.

20
DIODES:

Diodes are used to convert AC into DC these are used as half wave rectifier or full wave
rectifier. Three points must he kept in mind while using any type of diode.
1. Maximum forward current capacity
2. Maximum reverse voltage capacity
3. Maximum forward voltage capacity

The number and voltage capacity of some of the important diodes available in the market are as
follows:
Diodes of number IN4001, IN4002, IN4003, IN4004, IN4005, IN4006 and IN4007 have
maximum reverse bias voltage capacity of 50V and maximum forward current capacity
of 1 Amp.
Diode of same capacities can be used in place of one another. Besides this diode of more
capacity can be used in place of diode of low capacity but diode of low capacity cannot
be used in place of diode of high capacity. For example, in place of IN4002; IN4001 or
IN4007 can be used but IN4001 or IN4002 cannot be used in place of IN4007.The diode
BY125made by company BEL is equivalent of diode from IN4001 to IN4003. BY 126 is
equivalent to diodes IN4004 to 4006 and BY 127 is equivalent to diode IN4007.

PN JUNCTION OPERATION

Now that you are familiar with P- and N-type materials, how these materials are joined together
to form a diode, and the function of the diode, let us continue our discussion with the operation
of the PN junction. But before we can understand how the PN junction works, we must first
consider current flow in the materials that make up the junction and what happens initially within
the junction when these two materials are joined together.

Current Flow in the N-Type Material

Conduction in the N-type semiconductor, or crystal, is similar to conduction in a copper wire.


That is, with voltage applied across the material, electrons will move through the crystal just as
current would flow in a copper wire. This is shown in figure 1-15. The positive potential of the
battery will attract the free electrons in the crystal. These electrons will leave the crystal and flow
into the positive terminal of the battery. As an electron leaves the crystal, an electron from the
negative terminal of the battery will enter the crystal, thus completing the current path.
Therefore, the majority current carriers in the N-type material (electrons) are repelled by the
negative side of the battery and move through the crystal toward the positive side of the battery.

Current Flow in the P-Type Material

Current flow through the P-type material is illustrated. Conduction in the P material is by
positive holes, instead of negative electrons. A hole moves from the positive terminal of the P
material to the negative terminal. Electrons from the external circuit enter the negative terminal
21
of the material and fill holes in the vicinity of this terminal. At the positive terminal, electrons
are removed from the covalent bonds, thus creating new holes. This process continues as the
steady stream of holes (hole current) moves toward the negative terminal.

GSM MODULE:
This is a GSM/GPRS-compatible Quad-band cell phone, which works on a frequency of
850/900/1800/1900MHz and which can be used not only to access the Internet, but also for oral
communication (provided that it is connected to a microphone and a small loud speaker) and for SMSs.
Externally, it looks like a big package (0.94 inches x 0.94 inches x 0.12 inches) with L-shaped contacts on
four sides so that they can be soldered both on the side and at the bottom.

Internally, the module is managed by an AMR926EJ-S processor, which controls phone


communication, data communication (through an integrated TCP/IP stack), and (through an UART and a
TTL serial interface) the communication with the circuit interfaced with the cell phone itself. The
processor is also in charge of a SIM card (3 or 1.8 V) which needs to be attached to the outer wall of the
module. In addition, the GSM900 device integrates an analog interface, an A/D converter, an RTC,
an SPI bus, an IC, and a PWM module. The radio section is GSM phase 2/2+ compatible and is either
class 4 (2 W) at 850/ 900 MHz or class 1 (1 W) at 1800/1900 MHz The TTL serial interface is in charge
not only of communicating all the data relative to the SMS already received and those that come in during
TCP/IP sessions in GPRS (the data-rate is determined by GPRS class 10: max. 85,6 kbps), but also of
receiving the circuit commands (in our case, coming from the PIC governing the remote control) that can
be either AT standard or AT-enhanced SIM Com type. The module is supplied with continuous energy
(between 3.4 and 4.5 V) and absorbs a maximum of 0.8 A during transmission.

4.3 SOFTWARE SPECIFICATIONS:

SOFTWARE

The Raspberry Pi is a low cost, credit-card sized computer that plugs into a computer monitor
or TV, and uses a standard keyboard and mouse. It is a capable little device that enables people
of all ages to explore computing, and to learn how to program in languages like Scratch and
Python. Its capable of doing everything youd expect a desktop computer to do, from browsing
the internet and playing high-definition video, to making spreadsheets, word-processing, and
playing games.
Whats more, the Raspberry Pi has the ability to interact with the outside world, and has been
used in a wide array of digital maker projects, from music machines and parent detectors to
weather stations and tweeting birdhouses with infra-red cameras. We want to see the Raspberry
Pi being used by kids all over the world to learn to program and understand how computers
work.

22
NOOBS
New out Of the Box Software is an easy operating system installation manager for the
Raspberry Pi.

NOOBS SETUP
To get started with Raspberry Pi, you need an operating system. NOOBS (New out Of Box
Software) is an easy operating system install manager for the Raspberry Pi.
HOW TO GET AND INSTALL NOOBS
We recommend using an SD card with a minimum capacity of 8GB.
Using a computer with an SD card reader, visit the Downloads page.
Click on the Download ZIP button under NOOBS (offline and network install), and select a
folder to save it to.
Extract the files from the zip.

FORMAT YOUR SD CARD


It is best to format your SD card before copying the NOOBS files onto it. To do this:
Visit the SD Associations website and download SD Formatter 4.0 for either Windows or Mac.
23
Follow the instructions to install the software.
Insert your SD card into the computer or laptops SD card reader and make a note of the drive
letter allocated to it, e.g. G:/
In SD Formatter, select the drive letter for your SD card and format it.
DRAG AND DROP NOOBS FILES
Once your SD card has been formatted, drag all the files in the extracted NOOBS folder and drop
them onto the SD card drive.
The necessary files will then be transferred to your SD card.
When this process has finished, safely remove the SD card and insert it into your Raspberry Pi.

FIRST BOOT
Plug in your keyboard, mouse, and monitor cables.
Now plug the USB power cable into your Pi.
Your Raspberry Pi will boot, and a window will appear with a list of different operating systems
that you can install. We recommend that you use Raspbian tick the box next to Raspbian and
click on Install.
Raspbian will then run through its installation process. Note that this can take a while.
When the install process has completed, the Raspberry Pi configuration menu (raspi-config) will
load. Here you are able to set the time and date for your region, enable a Raspberry Pi camera
board, or even create users. You can exit this menu by using Tab on your keyboard to move
to Finish.

Booting your Pi for the first time:


The first time you boot the Raspberry Pi you'll see a configuration tool called "raspi-config." (If
you ever need to revisit this configuration screen again, you can always call the "raspi-config"
command from the terminal of your Pi.) While you're there, you'll need to change a few options.

24
First off, we need to select "expand_rootfs". What this does is expand the installed image to use
the maximum available size of your SD card. If you are using a larger card (16GB, say), you'll
definitely want to make sure you can use the full capacity, since the install image is only about
2GB. Highlight that "expand_rootfs" option and press Enter. You'll then see the confirmation
below, at which point pressing Enter will take you back to the main raspi-config screen.

Next up is the over scan option. If you notice, the screen is not taking up the entire real estate
afforded by your monitor; it's best to disable over scan so that you can utilize your monitor or

25
television to its entirety. If your screen looks fine, though, you can skip this step. In any case,
assuming you do go through with this step, select "over scan" and press Enter.

Here you get the option to disable or enable. If you ever upgrade to a new monitor or television
you may need to re-enable over scan at a later point.

After that quick step, now we want to verify our keyboard settings. If you are in America you
want to change this; if you're in Great Britain these are safe to leave at the standard config.

Select "configure keyboard" and press Enter. Then you'll be presented with a very long list of
keyboard options. If you know your keyboard setup, select it in the list, otherwise you'll be fine
with the default 105-key option.

After selecting your keyboard type, you'll need to specify the layout. There's a good chance you
want a different layout than English (UK), so choose "Other" and select the most appropriate
option.

26
You'll then be asked about modifier keys -- just choose the default here, as well as "No compose
key" on the next screen. If later you find you need a compose key to create alternative characters,
you can return to this configuration screen by running "raspi-config".

The last option you'll need to set in the Keyboard configuration is the ALT / CTRL /
BACKSPACE feature to kill X11. We recommend you enable this, so that in case your GUI ever
crashes you can safely kill it without rebooting.

Back at the main menu, the next step is to set a user password.

27
Select "change pass" and press Enter. After a confirmation screen, you'll be prompted to choose
a new UNIX user password.

Almost done now. Let's set your "locale," which is the general character set used by your native
language. Again, if you don't live in Great Britain, you'll want to change this to your local
character set. If you're in the good ol' US of A, you want en_US.UTF-8. Scroll down to your
locale of choice, and de-select the en_GB option on your way. In our case, we'll be enabling
en_US.UTF-8

28
The next dialogue window will ask you to choose a default locale, select the locale you just
chose on the previous screen and press Enter.

29
Back on raspi-config main menu, set the appropriate time zone by selecting -- you guessed it --
the "change_timezone" option. You'll be presented with a list of regions first.

The next dialogue will show you a list of zones within that region. We think you know what to
do here.

Back at the main setup, you can safely ignore the remaining options for now and select "Finish."
You'll be prompted to reboot to make changes; do so. Once your system is back online, you'll get
a login prompt like so:

30
Your login is "pi" and the password will be what you set it to earlier.

Using your Raspberry Pi

Now that you've logged in to your freshly baked Raspberry Pi, the first thing you want to do is
type "start" to get your GUI environment loaded, which from here on out we'll refer to as your
Window Manager.

After a quick screen flicker you should end up with this (minus the terminal window):

31
Welcome to the LXDE Window Manager. LXDE is a very lightweight, full-featured UI that runs
pretty well on the Raspberry Pi. If you've never used LXDE before, it drives very similar to
Windows. If you click the lower left icon, you'll see an application list. It works exactly how
you'd expect it to.

Writing your first program on the Raspberry Pi


Raspbian comes preloaded with Python, the official programming language of the Raspberry Pi
and IDLE 3, a Python Integrated Development Environment. We're going to show you know
how to get started with IDLE and write your very first, albeit simple, Python program.

When learning a new language, it's very common to create the classic "Hello World!" program,
which is what we're going to show you how to do, but with a small twist. This Python program
will ask for your name and introduce itself to you.

First, load up IDLE 3 by double-clicking the icon on your LXDE desktop.


32
Click File > New Window, which will then bring up a new blank window which you can type in.

Then, type the following in your new window:

#my first Python program


username = input("Hello, I'm Raspberry Pi! What is your name? ")
print ('Nice to meet you, ' + username + ' have a nice day!')

33
Now click File > Save As and in the new dialogue window that pops up, call your file "hello"
and click "Save".

Let's run that program you just wrote!

Click Run > Run Module or simply press F5.

34
When you get prompted "Hello, I'm Raspberry Pi! What is your name?" in the IDLE 3 window,
type your name and press Enter. You'll see the Raspberry Pi responds. Et voila! Not much else to
it.

35
HARDWARE TESTING:
CONTINUITY TEST:
In electronics, a continuity test is the checking of an electric circuit to see if current flows (that it
is in fact a complete circuit). A continuity test is performed by placing a small voltage (wired in
series with an LED or noise-producing component such as a piezoelectric speaker) across the
chosen path. If electron flow is inhibited by broken conductors, damaged components, or
excessive resistance, the circuit is "open".

Devices that can be used to perform continuity tests include multi meters which measure current
and specialized continuity testers which are cheaper, more basic devices, generally with a simple
light bulb that lights up when current flows. An important application is the continuity test of a
bundle of wires so as to find the two ends belonging to a particular one of these wires; there will
be a negligible resistance between the "right" ends, and only between the "right" ends.

This test is the performed just after the hardware soldering and configuration has been
completed. This test aims at finding any electrical open paths in the circuit after the soldering.
Many a times, the electrical continuity in the circuit is lost due to improper soldering, wrong and
rough handling of the PCB, improper usage of the soldering iron, component failures and
presence of bugs in the circuit diagram. We use a multi meter to perform this test. We keep the
multi meter in buzzer mode and connect the ground terminal of the multi meter to the ground.
We connect both the terminals across the path that needs to be checked. If there is continuation
then you will hear the beep sound.

POWER ON TEST:
This test is performed to check whether the voltage at different terminals is according to the
requirement or not. We take a multi meter and put it in voltage mode. Remember that this test is
performed without microcontroller. Firstly, we check the output of the transformer, whether we
get the required 12 v AC voltage.

Then we apply this voltage to the power supply circuit. Note that we do this test without
microcontroller because if there is any excessive voltage, this may lead to damaging the
controller. We check for the input to the voltage regulator i.e., are we getting an input of 12v and
an output of 5v. This 5v output is given to the microcontrollers 40th pin. Hence we check for the
voltage level at 40th pin. Similarly, we check for the other terminals for the required voltage. In
this way we can assure that the voltage at all the terminals is as per the requirement.

36
CHAPTER 5
METHODOLOGY
5.1 BLOCK DIAGRAM
This system provides a unique method to curb drunken people. The system has an alcohol
sensor embedded on the steering of the car. Whenever the driver starts ignition, the sensor
measures the content of the alcohol in his breath and automatically switches off the car if he is
drunken. In this system the sensor delivers a current with a linear relationship to the alcohol
molecules from zero to very high concentration. The output of the sensor is fed to the Raspberry
Pi 3 for comparison. If the measured value reaches the threshold, relay cut off automatically and
the buzzer generates sound. Once the buzzer produces sound the system communicates with
configured telecom device unique number using the GSM Module.

The existing systems in the market include Breathalyzer and Smart helmet which is not sufficient
to curb the tragic reality. Hence, we introduce to you our system automated drunk and driving
system with SMS Alert [ADDA]. Automated drunk and driving system with SMS Alert [ADDA]
consists of one Raspberry Pi, one GSM Sim 900 module and one Interface circuitry to
communicate.
37
5.2 CIRCUIT DIAGRAM

38
5.3 WORKING

The circuit has an alcohol sensor. This sensor measures the content of alcohol from the
breath of drunken people. The sensor delivers a current with linear relationship to the alcohol
molecules from zero to very high concentrations. Output of the sensor is directly proportional to
the alcohol content. When the alcohol molecules in the air meet the electrode that is between
alumina and tin dioxide in the sensor, ethanol burns into acetic acid then more current is
produced. So the more alcohol molecules more will be the current produced. Because of this
current change, we get the different values from the sensor. Output of the sensor is then fed to
the microcontroller for comparison. The output of the sensor is in the analog nature which should
be converted into digital format. This is done by the Raspberry Pi unit. The Raspberry Pi controls
the entire circuit. When the measured value reaches the threshold (here it is 255) the
microcontroller switches the ignition ON. Then relay cuts off automatically and buzzer produces
sound. Once the buzzer produces the sound, the text message will be sent to configured devices.
The LCD displays the message that sent from the Raspberry Pi unit. The working conditions and
various constraints were properly studied before carrying out further steps. The components were
purchased and the circuit was initially set on the breadboard. The PCB was fabricated as per the
requirement and was soldered with components, taking proper care to avoid shorting between
various connections. Milling method was used for PCB Fabrication. The output was verified on
the PCB. The circuit worked successfully.

39
CHAPTER 6
DISCUSSION AND RESULTS

The existing systems in the market include Breathalyzer and Smart helmet which is not
sufficient to curb the tragic reality. Hence, we introduce to you our system automated drunk and
driving system with SMS Alert [ADDA]. Automated drunk and driving system with SMS Alert
[ADDA] consists of one Raspberry Pi, one GSM Sim 900 module and one Interface circuitry to
communicate. The main idea behind using Raspberry Pi instead of cheaper alternatives like
Arduino is that for future development we need higher processing power and better device
management. For demonstrative purpose, we have used a 500 RPM DC motor in place of car
engine and push button switch in place of Car ignition. In practical implementation, we will
directly connect the system to the ABS of the car. We believe our system will curb the tragic
reality and make a positive impact in the world. Let us now understand the system in detail.
The circuit has an alcohol sensor. This sensor measures the content of alcohol from the
breath of drunken people. The sensor delivers a current with linear relationship to the alcohol
molecules from zero to very high concentrations. Output of the sensor is directly proportional to
the alcohol content. When the alcohol molecules in the air meet the electrode that is between
alumina and tin dioxide in the sensor, ethanol burns into acetic acid then more current is
produced. So the more alcohol molecules more will be the current produced. Because of this
current change, we get the different values from the sensor. Output of the sensor is then fed to
the microcontroller for comparison. The output of the sensor is in the analog nature which should
be converted into digital format. This is done by the Raspberry Pi unit. The Raspberry Pi controls
the entire circuit. When the measured value reaches the threshold (here it is 255) the
microcontroller switches the ignition ON. Then relay cuts off automatically and buzzer produces
sound. Once the buzzer produces the sound, the text message will be sent to configured devices.
The LCD displays the message that sent from the Raspberry Pi unit. The working conditions and
various constraints were properly studied before carrying out further steps. The components were
purchased and the circuit was initially set on the breadboard. The PCB was fabricated as per the
requirement and was soldered with components, taking proper care to avoid shorting between
various connections. Milling method was used for PCB Fabrication. The output was verified on
the PCB. The circuit worked successfully.
Our project ADDA was implemented successfully. This device provides much advanced
facilities in now a days life as it can be easily implemented in vehicles. Thus we can reduce
alcohol related road accidents and hence these kinds of detectors have a great relevance. It can
also be used in schools, colleges, offices and some public places such as hospitals, libraries etc.

40
CHAPTER7
CONCLUSION

The circuit has an alcohol sensor. This sensor measures the content of alcohol from the
breath of drunken people. The sensor delivers a current with linear relationship to the alcohol
molecules from zero to very high concentrations. Output of the sensor is directly proportional to
the alcohol content. When the alcohol molecules in the air meet the electrode that is between
alumina and tin dioxide in the sensor, ethanol burns into acetic acid then more current is
produced. So the more alcohol molecules more will be the current produced. Because of this
current change, we get the different values from the sensor. Output of the sensor is then fed to
the microcontroller for comparison. The output of the sensor is in the analog nature which should
be converted into digital format. This is done by the Raspberry Pi unit. The Raspberry Pi controls
the entire circuit. When the measured value reaches the threshold (here it is 255) the
microcontroller switches the ignition ON. Then relay cuts off automatically and buzzer produces
sound. Once the buzzer produces the sound, the text message will be sent to configured devices.
The LCD displays the message that sent from the Raspberry Pi unit. The working conditions and
various constraints were properly studied before carrying out further steps. The components were
purchased and the circuit was initially set on the breadboard. The PCB was fabricated as per the
requirement and was soldered with components, taking proper care to avoid shorting between
various connections. Milling method was used for PCB Fabrication. The output was verified on
the PCB. The circuit worked successfully.
The project can be extended to an improved version for preventing drunk drivers from
getting on the road with new concept car filled with alcohol- detection sensors. These new
sensors check a persons odors, sweat, and driver awareness to see if they are capable of driving
their car. If theyre not quite sober, the car locks up the ignition system thereby preventing the
driver from getting on the road. In this project we embedded the sensor on the steering of the car.
In addition to the Breathalyzer, skin sensors can also be provided for more safety. We can also
introduce Camera and GPRS system for more effective tracking.

41
REFERENCES

[1] Martin Jawitz,Printed circuit board materials hand book.


[2] www.alldatasheets.com
[3] https://www.raspberrypi.org/documentation/
[4] Wong, George (24 October 2011). "Build your own prototype Raspberry Pi minicomputer".
ubergizmo.
[5] Raspberry Pi For Dummies; Sean McManus and Mike Cook; 432 pages; 2013; ISBN 978-
1118554210.
[6] Raspberry Pi User Guide; Eben Upton and Gareth Halfacree; 312 pages; 2014; ISBN 978-
1118921661.
[7] Getting Started with Raspberry Pi; Matt Richardson and Shawn Wallace; 176 pages;
2013; ISBN 978-1449344214.
[8] Hello Raspberry Pi!; Ryan Heitz; 320 pages; 2016; ISBN 978-1617292453.

42
APPENDIX A
PCB LAYOUT

43
APPENDIX B
CODE OF THE PROJECT
import Adafruit_CharLCD as LCD
import RPi.GPIO as GPIO
import time
from time import sleep
from datetime import datetime
import os
import serial
import re
from smbus import SMBus

port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=0.5) #turn on the serial


communication

#get alcohol level


def get_alcohol_level():
reading = bus.read_byte_data(0x48,0x00) # read byte on I2C bus
reading2 = float(reading * 0.43)
return reading2

#send command to gsm module


def send_cmd(cmd,response=None,debug=False,t=0.5):
port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=t)
cmd = cmd + "\r\n"
port.write(cmd)

44
if debug:
rcv = port.readall().strip()
if response:
return rcv.endswith(response)
else:
return rcv
else:
return ""

#function to exicuite command for gsm


def exicute_cmd(c,r,t):

t1 = datetime.now()
while True:
if(send_cmd(c,r,True,0.2)):
return True

t2 = datetime.now()
delta = t2 - t1
time_elapse = delta.total_seconds()
if time_elapse > t:
return False
sleep(1)

#function to connect gsm by sending commands


def connect_gsm():
exicute_cmd("AT",ok,5)
45
exicute_cmd("ATE0",ok,5)
send_cmd("AT+CGPSPWR=1",None,True,1)
if exicute_cmd("AT+CPIN?",ok,5):
if exicute_cmd("AT+CLIP=0",ok,5):
if exicute_cmd("AT+COLP=1",ok,5):
if exicute_cmd("AT+CLCC=1",ok,5):
if exicute_cmd("AT+CMGF=1",ok,5):
if exicute_cmd("AT+CNMI=0,0,0,0",ok,5):
if exicute_cmd("AT+CMGDA=\"DEL ALL\"",ok,5):
return True
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False
else:
return False

#function use to detect call


def call_status():
46
sleep(1)
if port.inWaiting() > 0:
rcv = port.readall().strip()
if rcv.find(CLCC) >= 0 or rcv.find("RING") >= 0:
return RECEIVING_CALL
else:
return IDLE

#function to get recived call number


def get_call_number():

call_data = send_cmd("AT+CLCC",None,True)
if call_data.find(CLCC) >=0:
index1 = call_data.find('\"')
num = call_data[index1+1:]
index2 = num.find('"')
num = num[:index2]
return num
else:
return None

#function use to cut call


def hangcall():
send_cmd("ATH",ok,True,1)

#funtion use to send sms


def send_sms(text,num):
47
lcd.clear()
lcd.message('Sending sms to\n'+num)
send_cmd("AT+CMGF=1",ok,True,1)
if send_cmd("AT+CMGS=\""+num+'\"','>',True,1):
if send_cmd(text+"\x1a",ok,True,10):
return True
else:
return False

#function to beep the buzzer


def tone_buzzer(beep_cnt , beep_len):
for x in range(0 , beep_cnt):
GPIO.output(buzzer, True)
sleep(beep_len)
GPIO.output(buzzer, False)
sleep(0.05)

#function to config numbers


def config_number():
no1_configured = 0
global numtel1

no2_configured = 0
global numtel2

no3_configured = 0
global numtel3
48
rto = 0
global rto_num

global main

while no1_configured == 0:
lcd.clear()
lcd.message('Waiting for\ncall')
tone_buzzer(1,0.5)
if GPIO.input(restart) == False:
main = False
return False
if call_status() == RECEIVING_CALL:
numtel1 = get_call_number()
if numtel1 != None:
lcd.clear()
lcd.message('receiving call\n'+numtel1)
hangcall()
time.sleep(1)
if send_sms(config_sms,numtel1):
lcd.clear()
lcd.message('SMS sent')
time.sleep(1)
no1_configured = 1

while no2_configured == 0 and main:


49
lcd.clear()
lcd.message('Waiting for\ncall')
tone_buzzer(2,0.2)
if GPIO.input(restart) == False:
main = False
return False
if call_status() == RECEIVING_CALL:
numtel2 = get_call_number()
if numtel2 != None:
lcd.clear()
lcd.message('receiving call\n'+numtel2)
hangcall()
if numtel2 != numtel1:
if send_sms(config_sms,numtel2):
print "sms sent"
lcd.clear()
lcd.message('SMS sent')
time.sleep(1)

no2_configured = 1

else:
lcd.clear()
lcd.message('Nummber already\nexist')
time.sleep(1.5)

while no3_configured == 0 and main:


50
lcd.clear()
lcd.message('Waiting for\ncall')
tone_buzzer(3,0.1)
if GPIO.input(restart) == False:
main = False
return False
if call_status() == RECEIVING_CALL:
numtel3 = get_call_number()
if numtel3 != None:
lcd.clear()
lcd.message('receiving call\n'+numtel3)
hangcall()
if numtel3 != numtel1 and numtel3 != numtel2:
hangcall()
if send_sms(config_sms,numtel3):
lcd.clear()
lcd.message('SMS sent')
time.sleep(1)

no3_configured = 1

else:
lcd.clear()
lcd.message('Nummber already\nexist')
time.sleep(1.5)

while rto == 0 and main:


51
lcd.clear()
lcd.message('Waiting for\nRTO')
tone_buzzer(4,0.1)
if GPIO.input(restart) == False:
main = False
return False
if call_status() == RECEIVING_CALL:
rto_num = get_call_number()
if rto_num != None:
lcd.clear()
lcd.message('receiving call\n'+rto_num)
hangcall()
if rto_num != numtel1 and rto_num != numtel2 and rto_num != numtel3:
hangcall()
if send_sms("This number is configure as RTO..",rto_num):
lcd.clear()
lcd.message('SMS sent')
time.sleep(1)
rto = 1
return True

else:
lcd.clear()
lcd.message('Nummber already\nexist')
time.sleep(1.5)
return True

52
#function to get gps coordinates
def gps_track():
lcd.clear()
lcd.message('Tracking')
time.sleep(2)
gps_data = send_cmd("AT+CGPSINF=2",None,True,2)
if gps_data.find("+CGPSINF:") >= 0:
index1 = gps_data.find(',N')
_lat = gps_data[0:index1]
index2 = _lat.rfind(',')
_lat = str(_lat[index2 : ])

index1 = gps_data.find(',E')
_lon = gps_data[0:index1]
index2 = _lon.rfind(',')
_lon = str(_lon[index2 : ])

print "lat = " , float(_lat)


print "lon = " , float(_lon)
return _lat,_lon
else:
return "",""

RECEIVINGCALL = 1
IDLE = 2
BUSY = 3
NO_ANSWER = 4
53
TALKING = 5
ERROR = 6

ok = "OK"
ERROR_str = "ERROR"
IDLE = "IDLE"
config_sms = "This number is configured."
user_cut_call = "call cut"
USER_not_Answering = "no Answer"
call_establish = "call establish"
disconnecting_call = "disconnecting"
cant_make_CALL = "CALL error"
CLCC = "+CLCC:"
CMGL = "+CMGL:"
RECEIVING_CALL = "RECEIVING CALL"

notConnected = True
call_rcv = False
gsm_connect = False
DND = False

numtel1 = ""
numtel2 = ""
numtel3 = ""
rto_num = ""

bus = SMBus(1) #turn on I2C bus


54
port = serial.Serial("/dev/ttyAMA0", baudrate=9600, timeout=0.5)

ok = "OK"
admin_num = ""

rcv = None

restart = 23
led = 8
button = 25
buzzer = 7
motor1 = 6
motor2 = 13

# Raspberry Pi pin configuration for LCD


lcd_rs = 26
lcd_en = 19
lcd_d4 = 21
lcd_d5 = 20
lcd_d6 = 16
lcd_d7 = 12

# Define LCD column and row size for 16x2 LCD.


lcd_columns = 16
lcd_rows =2

#call instance of LCD


55
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns,
lcd_rows)

#setup the GPIO pins


GPIO.setup(restart,GPIO.IN)
GPIO.setup(button,GPIO.IN,)
GPIO.setup(led,GPIO.OUT)
GPIO.setup(buzzer,GPIO.OUT)
GPIO.setup(motor1,GPIO.OUT)
GPIO.setup(motor2,GPIO.OUT)

reset = True

#main loop
while reset == True:

alcohol = get_alcohol_level()
sms_sent = False
ok = "OK"
admin_num = ""
RTO_num = ""
number = ""
rcv = None
admin_config = False
RTO_config = False

p = GPIO.PWM(motor1,50) #set one pin of motor as pwm


56
p.start(0) #start pwm at 0

GPIO.output(led, False) #turn off led


GPIO.output(buzzer, False) #turn off buzzer
GPIO.output(motor2, False) #turn off motor

main = True

lcd.clear()
lcd.show_cursor(False)
lcd.message(' Alcohol ') #display msg on LCD
lcd.set_cursor(0,1) #set cursor on LCD at zero column and first row
lcd.message('Detection system')
time.sleep(4) #time delay for 4 sec

if main:
lcd.clear()
lcd.message('connecting GSM')

while True:
if connect_gsm():
lcd.clear()
lcd.message('GSM connected')
time.sleep(2)
break
else:
lcd.clear()
57
lcd.message('GSM not \nconnected')
main = False
time.sleep(3)
lcd.clear()
lcd.message('connect GSM and\nrestart system')
while GPIO.input(restart) == True:
None
break

if main:
if config_number():
lcd.clear()
lcd.message('All numbers are\ncofigured')
time.sleep(2)

lcd.clear()
lcd.message('Press switch...')
full_on = False
half_on = False

while main == True:


sm = 1
if not GPIO.input(button): #check if button is press or not
lcd.clear()
lcd.message('Please Wait....')
time.sleep(1)
while True:
58
alcohol = get_alcohol_level() #get alcohol level
time.sleep(1)
lcd.clear()
lcd.message('Alcohol : ')
lcd.message(str(alcohol) + '% ')

if alcohol < 50 and alcohol > 20:


sms_sent = False
lcd.set_cursor(0,1)
lcd.message('Engin speed 50% ')
GPIO.output(motor2, False)
if full_on == True:
for dc in range(100,50,-5):
p.ChangeDutyCycle(dc) #set pwm level for motor
time.sleep(0.1)
elif half_on == False:
for dc in range(0,50,5):
p.ChangeDutyCycle(dc)
time.sleep(0.1)
half_on = True
full_on = False
GPIO.output(led, False)
GPIO.output(buzzer, False)

if alcohol < 20:


sms_sent = False
lcd.set_cursor(0,1)
59
lcd.message('Engin speed 100%')
GPIO.output(motor2, False)
if half_on == True:
for dc in range(55,100,5):
p.ChangeDutyCycle(dc)
time.sleep(0.1)
half_on = False
full_on = True

elif full_on == False:


for dc in range(0,100,5):
p.ChangeDutyCycle(dc)
time.sleep(0.1)
half_on = False
full_on = True
GPIO.output(led, False)
GPIO.output(buzzer, False)

if alcohol > 50:


lcd.set_cursor(0,1)
lcd.message(' Engin stop ')
GPIO.output(led, True)
GPIO.output(buzzer, True)
GPIO.output(motor2, False)
if half_on == True:
for dc in range(50,-1,-5):
p.ChangeDutyCycle(dc)
60
time.sleep(0.1)
full_on = False
half_on = False

elif full_on == True:


for dc in range(100,-1,-5):
p.ChangeDutyCycle(dc)
time.sleep(0.1)
full_on = False
half_on = False
time.sleep(2)
GPIO.output(led, False)
GPIO.output(buzzer, False)

if sms_sent == False:
lat,lon = gps_track()

if lat > 0 and lon > 0:


lcd.clear()
lcd.message('lat: ' + str(lat))
lcd.set_cursor(0,1)
lcd.message('lon: ' + str(lon))
time.sleep(1.5)
map_site = "Alcohol Detected!!\n" +
"http://maps.google.com/maps?f=q&q=" + str(lat) + "," + str(lon) + "&z=16"
print map_site
if send_sms(map_site,rto_num):
61
lcd.clear()
lcd.message('SMS sent')
time.sleep(3)
if send_sms(map_site,numtel1):
lcd.clear()
lcd.message('SMS sent')
time.sleep(3)
if send_sms(map_site,numtel2):
lcd.clear()
lcd.message('SMS sent')
time.sleep(3)
if send_sms(map_site,numtel3):
lcd.clear()
lcd.message('SMS sent')
sms_sent = True

else:
lcd.clear()
lcd.message("gps not working")
time.sleep(1.5)
map_site = "Alcohol Detected!!\n" + "gps not working"
if send_sms(map_site,rto_num):
lcd.clear()
lcd.message('SMS sent')
time.sleep(3)
if send_sms(map_site,numtel1):
lcd.clear()
62
lcd.message('SMS sent')
time.sleep(3)
if send_sms(map_site,numtel2):
lcd.clear()
lcd.message('SMS sent')
time.sleep(3)
if send_sms(map_site,numtel3):
lcd.clear()
lcd.message('SMS sent')
sms_sent = True

lcd.clear()
lcd.message('Press switch...')
break

if not GPIO.input(button):
sms_sent = False
lcd.clear()
lcd.message(' Engin stop ')
GPIO.output(motor2, False)
if half_on == True:
for dc in range(50,-1,-5):
p.ChangeDutyCycle(dc)
time.sleep(0.1)
full_on = False
half_on = False
63
elif full_on == True:
for dc in range(100,-1,-5):
p.ChangeDutyCycle(dc)
time.sleep(0.1)
full_on = False
half_on = False
GPIO.output(led, False)
GPIO.output(buzzer, False)
time.sleep(1)
sm = 0
lcd.clear()
lcd.message('Press switch...')
print "press switch"
break

if GPIO.input(restart) == False:
main = False
break

time.sleep(1)
time.sleep(1)
if GPIO.input(restart) == False:
break

64

Vous aimerez peut-être aussi