#include <WiFi.h>
#include <PubSubClient.h>
const int analogPin = 35; // the number of the pushbutton pin
#define LED 2
// the number of the LED
float voltagevalue = 0;
// variable for storing the pushbutton status
int analogPinState = 0;
const char* ssid = "Wokwi-GUEST"; // Substitua pelo nome da sua rede WiFi
const char* password = ""; // Substitua pela senha da sua rede WiFi
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char* temp_topic = "fimca/ito";
const char* led = "fimca/ito/led";
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Conectando a ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi conectado");
Serial.println("Endereço IP: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
while (!client.connected()) {
Serial.print("Tentando conectar ao MQTT...");
if (client.connect("ito")) {
Serial.println("conectado");
} else {
Serial.print("falhou, rc=");
Serial.print(client.state());
Serial.println(" tentará novamente em 2 segundos");
delay(2000);
}
}
}
void setup() {
Serial.begin(115200);
// initialize the pushbutton pin as an input
pinMode(analogPin, INPUT);
// initialize the LED pin as an output
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
pinMode(LED, OUTPUT);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
analogPinState = analogRead(analogPin);
Serial.print("Valor do Sensor é:");
Serial.println(analogPinState);
const String ALERT = String(analogPinState);
client.publish(temp_topic, ALERT.c_str());
if (analogPinState > 1000) {
digitalWrite(LED, HIGH);
String LED_LIGADO = String("HIGH");
client.publish(led, LED_LIGADO.c_str());
} else {
digitalWrite(LED, LOW);
String LED_DESLIGADO = String("LOW");
client.publish(led, LED_DESLIGADO.c_str());
}
}