Skip to content

Instantly share code, notes, and snippets.

@mcattani
Last active April 24, 2023 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcattani/91e7d6d876fbd70174282f23927227ae to your computer and use it in GitHub Desktop.
Save mcattani/91e7d6d876fbd70174282f23927227ae to your computer and use it in GitHub Desktop.
Servidor web con esp8266, sensor DHT11 para mostrar tempertura y humedad y conexión a servidor NTP para mostrar la hora local.
/*
Creamos un servidor web con un ESP8266 para mostrar temperatura y humedad
utilizando un sensor DHT11.También mostraremos la hora actual conectándonos
a un servidor NTP. Más información en: https://thenerdyapprentice.blogspot.com/
The Nerdy Apprentice
*/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "DHT.h"
#define DHTTYPE DHT11 // Definimos el tipo de sensor que es
// Librerías necesarias para conexión al servidor NTP
#include <WiFiUdp.h>
#include <NTPClient.h>
const byte DHTPIN = D2; // Recordar que si usamos el ESPXX hay que definirlo con la D
DHT dht(DHTPIN, DHTTYPE); // Creamos el objeto DHT
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "1.ar.pool.ntp.org", -10800, 6000); //-10800 corresponde al offset de Buenos Aires GMT-3
// Variables de conexión WiFi
const char* ssid = "OzyMain-2.4Ghz"; // SSID - Nombre de la red a la cual nos conectaremos
const char* password = "-------"; // Password de la red
ESP8266WebServer server(80); // Creamos el objeto server
// Creamos las variables donde almacenaremos los valores leídos.
int Temperatura;
int Humedad;
void setup() {
Serial.begin(115200);
pinMode(DHTPIN, INPUT);
dht.begin(); // Iniciamos el sensor
timeClient.begin(); // Iniciamos el objeto timeClient
Serial.print("Conectando a: ");
Serial.println(ssid);
WiFi.begin(ssid, password); // Intentamos conectar a la red WiFi
while (WiFi.status() != WL_CONNECTED) { // Esperamos a que se realice la conexión
delay(500);
Serial.println("*");
}
Serial.println("Conexión exitosa!");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
server.on("/", handle_OnConnect); // Si se accede a / (root) se llama la función handle_OnConnect
server.onNotFound(handle_NotFound); // Si no se encuentra la URL
server.begin(); // Iniciamos el servidor
Serial.println("Servidor Web Iniciado");
}
void loop() {
timeClient.update();
server.handleClient();
}
void handle_OnConnect() {
Temperatura = dht.readTemperature(); // Leemos los datos del sensor
Humedad = dht.readHumidity();
server.send(200, "text/html", SendHTML(Temperatura, Humedad));
}
void handle_NotFound() {
server.send(404, "text/plain", "Pagina no encontrada.");
}
String SendHTML(int TemperaturaR, int HumedadR) {
String ptr = "<!DOCTYPE html> <html>\n"; // Indicamos con !DOCTYPE que vamos a enviar HTML
ptr += "<head> <meta http-equiv=\"refresh\" content=\"10\">\n"; // Refrescamos la página cada 10 segundos
ptr += "<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css2?\n"; // Vamos a utilizar fuentes e íconos de Google.
ptr += "family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200\" />\n";
ptr += "<title>ESP8266 Lectura Sensor DHT11 </title>\n"; // Título de la página
ptr += "<style>\n";
ptr += "html { font-family: 'Open Sans', sans-serif; display: block; margin: 0px auto; text-align: center; color: #333333;}\n";
ptr += "material-symbols-outlined {font-variation-settings:'FILL'0, 'wght'400,'GRAD'0'opsz'48}\n";
ptr += "</style>\n";
ptr += "<body>\n";
ptr += "<h1>Lecturas del sensor:</h1>\n";
ptr += "<table style=\"margin-left:auto; margin-right:auto; text-align:center;cellpadding=\"5\"; border=\"0\"\n>";
ptr += "<TR>\n";
ptr += "<TD>\n";
ptr += "<span class=\"material-symbols-outlined\"> device_thermostat </span>\n"; // Iconos
ptr += "</TD>\n";
ptr += "<TD>";
ptr += String(TemperaturaR) + " C"; // Lecturas del Sensor
ptr += "</TD>\n";
ptr += "</TR>\n";
ptr += "<TR>\n";
ptr += "<TD>\n";
ptr += "<span class=\"material-symbols-outlined\"> humidity_percentage </span>\n";
ptr += "</TD>\n";
ptr += "<TD>";
ptr += String(HumedadR) + "%";
ptr += "</TD>\n";
ptr += "</TABLE>\n";
ptr += "<h3> Hora: </h3>\n";
ptr += timeClient.getFormattedTime();
ptr += "<hr size=\"2px\" color=\"black\" />\n";
ptr += "<a href=\"https://thenerdyapprentice.blogspot.com/\">https://thenerdyapprentice.blogspot.com/</a>\n";
ptr += "</body>\n";
ptr += "</html>";
return ptr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment