Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ArduinoJson.h>
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- #include "DHT.h"
- #define DHTTYPE DHT22
- long last;
- const int DHTPin = D2;
- const int APin = A0;
- int motion=2;
- const char* ssid = "pi_ap";
- const char* password = "password";
- const char* mqttServer = "192.168.50.10";
- const int mqttPort = 1883;
- const char* mqttUser = "admin";
- const char* mqttPassword = "password";
- const char* mqttDeviceID = "ESP8266_01";
- const char* data;
- boolean pir;
- DHT dht(DHTPin, DHTTYPE);
- WiFiClient espClient;
- PubSubClient client(espClient);
- float temperature = 0;
- float humidity = 0;
- float Gas = 0;
- float LDR = 0;
- StaticJsonBuffer<200> jsonBuffer;
- JsonObject& root = jsonBuffer.createObject();
- void setup() {
- Serial.begin(115200);
- dht.begin();
- pinMode(D6, OUTPUT);
- client.setServer(mqttServer, mqttPort);
- }
- void reconnect() {
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.println("Connecting to WiFi..");
- }
- Serial.println("Connected to the WiFi network");
- while (!client.connected()) {
- Serial.println("Connecting to MQTT...");
- if (client.connect(mqttDeviceID, mqttUser, mqttPassword )) {
- Serial.println("connected");
- } else {
- Serial.print("failed with state ");
- Serial.print(client.state());
- delay(3000);
- }
- }
- }
- void readSensor() {
- float h = dht.readHumidity();
- float t = dht.readTemperature();
- digitalWrite(D6,LOW);
- delay(2);
- float sensorValue = analogRead(A0);
- LDR = (10*sensorValue/1023)*100;
- digitalWrite(D6,HIGH);
- delay(2);
- float sensorValue2 = analogRead(A0);
- Gas = ((1,5*sensorValue2) / 1023)*100;
- pir = digitalRead(D1);
- if (pir == LOW) { motion = 0;}
- else { motion = 1; }
- if (isnan(h) || isnan(t)) {
- Serial.println("Failed to read from DHT sensor!");
- temperature = 0;
- humidity = 0;
- return;
- }else {
- temperature = t;
- humidity = h;
- }
- }
- void preparedata(){
- root["myName"] = mqttDeviceID;
- root["temp"] = temperature;
- root["humid"] = humidity;
- root["motion"] = motion;
- root["gas"] = Gas;
- root["LDR"] = LDR;
- }
- void MinuteDelay(int number){
- for (int i = 0; i < number; ++i)
- {
- // use 6 10 second delays for each minute
- for(int j=0; j<6 ;j++)
- {
- Serial.print("*");
- delay(10000);
- }
- }
- }
- void loop()
- {
- if (!client.connected()) {
- reconnect();
- }
- if(millis()-last>300000){ //send message after every 5 minute
- last=millis();
- delay(550);//try to change this delay if you get problem in sending message
- client.loop();
- readSensor();
- preparedata();
- char JSONmessageBuffer[150];
- root.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
- Serial.println(JSONmessageBuffer);
- client.publish("esp8266/esp_01/sensors", JSONmessageBuffer);
- }
- }
Add Comment
Please, Sign In to add comment