#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
///########### configuração do wifi
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
// Defining the WiFi channel speeds up the connection:
#define WIFI_CHANNEL 6
int status = WL_IDLE_STATUS; // the Wifi radio's status
//////###configuração do LDR
#define LDR_PIN 34 ///define o pino de leitura do fotoresistor
// LDR Characteristics
// Essas constantes devem corresponder aos atributos "gama" e "rl10" do fotoresistor
const float GAMMA = 0.7;
const float RL10 = 33;
int valorAnterior = 0; // Variável para armazenar o valor anterior
float lux=0;
///########## configuração do MQTT
const char* mqtt_server = "test.mosquitto.org";// MQTT broker
char* my_topic_SUB = "FIT/SUB";// the chosen topic
char* my_topic_PUB = "FIT/PUB";// the chosen topic
/////##### configuração do wifi e MQTT
WiFiClient espClient;
PubSubClient client(espClient);
/////###configuração do tempo de leitura
int contador = 1;
char mensagem[30];
unsigned long lastMillis = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
conectawifi();
client.setServer(mqtt_server, 1883); // Set the MQTT broker server and port
client.setCallback(callback); // Set the callback function for incoming MQTT messages
}
void loop() {
// put your main code here, to run repeatedly:
float luz = fotoresistor();
// Check MQTT connection and process incoming messages
if (!client.connected()) {
reconnect();
}
client.loop();
delay(100); // Add a delay to avoid flooding the MQTT broker with messages
//Aguarda 15 segundos para enviar uma nova mensagem
if (millis() - lastMillis > 15000) {
lastMillis = millis();
sprintf(mensagem, "%d", luz);
//sprintf(mensagem, "MQTT ESP32 - Mensagem no. %d", contador);
Serial.print("Mensagem enviada: ");
Serial.println(mensagem);
//Envia a mensagem ao broker
client.publish(my_topic_PUB, mensagem);
Serial.print(contador);
Serial.println("-Mensagem enviada com sucesso...");
//Incrementa o contador
contador++;
}
delay(10); // this speeds up the simulation
}
void conectawifi()
{
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Conectando ao WiFi ");
Serial.print(WIFI_SSID);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
//WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
}
Serial.println(" Conectado!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
float fotoresistor()
{
int analogValue = analogRead(LDR_PIN);
//Serial.println(analogValue);
////só faz a leitura se houver uma alteração no valor
if (analogValue != valorAnterior) {
float voltage = analogValue / 4096. * 3.3;
float resistance = 2000 * voltage / (1 - voltage / 3.3);
lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
Serial.print("Ambiente: ");
///Iluminação do escritório valor 400
if (lux > 400) {
Serial.println("Claro!");
} else {
Serial.println("Escuro ");
}
Serial.print("Luminosidade: ");
Serial.println(lux);
// Atualiza o valor anterior com o novo valor
valorAnterior = analogValue;
}
return lux;
}
// Process incoming MQTT message and control the servo motor
void callback(char* topic, byte* payload, unsigned int length) {
String string;
Serial.print("Chegou a mensagem [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
string+=((char)payload[i]);
}
Serial.print(string);
}
// Attempt to reconnect to the MQTT broker if the connection is lost
void reconnect() {
while (!client.connected()) {
Serial.print("Tentando conectar ao MQTT ...");
if (client.connect("ESPClient")) {
Serial.println("Conectado");
client.subscribe(my_topic_SUB);
} else {
Serial.print("falhou, rc=");
Serial.print(client.state());
Serial.println(" Tente novamente em 5 segundos");
}
}
}