//Jefferson da Conceição Dantas | RA 10401327
//Leonardo Medeiros Silva Aparicio | RA: 10401388
//Marina Miki Sinzato | RA: 10401880
//Zhuyu Su | RA 10400811
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <PubSubClient.h>
#define TX2 17
#define RX2 16
const char* SSID = "Wokwi-GUEST";
const char* PASSWORD = "";
const char* MQTT_BROKER_URL = "broker.hivemq.com";
const char* MQTT_CLIENT_NAME = "sensor_gas_client";
int BrokerPort = 1883; // Porta do broker MQTT
String TopicoPrefixo = "grupo11"; // Prefixo do tópico
String Topico_Gas = TopicoPrefixo + "/Gas"; // Nome do tópico para o sensor de gás
WiFiClient espClient;
PubSubClient mqttClient(espClient);
LiquidCrystal_I2C lcd(0x27, 16, 2);
int BuzzerPin = 2;
int ledgreen = RX2;
int ledred = TX2;
int fan = 5;
int sensor = 26;
volatile float gas = 0;
bool perigo = false;
void setup() {
// Configuração do WiFi
setup_wifi();
mqttClient.setServer(MQTT_BROKER_URL, BrokerPort);
Serial.begin(115200);
lcd.init();
lcd.backlight();
pinMode(ledgreen, OUTPUT);
pinMode(ledred, OUTPUT);
pinMode(fan, OUTPUT);
pinMode(BuzzerPin, OUTPUT);
lcd.begin(16, 2);
lcd.setCursor(1, 0);
lcd.print("Detector de Gas");
delay(1500);
lcd.setCursor(0, 1);
lcd.print("--------------------");
delay(1000);
lcd.clear();
}
void setup_wifi() {
delay(10);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
}
void reconnect() {
while (!mqttClient.connected()) {
if (mqttClient.connect(MQTT_CLIENT_NAME)) {
Serial.println("MQTT connected");
} else {
delay(5000);
}
}
}
void loop() {
// Verificação de conexão e manutenção do MQTT
if (!mqttClient.connected()) {
reconnect();
}
mqttClient.loop();
// Atraso para estabilização
delay(100);
// Leitura do sensor de gás
gas = analogRead(sensor);
gas = 400;
gas = gas * 100 / 4095;
// Atualização do display LCD
lcd.setCursor(0, 0);
lcd.print("NIVEL= ");
lcd.print(gas);
lcd.print(" % ");
lcd.setCursor(0, 1);
Serial.print("Gas Level: ");
Serial.println(gas);
// Lógica de alarme e display
if (gas > 50 && !perigo) {
perigo = true;
digitalWrite(BuzzerPin, HIGH);
digitalWrite(ledred, HIGH);
digitalWrite(ledgreen, LOW);
digitalWrite(fan, HIGH);
lcd.print("PERIGO!!!");
} else if (gas <= 50 && perigo) {
perigo = false;
digitalWrite(BuzzerPin, LOW);
digitalWrite(ledred, LOW);
digitalWrite(ledgreen, HIGH);
digitalWrite(fan, LOW);
lcd.print("SEM PERIGO ");
}
// Publicação MQTT
String payload = String(gas);
mqttClient.publish(Topico_Gas.c_str(), payload.c_str());
delay(5000); // Aguardar 5 segundos
}