Introduction: Midiendo Temperatura Con ESP8266 Y DHT11

About: Fundador de The Inventor's House Hackerspace, Movimiento Maker y Hardware Libre, DIY, Workaholic

Hola amigos hoy les voy a mostrar como conectar el sensor DHT11 o DHT22 al modulo ESP8266 y mostrar la temperatura y humedad en una pagina web de una forma muy sencilla y con ayuda del IDE de Arduino programaremos el modulo wifi.

Comencemos!

Step 1: Material

El material que vamos a necesitar para realizar este instructable es:

• ESP8266 version-03 o cualquier otra que tenga al alcance
• DHT11 / DHT22
• Resistencia 10K
• Fuente de alimentación 3.3v
• Convertidor USB-Serial / FTDI Friend Adafruit
• Push Botón (opcional, para poner el ESP en modo boot)

Step 2: Codigo

Lo primero que debemos realizar es agregar la tarjeta de desarrollo ESP8266 a nuestro IDE de Arduino si aun no lo han realizado pueden seguir el siguiente instructable desde el paso 2:

https://www.instructables.com/id/ESP8266-with-Neopixeles/

Ahora debemos de agregar la librería de DHT de Adafruit es una librería controlar el sensor DHT11 y DHT22, ademas funciona correctamente con el ESP8266

https://github.com/adafruit/DHT-sensor-library

Una vez reiniciado nuestro IDE ingresamos el siguiente código y cambiamos los datos de la wifi a la que lo vamos a conectar

Código en gist: https://gist.github.com/sabas1080/68c0f5cf6d4bb363bc39

<p>/* DHTServer - ESP8266 Webserver with a DHT sensor as an input<br> 
   Based on ESP8266Webserver, DHTexample, and BlinkWithoutDelay (thank you)
 
   Version 1.0  5/3/2014  Version 1.0   Mike Barela for Adafruit Industries
*/
#include 
#include 
#include 
#include 
#define DHTTYPE DHT11
#define DHTPIN  13
 
const char* ssid     = "Name Wifi";
const char* password = "Password wifi";
 
ESP8266WebServer server(80);
 
// 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 humidity, temp_f;  // Values read from sensor
String webString="";     // String to display
// 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 handle_root() {
  server.send(200, "text/plain", "Hello from the weather esp8266, read from /temp or /humidity");
  delay(100);
}
 
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());
   
  server.on("/", handle_root);
  
  server.on("/temp", [](){  // if you add this subdirectory to your webserver call, you get text below :)
    gettemperature();       // read sensor
    webString="Temperature: "+String((int)temp_f)+" C";   // Arduino has a hard time with float to string
    server.send(200, "text/plain", webString);            // send to someones browser when asked
  });
 
  server.on("/humidity", [](){  // if you add this subdirectory to your webserver call, you get text below :)
    gettemperature();           // read sensor
    webString="Humidity: "+String((int)humidity)+"%";
    server.send(200, "text/plain", webString);               // send to someones browser when asked
  });
  
  server.begin();
  Serial.println("HTTP server started");
}
 
void loop(void)
{
  server.handleClient();
} 
 
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)
    humidity = dht.readHumidity();          // Read humidity (percent)
    temp_f = dht.readTemperature();     // Read temperature as Celsius
    // Check if any reads failed and exit early (to try again).
    if (isnan(humidity) || isnan(temp_f)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
  }
}</p>

Ponemos el modo Boot el ESP8266 y cargamos el sketch

Step 3:

Una vez cargado el sketch reiniciamos en modo normal el modulo wifi y abrimos el monitor serial, podremos ver como el modulo se conecta a nuestro modem y obtiene una IP.

Ahora ingresamos esa IP en el navegador de nuestra computadora y veremos que se nos indica que podemos obtener la temperatura o humedad con solo agregar al final de nuestra IP lo que deseamos visualizar, en este caso

192.168.025/temp ----> es para temperatura

192.168.025/humudity -----> es para humedad

Un buen ejemplo para iniciar creando un pequeño servidor web en el ESP8266, espero esto les sirva para realizar otros proyectos que ustedes tengan en mente.

Hasta la próxima inventores!!