Guest User

Untitled

a guest
Jul 13th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. const char* ssid = "YourNetworkName";
  5. const char* password = "YourNetworkPassword";
  6. const char* mqttServer = "m11.cloudmqtt.com";
  7. const int mqttPort = 12948; //your port number
  8. const char* mqttUser = "YourMqttUser";
  9. const char* mqttPassword = "YourMqttUserPassword";
  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("esp/test", "Hello from ESP8266");
  46. client.subscribe("esp/test");
  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.loop();
  67. }
Add Comment
Please, Sign In to add comment