Advertisement
Guest User

NODEMCU_sketch

a guest
Jan 18th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. #define interruptPin D1
  5.  
  6. const char* ssid = "Jorge 2.4";
  7. const char* password = "";
  8. const char* mqtt_server = "iot.eclipse.org";
  9.  
  10. WiFiClient espClient;
  11. PubSubClient mqttClient(espClient);
  12.  
  13. long lastReconnectAttempt = 0;
  14. String message = "";
  15. int timer = millis();
  16. void callback(char* topic, byte* payload, unsigned int length) {
  17. message = "";
  18. for (int i = 0; i < length; i++) {
  19. message += (char) payload[i];
  20. }
  21. message.toLowerCase();
  22. message.trim();
  23. }
  24.  
  25. boolean reconnect() {
  26. String clientId = "ESP8266Client-";
  27. clientId += String(random(0xffff), HEX);
  28.  
  29. if (mqttClient.connect(clientId.c_str())) {
  30. mqttClient.publish("julinho/enable", "1");
  31. mqttClient.publish("julinho/sos", "0");
  32. mqttClient.subscribe("julinha/rota");
  33. }
  34.  
  35. return mqttClient.connected();
  36. }
  37.  
  38. void setup() {
  39. Serial.begin(9600);
  40. WiFi.begin(ssid, password);
  41. pinMode(interruptPin, OUTPUT);
  42. digitalWrite(interruptPin, HIGH);
  43. while (WiFi.status() != WL_CONNECTED) {
  44. delay(500);
  45. }
  46. mqttClient.setServer(mqtt_server, 1883);
  47. mqttClient.setCallback(callback);
  48. Serial.println("Setup feito");
  49. }
  50.  
  51. void loop() {
  52. if (!mqttClient.connected()) {
  53. long now = millis();
  54. if (now - lastReconnectAttempt > 5000) {
  55. lastReconnectAttempt = now;
  56. if (reconnect()) {
  57. lastReconnectAttempt = 0;
  58. }
  59. }
  60. return;
  61. }
  62. if (Serial.available()) {
  63. String messageCheck = Serial.readString();
  64. char check[messageCheck.length()];
  65. messageCheck.toCharArray(check, messageCheck.length());
  66. mqttClient.publish("julinho/check", check);
  67. }
  68.  
  69. boolean routeExists = message.compareTo("") != 0;
  70.  
  71. if (!routeExists) {
  72. delay(100);
  73. mqttClient.loop();
  74. return;
  75. }
  76.  
  77. digitalWrite(interruptPin, LOW);
  78. Serial.print(message);
  79. message = "";
  80. delay(2000);
  81. ESP.deepSleep(30e6);
  82. delay(100);
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement