Advertisement
mudhita_triari

ESP32 MQTT - Subscriber

Mar 24th, 2024
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | Source Code | 0 0
  1. #include <WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. // WiFi
  5. const char *ssid = "RobotikID";
  6. const char *password = "123456789";
  7.  
  8. // MQTT Broker
  9. const char *mqtt_broker = "free.mqtt.iyoti.id";
  10. const char *topic_pub = "robotikid/pub";
  11. const char *topic_sub = "robotikid/sub";
  12. //const char *mqtt_username = "RobotikID";
  13. //const char *mqtt_password = "1234567";
  14. const int mqtt_port = 1883;
  15. String client_id = "RobotikID";
  16.  
  17. WiFiClient espClient;
  18. PubSubClient client(espClient);
  19.  
  20. void setup() {
  21.    Serial.begin(115200);
  22.  
  23.    WiFi.begin(ssid, password);
  24.    while (WiFi.status() != WL_CONNECTED) {
  25.        delay(500);
  26.        Serial.println("Menghubungkan ke WiFi..");
  27.    }
  28.    Serial.println("Terhubung ke WiFi");
  29.  
  30.    //Menghubungkan ke mqtt broker
  31.    client.setServer(mqtt_broker, mqtt_port);
  32.    client.setCallback(callback);
  33.    while (!client.connected()) {
  34.        if (client.connect(client_id.c_str())) {
  35.            Serial.println("Terhubung ke mqtt broker");
  36.        } else {
  37.            Serial.print("Gagal Terhubung ");
  38.            Serial.print(client.state());
  39.            delay(2000);
  40.        }
  41.    }
  42.    
  43.    // publish and subscribe
  44.    client.publish(topic_pub, "Hi, ESP32");
  45.    client.subscribe(topic_sub);  
  46. }
  47.  
  48. void callback(char *topic, byte *payload, unsigned int length) {
  49.    Serial.print("Dari Topik: ");
  50.    Serial.println(topic);
  51.    Serial.print("Pesannya:");
  52.    for (int i = 0; i < length; i++) {
  53.        Serial.print((char) payload[i]);
  54.    }
  55.    Serial.println();
  56. }
  57.  
  58. void loop() {
  59.  client.loop();
  60. }
Tags: #esp32 #MQTT
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement