Guest User

Untitled

a guest
Nov 25th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. #include <Adafruit_Sensor.h> //Bibliotecas usadas no código
  2. #include <ArduinoJson.h>
  3. #include <ESP8266WiFi.h>
  4. #include <PubSubClient.h>
  5. #include <MQ135.h>
  6. #include "DHT.h"
  7. #include "MQ7.h"
  8. #include <stdlib.h>
  9.  
  10. #define DHTPIN 3 // pino do sensor de temperatura
  11. #define DHTTYPE DHT22 // DHT 22
  12. #define MQ135PIN A0 // pino do sensor de gas A0 = A0
  13.  
  14.  
  15. DHT dht(DHTPIN, DHTTYPE);
  16. MQ135 gasSensor = MQ135(MQ135PIN);
  17.  
  18. // Update these with values suitable for your network.
  19.  
  20. const char* ssid = "REDE";
  21. const char* password = "senha";
  22. const char* mqttServer = "broker.hivemq.com";
  23. const int mqttPort = 1883;
  24. const char* mqttUser = "";
  25. const char* mqttPassword = "";
  26.  
  27. char json[100];
  28.  
  29. WiFiClient espClient;
  30. PubSubClient client(espClient);
  31.  
  32. void setup()
  33. {
  34. Serial.begin(115200);
  35. Serial.println("DHTxx test!");
  36. dht.begin();
  37.  
  38. WiFi.begin(ssid, password);
  39.  
  40. while (WiFi.status() != WL_CONNECTED) {
  41. delay(500);
  42. Serial.println("Connecting to WiFi..");
  43. }
  44.  
  45. Serial.println("Connected to the WiFi network");
  46.  
  47. client.setServer(mqttServer, mqttPort);
  48.  
  49. while (!client.connected()) {
  50. Serial.println("Connecting to MQTT...");
  51.  
  52. if (client.connect("ESP8266Client", mqttUser, mqttPassword)) {
  53.  
  54. Serial.println("connected");
  55.  
  56. } else {
  57.  
  58. Serial.print("failed with state ");
  59. Serial.print(client.state());
  60. delay(2000);
  61.  
  62. }
  63. }
  64. }
  65.  
  66. void loop()
  67. {
  68. // A leitura da temperatura e umidade pode levar 250ms!
  69. // O atraso do sensor pode chegar a 2 segundos.
  70. float valor_umidade = dht.readHumidity();
  71. float valor_temp = dht.readTemperature();
  72. float valor_co2 = analogRead(A0);
  73.  
  74. // testa se retorno é valido, caso contrário algo está errado.
  75. if (isnan(valor_co2))
  76. {
  77. Serial.println("Failed to read from MQ-135");
  78. }
  79. else
  80. {
  81.  
  82.  
  83. DynamicJsonBuffer jBuffer;
  84. JsonObject & root = jBuffer.createObject();
  85.  
  86. root["temperatura"] = valor_temp;
  87. root["umidade"] = valor_umidade;
  88. root["nivel_co"] = valor_co2;
  89.  
  90. root.printTo(Serial);
  91. Serial.println();
  92.  
  93. root.printTo(json);
  94. client.publish("smartcity/tdc2", json);
  95. client.loop();
  96.  
  97. }
  98.  
  99. delay(10000);
  100.  
  101. }
Add Comment
Please, Sign In to add comment