You are on page 1of 11

/*

Arduino MQ4 gas sensor - Geekstips.com


This example is for calculating R0 which is
the resistance of the sensor at a known concentration
without the presence of other gases, or in fresh air
*/
void setup() {
Serial.begin(9600); //Baud rate
}

void loop() {
float sensor_volt; //Define variable for sensor voltage
float RS_air; //Define variable for sensor resistance
float R0; //Define variable for R0
float sensorValue; //Define variable for analog readings
for (int x = 0 ; x < 500 ; x++){
sensorValue = sensorValue + analogRead(A0); //Add analog values of sensor 500
times
}
sensorValue = sensorValue / 500.0; //Take average of readings
sensor_volt = sensorValue * (5.0 / 1023.0); //Convert average to voltage
RS_air = ((5.0 * 10.0) / sensor_volt) - 10.0; //Calculate RS in fresh air
R0 = RS_air / 4.4; //Calculate R0

Serial.print("R0 = ");
Serial.println(R0); //Display value of R0
delay(1000);
}

****************************************************
/*
Arduino MQ4 gas sensor - Geekstips.com
This example is to calculate the gas concentration using the R0
calculated in the example above
Also a OLED SSD1306 screen is used to display data, if you do not
have such a display, just delete the code used for displaying
*/

#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include <gfxfont.h>

#include <SPI.h> //Library for SPI interface


#include <Wire.h> //Library for I2C interface

#define OLED_RESET 11 //Reset pin


Adafruit_SSD1306 display(OLED_RESET); //Set Reset pin for OLED display

int led = 10; //LED pin


int buzzer = 9; //Buzzer pin
int gas_sensor = A0; //Sensor pin
float m = -0.318; //Slope
float b = 1.133; //Y-Intercept
float R0 = 11.820; //Sensor Resistance in fresh air from previous code

void setup() {
Serial.begin(9600); //Baud rate
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //Initialize screen
display.setTextColor(WHITE); //Set text color
display.setTextSize(3); //Set text size
pinMode(led, OUTPUT); //Set LED as output
digitalWrite(led, LOW); //Turn LED off
pinMode(buzzer, OUTPUT); //Set buzzer as output
digitalWrite(buzzer, LOW); // Turn buzzer off
pinMode(gas_sensor, INPUT); //Set gas sensor as input
}

void loop() {
display.clearDisplay(); //Clear display
display.setCursor(0, 5); //Place cursor in (x,y) location
float sensor_volt; //Define variable for sensor voltage
float RS_gas; //Define variable for sensor resistance
float ratio; //Define variable for ratio
float sensorValue = analogRead(gas_sensor); //Read analog values of sensor
sensor_volt = sensorValue * (5.0 / 1023.0); //Convert analog values to voltage
RS_gas = ((5.0 * 10.0) / sensor_volt) - 10.0; //Get value of RS in a gas
ratio = RS_gas / R0; // Get ratio RS_gas/RS_air

double ppm_log = (log10(ratio) - b) / m; //Get ppm value in linear scale


according to the the ratio value
double ppm = pow(10, ppm_log); //Convert ppm value to log scale
double percentage = ppm / 10000; //Convert to percentage
display.print(percentage); //Load screen buffer with percentage value
display.print("%"); //Load screen buffer with "%"
display.display(); //Flush characters to screen

if (ppm > 2000) {


//Check if ppm value is greater than 2000
digitalWrite(led, HIGH); //Turn LED on
digitalWrite(buzzer, HIGH); //Turn buzzer on
} else {
//Case ppm is not greater than 2000
digitalWrite(led, LOW);
//Turn LED off
digitalWrite(buzzer, LOW);
//Turn buzzer off
}
}
------------------------------------------

void setup() {
Serial.begin(9600);
}

void loop() {
float sensor_volt;
float RS_air;
float R0;
float sensorValue;
for (int x = 0 ; x < 500 ; x++){
sensorValue = sensorValue + analogRead(A0);
}
sensorValue = sensorValue / 500.0;
sensor_volt = sensorValue * (5.0 / 1023.0);
RS_air = ((5.0 * 10.0) / sensor_volt) - 10.0;
R0 = RS_air / 4.4;
Serial.print("R0 = ");
Serial.println(R0);
delay(1000);
}
--------------------------------------------------------------------

#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include <gfxfont.h>

#include <SPI.h>
#include <Wire.h>

#define OLED_RESET 11
Adafruit_SSD1306 display(OLED_RESET);
int led = 10;
int buzzer = 9;
int gas_sensor = A0;
float m = -0.318;
float b = 1.133;
float R0 = 11.820;

void setup() {
Serial.begin(9600);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.setTextColor(WHITE);
display.setTextSize(3);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
pinMode(buzzer, OUTPUT);
digitalWrite(buzzer, LOW);
pinMode(gas_sensor, INPUT);
}

void loop() {
display.clearDisplay();
display.setCursor(0, 5);
float sensor_volt;
float RS_gas;
float ratio;
float sensorValue = analogRead(gas_sensor);
sensor_volt = sensorValue * (5.0 / 1023.0);
RS_gas = ((5.0 * 10.0) / sensor_volt) - 10.0;
ratio = RS_gas / R0;
double ppm_log = (log10(ratio) - b) / m;
double ppm = pow(10, ppm_log);
double percentage = ppm / 10000;
display.print(percentage);
display.print("%");
display.display();

if (ppm > 2000) {

digitalWrite(led, HIGH);
digitalWrite(buzzer, HIGH);
} else {

digitalWrite(led, LOW);
digitalWrite(buzzer, LOW);

}
}
************************************************************

MQ-7

void setup() {
Serial.begin(9600); //Baud rate
pinMode(A1,INPUT);
}

void loop() {
float sensor_volt; //Define variable for sensor voltage
float RS_air; //Define variable for sensor resistance
float R0; //Define variable for R0
float sensorValue=0.0; //Define variable for analog readings
for(int x = 0 ; x < 500 ; x++) //Start for loop
{
sensorValue = sensorValue + analogRead(A1); //Add analog values of sensor 500
times
}
sensorValue = sensorValue/500.0; //Take average of readings
Serial.print("Average = ");
Serial.println(sensorValue);
sensor_volt = sensorValue*(5.0/1023.0); //Convert average to voltage
RS_air = ((5.0*10.0)/sensor_volt)-10.0; //Calculate RS in fresh air
R0 = RS_air/27; //Calculate R0
Serial.print("Sensor RAW value = ");
Serial.println(analogRead(A1));
Serial.print("R0 = "); //Display "R0"
Serial.println(R0); //Display value of R0
Serial.println(analogRead(A1));
delay(1000); //Wait 1 second

}
______________________________________________________________________

int gas_sensor = A0; //Sensor pin


float m = -0.6527; //Slope
float b = 1.30; //Y-Intercept
float R0 = 21.91; //Sensor Resistance in fresh air from previous code

void setup() {
Serial.begin(9600); //Baud rate

pinMode(gas_sensor, INPUT); //Set gas sensor as input


}

void loop() {

float sensor_volt; //Define variable for sensor voltage


float RS_gas; //Define variable for sensor resistance
float ratio; //Define variable for ratio
int sensorValue = analogRead(gas_sensor); //Read analog values of sensor

Serial.print("GAS SENSOR RAW VALUE = ");


Serial.println(sensorValue);
sensor_volt = sensorValue*(5.0/1023.0); //Convert analog values to voltage
Serial.print("Sensor value in volts = ");
Serial.println(sensor_volt);
RS_gas = ((5.0*10.0)/sensor_volt)-10.0; //Get value of RS in a gas
Serial.print("Rs value = ");
Serial.println(RS_gas);
ratio = RS_gas/R0; // Get ratio RS_gas/RS_air

Serial.print("Ratio = ");
Serial.println(ratio);
double ppm_log = (log10(ratio)-b)/m; //Get ppm value in linear scale according to
the the ratio value
double ppm = pow(10, ppm_log); //Convert ppm value to log scale
Serial.print("Our desired PPM = ");
Serial.println(ppm);
double percentage = ppm/10000; //Convert to percentage
Serial.print("Value in Percentage = "); //Load screen buffer with percentage
value
Serial.println(percentage);
delay(2000);
}
***************************************************************
void setup() {
Serial.begin(9600); //Baud rate
pinMode(A1,INPUT);
}

void loop() {
float sensor_volt;
float RS_air;
float R0;
float sensorValue=0.0;
for(int x = 0 ; x < 500 ; x++)
{
sensorValue = sensorValue + analogRead(A1);
}
sensorValue = sensorValue/500.0;
Serial.print("Average = ");
Serial.println(sensorValue);
sensor_volt = sensorValue*(5.0/1023.0);
RS_air = ((5.0*10.0)/sensor_volt)-10.0;
R0 = RS_air/27;
Serial.print("Sensor RAW value = ");
Serial.println(analogRead(A1));
Serial.print("R0 = ");
Serial.println(R0);
Serial.println(analogRead(A1));
delay(1000);

}
______________________________________________________________
int gas_sensor = A0;
float m = -0.6527;
float b = 1.30;
float R0 = 21.91;
void setup() {
Serial.begin(9600);
pinMode(gas_sensor, INPUT);
}

void loop() {

float sensor_volt;
float RS_gas;
float ratio;
int sensorValue = analogRead(gas_sensor);

Serial.print("GAS SENSOR RAW VALUE = ");


Serial.println(sensorValue);
sensor_volt = sensorValue*(5.0/1023.0);
Serial.print("Sensor value in volts = ");
Serial.println(sensor_volt);
RS_gas = ((5.0*10.0)/sensor_volt)-10.0;
Serial.print("Rs value = ");
Serial.println(RS_gas);
ratio = RS_gas/R0;

Serial.print("Ratio = ");
Serial.println(ratio);
double ppm_log = (log10(ratio)-b)/m;
double ppm = pow(10, ppm_log);
Serial.print("Our desired PPM = ");
Serial.println(ppm);
double percentage = ppm/10000;
Serial.print("Value in Percentage = ");
Serial.println(percentage);
delay(2000);
}
_________________________________________________________________________

ODS

#define USE_AVG

// Arduino pin numbers.


const int sharpLEDPin = 7; // Arduino digital pin 7 connect to sensor LED.
const int sharpVoPin = A5; // Arduino analog pin 5 connect to sensor Vo.

// For averaging last N raw voltage readings.


#ifdef USE_AVG
#define N 100
static unsigned long VoRawTotal = 0;
static int VoRawCount = 0;
#endif // USE_AVG

// Set the typical output voltage in Volts when there is zero dust.
static float Voc = 0.6;

// Use the typical sensitivity in units of V per 100ug/m3.


const float K = 0.5;

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

// Helper functions to print a data value to the serial monitor.


void printValue(String text, unsigned int value, bool isLast = false) {
Serial.print(text);
Serial.print("=");
Serial.print(value);
if (!isLast) {
Serial.print(", ");
}
}
void printFValue(String text, float value, String units, bool isLast = false) {
Serial.print(text);
Serial.print("=");
Serial.print(value);
Serial.print(units);
if (!isLast) {
Serial.print(", ");
}
}
___________________________________________________________________________________
____________________
int measurePin = A5;
int ledPower = 12;

unsigned int samplingTime = 280;


unsigned int deltaTime = 40;
unsigned int sleepTime = 9680;

float voMeasured = 0;
float calcVoltage = 0;
float dustDensity = 0;

void setup(){
Serial.begin(9600);
pinMode(ledPower,OUTPUT);
}

void loop(){
digitalWrite(ledPower,LOW);
delayMicroseconds(samplingTime);

voMeasured = analogRead(measurePin);

delayMicroseconds(deltaTime);
digitalWrite(ledPower,HIGH);
delayMicroseconds(sleepTime);

calcVoltage = voMeasured*(5.0/1024);
dustDensity = 0.17*calcVoltage-0.1;

if ( dustDensity < 0)
{
dustDensity = 0.00;
}

Serial.println("Raw Signal Value (0-1023):");


Serial.println(voMeasured);

Serial.println("Voltage:");
Serial.println(calcVoltage);

Serial.println("Dust Density:");
Serial.println(dustDensity);
delay(1000);
}

_________________________________________________________

import seaborn as sns


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('dataset.csv')
df = dataset.copy()

df.head()
df.info()
df.isnull().sum()

replacements = {'state': {r'Uttaranchal': 'Uttarakhand', }}


df.replace(replacements, regex = True, inplace = True)

df['agency'].value_counts()
# date format - mm/dd/yyyy
df['type'].value_counts()

#deleting all values which have null in type attribute


df = df.dropna(axis = 0, subset = ['type'])
# deleting all values which are null in location attribute
df = df.dropna(axis = 0, subset = ['location'])
#deleting all null values in so2 attribute
df = df.dropna(axis = 0, subset = ['so2'])

df.isnull().sum()

#not interested in agency


del df['agency']
del df['location_monitoring_station']
del df['stn_code']
del df['sampling_date']

#dataset after deleting the above columns


df.head()

# 298 locations, 34 states

#changing type to only 3 categories


a = list(df['type'])
for i in range(0, len(df)):
if str(a[i][0]) == 'R' and a[i][1] == 'e':
a[i] = 'Residential'
elif str(a[i][0]) == 'I':
a[i] = 'Industrial'
else:
a[i] = 'Other'

df['type'] = a
df['type'].value_counts()

######################################### do add threshold lines


#how many observations belong to each location
sns.catplot(x = "type", kind = "count", palette = "ch: 0.25", data = df)

#bar plot of so2 vs state - desc order


df[['so2', 'state']].groupby(['state']).median().sort_values("so2", ascending =
False).plot.bar()

# bar plot of no2 vs state - desc order


df[['no2', 'state']].groupby(['state']).median().sort_values("no2", ascending =
False).plot.bar(color = 'r')

# rspm = PM10
df[['rspm', 'state']].groupby(['state']).median().sort_values("rspm", ascending =
False).plot.bar(color = 'r')

# spm
df[['spm', 'state']].groupby(['state']).median().sort_values("spm", ascending =
False).plot.bar(color = 'r')

# pm2_5
df[['pm2_5', 'state']].groupby(['state']).median().sort_values("pm2_5", ascending =
False).plot.bar(color = 'r')

#Scatter plots of all columns


sns.set()
cols = ['so2', 'no2', 'rspm', 'spm', 'pm2_5']
sns.pairplot(df[cols], size = 2.5)
plt.show()

#Correlation matrix
corrmat = df.corr()
f, ax = plt.subplots(figsize = (15, 10))
sns.heatmap(corrmat, vmax = 1, square = True, annot = True)

# Creating an year column


df['date'] = pd.to_datetime(df['date'], format = '%m/%d/%Y')
df['year'] = df['date'].dt.year # year
df['year'] = df['year'].fillna(0.0).astype(int)
df = df[(df['year']>0)]

df.head()

# Heatmap Pivot with State as Row, Year as Col, No2 as Value


f, ax = plt.subplots(figsize = (10,10))
ax.set_title('{} by state and year'.format('so2'))
sns.heatmap(df.pivot_table('so2', index = 'state',
columns = ['year'], aggfunc = 'median', margins=True),
annot = True, cmap = 'YlGnBu', linewidths = 1, ax = ax, cbar_kws =
{'label': 'Average taken Annually'})

# Heatmap Pivot with State as Row, Year as Col, So2 as Value


f, ax = plt.subplots(figsize=(10,10))
ax.set_title('{} by state and year'.format('no2'))
sns.heatmap(df.pivot_table('no2', index='state',
columns=['year'],aggfunc='median',margins=True),
annot = True, cmap = "YlGnBu", linewidths = 1, ax = ax,cbar_kws =
{'label': 'Annual Average'})

# bar plot of no2 vs location - desc order - first 50


df[['no2', 'location']].groupby(['location']).median().sort_values("no2", ascending
= False).head(50).plot.bar(color = 'g')

# bar plot of no2 vs location - desc order - last 50


df[['no2', 'location']].groupby(['location']).median().sort_values("no2", ascending
= False).tail(50).plot.bar(color = 'g')

# bar plot of so2 vs location - desc order


df[['so2', 'location']].groupby(['location']).median().sort_values("so2", ascending
= False).head(50).plot.bar(color = 'y')

# bar plot of no2 vs location - desc order


df[['so2', 'location']].groupby(['location']).median().sort_values("so2", ascending
= False).tail(50).plot.bar(color = 'y')

# rspm = PM10 - location wise - first 50


df[['rspm', 'location']].groupby(['location']).median().sort_values("rspm",
ascending = False).head(50).plot.bar(color = 'r')

# rspm = PM10 - location wise - last 50


df[['rspm', 'location']].groupby(['location']).median().sort_values("rspm",
ascending = False).tail(50).plot.bar(color = 'r')

# spm = PM10 - location wise - first 50


df[['spm', 'location']].groupby(['location']).median().sort_values("spm", ascending
= False).head(50).plot.bar(color = 'r')

# pm2_5 vs location - all non null values


df[['pm2_5', 'location']].groupby(['location']).median().sort_values("pm2_5",
ascending = False).head(64).plot.bar(color = 'r')

# heatmap of rspm
f, ax = plt.subplots(figsize = (10,10))
ax.set_title('{} by state and year'.format('rspm'))
sns.heatmap(df.pivot_table('rspm', index='state',
columns = ['year'], aggfunc = 'median', margins = True),
annot = True, cmap = "YlGnBu", linewidths = 1, ax = ax, cbar_kws =
{'label': 'Annual Average'})

# heatmap of spm
f, ax = plt.subplots(figsize = (10, 10))
ax.set_title('{} by state and year'.format('spm'))
sns.heatmap(df.pivot_table('spm', index ='state',
columns = ['year'], aggfunc = 'median', margins = True)
, cmap = "YlGnBu", linewidths = 0.5, ax = ax, cbar_kws = {'label':
'Annual Average'})

You might also like