peepraeza

mqtt example

Oct 1st, 2018
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. const char* ssid = "Peerawit-WiFi";                   // wifi ssid
  5. const char* password =  "p12345678";         // wifi password
  6. const char* mqttServer = "192.168.0.104";    // IP adress Raspberry Pi
  7. const int mqttPort = 1883;
  8. const char* mqttUser = "";      // if you don't have MQTT Username, no need input
  9. const char* mqttPassword = "";  // if you don't have MQTT Password, no need input
  10.  
  11. WiFiClient espClient;
  12. PubSubClient client(espClient);
  13.  
  14. void setup() {
  15.  
  16.   Serial.begin(115200);
  17.  
  18.   WiFi.begin(ssid, password);
  19.  
  20.   while (WiFi.status() != WL_CONNECTED) {
  21.     delay(500);
  22.     Serial.println("Connecting to WiFi..");
  23.   }
  24.   Serial.println("Connected to the WiFi network");
  25.  
  26.   client.setServer(mqttServer, mqttPort);
  27.   client.setCallback(callback);
  28.  
  29.   while (!client.connected()) {
  30.     Serial.println("Connecting to MQTT...");
  31.  
  32.     if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
  33.  
  34.       Serial.println("connected");
  35.  
  36.     } else {
  37.  
  38.       Serial.print("failed with state ");
  39.       Serial.print(client.state());
  40.       delay(2000);
  41.  
  42.     }
  43.   }
  44.  
  45. //  client.publish("esp8266", "Hello Raspberry Pi");
  46. //  client.subscribe("esp8266");
  47.  
  48. }
  49.  
  50. void callback(char* topic, byte* payload, unsigned int length) {
  51.  
  52.   Serial.print("Message arrived in topic: ");
  53.   Serial.println(topic);
  54.  
  55.   Serial.print("Message:");
  56.   for (int i = 0; i < length; i++) {
  57.     Serial.print((char)payload[i]);
  58.   }
  59.  
  60.   Serial.println();
  61.   Serial.println("-----------------------");
  62.  
  63. }
  64.  
  65. void loop() {
  66.     client.publish("esp8266", "Hello Peeja");
  67.     client.subscribe("esp8266");
  68.     delay(300);
  69.      
  70.     client.loop();
  71. }
Add Comment
Please, Sign In to add comment