#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// --- Configurações de WiFi ---
const char* ssid = "Wokwi-GUEST"; // Ajuste para sua rede local se não for Wokwi
const char* password = "";
// --- Configurações MQTT (MAQIATTO) ---
const char* mqttserver = "maqiatto.com";
const int mqttport = 1883;
// ==========================================
// DADOS DA SUA CONTA MAQIATTO (PREENCHA AQUI)
// ==========================================
const char* mqttUser = "[email protected]"; // <<<< SEU EMAIL CADASTRADO NO MAQIATTO
const char* mqttPassword = "teste123"; // <<<< SUA SENHA DO MAQIATTO
// O prefixo do tópico no Maqiatto OBRIGATORIAMENTE deve ser "seu_email/nome_do_topico"
#define TOPIC_PREFIX "[email protected]"
WiFiClient espClient;
PubSubClient client(espClient);
// --- Pinos do Hardware (Mantive os que você enviou) ---
// Saídas
#define LED1_PIN 13
#define LED2_PIN 12
// Entradas Analógicas/Sensores
#define POT_PIN 33
#define LDR_PIN 35
#define DHT_PIN 32
#define DHTTYPE DHT22
// Entradas Digitais (Botões)
#define BTN1_PIN 14
#define BTN2_PIN 27
// Inicializa o DHT
DHT dht(DHT_PIN, DHTTYPE);
// --- Variáveis de Controle ---
unsigned long lastMsg = 0;
const long interval = 2000; // 2 segundos
// Estados dos botões
int lastBtn1State = HIGH;
int lastBtn2State = HIGH;
// --- Protótipos ---
void setup_wifi();
void callback(char* topic, byte* payload, unsigned int length);
void reconnect();
void checkButtons();
void setup() {
Serial.begin(115200);
// Configuração dos Pinos
pinMode(LED1_PIN, OUTPUT);
pinMode(LED2_PIN, OUTPUT);
pinMode(POT_PIN, INPUT);
pinMode(LDR_PIN, INPUT);
pinMode(BTN1_PIN, INPUT_PULLUP);
pinMode(BTN2_PIN, INPUT_PULLUP);
dht.begin();
setup_wifi();
client.setServer(mqttserver, mqttport);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
checkButtons();
unsigned long now = millis();
if (now - lastMsg > interval) {
lastMsg = now;
// --- 1. Leitura do Potenciômetro ---
int potValue = analogRead(POT_PIN);
float potPorcentagem = (potValue / 4095.0) * 100.0;
String msgPot = String(potPorcentagem, 0);
// --- 2. Leitura do LDR ---
int ldrValue = analogRead(LDR_PIN);
float ldrPorcentagem = (ldrValue / 4095.0) * 100.0;
String msgLdr = String(ldrPorcentagem, 0);
// --- 3. Leitura do DHT22 ---
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Falha ao ler o DHT sensor!");
// Não damos return aqui para garantir que os outros dados sejam enviados
} else {
String msgTemp = String(t, 1);
String msgHum = String(h, 1);
client.publish(TOPIC_PREFIX "/temp", msgTemp.c_str());
client.publish(TOPIC_PREFIX "/hum", msgHum.c_str());
Serial.printf("T: %sC | H: %s%% | ", msgTemp.c_str(), msgHum.c_str());
}
// --- Publicando Pot e LDR ---
client.publish(TOPIC_PREFIX "/pot", msgPot.c_str());
client.publish(TOPIC_PREFIX "/ldr", msgLdr.c_str());
Serial.printf("Pot: %s%% | LDR: %s%%\n", msgPot.c_str(), msgLdr.c_str());
}
}
void checkButtons() {
int currentBtn1 = digitalRead(BTN1_PIN);
int currentBtn2 = digitalRead(BTN2_PIN);
if (currentBtn1 != lastBtn1State) {
lastBtn1State = currentBtn1;
String status = (currentBtn1 == LOW) ? "PRESSIONADO" : "SOLTO";
client.publish(TOPIC_PREFIX "/btn1", status.c_str());
delay(50);
}
if (currentBtn2 != lastBtn2State) {
lastBtn2State = currentBtn2;
String status = (currentBtn2 == LOW) ? "PRESSIONADO" : "SOLTO";
client.publish(TOPIC_PREFIX "/btn2", status.c_str());
delay(50);
}
}
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Conectando ao WiFi: ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi conectado!");
}
void callback(char* topic, byte* payload, unsigned int length) {
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
Serial.print("Comando [");
Serial.print(topic);
Serial.print("]: ");
Serial.println(message);
if (String(topic) == TOPIC_PREFIX "/led1") {
if (message == "1" || message == "on" || message == "ON") digitalWrite(LED1_PIN, HIGH);
else if (message == "0" || message == "off" || message == "OFF") digitalWrite(LED1_PIN, LOW);
}
if (String(topic) == TOPIC_PREFIX "/led2") {
if (message == "1" || message == "on" || message == "ON") digitalWrite(LED2_PIN, HIGH);
else if (message == "0" || message == "off" || message == "OFF") digitalWrite(LED2_PIN, LOW);
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Conectando ao Maqiatto...");
// Cria um ID aleatório
String clientId = "ESP32-Eduardo-";
clientId += String(random(0xffff), HEX);
// --- AQUI ESTÁ A MUDANÇA PRINCIPAL PARA O MAQIATTO ---
// connect(clientId, username, password)
if (client.connect(clientId.c_str(), mqttUser, mqttPassword)) {
Serial.println("Conectado!");
client.publish(TOPIC_PREFIX "/status", "Online");
client.subscribe(TOPIC_PREFIX "/led1");
client.subscribe(TOPIC_PREFIX "/led2");
} else {
Serial.print("Falha, rc=");
Serial.print(client.state());
Serial.println(" Tentando em 5s...");
delay(5000);
}
}
}