working on it ...

Filters

Explore Public Snippets

Sort by

Found 71 snippets matching: dht22

    public by tomsim  1379  2  6  0

    ESP8266 wifi web server setup

    Lambda style Wifi web server with DHT22 data upload to ThingSpeak
    /* DHTServer - ESP8266 Webserver with a DHT sensor as an input
    
       Based on ESP8266Webserver, DHTexample, and BlinkWithoutDelay (thank you)
    
       Version 1.0  5/3/2014  Version 1.0 Mike Barela for Adafruit Industries
    */
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <DHT.h>
    #include <TimeLib.h>
    #include "ThingSpeak.h"
    
    #define DHTTYPE DHT22
    
    const int DHTPIN = D4;
    
    const char* ssid     = "mySSID";
    const char* password = "myPassword";
    
    ESP8266WebServer server(80);
    
    /*============ ThingSpeak setup ==================*/
    // Note:  Each channel has its own number and write API key
    // API key is what get used - wrong channel number doesn't matter
    
    // Temperature Humidity Channel
    static unsigned long myChannelNumber = 123456;
    static const char 	*myWriteAPIKey = "AB1CDEF6HIJKLMNO";
    static WiFiClient  client;
    
    /*============ End ThingSpeak setup ==============*/
    
    
    // Initialize DHT sensor 
    // NOTE: For working with a faster than ATmega328p 16 MHz Arduino chip, like an ESP8266,
    // you need to increase the threshold for cycle counts considered a 1 or 0.
    // You can do this by passing a 3rd parameter for this threshold.  It's a bit
    // of fiddling to find the right value, but in general the faster the CPU the
    // higher the value.  The default for a 16mhz AVR is a value of 6.  For an
    // Arduino Due that runs at 84mhz a value of 30 works.
    // This is for the ESP8266 processor on ESP-01 
    DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266
     
    float lastHumdty, lastTempF;  // Values read from sensor
    static int nextSampleMinute = 15;
    static int minuteSampleInterval = 15;
    
    // Generally, you should use "unsigned long" for variables that hold time
    unsigned long previousMillis = 0;        // will store last temp was read
    const long interval = 2000;              // interval at which to read sensor
    
    void getTemperature() {
      // Wait at least 2 seconds seconds between measurements.
      // if the difference between the current time and last time you read
      // the sensor is bigger than the interval you set, read the sensor
      // Works better than delay for things happening elsewhere also
      unsigned long currentMillis = millis();
     
      if(currentMillis - previousMillis >= interval) {
        // save the last time you read the sensor 
        previousMillis = currentMillis;   
    
        // Reading temperature for humidity takes about 250 milliseconds!
        // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
        lastHumdty = dht.readHumidity();          // Read humidity (percent)
        lastTempF = dht.readTemperature(true);     // Read temperature as Fahrenheit
        // Check if any reads failed and exit early (to try again).
        if (isnan(lastHumdty) || isnan(lastTempF)) {
          Serial.println("Failed to read from DHT sensor!");
          return;
        }
      }
    }
    
    static int uploadData(void)
    {
    	ThingSpeak.setField( 1, lastTempF);
    	ThingSpeak.setField( 2, lastHumdty);
    	int rc = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
    //	Serial.println(String("Post rc=")+rc);
    	return rc;
    }
    
     
    const String HTML_TYPE = "text/html";
    
    void handle_null() {
        Serial.println("Handle null");
    	server.send(200,HTML_TYPE,"");
    	delay(100);
    }
    void handleRoot()
    {
    	String wstr = 
    	"<p>Hello from the weather esp8266, read from /temp or /humidity"
    	"<br>set <a href=/set?minuteSampleInterval=5>5 minute</a> sample interval"
    	", <a href=/set?nextSampleMinute=15>sample at 15 </a> minute"
    	"<br>Take <a href=/sample>sample Data</a> and upload to ThingSpeak"
    	"<br><a href=/temp>Get Temperature</a>"
    	"<br><a href=/humidity>Get Humidity</a>";
    	wstr += "<br>Last temperature: " + String(lastTempF)+"F";
    	wstr += " humidity: " + String(lastHumdty)+"%";
    	wstr += "<br>Current minute: " + String(minute(now()));
    	wstr += " next sample time: " + String(nextSampleMinute)+" min.";
    	wstr += " sample interval: " + String(minuteSampleInterval)+" min.";
    	server.send(200,HTML_TYPE, wstr);
    	delay(100);
    }
    void doSample()
    {
    	Serial.println("DoSample");
    	getTemperature();
    	int rc = uploadData();
    	String wstr = "<p>Take sample data:  ";
    	wstr += "<br>Temperature " + String(lastTempF);
    	wstr += "<br>Humidity " + String(lastHumdty);
    	wstr += "<br>Upload thingspeak rc=" + String(rc);
    	server.send(200,HTML_TYPE, wstr);
    }
     
    // Web Server Service Definition structure
    // =======================================
    typedef struct s_WebServiceDef
    {
    	const char *urlName;
    	void (*doit)(void);
    } WebServiceDef;
    
    /* =======================================================================
    	Define web service definition here
    	Each entry has a URL name and a lambda function to service the request
       =======================================================================
    */
    static WebServiceDef wsd[] = {
    	{ "/", handleRoot },
    	{ "/favicon", handle_null },
    	{ "/temp",			// url name
    		[] ()				// lambda function
    		{
    			getTemperature();       // read sensor
    			String wstr="Temperature: "+String((int)lastTempF)+" F";
    			server.send(200, "text/plain", wstr);   // send to someones browser when asked
    		}
    	},
    	{ "/humidity", []()
    		{ 
    			getTemperature();
    			String wstr="Humidity: "+String((int)lastHumdty)+"%";
    			server.send(200, "text/plain", wstr);
    		}
    	},
    	{ "/sample", doSample },
    	{ "/set", []()
    		{
    			String n = String("minuteSampleInterval");
    			if (server.hasArg(n))
    			{
    				int v = server.arg(n).toInt();
    				if (v)
    					minuteSampleInterval = v;
    			}
    			n = String("nextSampleMinute");
    			if (server.hasArg(n))
    			{
    				int v = server.arg(n).toInt();
    				if (v)
    					nextSampleMinute = v;
    			}
    			server.send(200, "text/plain", "ok");
    		}
    	},
     	{0,0}
    };
    
    static void setupServerHandler(void)
    {
    	for (int i; wsd[i].urlName; i++)
    	{
    		server.on( wsd[i].urlName, wsd[i].doit);
    	}
    	server.onNotFound(handleRoot);
    }
    
    static int nextAlarmMin(int sampleInterval)
    {
    	int nextMin = minute(now());
    	nextMin = ((nextMin + sampleInterval) % 60);	// alarm every 5 min
    	return nextMin;
    }
    
    
    
    void setup(void)
    {
    	// You can open the Arduino IDE Serial Monitor window to see what the code is doing
    	Serial.begin(115200);  // Serial connection from ESP-01 via 3.3v console cable
    	dht.begin();           // initialize temperature sensor
    
    	// Connect to WiFi network
    	WiFi.begin(ssid, password);
    	Serial.print("\n\r \n\rWorking to connect");
    
    	// Wait for connection
    	while (WiFi.status() != WL_CONNECTED) {
    	delay(500);
    	Serial.print(".");
    	}
    	Serial.println("");
    	Serial.println("DHT Weather Reading Server");
    	Serial.print("Connected to ");
    	Serial.println(ssid);
    	Serial.print("IP address: ");
    	Serial.println(WiFi.localIP());
    
    	ThingSpeak.begin(client);
    
    	setupServerHandler();
    
    	server.begin();
    	Serial.println("HTTP server started");
    }
     
    void loop(void)
    {
    	int currentMinute = minute(now());
    
    	if (currentMinute == nextSampleMinute)
    	{
    		// trigger sample at set interval
    		Serial.println("Regular sample");
    		getTemperature();
    		int rc = uploadData();
    		Serial.println("rc=" + String(rc));
    
    		nextSampleMinute = nextAlarmMin(minuteSampleInterval);
    		delay(1000);
    	}
    
    	server.handleClient();
    } 
    
    

    external by Beinnova  68  1  1  0

    Sketch lettura DHT22

    Sketch lettura DHT22: gistfile1.ino
    // Sketch di prova per sensori DHT11/DHT21/DHT22
    
    #include "DHT.h"
    
    #define DHTPIN 2     // definisce il pin di ingresso del segnale proveniente da DHT22
    
    // definisce il tipo di sensore utilizzato
    //#define DHTTYPE DHT11   // DHT 11 
    #define DHTTYPE DHT22   // DHT 22  (AM2302)
    //#define DHTTYPE DHT21   // DHT 21 (AM2301)
    
    // Collegare il pin n°1 (a sinistra) del sensore a +5V
    // Collegare il pin n°2 del sensore DHT22 al pine che avete selezionato come DHTPIN
    // Collegare il pin n°4 del sensore DHT22 (a destra) alla massa comune (GROUND)
    // Collegare una resistenza da 10K tra il pin n°2 (data) e il pin n°1 (+5V) del sensore
    
    // Inizializza il sensore DHT per un arduino a 16 MHZ
    DHT dht(DHTPIN, DHTTYPE);
    
    void setup() {
      Serial.begin(9600); 
      Serial.println("DHT22 test by blaine 2015!");
     
      dht.begin();
    }
    
    void loop() {
      // definisce il tempo di attesa prima di effettuare una lettura
      delay(3000);
    
      // occhio che la lettura dei valori di temperatura è umidità dura circa 300 ms
      // in caso di linea dati non condizionata si vedono i cartoni animati
      float h = dht.readHumidity();
      // legge la temperatura in gradi Celsius
      float t = dht.readTemperature();
      // legge la temperatura in gradi Fahrenheit
      float f = dht.readTemperature(true);
      
      // controlla se esistono delle letture fallite, se si ritenta il ciclo e stampa un messaggio di errore
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("lettura dati fallita dal sensore DHT!");
        return;
      }
    
      // Calcola la temperatura percepita
      // temperatura percepita in gradi Fahrenheit
      float hi = dht.computeHeatIndex(f, h);
      // converte la temperatura percepita in gradi Celsius
      float c_hi = (5.00/9)*(hi-32);
    
    
      Serial.print("temperatura: "); 
      Serial.print(t);
      Serial.print(" *C ");
      Serial.print("umidita': "); 
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("temperatura percepita: ");
      Serial.print(c_hi);
      Serial.println(" *C");
    }
    
    

    external by Anuchit Chalothorn  3173  7  4  0

    nodemcu dht22 module

    nodemcu dht22 module: dht22.lua
    -- ***************************************************************************
    -- DHT22 module for ESP8266 with nodeMCU
    --
    -- Written by Javier Yanez 
    -- but based on a script of Pigs Fly from ESP8266.com forum
    --
    -- MIT license, http://opensource.org/licenses/MIT
    -- ***************************************************************************
    
    local moduleName = ...
    local M = {}
    _G[moduleName] = M
    
    local humidity
    local temperature
    
    function M.read(pin)
      local checksum
      local checksumTest
      humidity = 0
      temperature = 0
      checksum = 0
    
      -- Use Markus Gritsch trick to speed up read/write on GPIO
      local gpio_read = gpio.read
      
      local bitStream = {}
      for j = 1, 40, 1 do
        bitStream[j] = 0
      end
      local bitlength = 0
    
      -- Step 1:  send out start signal to DHT22
      gpio.mode(pin, gpio.OUTPUT)
      gpio.write(pin, gpio.HIGH)
      tmr.delay(100)
      gpio.write(pin, gpio.LOW)
      tmr.delay(20000)
      gpio.write(pin, gpio.HIGH)
      gpio.mode(pin, gpio.INPUT)
    
      -- Step 2:  DHT22 send response signal 
      -- bus will always let up eventually, don't bother with timeout
      while (gpio_read(pin) == 0 ) do end
      local c=0
      while (gpio_read(pin) == 1 and c < 500) do c = c + 1 end
      -- bus will always let up eventually, don't bother with timeout
      while (gpio_read(pin) == 0 ) do end
      c=0
      while (gpio_read(pin) == 1 and c < 500) do c = c + 1 end
      
      -- Step 3: DHT22 send data
      for j = 1, 40, 1 do
        while (gpio_read(pin) == 1 and bitlength < 10 ) do
          bitlength = bitlength + 1
        end
        bitStream[j] = bitlength
        bitlength = 0
        -- bus will always let up eventually, don't bother with timeout
        while (gpio_read(pin) == 0) do end
      end
    
      --DHT data acquired, process.
      for i = 1, 16, 1 do
        if (bitStream[i] > 4) then
          humidity = humidity + 2 ^ (16 - i)
        end
      end
      for i = 1, 16, 1 do
        if (bitStream[i + 16] > 4) then
          temperature = temperature + 2 ^ (16 - i)
        end
      end
      for i = 1, 8, 1 do
        if (bitStream[i + 32] > 4) then
          checksum = checksum + 2 ^ (8 - i)
        end
      end
    
      checksumTest = (bit.band(humidity, 0xFF) + bit.rshift(humidity, 8) + bit.band(temperature, 0xFF) + bit.rshift(temperature, 8))
      checksumTest = bit.band(checksumTest, 0xFF)
    
      if temperature > 0x8000 then
        -- convert to negative format
        temperature = -(temperature - 0x8000)
      end
    
      -- conditions compatible con float point and integer
      if (checksumTest - checksum >= 1) or (checksum - checksumTest >= 1) then
        humidity = nil
      end
    end
    
    function M.getTemperature()
      return temperature
    end
    
    function M.getHumidity()
      return humidity
    end
    
    return M
    
    

    external by anoochit  3423  2  4  0

    read temperature from dht22 for raspberry pi

    read temperature from dht22 for raspberry pi: dht22.py
    #!/usr/bin/python
    import sys
    import time
    import Adafruit_DHT
    
    sensor = Adafruit_DHT.DHT22
    pin = 4
    
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    
    while True:
      if humidity is not None and temperature is not None:
    	print 'Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity)
    	time.sleep(2)
      else:
    	print 'Failed to get reading. Try again!'
    	
    
    
    

    external by chaosong  1683  18  3  0

    nodemcu read dht22 and pms5003

    nodemcu read dht22 and pms5003: home_env.lua
    function initWIFI()
        print("Setting up WIFI...")
        wifi.setmode(wifi.STATION)
    
        wifi.sta.config("<wifi-id>", "<wifi-password>")
        wifi.sta.connect()
        tmr.alarm(1, 1000, 1,
            function()
                if wifi.sta.getip()== nil then
                    print("IP unavailable, Waiting...")
                else
                    tmr.stop(1)
                    print("Config done, IP is "..wifi.sta.getip())
                    end
                end -- function
        )
    end -- initWIFI
    
    
    function initUDP()
        -- setup UDP port
        cu = net.createConnection(net.UDP)
        cu:connect(55555, "192.168.18.163")
    end -- initUDP
    
    
    function parse(data)
        local bs = {}
        for i = 1, #data do
            bs[i] = string.byte(data, i)
        end
    
        if (bs[1] ~= 0x42) or (bs[2] ~= 0x4d) then
            return nil
        end 
    
        local d = {}
        
        d['pm1_0-CF1-ST'] = bs[5] * 256 + bs[6]
        d['pm2_5-CF1-ST'] = bs[7] * 256 + bs[8]
        d['pm10-CF1-ST'] = bs[9] * 256 + bs[10]
        d['pm1_0-AT'] = bs[11] * 256 + bs[12]
        d['pm2_5-AT'] = bs[13] * 256 + bs[14]
        d['pm10-AT'] = bs[15] * 256 + bs[16]
        d['0_3um-count'] = bs[17] * 256 + bs[18]
        d['0_5um-count'] = bs[19] * 256 + bs[20]
        d['1_0um-count'] = bs[21] * 256 + bs[22]
        d['2_5um-count'] = bs[23] * 256 + bs[24]
        d['5_0um-count'] = bs[25] * 256 + bs[26]
        d['10um-count'] = bs[27] * 256 + bs[28]
        
        return d
        
    end -- parse
    
    
    function serilize(t)
        ret = ''
        if t == nil then
            return ret
        end
        
        for k, v in pairs(t) do
            ret = ret .. k .. ':' .. v .. ','
        end
    
        if #ret > 0 then
            ret = string.sub(ret, 0, -2)
        end
      
        return ret 
    end --serilize
    
    
    function report()
        status, temp, humi, temp_dec, humi_dec = dht.readxx(pin)
        if status == dht.OK then
            -- Float firmware using this example
            print("DHT Temperature:"..temp..";".."Humidity:"..humi)
            cu:send('env,temp:' .. temp .. ',humi:' .. humi)
        elseif status == dht.ERROR_CHECKSUM then
            print( "DHT Checksum error." )
        elseif status == dht.ERROR_TIMEOUT then
            print( "DHT timed out." )
        end
    
        if aqi ~= nil then
            cu:send('aqi,' .. serilize(aqi))
        end
    end -- report
    
    
    initWIFI()
    initUDP()
    
    aqi = nil
    dht = require('dht')
    pin = 4
    
    
    uart.setup(0, 9600, 8, 0, 1, 0)
    uart.on("data", 32,
      function(data)
        aqi = parse(data)
        if aqi == nil then
           return
        end
    end, 0)
    
    
    print('hello')
    tmr.alarm(0, 10000, 1, report)
    
    

    external by David Cotterill-Drew  34  0  1  0

    Upload DHT22 data to LinkSprite IO

    Upload DHT22 data to LinkSprite IO: LinkNode_IO_DHT22.ino
    #include <ESP8266WiFi.h>
    #include <WString.h>
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include <WiFiManager.h>       
      
    #include "DHT.h"
      
    #define DHTPIN D3    // what pin we're connected to
      
    #define DHTTYPE DHT22   // DHT 22  (AM2302)
      
    char *tem="";
    String apikey = "cc5005ab-e1a3-4c9a-a5cf-9c5a513d7062";
    const char* deviceID="00000000cd";
    const char* server = "www.linksprite.io";
    WiFiClient client;
      
      
    DHT dht(DHTPIN, DHTTYPE);
      
    void setup() {
      Serial.begin(9600);
      WiFiManager wifiManager;
      wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
      wifiManager.autoConnect("LinkNodeAP");
      Serial.print("WiFi Connected ...\n");
      Serial.println("WiFi connected");
      Serial.println("DHTxx test!");
        
      dht.begin();
    }
      
    void loop() {
      
      delay(2000);
      
      float h = dht.readHumidity();
      float t = dht.readTemperature(); // Read temperature as Celsius (the default)
      float f = dht.readTemperature(true); // Read temperature as Fahrenheit (isFahrenheit = true)
      
       // Check if any reads failed and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }
      
      float hif = dht.computeHeatIndex(f, h); // Compute heat index in Fahrenheit (the default)
      float hic = dht.computeHeatIndex(t, h, false);// Compute heat index in Celsius (isFahreheit = false)
      
      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.print(" *C ");
      Serial.print(f);
      Serial.print(" *F\t");
      Serial.print("Heat index: ");
      Serial.print(hic);
      Serial.print(" *C ");
      Serial.print(hif);
      Serial.println(" *F");
        
      if (client.connect(server,80)) 
      {  
         String  postStr ="{";
               postStr +="\"action\":\"update\",";
               postStr +="\"apikey\":\"";
               postStr += apikey;
               postStr +="\",";
               postStr +="\"deviceid\":\"";
               postStr += deviceID;
               postStr +="\",";
               postStr +="\"params\":";
               postStr +="{";
                 
               postStr +="\"temperature\":\"";
               itoa(t,tem,10); 
               postStr +=tem;
               postStr +="\",";
              
               postStr +="\"humidity\":\"";
               itoa(h,tem,10); 
               postStr +=tem;
               postStr +="\"\r\n";
               postStr +="}";
               postStr +="}";
            
        client.print("POST /api/http HTTP/1.1\n");
        client.print("Host: ");
        client.print(server);
        client.print("\nContent-Type: application/json\n");
        client.print("Content-Length: ");
        client.print(postStr.length());
        client.print("\n\n");
        client.print(postStr); 
          
        String request = "";
        delay(1000);  
        while (client.available()) 
       {
         char c = client.read();
         request +=c;
       } 
      
      if (request!= NULL)
      {
       int index1 = request.indexOf(":{");
       int index2 = request.indexOf("},");
       String param = request.substring(index1, index2 + 1);
       String data="\0" ;
       Serial.print("The param is ");
       Serial.println(param);
      
       
       client.stop();
       Serial.println("waiting ...");    
       delay(1000);  
      } 
    }
      
    }
    
    

    external by Github  22  0  1  0

    temperature reading from DHT22 and putting onto RabbitMq queue

    temperature reading from DHT22 and putting onto RabbitMq queue: gistfile1.py
    import Adafruit_DHT
    import pika
    import threading
    from datetime import datetime
    import uuid
    import time
    import json
    
    sensor = Adafruit_DHT.DHT22
    pin = 4
    
    def read():
      humidity, temperature  = Adafruit_DHT.read(sensor, pin)
      current_datetime = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
      if temperature is not None and humidity is not None: 
        print 'temp: {0:0.1f}C humid: {1:0.1f}% at {2}'.format(temperature, humidity, current_datetime)
        id = uuid.uuid4()
    
        output={
            'id':str(id), 
            'created_at':current_datetime,
            'temperature': temperature,
            'humidity': humidity
        }
        return output 
      else:
        raise ValueError('temperature and humidity data is nothing at {0}'.format(current_datetime))
    
    connection = pika.BlockingConnection()
    channel = connection.channel()
    channel.queue_declare(queue='temperatures', durable=True)
    
    #read every 10 sec and queue up the reading
    while True:
      data = read()
      channel.basic_publish(exchange='', routing_key='temperatures',
          body=json.dumps(data),
          properties=pika.BasicProperties(delivery_mode=2))
      time.sleep(10)
    
    

    external by mammenj  22  0  1  0

    This code has been based on many other codebase available on the net. This allows you to measure temperature using ESP8266 with DHT22 sensor. It will post the temperature to test mqtt server here http://test.mosquitto.org/gauge/ Let me know if you nee...

    This code has been based on many other codebase available on the net. This allows you to measure temperature using ESP8266 with DHT22 sensor. It will post the temperature to test mqtt server here http://test.mosquitto.org/gauge/ Let me know if you need more info: dht.ino
    #include "DHT.h"
    #include <PubSubClient.h>
    #include <ESP8266WiFi.h>
    
    // DHT Sensor parameters
    #define DHTPIN 2     // what digital pin we're connected to
    #define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
    
    // WIFI parameters
    #define WIFI_SSID "***"
    #define WIFI_PASS "***"
    
    // MQTT parameters
    // Using http://test.mosquitto.org/gauge/ for demo temperature
    // #define MQTT_SERVER "iot.eclipse.org"
    #define MQTT_SERVER "test.mosquitto.org"
    #define MQTT_PORT 1883
    // MQTT topic where the temperature is published
    char* topic = "temp/random";
    
    
    void callback(char* topic, byte* payload, unsigned int length) {
      // handle message when arrived
    }
    
    //MQTT client
    WiFiClient wifiClient;
    PubSubClient client(MQTT_SERVER, MQTT_PORT, callback, wifiClient);
    
    String macToStr(const uint8_t* mac) {
      String result;
      for (int i = 0; i < 6; ++i) {
        result += String(mac[i], 16);
        if (i < 5)
          result += ':';
      }
      return result;
    }
    
    // Initialize DHT sensor.
    DHT dht(DHTPIN, DHTTYPE);
    
    void setup() {
      Serial.begin(9600);
      Serial.println("<<--- Connecting to WIFI --->>");
      // WIFI Connection
      wifiConnect();
      Serial.println("<<--- Connecting to *MQTT* --->>");
      // MQTT Connection
      connectMQTT();
      Serial.println("<<--- Begin Temperature and Humidity measurement --->>");
      // Initialize DHT sensor
      dht.begin();
    }
    
    void loop() {
      // Wait a few seconds between measurements.
      delay(2000);
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity();
      // Read temperature as Celsius (the default)
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit (isFahrenheit = true)
      float f = dht.readTemperature(true);
    
      // Check if any reads failed and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }
    
      // Compute heat index in Fahrenheit (the default)
      float hif = dht.computeHeatIndex(f, h);
      // Compute heat index in Celsius (isFahreheit = false)
      float hic = dht.computeHeatIndex(t, h, false);
    
      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.print(" *C ");
      Serial.print("Heat index: ");
      Serial.print(hic);
      Serial.print(" *C ");
      // send temperature and humidity to MQTT Server
      sendTeperature(t);
    }
    
    void connectMQTT() {
    
      // Generate client name based on MAC address and last 8 bits of microsecond counter
      String clientName;
      clientName += "jsmEsp8266-";
      uint8_t mac[6];
      WiFi.macAddress(mac);
      clientName += macToStr(mac);
      clientName += "-";
      clientName += String(micros() & 0xff, 16);
    
      Serial.print("Connecting to MQTT ");
      Serial.print(MQTT_SERVER);
      Serial.print(" as ");
      Serial.println(clientName);
    
      if (client.connect((char*) clientName.c_str())) {
        Serial.println("Connected to MQTT broker");
        Serial.print("Topic is: ");
        Serial.println(topic);
    
        if (client.publish(topic, "hello from ESP8266")) {
          Serial.println("Publish ok");
        }
        else {
          Serial.println("Publish failed");
        }
      } else {
        Serial.println("MQTT connect failed");
        Serial.println("Will reset and try again...");
        abort();
      }
    }
    
    void wifiConnect() {
      Serial.print("Connecting to ");
      Serial.println(WIFI_SSID);
      WiFi.mode(WIFI_STA);
      WiFi.begin(WIFI_SSID, WIFI_PASS);
    
      while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }
    
    
    void sendTeperature(float t) {
    
      String payload = "";
      payload += t;
      payload += "";
    
      if (client.connected()) {
        Serial.print("Sending payload to topic: ");
        Serial.println(topic);
        Serial.println(payload);
    
        if (client.publish(topic, (char*) payload.c_str())) {
          Serial.println("Published ok");
        } else {
          Serial.println("Publish failed");
        }
      }
      // Wait for 5 secs
      delay(5000);
    }
    
    

    external by mambows  1364  7  3  0

    WeMos with DHT22 sensor and Firebase

    WeMos with DHT22 sensor and Firebase: wemos-dht22-firebase.ino
    #include "DHT.h"
    #include <ESP8266WiFi.h>
    #include <FirebaseArduino.h>
    
    #define DHTPIN D3
    #define DHTTYPE DHT22
    
    #define FIREBASE_HOST "****"
    #define FIREBASE_AUTH "****"
    #define WIFI_SSID "****"
    #define WIFI_PASSWORD "****"
    
    DHT dht(DHTPIN, DHTTYPE);
    
    void setup() {
      Serial.begin(115200);
    
      // connect to wifi.
      WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
      Serial.print("connecting");
      while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(500);
      }
      Serial.println();
      Serial.print("connected: ");
      Serial.println(WiFi.localIP());
    
      Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
      dht.begin();
    }
    
    void loop() {
      delay(3000);
    
      DynamicJsonBuffer jsonBuffer;
      float humidity = dht.readHumidity();
      float temperature = dht.readTemperature();
    
      if(isnan(humidity) || isnan(temperature)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }
    
      float heatIndexCelcius = dht.computeHeatIndex(temperature, humidity, false);
    
      // Push to Firebase
      JsonObject& temperatureObject = jsonBuffer.createObject();
      JsonObject& tempTime = temperatureObject.createNestedObject("timestamp");
      temperatureObject["value"] = temperature;
      tempTime[".sv"] = "timestamp";
      Firebase.push("temperature", temperatureObject);
      // handle error
      if (Firebase.failed()) {
          Serial.print("pushing /temperature failed:");
          Serial.println(Firebase.error());
          return;
      }
    
      JsonObject& humidityObject = jsonBuffer.createObject();
      JsonObject& humidTime = humidityObject.createNestedObject("timestamp");
      humidityObject["value"] = humidity;
      humidTime[".sv"] = "timestamp";
      Firebase.push("humidity", humidityObject);
      // handle error
      if (Firebase.failed()) {
          Serial.print("pushing /humidity failed:");
          Serial.println(Firebase.error());
          return;
      }
    
      JsonObject& hicObject = jsonBuffer.createObject();
      JsonObject& hicTime = hicObject.createNestedObject("timestamp");
      hicObject["value"] = heatIndexCelcius;
      hicTime[".sv"] = "timestamp";
      Firebase.push("heat_index", hicObject);
      // handle error
      if (Firebase.failed()) {
          Serial.print("pushing /heat_index failed:");
          Serial.println(Firebase.error());
          return;
      }
    
    }
    
    
    

    external by funkfinger  1649  0  3  0

    Huzzah 8266 / DHT22 example mashup

    Huzzah 8266 / DHT22 example mashup: my_remote_temp_server.ino
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>
    
    
    //////////////////////////
    //  DHT sensor stuff....
    //////////////////////////
    #include "DHT.h"
    #define DHTPIN 2
    #define DHTTYPE DHT22
    DHT dht(DHTPIN, DHTTYPE);
    
    
    //////////////////////////
    //  debug mode
    //////////////////////////
    #define DEBUG false
    
    //////////////////////////
    //  ESP8266 stuff....
    //////////////////////////
    const char* ssid = "....................";
    const char* password = "....................";
    MDNSResponder mdns;
    ESP8266WebServer server(80);
    const int led = 0;
    
    void handleRoot() {
      //////////////////////////
      //  read DHT sensor
      //////////////////////////
      String response = "";
      char buf1[80];
      char buf2[16];
      float h = dht.readHumidity();
      float c = dht.readTemperature();
      float f = dht.readTemperature(true);
      float hif = dht.computeHeatIndex(f, h);
      float hic = dht.computeHeatIndex(c, h, false);
    
    
    
      if (isnan(h) || isnan(f)) {
        response = "Failed to read from DHT sensor!";
      }
      else {
    
        response += "{";
    
        // temp in fahrenheit
        dtostrf(f, 5, 2, buf2);
        sprintf(buf1, "\"tempF\": \"%s\",", buf2);
        response += buf1;
    
        // temp in celsius
        dtostrf(c, 5, 2, buf2);
        sprintf(buf1, "\"tempC\": \"%s\",", buf2);
        response += buf1;
    
        // humidity
        dtostrf(h, 5, 2, buf2);
        sprintf(buf1, "\"humidity\": \"%s\",", buf2);
        response += buf1;
    
        // heat index in fahrenheit
        dtostrf(hif, 5, 2, buf2);
        sprintf(buf1, "\"heatIndexF\": \"%s\",", buf2);
        response += buf1;
    
        // heat index in Ce;sius
        dtostrf(hic, 5, 2, buf2);
        sprintf(buf1, "\"heatIndexC\": \"%s\"", buf2);
        response += buf1;
    
        response += "}";
        
        if (DEBUG) doDebug(h, c, f, hic, hif);
      }
    
      digitalWrite(led, 1);
      server.send(200, "text/plain", response);
      digitalWrite(led, 0);
    
    
    
    }
    
    void handleNotFound() {
      digitalWrite(led, 1);
      String message = "File Not Found\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message += (server.method() == HTTP_GET) ? "GET" : "POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      for (uint8_t i = 0; i < server.args(); i++) {
        message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
      }
      server.send(404, "text/plain", message);
      digitalWrite(led, 0);
    }
    
    void doDebug(float h, float t, float f, float hic, float hif) {
      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.print(" *C ");
      Serial.print(f);
      Serial.print(" *F\t");
      Serial.print("Heat index: ");
      Serial.print(hic);
      Serial.print(" *C ");
      Serial.print(hif);
      Serial.println(" *F");
    }
    
    void setup(void) {
      //////////////////////////
      //  start DHT sensor
      //////////////////////////
      dht.begin();
    
      pinMode(led, OUTPUT);
      digitalWrite(led, 0);
      if (DEBUG) Serial.begin(115200);
      WiFi.begin(ssid, password);
      if (DEBUG) Serial.println("");
    
      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        if (DEBUG) Serial.print(".");
      }
    
      if (DEBUG) {
        Serial.println("");
        Serial.print("Connected to ");
        Serial.println(ssid);
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP());
      }
    
      if (mdns.begin("esp8266", WiFi.localIP())) {
        if (DEBUG) Serial.println("MDNS responder started");
      }
    
      server.on("/", handleRoot);
    
      server.onNotFound(handleNotFound);
    
      server.begin();
      if (DEBUG) Serial.println("HTTP server started");
    }
    
    void loop(void) {
      server.handleClient();
    }
    
    
    • Public Snippets
    • Channels Snippets