Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. const char* ssid = "*****";
  5. const char* password = "****";
  6. const char* mqttServer = "****";
  7. const int mqttPort = 1883;
  8. const char* mqttUser = ???;
  9. const char* mqttPassword = ???;
  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("topic1", "Hello from ESP8266_tester1");
  46. client.subscribe("topic1");
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement