#include <WiFi.h>
#include <PubSubClient.h>
// Pines del sensor de ultrasonidos
#define LED_BUILTIN 14
#define GPIO_A0 34
// Punto de acceso wifi al que se conecta el dispositivo
char ssid[] = "Wokwi-GUEST"; // your network SSID Name
char pass[] = ""; // your network password
int status = WL_IDLE_STATUS;
WiFiClient wifi_client;
const char* mqtt_server = "mqtt-dashboard.com";
const int mqtt_port = 1883;
PubSubClient mqttClient(wifi_client);
void reconnect() {
Serial.println("Connecting to MQTT Broker...");
while (!mqttClient.connected()) {
Serial.println("Reconnecting to MQTT Broker..");
String clientId = "ESP32Client-";
clientId += String("sefsefsefaesf");
mqttClient.setKeepAlive(60);
if (mqttClient.connect(clientId.c_str())) {
Serial.println("Connected.");
//mqttClient.subscribe("/ugr/#");
}else{
Serial.println("Not connected.");
}
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Callback - ");
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
}
void setupMQTT() {
mqttClient.setServer(mqtt_server, mqtt_port);
// set the callback function
mqttClient.setCallback(callback);
}
void setup() {
Serial.begin(9600);
pinMode ( LED_BUILTIN, OUTPUT );
//Conexión a la WiFi y al cloud
WiFi.begin(ssid, pass);
setupMQTT();
delay(500);
pinMode(GPIO_A0,INPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(500);
digitalWrite(LED_BUILTIN, LOW);
// Medida de la distancia
delayMicroseconds(10);
// These constants should match the photoresistor's "gamma" and "rl10" attributes
const float GAMMA = 0.7;
const float RL10 = 50;
// Convert the analog value into lux value:
int analogValue = analogRead(GPIO_A0);
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));
// Visualización por el puerto serie
Serial.print("Iluminacion: ");
Serial.println(lux);
if (!mqttClient.connected())
reconnect();
String mensaje = String(lux);
mqttClient.publish("ugr/josep/wokwi/iluminacion", mensaje.c_str());
delay(5000);
}