// Exemplo de codigo para esp32 realizando a leitura de botões e potenciometro
// mude os tópicos IFSP/led e esp32/ADC para personalizar seu IoT
// Instale em seu computador as bibliotecas PubSubClient e ArduinoJson
// https://www.arduino.cc/reference/en/libraries/pubsubclient/
// https://www.arduino.cc/reference/en/libraries/arduinojson/
#include <WiFi.h>
#include "PubSubClient.h"
#include <ArduinoJson.h>
// configurações da rede wifi
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// define canal de conexao wifi mais rapido
#define WIFI_CHANNEL 6
// servidor broker mqtt
const char* mqttServer = "broker.hivemq.com";
const int mqttPort = 1883;
const char* mqttUser = "mchavesferreira";
const char* mqttPassword = "Embar2022";
const char* mqttTopic = "IFSP/led";
const char* clientId = "ESP32";
const int analogPin = 36;
const int ledPin = 2;
int lastSensorValue = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void mqttSendJson(float valor1){
//Envia a mensagem ao broker
/// . produzindo mensagem Json
DynamicJsonDocument doc(1024);
doc["device"] = "ESP32";
doc["analogico"] = valor1;
char JSONmessageBuffer[200];
serializeJson(doc, JSONmessageBuffer);
client.publish("esp32/ADC", JSONmessageBuffer);
Serial.print("msg json enviado: ");
Serial.println(JSONmessageBuffer);
}
void mqttSendJsonIO(void){
//Envia a mensagem ao broker
/// . produzindo mensagem Json com o objeto
DynamicJsonDocument doc(1024);
doc["device"] = "ESP32";
doc["OUT1"] = digitalRead(34);
doc["OUT2"] = digitalRead(35);
char JSONmessageBuffer[200];
serializeJson(doc, JSONmessageBuffer);
client.publish("esp32/out", JSONmessageBuffer);
Serial.print("msg json out enviado: ");
Serial.println(JSONmessageBuffer);
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(34, INPUT);
pinMode(35, INPUT);
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connecting to WiFi ");
Serial.print(WIFI_SSID);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
Serial.println("Connected to WiFi");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect(clientId, mqttUser, mqttPassword)) {
Serial.println("Connected to MQTT");
client.subscribe(mqttTopic);
} else {
Serial.print("MQTT connection failed, retrying in 5 seconds...");
delay(5000);
}
}
}
void loop() {
client.loop();
int sensorValue = analogRead(analogPin);
// analise se o valor analógico teve variação maior que 10
if (abs(sensorValue - lastSensorValue) >= 10) {
client.publish("esp32/ADCraw", String(sensorValue).c_str());
lastSensorValue = sensorValue;
float valor=((float)sensorValue/4095)*3.3;
mqttSendJson(valor);
mqttSendJsonIO();
}
delay(500);
}
void callback(char* topic, byte* payload, unsigned int length) {
String topicStr = topic;
if (topicStr.equals("IFSP/led")) {
String payloadStr = "";
for (int i = 0; i < length; i++) {
payloadStr += (char)payload[i];
}
if (payloadStr.equals("on")) {
digitalWrite(ledPin, HIGH);
} else if (payloadStr.equals("off")) {
digitalWrite(ledPin, LOW);
}
}
}