0% found this document useful (0 votes)
18 views17 pages

Nick 1

modelo de programação para monitoramento da qualidade do ar ou da agua

Uploaded by

mlsilvermls
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views17 pages

Nick 1

modelo de programação para monitoramento da qualidade do ar ou da agua

Uploaded by

mlsilvermls
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 17

/*Chamando Bibliotecas*/

#include "DHTesp.h"
#include "Adafruit_CCS811.h"
#include "GP2YDustSensor.h"
#include <TFT_eSPI.h> // Hardware-specific library
#include <SPI.h>
#include <Wire.h>
#include <math.h>
#include <WiFi.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
///////////////////////////////////////////////////////////////////////////////////
//////////
/*Definindo pinos*/
#define pin_DHT 17 //Usando o DHT22
#define pin_MQ7 36 // Usando o sensor MQ7 - CO
#define pin_MQ5 37 // Usando o sensor MQ5 - GLP
#define SHARP_LED_PIN 33 // Usando o sensor de pariculado
#define SHARP_VO_PIN 32 // Usando o sensor de pariculado
/*Definindo constantes*/
#define RL_MQ7 10000
#define R0_MQ7 1301.57
#define RL_MQ5 20000
#define R0_MQ5 17280.05
#define voltagem 5 //define a voltagem do sensor
/*Variaveis Globais */
String nome = "primeiro prototipo";
int nivel = 0;
float umidade, temperatura, mp;
int co, co2, cov, particulado, glp;
int coMedio, coSoma, contCO, mpMedio, mpSoma, contMP, glpMedio, glpSoma, contGLP =
0;
int covMedio,covSoma, contCOV, co2Medio, co2Soma, contCO2 = 0;
int leitura_analogica_MQ7, leitura_analogica_MQ5;
int intervalo_envio = 300000; //Tempo de envio para o banco
int contador_temporal, aux_temporal= 0;
bool flag;
bool flagCO2, flagCOV, flagGLP = true;
//float R0_MQ5;
/*Variaveis WiFi*/
char ssid[] = "********";
char pass[] = "*********";
///////////////////////////////////////////////////////////////////////////////////
//////////////////
/*Variaveis do Banco*/
IPAddress server_addr(**,**,***,***);
char user[] = "********";
char password[] = "*********";
char INSERT_SQL[] = "INSERT INTO estacoes.prototipo01 (temperatura, umidade, co,
mp,
glp, co2, covt) VALUES(%s, %s, %s, %s, %s, %s, %s)";
char query[128];
///////////////////////////////////////////////////////////////////////////////////
///////////////////
/*Chamando Objetos em variaveis globais*/
TFT_eSPI tft = TFT_eSPI(); // Chama a biblioteca para a tela LCD
DHTesp dht;
WiFiClient client;
MySQL_Connection conn((Client *)&client);
Adafruit_CCS811 ccs;
GP2YDustSensor sensorParticulado(GP2YDustSensorType::GP2Y1010AU0F,
SHARP_LED_PIN, SHARP_VO_PIN);
void setup(){
pinMode(pin_MQ7, INPUT); //Iniciando pino como input
pinMode(pin_MQ5, INPUT); //Iniciando pino como input

tft.begin(); //Inicia a tela


tft.setRotation(1); //Faz a tela trabalhar na horizontal
Serial.begin(115200); //Inicia o monitor serial

dht.setup(pin_DHT, DHTesp::DHT22); // Conecta o DHT no Esp32

//Wire.begin(21,22);
//ccs.begin();
if(!ccs.begin()){
Serial.println("Falha ao iniciar sensor!");
}

sensorParticulado.begin(); //Iniciando o sensor de particulado


/*configurações da tela*/
tft.fillScreen(TFT_BLACK); //Cor de fundo preto
tft.setCursor(0,70); //Coloca cursor na coordenada (0,70)da tela
tft.setFreeFont(&FreeMono12pt7b); //Fonte escolhida
tft.setTextColor(TFT_WHITE, TFT_BLACK); //Cor do texto
tft.println("CONECTANDO WIFI"); //Mostra na tela

WiFi.begin(ssid, pass); //Inicia a conexão WiFi


Conecta_WiFi(); //Executa função de conexão e feedback

tft.fillScreen(TFT_BLACK);
tft.setCursor(0,70);
tft.println("CONECTADO!");
delay(5000); //espera 5 segundos
tft.fillScreen(TFT_BLACK);
tft.setCursor(0,70);
tft.println("CONECTANDO BANCO");
Conecta_Banco(); //Executa função de conexão do banco de dados
tft.fillScreen(TFT_BLACK);
tft.setCursor(0,70);
tft.println("AQUECENDO SENSOR");
Serial.println(F("AQUECENDO O SENSOR"));
delay(10000);
/*tft.fillScreen(TFT_BLACK);
tft.setCursor(0,70);
tft.println("CALIBRANDO...");
R0_MQ7 = Calibracao(7);
tft.fillScreen(TFT_BLACK);
tft.setCursor(0,70);
tft.print("R0_MQ7=");
tft.println(R0_MQ7);
delay(3600000);
tft.fillScreen(TFT_BLACK);
tft.setCursor(0,70);
tft.println("CALIBRANDO...");
R0_MQ5 = Calibracao(5);
tft.fillScreen(TFT_BLACK);
tft.setCursor(0,70);
tft.print("R0_MQ5=");
tft.println(R0_MQ5);
delay(3600000);
*/

float linha = sensorParticulado.getBaselineCandidate(); //Indica um valor para


calibração
sensorParticulado.setBaseline(2.1*linha); //Calibra utilizando o valor de
calibração e
um multiplicador
}
void loop(){
float RS_MQ7, RSR0_MQ7, RS_MQ5, RSR0_MQ5;
int ppmCO, ppmGLP;
//////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////
/*Leitura do sensor de Monóxido de Carbono*/
leitura_analogica_MQ7 = analogRead(pin_MQ7);
RS_MQ7 = RL_MQ7 * ((5/(0.001221 * leitura_analogica_MQ7))-1);
RSR0_MQ7 = Ajuste_R((RS_MQ7/R0_MQ7), 7);
ppmCO = pow(10, (-log10(RSR0_MQ7)+log10(19.949))/(0.655));
Serial.print(F("Leitura MQ7 CO: "));
Serial.print(leitura_analogica_MQ7);
Serial.print(" ");
Serial.print(ppmCO);
Serial.print(F("ppm\t"));
///////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////
/*Leitura do sensor de GLP*/
leitura_analogica_MQ5 = analogRead(pin_MQ5);
RS_MQ5 = RL_MQ5 * ((5/(0.001221 * leitura_analogica_MQ5))-1);
RSR0_MQ5 = Ajuste_R((RS_MQ5/R0_MQ5), 5);
ppmGLP = pow(10, (-log10(RSR0_MQ5)+log10(5.543))/(0.397));
Serial.print(F("Leitura MQ5 GLP: "));
Serial.print(leitura_analogica_MQ5);
Serial.print(" ");
Serial.print(ppmGLP);
Serial.print(F("ppm\t"));
temperatura = dht.getTemperature();
umidade = dht.getHumidity();
particulado = sensorParticulado.getDustDensity();
flag = ccs.available();
if(flag){
if(!ccs.readData()){
//Serial.println(" ");

co2 = ccs.geteCO2();
cov = ccs.getTVOC();
if(cov > 1187 and co2 > 8192 or co2 < 400){
co2 = NULL;
cov = NULL;
}

Serial.print(F("CO2: "));
Serial.print(co2);
Serial.print(F("ppm COVT: "));
Serial.print(cov);
Serial.print(F("ppb"));
if(cov != NULL and co2 != NULL){
co2Soma += co2;
covSoma += cov;
contCOV += 1;
contCO2 += 1;
}

}
}
co = ppmCO;
glp = ppmGLP;
mp = particulado;
mostrar_display();
mpSoma += mp;
contMP += 1;

if (umidade > 85 || umidade < 33 || temperatura > 50 || temperatura < 0){


co = NULL;
glp = NULL;
} else {
coSoma += ppmCO;
contCO += 1;
glpSoma += ppmGLP;
contGLP += 1;
}
contador_temporal = millis();
if (contador_temporal - aux_temporal > intervalo_envio){
aux_temporal = millis();
tft.setCursor(220, 75);
tft.println("E");
if (WiFi.status() == WL_DISCONNECTED){
WiFi.disconnect();
WiFi.begin(ssid, pass);
}
mpMedio = mpSoma/contMP;
coMedio = coSoma/contCO;
glpMedio = glpSoma/contGLP;
co2Medio = co2Soma/contCO2;
covMedio = covSoma/contCOV;
Envia_Dados();
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////
/*Relatório de envio*/
Serial.println("");
Serial.print("media MP: ");
Serial.print(mpMedio);
Serial.print(" media CO: ");
Serial.print(coMedio);
Serial.print(" media GLP: ");
Serial.print(glpMedio);
Serial.print(" media CO2: ");
Serial.print(co2Medio);
Serial.print(" media COVT: ");
Serial.println(covMedio);

mpSoma = 0;
contMP = 0;
coSoma = 0;
contCO = 0;
glpSoma = 0;
contGLP = 0;
co2Soma = 0;
contCO2 = 0;
covSoma = 0;
contCOV = 0;
}
co = NULL;
mp = NULL;
glp = NULL;
co2 = NULL;
cov = NULL;

delay(2000);
}
void mostrar_display()
{
delay(dht.getMinimumSamplingPeriod());
if(co >= 40 or mp >= 40){
nivel = 3; //emergência
}
if(co >=30 and co < 40){
nivel = 2; //alerta
}
if(mp >=420 and mp < 500){
nivel = 2; //alerta
}
if(co >=15 and co < 30){
nivel = 1; //atenção
}
if(mp >=250 and mp < 420){
nivel = 1; //atenção

}
if (co < 15 and mp < 250){
nivel = 0; //normal
}

switch (nivel){
case 0:
tft.fillScreen(TFT_BLACK);
break;
case 1:
tft.fillScreen(TFT_YELLOW);
break;
case 2:
tft.fillScreen(TFT_ORANGE);
break;
case 3:
tft.fillScreen(TFT_MAGENTA);
break;
}

//tft.fillScreen(TFT_BLACK);
//tft.setTextColor(TFT_GREEN, TFT_BLACK);
tft.setCursor(0,20);
tft.setFreeFont(&FreeMono12pt7b);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.println("Temp. Umid.");
tft.drawLine(0, 55,250,55, TFT_BLUE);
tft.drawLine(125, 0,125,55, TFT_BLUE);
//temperatura = dht.getTemperature();
//umidade = dht.getHumidity();
if(isnan(umidade)){
Serial.println(F("Erro na leitura da umidade."));
}else{
Serial.print(F(" Umidade:"));
Serial.print(umidade, 1);
Serial.print(F("%\t\t"));

if(isnan(temperatura)){
Serial.println(F("Erro na leitura da Temperatura."));
}else{
Serial.print(F("Temperatura:"));
Serial.print(temperatura, 1);
Serial.print("°C\t");
tft.setCursor(5, 50);
if(temperatura > 50 || temperatura < 0){
tft.setTextColor(TFT_YELLOW, TFT_BLACK);

tft.print(temperatura);
tft.print(F("°C"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
} else{
tft.print(temperatura);
tft.print(F(" C"));
}
}
Serial.print("\t");
Serial.print(F("Concentração de Particulado: "));
Serial.print(particulado);
Serial.println(F("ug/m3"));

tft.setCursor(135, 50);
if(umidade > 85 || umidade < 33){
tft.setTextColor(TFT_YELLOW, TFT_BLACK);
tft.print(umidade);
tft.println(F("%"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
} else{
tft.print(umidade);
tft.println(F("%"));
}
/////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////
/*#############Cor para o Monóxido de Carbono####################*/
if(co >= 15){

tft.setTextColor(TFT_PURPLE, TFT_WHITE);
tft.print(F("CO="));
tft.print(co);
tft.println(F("ppm"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);

}
if(co > 13 and co <=15){
tft.setTextColor(TFT_RED, TFT_WHITE);
tft.print(F("CO="));
tft.print(co);
tft.println(F("ppm"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}
if(co > 11 and co <=13){
tft.setTextColor(TFT_ORANGE, TFT_WHITE);
tft.print(F("CO="));
tft.print(co);
tft.println(F("ppm"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}
if(co > 9 and co <=11){
tft.setTextColor(TFT_YELLOW, TFT_WHITE);
tft.print(F("CO="));
tft.print(co);
tft.println(F("ppm"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}
if(co <= 9){
tft.setTextColor(TFT_GREEN, TFT_WHITE);
tft.print(F("CO="));
tft.print(co);
tft.println(F("ppm"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}
//Alternador para mostrar na tela
if (flagGLP){
flagGLP = false;
flagCO2 = true;
flagCOV = false;
} else{
if (flagCO2){
flagGLP = false;
flagCO2 = false;
flagCOV = true;
} else {
flagGLP = true;
flagCO2 = false;
flagCOV = false;
}
}
/////////////////////////////////////////////////////////////////////////////
/*#############Cor para o GLP####################*/
if (flagGLP){
if (glp > 2000){
tft.setTextColor(TFT_RED, TFT_WHITE);
tft.print(F("GLP="));
tft.print(glp);
tft.println(F("ppm"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}else{
tft.setTextColor(TFT_GREEN, TFT_WHITE);
tft.print(F("GLP="));
tft.print(glp);
tft.println(F("ppm"));
}
}
/*#############Cor para o Composto Orgânico Volátil####################*/
if (flagCOV){
if(cov>1187){
tft.print(F("COV="));
tft.println(F("ERRO"));
} else {
tft.print(F("COV="));
tft.print(cov);
tft.println(F("ppb"));
}
}
/*#############Cor para o Dióxido de Carbono####################*/
if (flagCO2){

if(co2<400 or co2>8192){
tft.print(F("ERRO"));
} else {
if(co2 <= 1000){
tft.setTextColor(TFT_GREEN, TFT_WHITE);
tft.print(F("CO2="));
tft.print(co2);
}
else{
tft.setTextColor(TFT_RED, TFT_WHITE);
tft.print(F("CO2="));
tft.print(co2);
}
}
tft.println(F("ppm"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}
//////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////
/*#############Cor para o Materiais Particulados####################*/
if(mp > 250){
tft.setTextColor(TFT_PURPLE, TFT_WHITE);
tft.print(F("C.Part.="));
tft.print(particulado);
tft.println(F("ug/m³"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}
if(mp > 150 and mp <= 250){
tft.setTextColor(TFT_RED, TFT_WHITE);
tft.print(F("C.Part.="));
tft.print(particulado);
tft.println(F("ug/m³"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}
if(mp > 100 and mp <= 150){
tft.setTextColor(TFT_ORANGE, TFT_WHITE);
tft.print(F("C.Part.="));
tft.print(particulado);
tft.println(F("ug/m³"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}
if(mp > 50 and mp <= 100){
tft.setTextColor(TFT_YELLOW, TFT_WHITE);
tft.print(F("C.Part.="));
tft.print(particulado);
tft.println(F("ug/m³"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}
if(mp <= 50){
tft.setTextColor(TFT_GREEN, TFT_WHITE);
tft.print(F("C.Part.="));
tft.print(particulado);
tft.println(F("ug/m³"));
tft.setTextColor(TFT_WHITE, TFT_BLACK);
}
}
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////
/************Calibrando sensores de gás*****************/
float Calibracao(int sensor){
int leitura_analogica;
float resistencia_em_ar_limpo, r0_Calibrado;
switch (sensor){
case 7:
resistencia_em_ar_limpo = 0;
for (int i = 0; i<100; i++){
leitura_analogica = analogRead(pin_MQ7);
resistencia_em_ar_limpo += RL_MQ7 * ((5/(0.001221 * leitura_analogica))-1);
delay(100);
Serial.print(F(" Calibrando MQ7: "));
Serial.print(i);
Serial.println(F("%"));
}
resistencia_em_ar_limpo = resistencia_em_ar_limpo / 100;
r0_Calibrado = resistencia_em_ar_limpo / (Ajuste_R(36.1286, sensor));
delay(1000);
break;
case 5:
resistencia_em_ar_limpo = 0;
for (int i = 0; i<100; i++){
leitura_analogica = analogRead(pin_MQ5);
resistencia_em_ar_limpo += RL_MQ5 * ((5/(0.001221 * leitura_analogica))-1);
delay(100);
Serial.print(F(" Calibrando MQ5: "));
Serial.print(i);
Serial.println(F("%"));
}
resistencia_em_ar_limpo = resistencia_em_ar_limpo / 100;
r0_Calibrado = resistencia_em_ar_limpo / (Ajuste_R(6.4754, sensor));
delay(1000);
break;
}
return r0_Calibrado;
}
/************Ajuste_R*************/
float Ajuste_R(float razao, int sensor){
float ajustado, valor_85, valor_33, umid, temp;
temp = dht.getTemperature();
umid = dht.getHumidity();
if(temp > 50){
Serial.println(F("Erro, temperatura acima de 50°C."));
return NAN;
}
if(temp < 0){
Serial.println(F("Erro, temperatura abaixo de 0°C."));
return NAN;
}
if(umid > 85){
Serial.println(F("Erro, umidade acima de 85%."));
return NAN;
}
if(umid < 33){
Serial.println(F("Erro, umidade abaixo de 33%."));
}
switch(sensor){
case 7:
valor_85 = -0.000002 * pow(temp, 3) + 0.0002 * pow(temp, 2) - 0.0123 * temp +
1.0268;
valor_33 = -0.000005 * pow(temp, 3) + 0.0005 * pow(temp, 2) - 0.0186 * temp +
1.2112;

ajustado = razao * (valor_85 + (valor_33 - valor_85) * (33 - umid)/(33-85));


break;
case 5:
valor_85 = -0.000002 * pow(temp, 3) + 0.0002 * pow(temp, 2) - 0.0114 * temp +
0.9944;
valor_33 = -0.000005 * pow(temp, 3) + 0.0004 * pow(temp, 2) - 0.016 * temp +
1.1711;
ajustado = razao * (valor_85 + (valor_33 - valor_85) * (33 - umid)/(33-85));
break;
}

return ajustado;
}
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////
/***********Insere no banco***************/
void Envia_Dados(){
sprintf(query, INSERT_SQL, String(temperatura), String(umidade), String(coMedio),
String(mpMedio), String(glpMedio), String(co2Medio), String(covMedio));
if (!conn.connect(server_addr,3306, user, password)){
conn.close();
Conecta_Banco();
}
MySQL_Cursor * cur_mem = new MySQL_Cursor(&conn);
cur_mem -> execute(query);
delete cur_mem;
Serial.println(F("Dados enviados!"));
}
/************Conecta no banco*****************/
void Conecta_Banco(){
Serial.println(F("Conectando ao banco de dados..."));
while(!conn.connect(server_addr,3306, user, password)){
Serial.println(F("Conexão falhou!"));
conn.close();
delay(100);
Serial.println(F("Conectando ao Banco novamente."));
}
Serial.println(F("Conectado ao Banco de dados"));
}
void Conecta_WiFi(){
Serial.print(F("Conectando no WiFi..."));
while(WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.print("");
Serial.print(F("WIFI CONECTADA!"));
Serial.println("");
}
/******2 – CÓDIGO DO BANCO DE DADOS******/
CREATE DATABASE EstacoesGases;
USE EstacoesGases;
CREATE TABLE prototipo1(
id SERIAL PRIMARY KEY NOT NULL AUTO_INCREMENT,
nome VARCHAR(50) NOT NULL,
data TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
temperatura DECIMAL(4,1) NULL,
umidade DECIMAL(4,1) NULL,
co INT NULL,
glp INT NULL,
metano INT NULL,
v_alcool INT NULL,
benzeno DECIMAL(10,2) NULL,
amonia INT NULL,
sulf_hidrog DECIMAL(10,2) NULL,
mp DECIMAL(10,2) NULL,
fumaca DECIMAL(10,2) NULL,
cov INT NULL,
co2 INT NULL,
);
fig = go.Figure(data=[go.Scatter(x=df['data'], y=df['temperatura'])],
layout=go.Layout(title=g
o.layout.Title(text="Hitórico de Medições de Temperatura")))
fig.update_layout(xaxis_title="Tempo", yaxis_title="°C")
fig.show()
fig = go.Figure(data=[go.Scatter(x=df['data'], y=df['umidade'])],
layout=go.Layout(title=go.la
yout.Title(text="Hitórico de Medições de Umidade do ar")))
fig.update_layout(xaxis_title="Tempo", yaxis_title="Umidade (%)")
fig.show()
fig = px.area(df, x="data", y="co")
fig.update_layout(title="Hitórico de Medições de Monóxido de
Carbono",xaxis_title="Tempo
", yaxis_title="ppm")
fig.show()
fig = px.area(df, x="data", y="glp")
fig.update_layout(title="Hitórico de Medições de Gás Liquefeito de
Petróleo",xaxis_title="Te
mpo", yaxis_title="ppm")
fig.show()
fig = px.area(df, x="data", y="co2")
fig.update_layout(title="Hitórico de Medições de Dióxido de
Carbono",xaxis_title="Tempo",
yaxis_title="ppm")
fig.show()
fig = px.area(df, x="data", y="covt")
fig.update_layout(title="Hitórico de Medições de Composto Orgânico
Volátil",xaxis_title="T
empo", yaxis_title="ppb")
fig.show()
fig = px.area(df, x="data", y="mp")
fig.update_layout(title="Hitórico de Medições de Particulas em Suspenção",
xaxis_title="Tem
po", yaxis_title="ug/m³")
fig.show()
ultima_hora_medicao = df.iloc[-1]['data']
media_movel_CO = {'data': [], 'co': []}
media_movel_MP = {'data': [], 'mp': []}
media_movel_COVT = {'data': [], 'covt': []}
for i, linha in df.iterrows():
*/////////////////////////////////////////////////////////////////////////////*
#Calculando média movel de Monóxido de Carbono
if (linha['data'] + timedelta(hours = 8)) <= ultima_hora_medicao:
aux = df[df['data'] <= (linha['data'] + timedelta(hours = 8))]
aux = aux[aux['data'] >= linha['data']]
media_movel_CO['co'].append(aux.co.mean())
media_movel_CO['data'].append(aux.iloc[-1]['data'])
media_movel_COVT['covt'].append(aux.covt.mean())
media_movel_COVT['data'].append(aux.iloc[-1]['data'])
#Calculando média movel de particulas suspensas
if (linha['data'] + timedelta(hours = 24)) <= ultima_hora_medicao:
aux = df[df['data'] <= (linha['data'] + timedelta(hours = 24))]
aux = aux[aux['data'] >= linha['data']]
media_movel_MP['mp'].append(aux.mp.mean())
media_movel_MP['data'].append(aux.iloc[-1]['data'])
media_movel_CO = pd.DataFrame(media_movel_CO)
media_movel_MP = pd.DataFrame(media_movel_MP)
media_movel_COVT = pd.DataFrame(media_movel_COVT)
fig = px.area(media_movel_CO, x="data", y="co")
fig.update_layout(title="Média Móvel de Monóxido de Carbono", xaxis_title="Tempo",
yaxis
_title="ppm")
fig.show()
fig = px.area(media_movel_COVT, x="data", y="covt")
fig.update_layout(title="Média Móvel de Composto Orgânico
Volátil",xaxis_title="Tempo",
yaxis_title="ppb")
fig.show()
fig = px.area(media_movel_MP, x="data", y="mp")
fig.update_layout(title="Média Móvel de Particulas em Suspensão",
xaxis_title="Tempo", ya
xis_title="ug/m³")
fig.show()
dicionario ={ 'Qualidade':['Boa', 'Moderada', 'Ruim', 'Muito Ruim', 'Péssima'],
'Indice Inicial': [0, 40, 80, 120, 200],
'Indice Final': [40, 80, 120, 200, 300],
'MP10 Inicial': [0, 50, 100, 150, 250],
'MP10 Final': [50, 100, 150, 250, 10000],
'MP25 Inicial': [0, 25, 50, 75, 125],
'MP25 Final': [25, 50, 75, 125, 10000],
'CO Inicial': [0, 9, 11, 13,15],
'CO Final': [9, 11, 13, 15, 10000]}
tabela_qualidade = pd.DataFrame(dicionario)
tabela_qualidade
def calculo_iqar_CO(ultimo_valor):
for i, linha in tabela_qualidade.iterrows():
if ultimo_valor < linha['CO Final'] and ultimo_valor >= linha['CO Inicial']:
if linha['Qualidade'] == 'Péssima':
iqar_CO = 400
else:
iqar_CO = linha['Indice Inicial'] + ((linha['Indice Final'] - linha['Indice
Inicial']) / (linha['
CO Final'] - linha['CO Inicial'])) * (ultimo_valor - linha['CO Inicial'])
return iqar_CO
def verifica_qualidade_CO(iqar_CO):
for e, linha2 in tabela_qualidade.iterrows():
if iqar_CO >= linha2['Indice Inicial'] and iqar_CO <= linha2['Indice Final']:
return linha2['Qualidade']
lista_IQAr_CO = []
lista_qualidade_CO = []
for i, linha in media_movel_CO.iterrows():
iqar = calculo_iqar_CO(linha['co'])
lista_IQAr_CO.append(iqar)
lista_qualidade_CO.append(verifica_qualidade_CO(iqar))
media_movel_CO['IQAr'] = lista_IQAr_CO
media_movel_CO['Qualidade'] = lista_qualidade_CO
def calculo_iqar_MP10(ultimo_valor):
for i, linha in tabela_qualidade.iterrows():
if ultimo_valor < linha['MP10 Final'] and ultimo_valor >= linha['MP10 Inicial']:
if linha['Qualidade'] == 'Péssima':
iqar_MP10 = 400
else
iqar_MP10 = linha['Indice Inicial'] + ((linha['Indice Final'] - linha['Indice
Inicial']) / (linh
a['MP10 Final'] - linha['MP10 Inicial'])) * (ultimo_valor - linha['MP10 Inicial'])

return iqar_MP10
def calculo_iqar_MP25(ultimo_valor):
for i, linha in tabela_qualidade.iterrows():
if ultimo_valor < linha['MP25 Final'] and ultimo_valor >= linha['MP25 Inicial']:
if linha['Qualidade'] == 'Péssima':
iqar_MP25 = 400
else:
iqar_MP25 = linha['Indice Inicial'] + ((linha['Indice Final'] - linha['Indice
Inicial']) / (linh
a['MP25 Final'] - linha['MP25 Inicial'])) * (ultimo_valor - linha['MP25 Inicial'])

return iqar_MP25
def verifica_qualidade_MP10(iqar_MP10):
for e, linha2 in tabela_qualidade.iterrows():
if iqar_MP10 >= linha2['Indice Inicial'] and iqar_MP10 <= linha2['Indice Final']:
return linha2['Qualidade']
def verifica_qualidade_MP25(iqar_MP25):
for e, linha2 in tabela_qualidade.iterrows():
if iqar_MP25 >= linha2['Indice Inicial'] and iqar_MP25 <= linha2['Indice Final']:
return linha2['Qualidade']
lista_IQAr_MP10 = []
lista_qualidade_MP10 = []
for i, linha in media_movel_MP.iterrows():
iqar = calculo_iqar_MP10(linha['mp'])
lista_IQAr_MP10.append(iqar)
lista_qualidade_MP10.append(verifica_qualidade_MP10(iqar))
media_movel_MP['IQAr MP10'] = lista_IQAr_MP10
media_movel_MP['Qualidade MP10'] = lista_qualidade_MP10
lista_IQAr_MP25 = []
lista_qualidade_MP25 = []
for i, linha in media_movel_MP.iterrows():
iqar = calculo_iqar_MP25(linha['mp'])
lista_IQAr_MP25.append(iqar)
lista_qualidade_MP25.append(verifica_qualidade_MP25(iqar))
media_movel_MP['IQAr MP25'] = lista_IQAr_MP25
media_movel_MP['Qualidade MP25'] = lista_qualidade_MP25
mmco_boa = []
mmco_moderada =[]
mmco_ruim = []
mmco_muito_ruim = []
mmco_pessima = []
for i, linha in media_movel_CO.iterrows():
if linha['Qualidade'] == "Boa":
mmco_boa.append(linha['IQAr'])
mmco_moderada.append(0)
mmco_ruim.append(0)
mmco_muito_ruim.append(0)
mmco_pessima.append(0)
elif linha['Qualidade'] == "Moderada":
mmco_boa.append(0)
mmco_moderada.append(linha['IQAr'])
mmco_ruim.append(0)
mmco_muito_ruim.append(0)
mmco_pessima.append(0)
elif linha['Qualidade'] == "Ruim":
mmco_boa.append(0)
mmco_moderada.append(0)
mmco_ruim.append(linha['IQAr'])
mmco_muito_ruim.append(0)
mmco_pessima.append(0)
elif linha['Qualidade'] == "Muito Ruim":
mmco_boa.append(0)
mmco_moderada.append(0)
mmco_ruim.append(0)
mmco_muito_ruim.append(linha['IQAr'])
mmco_pessima.append(0)
else:
mmco_boa.append(0)
mmco_moderada.append(0)
mmco_ruim.append(0)
mmco_muito_ruim.append(0)
mmco_pessima.append(linha['IQAr'])
media_movel_CO['BOA'] = mmco_boa
media_movel_CO['MODERADA'] = mmco_moderada
media_movel_CO['RUIM'] = mmco_ruim
media_movel_CO['MUITO RUIM'] = mmco_muito_ruim
media_movel_CO['PESSIMA'] = mmco_pessima
fig = go.Figure()
fig.add_trace(go.Scatter(x=media_movel_CO['data'], y=media_movel_CO['BOA'],
fill='tozer
oy', name='Qualidade Boa', mode='lines', line=dict(width=0.8,color = 'rgb(0, 255,
0)'), fillcolo
r = 'rgba(0, 255, 0,0.7)'))
fig.add_trace(go.Scatter(x=media_movel_CO['data'], y=media_movel_CO['MODERADA'], fi
ll='tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(255, 200, 86)'),
name='Qualidade
Moderada', fillcolor = 'rgb(255, 200, 86)'))
fig.add_trace(go.Scatter(x=media_movel_CO['data'], y=media_movel_CO['RUIM'],
fill='toze
roy',mode='lines', line=dict(width=0.8, color = 'rgb(255, 165, 0)'),
name='Qualidade Ruim', fil
lcolor = 'rgba(255, 165, 0,0.8)'))
fig.add_trace(go.Scatter(x=media_movel_CO['data'], y=media_movel_CO['MUITO RUIM'],
fill='tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(255, 0, 0)'),
name='Qualidade Mu
ito Ruim', fillcolor = 'rgba(255, 0, 0, 0.8)'))
fig.add_trace(go.Scatter(x=media_movel_CO['data'], y=media_movel_CO['PESSIMA'],
fill='
tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(128, 0, 128)'),
name='Qualidade Péssi
ma', fillcolor = 'rgba(128, 0, 128, 0.8)'))
fig.update_layout(title="Índice de Qualidade do Ar de Monóxido de Carbono",
xaxis_title="T
empo", yaxis_title="")
fig.show()
mmmp10_boa = []
mmmp10_moderada =[]
mmmp10_ruim = []
mmmp10_muito_ruim = []
mmmp10_pessima = []
for i, linha in media_movel_MP.iterrows():
if linha['Qualidade MP10'] == "Boa":
mmmp10_boa.append(linha['IQAr MP10'])
mmmp10_moderada.append(0)
mmmp10_ruim.append(0)
mmmp10_muito_ruim.append(0)
mmmp10_pessima.append(0)
elif linha['Qualidade MP10'] == "Moderada":
mmmp10_boa.append(0)
mmmp10_moderada.append(linha['IQAr MP10'])
mmmp10_ruim.append(0)
mmmp10_muito_ruim.append(0)
mmmp10_pessima.append(0)
elif linha['Qualidade MP10'] == "Ruim":
mmmp10_boa.append(0)
mmmp10_moderada.append(0)
mmmp10_ruim.append(linha['IQAr MP10'])
mmmp10_muito_ruim.append(0)
mmmp10_pessima.append(0)
elif linha['Qualidade MP10'] == "Muito Ruim":
mmmp10_boa.append(0)
mmmp10_moderada.append(0)
mmmp10_ruim.append(0)
mmmp10_muito_ruim.append(linha['IQAr MP10'])
mmmp10_pessima.append(0)
else:
mmmp10_boa.append(0)
mmmp10_moderada.append(0)
mmmp10_ruim.append(0)
mmmp10_muito_ruim.append(0)
mmmp10_pessima.append(linha['IQAr MP10'])
media_movel_MP['MP10 BOA'] = mmmp10_boa
media_movel_MP['MP10 MODERADA'] = mmmp10_moderada
media_movel_MP['MP10 RUIM'] = mmmp10_ruim
media_movel_MP['MP10 MUITO RUIM'] = mmmp10_muito_ruim
media_movel_MP['MP10 PESSIMA'] = mmmp10_pessima
fig = go.Figure()
fig.add_trace(go.Scatter(x=media_movel_MP['data'], y=media_movel_MP['MP10 BOA'],
fill
='tozeroy', name='Qualidade Boa', mode='lines', line=dict(width=0.8,color = 'rgb(0,
255, 0)'),
fillcolor = 'rgba(0, 255, 0,0.7)'))
fig.add_trace(go.Scatter(x=media_movel_MP['data'], y=media_movel_MP['MP10 MODERA
DA'], fill='tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(255, 200,
86)'), name='Qua
lidade Moderada', fillcolor = 'rgb(255, 200, 86)'))
fig.add_trace(go.Scatter(x=media_movel_MP['data'], y=media_movel_MP['MP10 RUIM'],
fil
l='tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(255, 165, 0)'),
name='Qualidade Ru
im', fillcolor = 'rgba(255, 165, 0,0.8)'))
fig.add_trace(go.Scatter(x=media_movel_MP['data'], y=media_movel_MP['MP10 MUITO R
UIM'], fill='tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(255, 0, 0)'),
name='Qualid
ade Muito Ruim', fillcolor = 'rgba(255, 0, 0, 0.8)'))
fig.add_trace(go.Scatter(x=media_movel_MP['data'], y=media_movel_MP['MP10 PESSIMA'
], fill='tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(128, 0, 128)'),
name='Qualidad
e Péssima', fillcolor = 'rgba(128, 0, 128, 0.8)'))
fig.update_layout(title="Índice de Qualidade do Ar para Particulas em Suspenção
MP10", xax
is_title="Tempo", yaxis_title="")
fig.show()
mmmp25_boa = []
mmmp25_moderada =[]
mmmp25_ruim = []
mmmp25_muito_ruim = []
mmmp25_pessima = []
for i, linha in media_movel_MP.iterrows():
if linha['Qualidade MP25'] == "Boa":
mmmp25_boa.append(linha['IQAr MP25'])
mmmp25_moderada.append(0)
mmmp25_ruim.append(0)
mmmp25_muito_ruim.append(0)
mmmp25_pessima.append(0)
elif linha['Qualidade MP25'] == "Moderada":
mmmp25_boa.append(0)
mmmp25_moderada.append(linha['IQAr MP25'])
mmmp25_ruim.append(0)
mmmp25_muito_ruim.append(0)
mmmp25_pessima.append(0)
elif linha['Qualidade MP25'] == "Ruim":
mmmp25_boa.append(0)
mmmp25_moderada.append(0)
mmmp25_ruim.append(linha['IQAr MP25'])
mmmp25_muito_ruim.append(0)
mmmp25_pessima.append(0)
elif linha['Qualidade MP25'] == "Muito Ruim":
mmmp25_boa.append(0)
mmmp25_moderada.append(0)
mmmp25_ruim.append(0)
mmmp25_muito_ruim.append(linha['IQAr MP25'])
mmmp25_pessima.append(0)
else:
mmmp25_boa.append(0)
mmmp25_moderada.append(0)
mmmp25_ruim.append(0)
mmmp25_muito_ruim.append(0)
mmmp25_pessima.append(linha['IQAr MP25'])
media_movel_MP['MP25 BOA'] = mmmp25_boa
media_movel_MP['MP25 MODERADA'] = mmmp25_moderada
media_movel_MP['MP25 RUIM'] = mmmp25_ruim
media_movel_MP['MP25 MUITO RUIM'] = mmmp25_muito_ruim
media_movel_MP['MP25 PESSIMA'] = mmmp25_pessima
fig = go.Figure()
fig.add_trace(go.Scatter(x=media_movel_MP['data'], y=media_movel_MP['MP25 BOA'],
fill
='tozeroy', name='Qualidade Boa', mode='lines', line=dict(width=0.8,color = 'rgb(0,
255, 0)'),
fillcolor = 'rgba(0, 255, 0,0.7)'))
fig.add_trace(go.Scatter(x=media_movel_MP['data'], y=media_movel_MP['MP25 MODERA
DA'], fill='tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(255, 200,
86)'), name='Qua
lidade Moderada', fillcolor = 'rgb(255, 200, 86)'))
fig.add_trace(go.Scatter(x=media_movel_MP['data'], y=media_movel_MP['MP25 RUIM'],
fil
l='tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(255, 165, 0)'),
name='Qualidade Ru
im', fillcolor = 'rgba(255, 165, 0,0.8)'))
fig.add_trace(go.Scatter(x=media_movel_MP['data'], y=media_movel_MP['MP25 MUITO R
UIM'], fill='tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(255, 0, 0)'),
name='Qualid
ade Muito Ruim', fillcolor = 'rgba(255, 0, 0, 0.8)'))
fig.add_trace(go.Scatter(x=media_movel_MP['data'], y=media_movel_MP['MP25 PESSIMA'
], fill='tozeroy',mode='lines', line=dict(width=0.8, color = 'rgb(128, 0, 128)'),
name='Qualidad
e Péssima', fillcolor = 'rgba(128, 0, 128, 0.8)'))
fig.update_layout(title="Índice de Qualidade do Ar para Particulas em Suspenção
MP25", xax
is_title="Tempo", yaxis_title="")
fig.show()
df.to_csv("Dados do Banco.csv")
df.to_excel("Dados do Banco.xlsx")

You might also like