Guest User

Untitled

a guest
Nov 9th, 2018
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. #include <PubSubClient.h>
  2. #include <WiFi.h>
  3.  
  4. const char* ssid = “rede”;
  5. const char* password = “senha”;
  6. const char* mqttServer = “m15.cloudmqtt.com”;
  7. const int mqttPort = 16836;
  8. const char* mqttUser = “usuario”;
  9. const char* mqttPassword = “senha”;
  10. int LED_BUILTIN = 2;
  11. WiFiClient espClient;
  12. PubSubClient client(espClient);
  13.  
  14. void setup() {
  15. pinMode (LED_BUILTIN, OUTPUT);
  16.  
  17. Serial.begin(115200);
  18. WiFi.begin(ssid, password);
  19.  
  20. while (WiFi.status() != WL_CONNECTED) {
  21. delay(500);
  22. Serial.print(“Connecting to WiFi:”);
  23. Serial.println(ssid);
  24. }
  25.  
  26. Serial.println(“Connected to the WiFi network”);
  27. Serial.println(“”);
  28. Serial.println(“IP address: “);
  29. Serial.println(WiFi.localIP());
  30. client.setServer(mqttServer, mqttPort);
  31. client.setCallback(callback);
  32.  
  33. while (!client.connected()) {
  34. Serial.println(“Connecting to MQTT…”);
  35. String clientId = “ESP32Client-”;
  36. clientId += String(random(0xffff), HEX);
  37. if (client.connect(clientId.c_str(), mqttUser, mqttPassword )) {
  38. Serial.println(“connected”);
  39. } else {
  40. Serial.print(“failed with state “);
  41. Serial.print(client.state());
  42. delay(2000);
  43. }
  44. }
  45.  
  46. Serial.print(“Tentando enviar a mensagem”);
  47. client.publish(“esp∕test”, “Hello from ESP32”);
  48. client.subscribe(“esp/test”);
  49.  
  50. }
  51.  
  52. void callback(char* topic, byte* payload, unsigned int length) {
  53.  
  54. Serial.print(“Message arrived in topic: “);
  55. Serial.println(topic);
  56.  
  57. Serial.print(“Message:”);
  58. for (int i = 0; i < length; i++) {
  59. Serial.print((char)payload[i]);
  60. }
  61.  
  62. if (payload[0] == ‘0’){
  63. Serial.println(“Desligando luz”);
  64. digitalWrite(LED_BUILTIN, LOW);
  65. }
  66.  
  67. if (payload[0] == ‘1’){
  68. Serial.println(“Ligando luz”);
  69. digitalWrite(LED_BUILTIN, HIGH);
  70. }
  71.  
  72. Serial.println();
  73. Serial.println(“ — — — — — — — — — — — -”);
  74.  
  75. }
  76.  
  77. void loop() {
  78. client.loop();
  79. }
Add Comment
Please, Sign In to add comment