This document discusses gas sensing technology and oxygen measurement. It provides background on how gas sensing has evolved from using canaries to modern sensors. It then describes how the author uses oxygen sensors, analog to digital conversion, and an Arduino board to measure oxygen levels. The document discusses different gas sensing methods like catalytic sensors and how oxygen sensors work electrochemically to produce a current proportional to oxygen concentration.
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Gas Sensing and Monitoring
1. CIRCUIT CELLAR • OCTOBER 2017 #32762COLUMNS
Gas sensing technology has come long way since the days of
canaries in coal mines. This month columnist Jeff covers the
background issues surrounding gas monitoring and sensing.
Then he describes how he uses sensors, A/D conversion and
Arduino technologies to do oxygen measurement.
By Jeff Bachiochi
From the Bench
Gas Monitoring and Sensing (Part 1)
Fun with Fragrant Analysis
tec
oa
iss
crib
hno
chi
COLUMNS
Gas sensing t
canaries in c
background i
Then he desc
Arduino tech
By Jeff Bachioc
When coal miners began
dropping like flies, it was
determined that poisonous
gas was the culprit. To date
there was no test to detect the presence
of this odorless ghost. Sacrificial canaries
became the guinea pigs, giving up their lives
to save the miners. These birds are especially
sensitive to methane and carbon monoxide.
When the song bird stopped singing, miners
headed for a breath of fresh air until the mine
could be cleared of the silent killer.
Seemingly ripe for disaster, the flame
height of an oil lamp was used for detecting
dangerous conditions in the 1800s. A
shrinking flame indicated reduced oxygen,
while a stronger flame indicated the presence
of methane—or other combustible gas. Flame
arrestors kept the combustion internal to the
lamp, preventing external gas ignition unless
it was dropped.
In the 1900s, it was discovered that
the current through an electric heater was
affected when nearby combustible gases
increased in temperature. The use of a
catalytic material—such as palladium—lowers
the temperature at which combustion takes
place. Using these heaters in a Whetstone
bridge configuration—where one leg is
exposed to the gas—can create an easily
measured imbalance proportional to the
concentration of the combustible gas.
Infrared light can be used to measure the
concentration of many hydrocarbon gases.
When compared to a gas-free path, the IR
absorption through a gas can indicate the
concentration of hydrocarbon molecules.
Gases can be identified by their molecular
makeup. That is the amount of each element
present. Absorption bands can be identified
by dispersion through diffraction or non-
dispersion through filtration. Concentration
is the relationship of a particular wavelength
between a reference path and a gas absorption
path.
There are many techniques available
today for monitoring gases. Refer to Table 1
for a breakdown of gas monitoring methods
and their associated advantages and
disadvantages. HAZMAT Class 2 in United
States identifies all gases which can be
compressed and stored for transportation.
Even though we are not directly dealing with
storage or transportation, the class is further
defined by three groups of gases: flammable,
toxic and others (non-flammable). You can
see how a gas of interest is classified under
HAZMAT rules in Table 2.
2. circuitcellar.com 63
COLUMNS
Basically, a gas detector is a device which
detects the presence of various gases within
an area. This is usually part of a safety system
that can indicate a hazardous condition.
It might sound an alarm or otherwise alert
humans to leave the area as many gases are
harmful to organic life. This project delves
into the catalytic gas sensors most often used
to detect levels of combustible gasses—for
example the mandatory carbon monoxide
detector in your home. Catalytic gas sensors
fall under the ‘calorimetric methods’ category
of gas sensing techniques.
CATALYTIC BEAD SENSORS
The catalytic bead sensor comprises a
bead or ‘pellistor’ made of a platinum coil with
a ceramic coating (alumina) soaked with a
special palladium catalyst. A catalyst enables
combustion to occur at lower temperatures
without affecting the chemical equilibrium
of a reaction. A Nickel-Chromium heating
element passes through the pellistor raising
its temperature and oxidizes the gas. The
pellistor is supported within a flameproof body
that allows the gas to enter via a stainless-
steel mesh and prevents combustion from
exiting the sensor. A good tear down of this
sensor can be seen at www.engineersgarage.
com/insight/how-gas-sensor-works. NOTE: A
slightly more complex sensor will have two
beads. One is exposed to the gas in question,
while the second is not—it is used instead as
a reference.
Catalytic gas sensors are calorimetric in
nature. The platinum heating coil raises the
internal temperature of the catalytic layer
to where any available combustible gas will
TABLE 1
This summary of the basic gas sensing methods includes their advantages, disadvantages and general areas of use. (Source: www.equipcoservices.com/support/reference/
ionization-potentials-of-common-chemicals)
Materials Advantages Disadvantages Target Gases and Application Fields
Metal Oxide
Semiconductor
Low cost
Short response time
Wide range of target gases
Long lifetime
Relatively low sensitivity and
selectivity
Sensitive to environmental factors
High energy consumption
Industrial applications and
civil use
Polymer
High sensitivity
Short response time
Low cost of fabrication
Simple and portable structure
Low energy consumption
Long-time instability
Irreversibility
Poor selectivity
Indoor air monitoring
Storage place of synthetic
products as paints, wax or
fuels
Workplaces like chemical
industries
Carbon
Nanotubes
Ultra-sensitive
Great adsorptive capacity
Quick response time
Low weight
Difficulties in fabrication and
repeatability
High cost
Detection of partial discharge
(PD)
Moisture
Absorbing
Material
Low cost
Low weight
High selectivity to water vapor
Vulnerable to friction
Potential irreversibility in high
humidity
Humidity monitoring
Optical
Methods
High sensitivity, selectivity and
stability
Long lifetime
Insensitive to environment
change
Difficulty in miniaturization
High cost
Remote air quality monitoring
Gas leak detection systems
with high accuracy and safety
High-end market applications.
Calorimetric
Methods
Stable at ambient temperature
Low cost
Adequate sensitivity for
industrial detection (ppth range)
Risk of catalyst poisoning and
explosion
Intrinsic deficiencies in selectivity
Most combustible gases under
industrial environment
Petrochemical plants
Mine tunnels
Kitchens
Gas
Chromatograph
Excellent separation
performance
High sensitivity and selectivity
High cost
Difficulty in miniaturization for
portable applications
Typical laboratory analysis
Accoustic
Methods
Long lifetime
Avoiding secondary pollution
Low sensitivity
Sensitive to environmental change
Components of Wireless
Sensor Networks
3. CIRCUIT CELLAR • OCTOBER 2017 #32764COLUMNS
burn on its surface. The additional heat from
this combustion changes the resistance of the
coil, which can be measured electronically.
The limit of detection (LOD) for calorimetric
sensors is typically in the low parts-per-
thousand (ppth) range.
You may recall from elementary school fire
prevention classes that there are three ways
to extinguish a fire: eliminate the fuel, the
air or the heat. A fire must have an adequate
supply of each of these to sustain combustion.
And our sensors must have these to operate
as well. Let’s takes a closer look at this. We’ve
just discussed how catalytic sensors use a
heating element in conjunction with a catalyst
to provide an adequate amount of heat to
sustain combustion. We must also have a
supply of oxygen (air) for our fuel to burn.
By volume, dry air contains 78.09% nitrogen,
20.95% oxygen, 0.93% argon, 0.04% carbon
dioxide and small amounts of other gases.
Air also contains a variable amount of water
vapor—on average around 1% at sea level.
Note: The minimum oxygen concentration for
normal human breathing is 19.5%. That’s not
much wiggle room!
Obviously in an area where the typical
atmosphere is artificially altered by the
introduction of a combustible gas, the ratio
of that gas to the oxygen content is changed.
Gases
Nonliquefied
Compressed Gas
Liquefied
Gas
Physical
Hazards
Flammable Limits
in Air (1) Vol %
Additional Gas Properties
Inert Corrosive Toxic
Acetylene (2) Flammable 2.5 - 100
Air X Oxidizer
Allene X Flammable 2.2 - n/a
Ammonia X Nonflammable 15 - 28 X
Argon X Nonflammable X
Arsine X Flammable 5.1 - 78 (4)
Boron Trichloride X Nonflammable X X
Boron Trifluoride X Nonflammable X (4)
1,3-Butadiene (5) Flammable 2 - 11.5
Butane X Flammable 1.8 - 8.4
Butenes X Flammable 1.6 - 10
Carbon Dioxide X Nonflammable X
Carbon Monoxide X Flammable 12.5 - 74 X
Carbonyl Sulfide X Flammable 11.9 - 28.5 (3) X
Chlorine X Oxidizer (3) (4)
Cyanogen X Flammable 6.6 - 32 (4)
Cyclopropane X Flammable 2.4 - 10.4
Deuterium X Flammable 4.9 - 75
Diborane X Flammable 0.8 - 98 (4)
Dimethylamine X Flammable 2.8 - 14.4 X
Dimethyl Ether X Flammable 3.4 - 27
Ethane X Flammable 3 - 12.4
Ethyl Acetylene X Flammable (7)
Ethyl Chloride X Flammable 3.8 - 15.4
Ethylene X Flammable 2.7 - 36
Ethylene Oxide (6) Flammable 3.6 - 100 X
Fluorine X Oxidizer (4)
Germane X Flammable (7) (4)
Halocarbon 12 X Nonflammable X
Halocarbon 13 X Nonflammable X
Halocarbon 14 X Nonflammable X
Halocarbon 22 X Nonflammable X
Helium X Nonflammable X
Hydrogen X Flammable 4 - 75
Hydrogen Bromide X Nonflammable (3) (4)
Hydrogen Chloride X Nonflammable (3) (4)
4. circuitcellar.com 65
COLUMNS
If the ratio is high in oxygen, there will be
too little gas to support combustion—a
lean mixture. On the opposite extreme, if
the ratio is high in gas, that means there is
too little oxygen to support combustion—a
rich mixture. That all illustrates that the
ratio has a sweet spot, outside of which
no combustion can take place. Each gas
has its own sweet spot or flammability
range. The flammability of any gas has
both a Lower Energy Level (LEL) point and
an Upper Energy Level (UEL) point. The gas
concentration between these two points
is known as the Flammability Range. This
range is different for each gas. A gas is
considered hazardous once 5% to 10% of
the LEL has been reached.
We just saw how our atmospheric content
is critical to our existence. Given that the
same is true of combustion, and that the LEL
is based on knowing the oxygen level, we can
either assume it is normal or measure it.
In open air or ventilated areas, you may be
able to assume the oxygen content. In closed
areas, this is not the case. With that in mind,
let’s look at oxygen measurement.
OXYGEN SENSOR
I chose the Winsen Electronics
Technologies ME2-O2 Electrochemical Sensor
TABLE 2
Gas mixtures assume the categories
of the components of the mixture,
with the predominant component
determining the final classification of
the mixture. The exception for gases
is when a component is toxic to a
degree sufficient to influence the final
classification. Table Copyright 2012
by the authors; licensee MDPI, Basel,
Switzerland. www.ncbi.nlm.nih.gov/
pmc/articles/PMC3444121
Gases
Nonliquefied
Compressed Gas
Liquefied
Gas
Physical
Hazards
Flammable Limits
in Air (1) Vol %
Additional Gas Properties
Inert Corrosive Toxic
Hydrogen Fluoride X Nonflammable X (4)
Hydrogen Sulfide X Flammable 4 - 44 (3) (3) (4)
Isobutane X Flammable 1.8 - 9.6
Isobutylene X Flammable 1.8 - 9.6
Krypton X Nonflammable X
Methane X Flammable 5 - 15
Methyl Chloride X Flammable 10.7 - 17.4
Methyl Mercaptan X Flammable 3.9 - 22 (4)
Monoethylamine X Flammable 3.5 - 14 X
Monomethylamine X Flammable 4.9 - 20.7 X
Neon X Nonflammable X
Nitric Oxide X Oxidizer (3) (4)
Nitrogen X Nonflammable X
Nitrogen Dioxide X Oxidizer (3) (4)
Nitrogen Trioxide X Oxidizer (3) (4)
Nitrosyl Chloride X Oxidizer (3) (4)
Nitrous Oxide X Oxidizer
Oxygen X Oxidizer
Phosgene X Nonflammable X (4)
Phosphine X Flammable 1.6 - 99 (4)
Propane X Flammable 2.1 - 9.5
Propylene X Flammable 2 - 11
Silane X Flammable 1.5 - 98
Sulfur Dioxide X Nonflammable (3) (4)
Sulfur Hexafluoride X Nonflammable X
Sulfur Tetrafluoride X Nonflammable X (4)
Trimethylamine X Flammable 2 - 12 X
Vinyl Bromide X Flammable 9 - 15
Vinyl Chloride (5) Flammable 3.6 - 33
Xenon X Nonflammable X
(1) Flammable limits are normal atmospheric pressure and temperature. Other conditions will change the limits.
(2) Dissolved in solvent under pressure. Gas may be unstable and explosive above 15 psig (1 bar).
(3) Corrosive in the presence of moisture.
(4) Toxic: It is recommended that the user be thoroughly familiar with the toxicity and other properties of this gas.
(5) Cancer suspect agent.
(6) Recognized human carcinogen.
(7) Flammable, however, limits are not known.
3OHDVH 1RWH +DOFDUERQ 'LFKORURGLÀXRURPHWKDQH +DORFDUERQ KORURWULÀXRURPHWKDQH +DORFDUERQ
7HWUDÀXRURPHWKDQH +DORFDUERQ KORURGLÀXRURPHWKDQH
5. CIRCUIT CELLAR • OCTOBER 2017 #32766COLUMNS
to monitor oxygen level. This type of sensor
generates a current and can be considered a
micro fuel cell. It consists of an electrolyte
specifically chosen for its reaction to the gas
of interest. Gas enters the sensor through
a hydrophobic barrier—to eliminate most
water from entering the sensor. The gas then
eventually reaches the electrode—a cathode
made of platinum, for example. Platinum is a
catalyst for the reduction of oxygen. Oxygen
atoms react with the electrolyte—potassium
hydroxide for example—producing hydroxyl
ions. Each resultant anion OH molecule has
a negative charge attributable to reduction.
O2 + 2H2O + 4e-- → 4OH--
These hydroxyl ions migrate through the
electrolyte carrying their negative charge
to the lead anode. They react with the lead
anode which is then oxidized into lead oxide.
The charge is lost through oxidation.
2Pb + 4OH-- → 2PbO + 4e-- + 2H2O
The water remains in the electrolyte.
The charge will produce a current when the
sensor’s cathode is connected to its anode
with an external resistor. The current—and
voltage—through the resistor is proportional
to the amount of O2 (OH) that moves through
the electrolyte.
I purchased an oxygen sensor with a
carrier PCB from LinkSprite that is similar to
other gas sensors—although the pin out is not
the same. I added a 4-pin header to make all
gas sensor connections the same. This project
will be based on the Arduino architecture.
Arduino provides lots of analog and digital
I/O and can handle floating point math, which
we’ll need to present concentration levels for
each sensor.
The schematic I used in this initial
experiment can be seen in Figure 1. It was
designed to take advantage of one analog
LISTING 1
The oxygen sensor application is in a generic form which will allow easy inclusion of additional analog sensors
as necessary.
//*****************************************
// ME2-O2 Declare Start
//*****************************************
const float VRef = 5.0; // voltage of adc reference
const int pinO2ADC = A0; // pin 54 is the first analog pin
const String SignOnO2=”ME2-O2 5/22/2017”;
//*****************************************
// ME2-O2 Declare Start
//*****************************************
byte debug=1;
//
void setup()
{
Serial.begin(9600);
//*****************************************
// ME2-O2 setup Start
//*****************************************
Serial.println(SignOnO2);
Serial.println(“Oxygen Sensor on pin:” + String(pinO2ADC));
//*****************************************
// ME2-O2 setup End
//***************************************** (continued)
! ! ! !) !* !+ ! !
!
!
!
) ) ) ) ) ) ) )
)
)
*
+
)
.' ('
16. % 5'
6
47 8
FIGURE 1
The physical layout of the connectors in this schematic place all of the gas sensors on the same plane. The PCB plugs onto an analog port of most Arduinos, with power and one
DIO coming from the Arduino’s SPI connector.
17. circuitcellar.com 67
COLUMNS
port (8 sensors) on the Arduino. Power—
and a single digital I/O—comes from the
ICSP 2x3 header. While all the gas sensors
have identical 4-pin connections, there is a
separate 4-pin connector for a humidity and
temperature sensor. We’ll get to this shortly.
Let’s begin with this oxygen sensor
connected to A0. The 4-pin sensor connector
will contain the following signals: VCC, ground,
digital out and analog out. While many of
the sensor carrier PCBs contain support
circuitry with a comparator for level sensing
(digital) output, I won’t be using this pin. The
switching level can be set via an on-board
pot. Basically, each sensor will provide an
analog output to the 10-bit A/D converter
of the Arduino. Each 4-pin sensor connector
has its analog output connected to a different
analog input pin. Support for each sensor will
therefore have three parts: definition, setup
and loop—and support routines. Listing 1
shows these for the oxygen sensor in our first
Arduino program.
The declare section initializes the floating
point 5.0 reference voltage we’ll be using in
all ADC calculations. We are designating a
connection to analog channel 0 (pin 54 on
the MEGA 2560) for the Oxygen sensor. I like
to use a SignOn message which includes the
program name and date in all my Arduino
programs. Once an Arduino has been
programmed with an application and gets
set aside, it is impossible to figure out what
it’s been programmed with unless you leave
yourself a trail of crumbs!
In the setup section, the serial port
is initialized for display (and debug) and
the SignOn message is sent out. For most
applications, the USB console port makes it
simple to display information. The main loop
handles access to the sensor support routines
for collecting data. This loop can be used
to continuously send formatted data to the
console. Here I use a debug flag to include
or skip intermediate data—such as analog
voltage measured from the port.
Two support routines are used for the
oxygen sensor: collect and concentration.
The collection routine handles requesting
the ADC’s representation of the analog input
voltage and converting this back to a voltage.
We know the ADC breaks the reference
voltage into 1,024 distinct voltage levels and
will compare each of these to the analog input
to find the closest match. You can query the
ADC to find out which one of those levels it has
determined is the closest to the actual input.
To convert this 10-bit digital representation
of the input voltage back into a voltage, we
need to know what voltage value each bit
represents. In this case the reference voltage
was defined as 5.0 V. This is divided by the ADC
(Listing 1 continued)
}
//
void loop()
{
//*****************************************
// ME2-O2 loop Start
//*****************************************
float Vout =0;
Vout = readO2Data();
if(debug 1)
{
Serial.print(“Vout =”);
Serial.print(Vout);
Serial.print(“ V, “);
}
//
float Concentration=0;
Concentration = calcO2Concentration(Vout);
Serial.print(“O2 is “);
Serial.print(Concentration);
Serial.println(“%”);
//*****************************************
// ME2-O2 loop Start
//*****************************************
delay(500);
}
//*****************************************
// ME2-O2 Support Start
//*****************************************
float readO2Data() // average 32 samples
{
long sum = 0;
for(int i=0; i32; i++)
{
sum += analogRead(pinO2ADC);
}
sum = 5;
float MeasuredVout = sum * (VRef / 1023.0);
return MeasuredVout;
}
float calcO2Concentration(float MeasuredVout)
{
// Vout samples are with reference to 5.0V
//float Concentration = 21%, when its output voltage is 2.0V,
float Concentration = MeasuredVout * 0.21 / 2.0;
float Concentration_Percentage=Concentration*100;
return Concentration_Percentage;
}
//*****************************************
// ME2-O2 Support End
//*****************************************
18. CIRCUIT CELLAR • OCTOBER 2017 #32768COLUMNS
resolution 1024-1 (10-bits) to get 4.9 mV/
bit. Multiply 4.9 m times the ADC conversion
number to get the input voltage represented
by that ADC conversion number. Note: The
calculated voltage isn’t exact, but should be
within +/- one-half bit of the actual voltage.
The higher the ADC resolution, the closer the
conversion will be. It’s typical for an analog
voltage to be a bit noisy, especially when
amplifiers are involved. Averaging multiple
ADC readings is a good way to smooth out
that fluctuation—unless that’s your data of
interest. For this sensor, we do this by taking
multiple samples and dividing their sum by
the number of samples.
The concentration routine calculates the
concentration of oxygen represented by
the analog voltage. The data sheet for the
oxygen sensor gives a graph that shows
the sensor’s output voltage in relation to
oxygen concentration. The carrier PCB has
an amplifier which multiplies this output to a
level that we can more easily measure by an
ADC using either a 3.3 V or 5.0 V reference.
This means its output must be less than
3.3 V. In this case 2.0 V indicates a 21%
concentration of Oxygen. The equation using
this fact is:
concentration
ADC voltage
volts
=
× 21
2 0
%
.
or
ADC voltage
volts
× 0 21
2 0
.
.
Notice when ADC voltage = 2.0 V, the 2.0s
cancel leaving 0.21 or 21%. And when ADC
voltage = 0 V we get 0/2.0 or 0%. The sensor
is rated to 25% (30% max).
HUMIDITY/TEMPERATURE
Ever notice how it gets more difficult to
breathe as the humidity goes up? For many
with chronic breathing issues, the only relief
is moving to a more suitable climate. The level
of discomfort we feel in high temperatures is
closely associated with the dew point. The
dew point is the temperature at which the
water vapor in a sample of air condenses
into liquid water at the same rate at which
it evaporates. At temperatures higher than
the dew point, evaporation is taking place
while lowering humidity. A relative humidity
of 100% indicates the dew point is equal to
the current temperature and that the air is
saturated with water. When the moisture
content remains constant and temperature
increases, relative humidity decreases.
All this is true for any given barometric
pressure.
When the air temperature is high,
the human body uses the evaporation of
sweat to cool down. The cooling effect is
directly related to how fast the perspiration
evaporates. And this directly relates to how
much moisture is in the air and how much
moisture the air can hold. If the air is already
saturated with moisture, perspiration will
not evaporate and you just remain sweaty.
As you might imagine, the concentration
of oxygen can be affected by both humidity
and temperature. Refer to the graph
in Figure 2 to see how they affect O2
concentration. Knowing this, it might be
good idea if we monitor both the humidity
and temperature to better understand what
is happening in our environment. From the
graph, we can see that with a high relative
humidity and temperature the O2 content
can become dangerously low.
I’ve chosen the combo humidity/
temperature sensor module from Seeed
Studio which uses the HDT11 sensor fromcircuitcellar.com/ccmaterials
RESOURCE
Tear down of catalytic sensor technology
(pages 1-3)
www.engineersgarage.com/insight/
how-gas-sensor-works
FIGURE 2
This graph shows how humidity and temperature affect the oxygen content of the atmosphere we breathe.
As the humidity increases the concentration of oxygen falls, which makes it more difficult for us to take in
adequate oxygen. (Source: Effect of Humidity and Temperature on Galvanic Oxygen Sensors
aii1.com/PDF/r_s_humd.pdf)
19. circuitcellar.com 69
COLUMNS
Aosong Electronics (Photo 1). You’ll note
the schematic (Figure 1) has one digital I/O
connection for this module as it will transmit
its data serially whenever the data line is
forced low for at least 18 ms. Once the sensor
sees a low on its data line for greater than
18 ms—and a release of the bus—it will wake
up and send an acknowledge consisting of a
low sink pulse of 80 ns and a release of the
bus (pull-up) for 80 µs.
The data consists of 40 bits: the one-
byte integer portion of the humidity followed
by one byte of the decimal portion of the
humidity value. The second two bytes are in
the same format for temperature. The final
byte is a checksum—the least significant byte
(LSB) of the total of the first 4 bytes. Each
bit is determined by the length of time the
data bus stays high after the bus has been
held low for 50 µs. A data=0 remains high
for only approximately 35 µs, however a
data=1 remains high for approximately 70 µs.
This means the sensor will again pull down
the bus to signify the end of the 40th bit.
The response should therefore take less than
5 ms. The sensor samples data in around
1 second, so it won’t help to read the data any
faster. Current consumption is about 1 mA
while active and 100 µA in standby.
While we don’t need to convert and data
from the sensor, we do need to receive and
interpret it. Refer to Listing 2 to see how
I chose to do this using the pulseIn()
command. We wake up the sensor with a
low pulse of a minimum of 18 ms, followed
by a release of the bus—changing the pin’s
mode to INPUT_PULLUP in preparation of the
senor’s response. The sensor will then send
an acknowledge pulse of 80 µs low and an
idle (high) of 80 µs. Here I look for HIGH
pulse in using pulseIn(pinDHT11, HIGH,
200)==0). NOTE: Since the bus is now HIGH
(pulled up) the command will wait for the input
to go LOW and then HIGH, before beginning
to measure the HIGH duration. The 200 is an
optional timeout (200 µs). We know response
from the sensor contains a low 80 µs pulse, so
if we don’t see one in 200 µs, then we escape
the routine and indicate an error (timeout)
condition.
If the response is seen, then we can
continue on receiving the next 40 bits or
5 bytes of data. The 5 bytes of data are
received via a call to the getAByte()
routine. These bytes contain the integer
and decimal data for the humidity and
temperature, plus a checksum byte—the LSB
byte of the total of the first 4 bytes. We can
compare the checksum and report any error
condition and then display any ‘good’ data.
The display format is “Humidity: x.x%” and
”Temperature: x.xC”.
The data for each of the 5 bytes is collected
by using pulseIn(pinDHT11, HIGH,
150). The data is determined by the duration
of the HIGH time for each data bit. A data bit
consists of a low pulse of 50 µs, followed by
an idle (HIGH) time of approximately 30 µs for
a data=0 and 70 µs for a data=1. I’m testing
the pulseIn() result first for ‘0’ to see if the
sensor is responding, and then greater than
35 µs to indicate a data=1, else data=0. I
keep track of the data via the variable Value
initialized to ‘0’. After each bit test, Value is
shifted left 1 bit and then ‘1’ is added only if
data=1. The data is received most significant
bit (MSB) first, so the shift is to the left.
ENVIRONMENTAL MONITORING
We’ll begin next month by looking at a few
of the inexpensive gas sensors available to
us as well as the general routines required
ABOUT THE AUTHOR
Jeff Bachiochi (pronounced BAH-key-AH-
key) has been writing for Circuit Cellar
since 1988. His background includes
product design and manufacturing. You can
reach him at:
jeff.bachiochi@imaginethatnow.com or at:
www.imaginethatnow.com.
PHOTO 1
This screenshot/photo shows the application output with the sensor array PCB hanging off the Arduino’s
analog port. The ME2-O2 oxygen sensor is plugged into slot ‘0’ (of 8). The DHT-11 humidity/temperature
sensor has its own digital port—sticking up with the blue box shaped sensor.
20. CIRCUIT CELLAR • OCTOBER 2017 #32770COLUMNS
//*****************************************
// DHT-11 Declare Start
//*****************************************
#define pinDHT11 52 // PB1 (D52)
byte dataDHT11[5];
const String SignOnDHT11=”DHT-11 5/22/2017”;
//*****************************************
// DHT-11 Declare End
//*****************************************
byte debug=1;
//
void setup()
{
Serial.begin(9600);
//*****************************************
// setup DHT11 Start
//*****************************************
pinMode(pinDHT11, OUTPUT); // sets the digital pin as output
digitalWrite(pinDHT11, HIGH); // sets the digital output high
Serial.println(SignOnDHT11);
//*****************************************
// setup DHT11 End
//*****************************************
}
//
void loop()
{
//*****************************************
// loop DHT11 Start
//*****************************************
if(readDHT11Data())
{
Serial.print(“Current humdity = “);
Serial.print(dataDHT11[0], DEC);
Serial.print(“.”);
Serial.print(dataDHT11[1], DEC);
Serial.print(“% “);
Serial.print(“temperature = “);
Serial.print(dataDHT11[2], DEC);
Serial.print(“.”);
Serial.print(dataDHT11[3], DEC);
Serial.println(“C “);
}
//*****************************************
// loop DHT11 End
//*****************************************
delay(2000);
}
//*****************************************
// DHT11 Support Start
//*****************************************
boolean readDHT11Data()
{
digitalWrite(pinDHT11, LOW); // force i/o pin low for 18ms
delay(18);
digitalWrite(pinDHT11, HIGH); // force i/o pin high for 40ms
delayMicroseconds(40);
pinMode(pinDHT11, INPUT); // 3. i/o pin now input and wait 40ms
delayMicroseconds(40);
byte inDHT11 = digitalRead(pinDHT11); // read state of i/o pin
if(debug 1) // report status errors?
{
if(inDHT11) // high? (continued)
LISTING 2
The DHT-11 humidity/temperature
sensor requires its own digital
communication routine. The sensor
is factory calibrated and reports in a
two-byte integer/decimal format for
humidity and temperature.
21. circuitcellar.com 71
COLUMNS
to convert the sensor’s data. Environmental
monitoring is being used to establish air
pollutant concentrations. Air monitors are
operated by citizens, regulatory agencies and
researchers to investigate air quality and the
effects of air pollution on us and our world.
Our fragile weather system is entangled with
what we put in the environment.
On January 23, 1978, Sweden announced
it would ban aerosol sprays containing
chlorofluorocarbons (CFCs) as the propelling
agent. Scientific evidence had mounted that
CFCs were damaging to Earth’s ozone layer.
Virtually every country on Earth ultimately
followed Sweden in banning CFCs, via an
international treaty known as the Montreal
Protocol by January 1, 1989. We are still
evaluating the results today, but monitoring
suggests there is evidence of a reversal. What
other pollutants could be affecting how the
atmosphere protects our world? Can we have
any significant impact on Mother Nature?
(Listing 2 continued)
{
Serial.println(“DHT-11 low condition illegal”);
pinMode(pinDHT11, OUTPUT); // sets the digital pin as output
digitalWrite(pinDHT11, HIGH); // sets the digital output high
return 0;
}
delayMicroseconds(80);
inDHT11 = digitalRead(pinDHT11);
if(!inDHT11) // low?
{
Serial.println(“DHT-11 high condition illegal”);
pinMode(pinDHT11, OUTPUT); // sets the digital pin as output
digitalWrite(pinDHT11, HIGH); // sets the digital output high
return 0;
}
delayMicroseconds(80);
}
for (byte i=0; i5; i++) // read 40 bits (5 bytes)
{
byte result=0;
for(byte j=0; j 8; j++)
{
while(!digitalRead(pinDHT11)); // wait for 50us
delayMicroseconds(30);
if(digitalRead(pinDHT11))
{
result |=(1(7-j));
}
while(digitalRead(pinDHT11)); // wait ‘1’ finish
}
dataDHT11[i]=result;
}
// 7. force i/o high as output
pinMode(pinDHT11, OUTPUT); // sets the digital pin as output
digitalWrite(pinDHT11, HIGH); // sets the digital output high
if(debug 1)
{
byte checksumDHT11 = dataDHT11[0]+dataDHT11[1]+dataDHT11[2]+dataDHT11[3];
if(dataDHT11[4]!= checksumDHT11)
{
Serial.println(“DHT-11 checksum error”);
}
}
pinMode(pinDHT11, OUTPUT); // sets the digital pin as output
digitalWrite(pinDHT11, HIGH); // sets the digital output high
return 1;
}
//*****************************************
// DHT11 Support End
//*****************************************
22. CIRCUIT CELLAR • NOVEMBER 2017 #32868COLUMNS
Jeff continues his exploration of gas monitoring and
sensing. This time he discusses some of the inexpensive
sensors available that can be applied to this application.
Jeff then tackles the factors to consider when calibrating
these sensors and how to use them effectively.
By Jeff Bachiochi
From the Bench
Gas Monitoring and Sensing (Part 2)
Putting the Sensor to Work
es
s t
ilab
ckle
rs a
ioc
COLUMNS
Jeff continu
sensing. Thi
sensors avai
Jeff then tac
these sensor
By Jeff Bachi
Last month’s article left you with
the question: “Can we have any
significant impact on Mother
Nature?” According to Simon Lewis,
an ecologist at University College London, and
geologist Mark Maslin of Leeds University, a
massive dip in carbon dioxide levels can be
seen in Antarctic ice cores dating back to
1620, when the Mayflower arrived in the New
World. They suggest this is the result of as
many as 50 million Native Americans dying
due to infectious diseases such as smallpox
brought over from Europe. As their numbers
dwindled, the resultant loss in agriculture
allowed forests to re-grow throughout the
Americas. These expanded forests scrubbed
the atmosphere of carbon dioxide.
Whether this makes sense to you or not,
you can’t help but see the effect we have
on water, air and soil. It’s hard to separate
any one of these from the others as they
are so entwined with the global weather of
our planet. The 2011 Tōhoku earthquake
and tsunami damaged nuclear facilities in
Fukushima. Dust particles contaminated with
radioactive cesium were found more than
100 miles from the site, and in April of that
same year, particles could be detected on the
West Coast of the U.S. We are all connected
caretakers of this planet and it's foolish to
think: “It doesn’t affect me.”
Fortunately for our planet, our health is
also being affected by these same pollutants.
While the planet can survive without us, we
can’t survive without the environment. But
it’s not all doom and gloom. Our civilization
is making small changes that protect us. The
weatherman warns us of unhealthy conditions,
such as the UV index and air quality levels.
Building codes now require carbon monoxide
detectors in addition to smoke alarms in our
homes. There are global discussions on CO2
reduction. Meanwhile, the recent withdrawal
from the Paris climate accord by the US
is unfortunate as it revokes our reduction
level promises. And in turn, meeting global
reduction goals is now in jeopardy.
It’s now more important than ever to be
able to identify and monitor those components
that jeopardize humankind. Air pollutants
can be blown either to a new location or
cleansed from low earth atmosphere by
weather conditions. While the atmospheric
cleansing process helps us breathe easier, it
really only changes the habitat of pollutants
from the air to the soil, where they can affect
crop growth and our food chain. Besides their
pollutant side effects, technology has given us
23. circuitcellar.com 69
COLUMNS
the ability to measure those harmful/valuable
elements around us. The oxygen content
makes up only around 20% of our breathable
atmosphere. Yet its concentration is critical to
life and other functions, such as combustion,
that we take for granted every day.
LOOKING BACK
Last month we looked at the principal
ways in which a gas might be measured. One
of those methods is by measuring the heat
produced through catalytic combustion. This
type of sensor is constructed of a catalytic
bead impregnated with a special catalyst that
promotes oxidation and a fine platinum wire
embedded in the bead. Current is passed
through a heating element causing the bead
to reach a temperature at which oxidation
of a gas readily occurs (about 500°C). The
combusted gas raises the temperature further
which increases the resistance of the platinum
coil in the catalyzed bead. This change can be
measured, and is linear for most gases.
Note that a minimum oxygen content is
required for oxidation to take place. It only
made sense to begin this project by measuring
oxygen content. This was accomplished by
using a ME2-02 sensor. Its output, like most
gas sensors, have been tailored to present
an analog voltage output that is related to
gas concentration. I began the project using
an Arduino to provide access with at least
8 analog inputs capable of measuring input
voltage with a precision of 10 bits or 4.9 mV
per bit (5V / 1024 bits = .0049 V). Another
advantage of using an Arduino is its friendly
math functions including floating point
arithmetic that makes analog conversions
much easier—and more precise.
Before concluding the last article, I added
another sensor that also has a bearing on
how gases react. Humidity and temperature
can affect the concentration of gas in the
atmosphere, so I added a DHT-11 combination
sensor that communicates digitally via a
1-bit bus. This sensor is factory calibrated to
output humidity and temperature whenever
it recognizes that the normally high idle
bus state is forced low for at least 18 ms.
It outputs the integer value and decimal
value of the humidity followed by the integer
value and decimal value of the temperature
along with checksum (LSB of the sum of the
previous 4 bytes).
A simple application was presented
to demonstrate acquiring data for these
sensors. Now it’s time to discuss some of
the available catalytic pellistor type sensors
that can be used in this project. Table 1 is a
list of the inexpensive sensors I picked up to
Sensor Sensing Resistance Heater Resistance in Gas = Resistance in Air Suggested Other Gases
MQ-2 2 kΩ - 20 kΩ 5 V (1,000 ppm H2) hydrogen
LPG, methane, carbon monoxide, alcohol,
propane
MQ-3 2 kΩ - 20 kΩ 5 V (0.4 mg/l OH) alcohol hydrogen, methane, carbon monoxide
MQ-4 2 kΩ - 20 kΩ 5 V (5,000 ppm CH4) methane hydrogen, LPG, carbon monoxide, alcohol
MQ-6 2 kΩ - 20 kΩ 5 V (2,000 ppm C3H8) LPG/propane
hydrogen, methane, carbon monoxide,
alcohol
MQ-7 2 kΩ - 20 kΩ 5 V / 1.5 V
(100 ppm CO) carbon
monoxide
hydrogen, methane
MQ-8 10 kΩ - 60 kΩ 5 V (1,000 ppm H2) hydrogen LPG, methane, carbon monoxide, alcohol
MQ-9 2 kΩ - 20 kΩ 5 V / 1.5 V
(600 ppm CO) carbon
monoxide
LPG, methane
MQ-135 2 kΩ - 20 kΩ 5 V (100 ppm NH3) ammonia hydrogen, sulfide, benzene
MQ-137 2 kΩ - 15 kΩ 5 V (50 ppm NH3) ammonia hydrogen, ethanol
MQ-138 2 kΩ - 20 kΩ 5 V (50 ppm toluene) methanol, acetone, ethanol, hydrogen
MQ-216 30 Ω – 200 Ω 6 V (1,000 ppm) isobutane LPG, methane, alcohol, propane
MQ-
303A
4 kΩ - 400 kΩ 0.9 V
(1,000 ppm) alcohol
RS/RO=0.1
butane, hydrogen, ethanol
MQ-
306A
2 kΩ - 200 kΩ 0.9 V
(1,000 ppm) butane
RS/RO=0.1
methane, hydrogen, ethanol
MQ-
309A
2 kΩ - 20 KΩ
0.9 V /
0.2 V
(1,000 ppm CH4) methane hydrogen, ethanol, carbon monoxide
TABLE 1
Here are a few gas sensors you can find for sale on the internet. Carrier PCBs are also available that run on 3.3 VDC to 5 VDC. Most have both analog and digital outputs. The
digital output switching point can be set with an on-board pot.
24. CIRCUIT CELLAR • NOVEMBER 2017 #32870COLUMNS
experiment with. Many portable instruments
use these sensors in their products. Most
handheld instruments are designed for one
particular gas of interest, but you will find
that most are sensitive to multiple gases. Lets
use the first one on the list—MQ-2 (hydrogen)
sensor—to illustrate how they are to be used.
LOOKING FORWARD
The MQ-2 sensor is optimized for
measuring hydrogen. This means the
sensor materials have been selected to have
optimum response to hydrogen. The MQ-2’s
data sheet presents a graph (Figure 1) of
the sensor’s sensitivity to specific gas as its
resistance ratio to parts per million (ppm) gas
concentration. It’s resistance ratio is unity at
1000 ppm of hydrogen. This resistance ratio
is the resistance of the sensor at different
concentrations of gas over its reference
resistance at 1,000 ppm. The graph also
shows a minimum and maximum ppm that
can be measured using the sensor. The span
of concentration can be considered linear.
It might help to see this graph presented
with its base 10 representation (Figure 2).
You’ll note that with two points on the graph’s
H2 (hydrogen) line we can determine its slope.
This slope represents the resistance of the
sensor as it changes due to gas concentration.
Using one reference point (at 1,000 ppm) and
the line’s slope, we can project where the
sensor might see say 1 ppm hydrogen. It is
a point about 1.5 times greater than that of
the reference point (at 1,000 ppm). In reality,
there is some amount of hydrogen in ‘fresh’
air and the graph in Figure 1 has this as the
horizontal line labeled ‘air’.
Why is this important? We don’t know the
actual resistance of the sensor. If we could
apply exactly 1,000 ppm of hydrogen to the
sensor and measure its resistance, we would
have a calibrated resistance for this reference
point and could base all measurements from
this calibration point. If you want to truly
calibrate the sensor, you will need to have
access to a supply of gas in this concentration.
For this project, I will use fresh air as the
calibration point. Calculating this reference
point (as explained earlier) gives us a place to
start, because we can measure the sensor‘s
resistance while exposed to fresh air.
ANALOG
The datasheet suggests using a load
resistor of from 5 kΩ to 47 kΩ for this sensor.
I’ve found my carrier boards to have a 1 kΩ
resistor in this location. This simplified circuit
shows a 1 kΩ resistor from the analog input
Air
Hydrogen
Lpg
Alcohol
Carbon monoxide
Methane
Propane
10
1
0.1
100 1,000 10,000
ppm
Ratio
FIGURE 1
This is the sensitivity graph from
the MQ-2 hydrogen gas sensor data
sheet. Note the range of the sensor is
from 200 ppm to 10,000 ppm.
Slope = (0.3–[−0.5])⁄(2.3–4) = −0.8⁄1.7 = –0.47
(100) 2
(10) 1
(1) 0
(0.1) –1
H2
(31.6)
(2.05)
(200) (0.31)
(0.1)–1 (1)0 (10)1 (100)2 (1,000) (10,000) (100,000)
FIGURE 2
The log-log graph from Figure 1 has been labeled with base 10 in parenthesis. The values from Figure 1 are
in the yellow oval. Note the slope is extended to the estimated point of intersection for 1 ppm. The slope of
the H2 sensor can be calculated at -0.47. Since we know the reference point at 1,000 ppm is (0,3) and the
slope of the line, we can calculate the point on the x axis (x,0) as 0 - 3= -3. Here’s the math: -3 x -0.47 =
1.41 (1.41, 0). This point references the resistance of the sensor with no hydrogen.
25. circuitcellar.com 71
COLUMNS
to ground, with the sensor between +5 V and
the analog input:
+5V-----RX-----A0-----1K-----GND
If the resistance of the sensor RX =
1 kΩ, then the +5 V is equally divided and
+2.5 V is applied to the analog input. As the
RX increases, the analog voltage goes down.
As RX decreases, the analog voltage goes up.
The change is not linear however. The best
resolution occurs around the point where the
load resistor equals the sensor resistance at
the 1,000-ppm reference point.
Table 2 shows the relationship between
the load resistor across the analog input and
a change in sensor resistance due to gas
concentration. The most accurate readings will
be when the two are equal. This will diminish
greatly as the sensor’s factor surpasses 10
either way (either 1/10 or 10x). Note that with
R1 = 1 kΩ, if the sensor’s resistance is either
less than 1/10th of R1 or greater than 10 X R1,
then the ADC voltages quickly approach values
that can no longer be differentiated. Hold that
thought for now and look more closely at the
resistance of the sensor in fresh air.
Using the application previously written
for the humidity/temperature and oxygen
sensors, we can add an additional sensor
to analog input 1 and print out the voltage
measurement from the stock carrier board.
Assuming we have fresh air conditions, the
gas concentration should be about nil. With
the Arduino powered from USB, the Vref =
4.67 V. The MQ-2 sensor reads 0.31 V. From
this we know two things: the voltage across
the sensor Vx = 4.67 (Vref) - 0.31 (ADC) or
4.35 V, and the current through R1 =0.31 V
/ 1,000 Ω or 0.31 mA. This current also runs
through the sensor, so its resistance must be
4.35V/0.00031A or 14,032 Ω in fresh air.
V
raw ADC value
L
ref
=
×' ' V
1023
(VL is the voltage calculated across RL from
the ADC value)
float VL
ref
analogRead(chanel)
V
= ×
1023 0.
VS ref L
= −V V:
(voltage across the sensor =
Voltage Reference - VL)
IL
L
=
V
1000
(current through RL = voltage across the load
resistor/its value)
R
I
S
S
L
=
V
(resistance of the sensor = voltage across the
sensor/current through it)
Putting those together:
R
V
V V V
V
R channel
V
S
ref L
L ref L
L
S
r
=
−⎛
⎝⎜
⎞
⎠⎟
= ×
−( )
= ×
V
1000
1000
1000[ ] eef L
L
V channel
V channel
−( )[ ]
[ ]
Note: The actual code uses arrays for
some values. This will allow the same routine
to be used for additional sensors.
The sensor resistance (in fresh air) is just
less than 10 times (from the graph) that of the
resistance at 1,000 ppm. So, we can set RO
= 14032/10 or 1403 Ω. This is our calibration
reference. From here on out we’ll use this
with actual measurements to determine
the sensitivity RS/RO and to determine gas
concentration along with the slope. Ideally,
we like to have our RL equal to that. The
carrier board has a 1 kΩ resistor on it so we’ll
work with that. We determine the slope using
points taken from the graph.
Here’s the math to determine the slope:
MQ2[] = {2.10, 200, 0.31, 10000};
where data is X and Y values for 2 points on the
graph: {point 1X, point 1Y, point2X, point 2Y}
X1=pow(10, MQ2[0]);
X2=pow(10, MQ2[2]);
Y1=pow(10, MQ2[1]);
Y2=pow(10, MQ2[3]);
slope = Y1-Y2 / X1-X2;
slope = 0.32 - (-0.51) / 2.3 -4 = 0.83/1.7 = -0.49
1,000 ppm is equal to 0.1% concentration. So,
this sensor (when RL = RS at 1,000 ppm) will most
accurately measure 0.02% to 1% concentration.
You can see that selecting a fixed-load resistor
is important to the how the measured voltage
will relate to the gas concentration.
SENSOR MEASUREMENT VS
CONCENTRATION
We now have the basics to determine the
sensor’s resistance and the data required
to extrapolate how a new sensor resistance
relates gas concentration based on the
TABLE 2
This shows the relationship between
the load resistor across the analog
input and a change in sensor
resistance due to gas concentration.
The most accurate readings will be
when the two are equal. This will
diminish greatly as the sensor’s factor
surpasses 10 in either direction—
either 1/10th or 10x.
R1 RX A0 Voltage Tap (with Vref= 5 V)
1 kΩ 100 Ω (1/10 of R1) 4.54 V
1 kΩ 1 kΩ (=R1) 2.5 V
1 kΩ 10 kΩ (10 times R1) 0.45 V
26. CIRCUIT CELLAR • NOVEMBER 2017 #32872COLUMNS
calibration resistance of 0 ppm. Again, we can
start with the slope. We know point2 X2 and
Y2 from MQ2[] and the slope (-0.47).
When we use log(RS/RO) for Y1, we can
solve for X1 like this:
slope = (log(RS/RO)-Y2) / (X1-X2)
slope x (X1-X2) = (log(RS/RO)-Y2))
X1-X2 = (log(RS/RO)-Y2) / slope
X1 =((log(RS/RO)-Y2)/slope)+X2
Next, un-log the result to get the ppm.
ppm channel
pow
RS
RO
Y
slope
X
[ ]
,
log
=
−
+
⎛
⎝
⎜
⎜
⎜
⎞
⎠
⎟
⎟
⎟
⎛
⎝
⎜
⎜
⎜
⎞
⎠
⎟
⎟
⎟
10
2
2
So, if the sensor measurement is RS= 1403
then we have:
ppm channel
pow
[ ]
,
log .
.
=
− −( )
−
+
⎛
⎝
⎜
⎜
⎜
⎞
⎠
⎟
⎟
⎟
⎛
⎝
⎜
10
1403
1403
0 51
0 49
4⎜⎜
⎜
⎞
⎠
⎟
⎟
⎟
ppm channel
pow
[ ]
,
log .
.
=
( )− −( )
−
+
⎛
⎝⎜
⎞
⎠⎟
⎛
⎝
⎜
⎞
⎠
⎟10
1 0 51
0 49
4
ppm channel pow[ ] ,
.
.
=
− −( )
−
+
⎛
⎝⎜
⎞
⎠⎟
⎛
⎝
⎜
⎞
⎠
⎟10
0 0 51
0 49
4
ppm channel pow[ ] ,
.
.
=
−
+
⎛
⎝⎜
⎞
⎠⎟
⎛
⎝⎜
⎞
⎠⎟10
0 51
0 49
4
ppm channel pow[ ] , .= − +( )( )10 1 04 4
ppm channel pow
ppm channel
[ ] , .
[ ]
= ( )( )
=
10 2 96
912
With the data points estimated from the
data sheet graphs, the calculations are within
about 9% of the actual reference point (at
1,000 ppm). Perhaps we could have better
results with more accurate data? Actually,
there are applications that enable you
to extract data from graphs. I found
WebPlotDigitizer online at arohatgi.info/
WebPlotDigitizer/app. This browser based app
lets you import a picture of a graph, calibrate
the axis, pick data points and present a list
of the points. I copied the MQ-2 graph and
picked off the end points of each element.
Figure 3 shows this graph and the data.
So far, we’ve dealt with only H2, but I took
extracted data for all the graph elements.
If I use the data for H2 from this list for
the calculations above, the error between
calculated and reference gets cut in half.
This shows the importance of the data GIGO
(Garbage In, Garbage Out) concept. While a
sensor is optimized for a specific element,
it will also be sensitive to other elements.
This means that a particular sensor will be
affected by other elements and you may be
seeing concentrations of those. It is important
therefore, to know what gasses you are
expecting in your environment.
ADDING ADDITIONAL SENSORS
With the basics down for calculating gas
concentration, I added not only the other
FIGURE 3
Using the WebPlotDigitizer app, I prepped by scanning this graph and downloading it into the application on
line. After picking two X and Y axis points along with the data of interest, the app listed all the points with X
and Y coordinates. I captured the data and entered it into my application.
WebPlotDigitizer app scanned the plot above
and output the following:
9.292391310855573, 200.5202666126466
9.464455149705113, 9999.99999999996
5.261572243931346, 200.5202666126466
1.4041398293327734, 9999.99999999998
3.0343921987338427, 200.5202666126468
0.712179783743607, 9999.99999999998
2.8196759701242295, 200.5202666126468
0.6497540631502284, 10000
2.0641489636309776, 200.5202666126468
0.335657545405408, 10000
1.6869089152540644, 200.5202666126468
0.27939275455712637, 10000
1.5675417746311666, 200.5202666126468
0.25026860594701816, 10000
27. circuitcellar.com 73
COLUMNS
LISTING 1
Shown here is the data for a typical complete sensor, the MQ-2 in this case.
gasses listed on a sensor’s data sheet, but
also seven other sensors for a total of eight—
including oxygen. It was easy to add these using
the WebPlotDigitizer application mentioned
earlier. The data for a typical complete sensor,
like the MQ-2, is seen in Listing 1.
In most cases you won’t have a need to use
eight sensors. This project assigned particular
sensors to the first eight analog inputs on
the Arduino Mega board. One of the effects
of using a full complement of eight sensors
is the total current needed power them—
especially from a USB port. Each sensor adds
up to 200 mA to the circuit current. A USB
hub will limit current to 100 mA unless it is a
powered hub, which limits current to 500 mA.
Therefore, a full complement of sensors will
cause a shut down USB—putting the hub in
self-preservation mode.
Applying external power through the
on-board Arduino regulator has problems
as well. The regulator on my Mega is the
NCP1117ST50T3G. This is a surface mount
SOT-223 part that can handle 1 A at 12 V.
You couldn’t heatsink enough heat away from
this device at those levels. The 5.0 V fixed
regulation would drop 7 V across it and at
1 A that would result in 7 W. This is a low-
drop out regulator that requires at least
1.2 V for regulation. With a 7 V input and a
full complement of sensors, that would be
approximately 640 mA which is greater than
1.3 W (2V x 0.64A). Still quite warm for such a
tiny device. If all eight sensors were required,
you could power the board from an externally
regulated wall wart power supply. For many
this won’t be an issue, but it was of concern
to me in this project.
With an analog input left unconnected (no
sensor plugged in) the analog reading just
floats around. That’s because there is no real
load of any kind on the input. I added a high
resistance load across each input that would
not interfere with a sensor when plugged in.
This causes the input to get pulled to ground
when no sensor is connected. In the calibration
routine that runs every time the application is
started, I calculate RO[channel] to determine
whether or not a sensor is attached and give
an appropriate message when necessary.
All the sensor datasheets suggest each
sensor be preheated or burned in for 48
hours prior to trusting any output. This must
be repeated if the sensor is left unpowered
for any great length of time. This can easily
be seen with the oxygen sensor. When
powered up in fresh air after a period of non-
use, I found concentration levels that could
not possibly sustain human life. We know the
normal oxygen concentration should be around
20% to 23%. It began producing a reasonable
output in less than an hour. Photo 1 shows
the setup with a full complement of sensors
and truncated application output.
SENSOR INCOMPATIBILITY
You’ll note that I used only 5-V compatible
sensors with the circuit presented last month.
Of the list of sensors in Table 1, a few sensors
require heater voltages other than 5 V. In fact,
for proper operation some sensors require
two heater voltages. A change in heater
voltage (temperature of the pellistor) can be
used to adjust combustion temperatures for
specific gases. Or it might be used to burn off
contaminants that would affect the reading of
a gas.
You may need to design a special
circuit for using one of these sensors. The
//*****************************************
// MQ-2 Declare Start
//*****************************************
const int pinMQ2ADC = A1; // pin 55 is the second
analog pin
const String SignOnMQ2=”MQ-2 6/12/2017”;
const int MQ2Elements = 7;
const float MQ2[(MQ2Elements*5)+1] = {
0, 9.108990, 200.0, 9.420527, 10000.0,
5, 5.261572, 200.0, 1.404139, 10000.0,
8, 3.034392, 200.0, 0.712179, 10000.0,
1, 2.819675, 200.0, 0.649754, 10000.0,
6, 2.064148, 200.0, 0.335657, 10000.0,
9, 1.686908, 200.0, 0.279392, 10000.0,
7, 1.567541, 200.0, 0.250268, 10000.0}; //
Sensitivity from graph [gasNames[],Y1,X1,Y2,X2]
float MQ2Slope[MQ2Elements+1];
float MQ2PPM[MQ2Elements+1];
//*****************************************
// MQ-2 Declare End
//*****************************************
Where the gas list is:
String gasNames[]={
“Air”,”Alcohol (OH)”,
“Ammonia (NH3)”,
“Benzine “,
“Butane (C4H10)”,
“Carbon Monoxide (CO)”,
“Hydrogen (H2)”,
“Liquid Propane Gas (Propane/Butane)”,
“Methane (CH4)”,
“Propane (C3H8)”,
“Hexane (C6H14)”,
“smoke “,
“Carbon Dioxide (CO2)”,
“Toluene (CH3)”,
“Acetone ([CH3]2CO)”};
28. CIRCUIT CELLAR • NOVEMBER 2017 #32874COLUMNS
carrier boards that came with most of my
sensors have one leg of the heater and the
measurement electrode tied together. This
means whatever voltage you supply is applied
to both the heater and the measurement
electrode. That particular arrangement
doesn’t allow for separate voltages for the
heater and measurement electrode. This is
interesting since the MQ-7 and MQ-9 require
high and low heater voltages, and the carrier
board does not allow separating the heater
from the electrode.
Sensors like the MQ-7 require an upper
heater voltage of 5 V and a lower voltage of
1.5 V. There are a number of ways to do this.
Using a PWM produced from the Arduino, you
can charge a cap to various levels. The sensors
require up to 200 mA and the Arduino cannot
source that amount of current. As a result,
the PWM must drive a transistor that would
obtain current from an external source. While
the Arduino Mega can produce separate PWMs,
you may want to use extra analog inputs to
monitor that the PWM produced voltages
are correct. This requires coding closed loop
regulation for each channel in order to see
whether the voltages remain within specs.
Hmm...that might make a good project in itself
for a future article!
I suggest using an adjustable regulator
instead. The LM317 has been around for a
long while and is used to produce any voltage
from 1.2 V to 37 V, with sufficient input.
Two additional resistors are required to set
the regulation output level. Figure 4 shows
what this circuit would look like—using one
circuit for each sensor for individual control.
When you use a regulator like the LM7805, it
has a GND terminal and regulates its output
based on the voltage between the ground
terminal and the output terminal. You’ll
note the LM317 labels this pin as “adjust.”
It works the same way. It regulates the
voltage on its output pin to 1.25 V, based on a
240 Ω resistor from adjust to Vout. With 1.25
V across the 240 Ω resistor we get a current
through this resistor of 1.25V/240Ω or
5.2 mA. If a second resistor is placed from
the adjust pin to ground, then the 5.2 mA
will also flow through this second resistor.
If this resistor is also 240 Ω then we’ll have
another 1.25 V drop across it, for a total drop
of 2.5 V from Vout to ground. And, voila: a
2.5 V regulator.
There is a formula for figuring out what
that resistor value must be to produce a
required output voltage. It can be calculated
by rearranging the formula as follows:
Vout = 1.25V x (1+(R2/R1))
Vout / 1.25V = 1 + (R2/R1)
(Vout / 1.25) -1 = R2/R1
((Vout / 1.25) -1) x R1 = R2
((5V / 1.25) – 1) x 240 = R2
(4 – 1) x 240 = R2
3 x 240 = R2
720 = R2
By using a 720 Ω resistor as R2, we get 5 V
at Vout. From previous discussions we saw that
the MQ-7 requires 1.5 V as well as 5 V, so we
also need a 1.5 V regulator. Using the above
formula, we would find that replacing the
720 Ω resistor with a 48 Ω resistor would
produce a Vout of 1.5 V. In the schematic that
a second resistor R3 is in parallel with R2,
with a transistor that can both connect it and
disconnect it from the circuit.
There are two things that come into play
here. First, the value of 48 Ω in parallel with
720 Ω has an effective resistance of 34 Ω—
which would produce a Vout = 1.48 V (a bit
low). Second, with the transistor OFF (Control
= 0 V) it will look like an almost infinite
resistor and will have little effect on R2. When
Control is brought high, the transistor turns
ON and its resistance goes way down. How far
depends on the base current and transistor
gain. However, the low current (5.2 mA)
through the transistor keeps the transistor’s
CE drop to a minimum. This will also affect
the total series resistance of the transistor
and R3—and ultimately the series equivalent.
A digital output signal from the Arduino can
then be used to switch between the two output
voltage levels. I’ll leave the coding issue up
to the you for this. You’ll find that the multi-
voltage sensors have timing associated with
each voltage level and a proper point in time
in which to measure them. Enough said here.
PHOTO 1
As shown here, my application for
this project will dump the measured
concentrations for all connected
sensors in one big list. Also shown
is the sensor PCB I’ve wired to the
Arduino’s analog port.
For detailed article
references and additional
resources go to:
www.circuitcellar.com/
article-materials
RESOURCES
Arduino | www.arduino.cc
29. circuitcellar.com 75
COLUMNS
GAS SENSOR CALIBRATION
Gas sensors need to be calibrated and
periodically checked to ensure sensor
accuracy and system integrity. Normally, a
monthly calibration is adequate to ensure the
effectiveness of each sensor and to maintain
the system’s accuracy. Calibration of the gas
sensor involves two steps. The “zero” must be
set and then the “span” must be calibrated.
In this project, we used fresh air as the zero
point to establish the sensor‘s base resistance
and the slope was taken from the datasheet’s
graph. A point and slope determined the
concentration. The span in the calibration
sense is taking a second point to determine
slope. Each point comes from using a test gas
of a known concentration, both fresh air and
concentrated. The sensor readings with the
test gas become the calibration points. The
slope can then be calculated using those two
points, reading 1 at 0% concentration and
reading 2 at ?% concentration.
Test gases are bottled in pressurized
cylinders of many sizes and pressures.
Essentially, the gas of interest is mixed with
fresh air to a specific concentration. When you
expose the flow from the tank to the sensor,
it will provide a reading of that concentration.
You might want to put the sensor into an
empty zip lock bag and add gas to the bag.
This keeps the gas from dissipating into the
environment before you had a chance to get a
stable reading. When using liquids, it is much
more difficult as you need to know how much
liquid to add to a container of known volume—a
zip lock for instance. You might want to use
a micro syringe to measure the chemical and
add it to the zip lock bag. Once the liquid has
vaporized in the container the concentration
can be made. The volume can be calculated
with this equation:
Volume of Chemical
C Volume of Air
Molecular Weight of
ppm
=
× ×
CChemical
Density of Chemical24 5 109
. × ×
COMMON SENSE
Be aware that the gas of interest may
be heavier or lighter than fresh air, so when
indoors you will want to locate the sensor
appropriately—either at ceiling or floor level.
When there is forced air movement (HVAC)
remember that air currents will move the
gas and you will want to locate the sensor
downwind. Sensors should be located as
close to any potential leak source as possible.
Dispersion will reduce readings if the sensors
are any distance from the potential spill or leak.
Sensors should be protected from immersion
or direct contact with water (check humidity).
A catalytic sensor must be installed in a
vertical position, with the sensing elements
pointed at the floor. This prevents the sensing
elements from collecting moisture, and the
flame arrestor from becoming clogged.
Our homes are protected from fire by
particle monitoring smoke detectors and
from dangerous levels of uncombusted gases
by carbon monoxide detectors. It is suggested
that paints, thinners, gasoline and other VOCs
(volatile organic compounds) be stored
outside of the home to protect inhabitants
from the buildup of potentially hazardous
gasses. When this is not possible or in an
industrial environment, it only makes sense
to protect people and property from these
issues. Low-cost gas concentration sensors
can be used to monitor the environment and
indicate when an unsafe condition exists.
ABOUT THE AUTHOR
Jeff Bachiochi (pronounced BAH-key-AH-
key) has been writing for Circuit Cellar
since 1988. His background includes
product design and manufacturing. You can
reach him at:
jeff.bachiochi@imaginethatnow.com or at:
www.imaginethatnow.com.
-
30. )
* . .
!/
)
0
1!
231
4
2
2
2
2)
2
5
89:;!
$4
; % = 0 0
FIGURE 4
The LM317 adjustable regulator can be used to provide a programmable regulated voltage. The voltage is
programmed via a resistor divider between ground, the regulator ‘adj’ terminal and output terminal. The
resistor-to-ground is calculated for any specific regulated output between 1.2 V and 37 V (assuming a Vin
at least 5 V Vout). Here a parallel resistor can be switched in and out to change the regulation output
between two voltages.
31. 1 www.handsontec.com
Handson Technology
Data Specs
MQ-3 Alcohol Sensor Module
MQ-3 gas sensor has high sensitivity to alcohol, and has good resistance to disturbances of gasoline, smoke and
vapor. The sensor could be used to detect alcohol with different concentration; it is with low cost and suitable
for different application. Sensitive material of MQ-3 gas sensor is SnO2, which with lower conductivity in clean
air. When the target alcohol gas exists, sensor’s conductivity is proportional to the gas concentration.
SKU: SSR-1000
Description:
Model No: MQ-3.
Heater voltage: 5±0.2V.
Loop voltage: ≤24V (DC)
Load resistance: Adjustable.
Heating Resistance: 31Ω±3Ω (Room temperature).
Heating Power: ≤ 900mW.
Surface thermal resistance: 2Kohm-20Kohm (0.4mg/L alcohol).
Sensitivity: Rs (in air)/Rs (0.4mg/L alcohol) ≥ 5.
33. 3 www.handsontec.com
Application Example with Arduino Uno:
Connect the MQ-3 alcohol sensor module to Arduino Uno board as shown below:
Upload the below sketch to Arduino Uno board:
/* MQ-3 Alcohol Sensor Circuit with Arduino */
const int AOUTpin=A0; //the AOUT pin of the alcohol sensor goes into analog pin A0 of the arduino
const int DOUTpin=8; //the DOUT pin of the alcohol sensor goes into digital pin D8 of the arduino
const int ledPin=13; //the anode of the LED connects to digital pin D13 of the arduino
int limit;
int value;
void setup() {
Serial.begin(115200); //sets the baud rate
pinMode(DOUTpin, INPUT); //sets the pin as an input to the arduino
pinMode(ledPin, OUTPUT); //sets the pin as an output of the arduino
}
void loop()
{
value= analogRead(AOUTpin); //reads the analaog value from the alcohol sensor's AOUT pin
limit= digitalRead(DOUTpin); //reads the digital value from the alcohol sensor's DOUT pin
Serial.print( Alcohol value: );
Serial.println(value); //prints the alcohol value
Serial.print(Limit: );
Serial.print(limit); //prints the limit reached as either LOW or HIGH (above or underneath)
delay(100);
if (limit == HIGH){
digitalWrite(ledPin, HIGH); //if limit has been reached, LED turns on as status indicator
}
else{
digitalWrite(ledPin, LOW); //if threshold not reached, LED remains off
}
}
34. 4 www.handsontec.com
Open up the Serial Monitor with Baud rate of 115200, the alcohol level detected will be shown as analog value.
The alcohol limit value can be set with sensitivity potentiometer: if the alcohol level detected is below the set
limit, the D0 green indicator will be off. If detected alcohol level is beyond the set limit, the DO LED will light
up.
35. 1 www.handsontec.com
Handson Technology
Sensors Selection Guide
MQ-3 Alcohol Sensor
HX711 Load Cell Sensor ADC Module 10KG Load Cell Weigh Sensor
MQ-2 Gas Sensor PIR501 Motion Detector Capacitive Touch Sensor
DS18B20+ Digital Temperature
Sensor
ACS712 Hall Current Sensor
HC-SR04P Ultrasonic Sensor
MPU6050 Accelerometer/ Gyro
Sensor HT1209 Digital Thermostat
36. 2 www.handsontec.com
Handsontec.com
We have the parts for your ideas
HandsOn Technology provides a multimedia and interactive platform for
everyone interested in electronics. From beginner to diehard, from student
to lecturer. Information, education, inspiration and entertainment. Analog
and digital, practical and theoretical; software and hardware.
HandsOn Technology support Open Source Hardware (OSHW)
Development Platform.
Learn : Design : Share
www.handsontec.com
37. 3 www.handsontec.com
The Face behind our product quality…
In a world of constant change and continuous technological development, a new or replacement
product is never far away – and they all need to be tested.
Many vendors simply import and sell wihtout checks and this cannot be the ultimate interests of
anyone, particularly the customer. Every part sell on Handsotec is fully tested. So when buying from
Handsontec products range, you can be confident you’re getting outstanding quality and value.
We keep adding the new parts so that you can get rolling on your next project.
Breakout Boards Modules Connectors Electro-Mechanical Parts
Engineering Material Mechanical Hardware
P
Electronics Components
Power Supply Arduino Board Shield Tools Accessory