evenjc

ESP32-WiFi-MQTT-Publis-Reconnect

May 24th, 2023 (edited)
1,015
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. const char* ssid = "ssid";
  5. const char* password = "psk";
  6.  
  7. const char* mqtt_server = "192.168.245.157";
  8.  
  9. WiFiClient espClient;
  10. PubSubClient client(espClient);
  11.  
  12. void setup() {
  13.   Serial.begin(115200);
  14.   WiFi.begin(ssid, password);
  15.  
  16.   while (WiFi.status() != WL_CONNECTED) {
  17.     delay(500);
  18.     Serial.print(".");
  19.   }
  20.  
  21.   Serial.println("");
  22.   Serial.println("WiFi connected");
  23.   Serial.println("IP address: ");
  24.   Serial.println(WiFi.localIP());
  25.  
  26.   client.setServer(mqtt_server, 1883);
  27. }
  28. void reconnect() {
  29.   // Loop until we're reconnected
  30.   while (!client.connected()) {
  31.     Serial.print("Attempting MQTT connection...");
  32.     // Attempt to connect
  33.     if (client.connect("ESP8266Client")) {
  34.       Serial.println("connected");
  35.       // Subscribe
  36.       client.subscribe("esp32/output");
  37.     } else {
  38.       Serial.print("failed, rc=");
  39.       Serial.print(client.state());
  40.       Serial.println(" try again in 5 seconds");
  41.       // Wait 5 seconds before retrying
  42.       delay(5000);
  43.     }
  44.   }
  45. }
  46. void loop() {
  47.   if (!client.connected()) {
  48.     reconnect();
  49.   }
  50.   client.loop();
  51.   // Sender value til topic/topic og venter 10 sek.
  52.  
  53.   Serial.println("Sender heia til esp32/test");
  54.   client.publish("esp32/test", "heia");
  55.   delay(10000);
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment