##// END OF EJS Templates
Publica y suscribe valores aleatorios...
JesusTapia-dev -
r10:cc99a83a23bd
parent child
Show More
@@ -1,9 +1,80
1 void setup() {
1 #include <WiFi.h>
2 // put your setup code here, to run once:
2 #include <PubSubClient.h>
3
4 const char *ssid = "maracumango";
5 const char *password = "12345678";
6 const char *mqtt_server = "192.168.199.158";
7 const int mqtt_port = 1883;
8 const char *mqtt_client_id = "ESP32_Client";
9 const char *subscribe_topic = "tesis/potenciaNominal";
10 const char *publish_topic = "tesis/potencia";
11
12 WiFiClient espClient;
13 PubSubClient client(espClient);
3
14
15 void setup_wifi() {
16 delay(10);
17 Serial.println();
18 Serial.print("Conectando a ");
19 Serial.println(ssid);
20 WiFi.begin(ssid, password);
21 while (WiFi.status() != WL_CONNECTED) {
22 delay(500);
23 Serial.print(".");
24 }
25 Serial.println("");
26 Serial.println("Conectado a la red WiFi");
27 Serial.println("Dirección IP: ");
28 Serial.println(WiFi.localIP());
4 }
29 }
5
30
6 void loop() {
31 void callback(char *topic, byte *payload, unsigned int length) {
7 // put your main code here, to run repeatedly:
32 Serial.print("Mensaje recibido en el tópico: ");
33 Serial.println(topic);
34 // Convierte el payload a una cadena de caracteres
35 char receivedValue[length + 1];
36 strncpy(receivedValue, (char *)payload, length);
37 receivedValue[length] = '\0';
38 // Convierte la cadena a un número (en este caso, asume que es un float)
39 float potenciaNominal = atof(receivedValue);
40 // Realiza cálculos basados en la potencia nominal recibida (sustituye con tu lógica)
41 float voltajeCalculado = potenciaNominal * 1.2;
42 // Publica el resultado en el tópico de voltaje
43 char result[10];
44 snprintf(result, sizeof(result), "%.2f", voltajeCalculado);
45 client.publish(publish_topic, result);
46 }
47
48 void reconnect() {
49 while (!client.connected()) {
50 Serial.print("Intentando conexión MQTT...");
8
51
52 if (client.connect(mqtt_client_id)) {
53 Serial.println("Conectado al servidor MQTT");
54 client.subscribe(subscribe_topic);
55 } else {
56 Serial.print("Falló, rc=");
57 Serial.print(client.state());
58 Serial.println(" Intentando de nuevo en 5 segundos");
59 delay(5000);
60 }
61 }
62 }
63
64 void setup() {
65 Serial.begin(115200);
66 setup_wifi();
67 client.setServer(mqtt_server, mqtt_port);
68 client.setCallback(callback);
69 }
70
71 void loop() {
72 if (!client.connected()) {
73 reconnect();
74 }
75 client.loop();
76 char str[16];
77 sprintf(str, "%u", random(100));
78 client.publish(publish_topic, str);
79 delay(500);
9 }
80 }
General Comments 0
You need to be logged in to leave comments. Login now