Tutorial del Internet de las Cosas y Bluetooth con el ESP32
Juan Antonio Villalpando
Volver al índice del tutorial
____________________________
123.- Wemos D1 R32 ESP32. Hora. NTP. Cliente web.
- Obtención de fecha y hora desde un servidor NTP.
- Obtiene la hora del servidor NTP pool.ntp.org, cuya dirección está configurada en la Librería.
- Librería: NTPClient.zip
- Código: https://randomnerdtutorials.com/esp32-ntp-client-date-time-arduino-ide/
fecha_hora.ino |
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
// Replace with your network credentials
const char* ssid = "Nombre_de_tu_red_Wifi";
const char* password = "Clave_Wifi";
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
// Variables to save date and time
String formattedDate;
String dayStamp;
String timeStamp;
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Initialize a NTPClient to get time
timeClient.begin();
// Set offset time in seconds to adjust for your timezone, for example:
// GMT +1 = 3600
// GMT +8 = 28800
// GMT -1 = -3600
// GMT 0 = 0
timeClient.setTimeOffset(3600);
}
void loop() {
while(!timeClient.update()) {
timeClient.forceUpdate();
}
// The formattedDate comes with the following format:
// 2018-05-28T16:00:13Z
// We need to extract date and time
formattedDate = timeClient.getFormattedDate();
Serial.println(formattedDate);
// Extract date
int splitT = formattedDate.indexOf("T");
dayStamp = formattedDate.substring(0, splitT);
Serial.print("DATE: ");
Serial.println(dayStamp);
// Extract time
timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);
Serial.print("HOUR: ");
Serial.println(timeStamp);
delay(1000);
}
|
____________________________________
- Otro método para obtener la fecha y la hora. PHP.
- Si dispones de un servidor web con PHP, puedes subir este código para obtener la hora.
- Mediante PHP
<?php
date_default_timezone_set('America/Bogota');
echo date('d/m/Y/H/i/s', time());
?>
- Puedes poner la zona horaria que te interese:
http://php.net/manual/es/timezones.europe.php
http://php.net/manual/es/timezones.america.php
- Otra manera de obtener fecha y hora es subiendo un archivo PHP con este contenido:
<?php
$timestamp = time();
$datum = date("d/m/Y/H/i/s",$timestamp);
echo "$datum";
?>
- También podemos dejar el archivo anterior
<?php
$datos = $_GET;
$contenido = $datos['contenido'];
date_default_timezone_set($contenido);
echo date('d/m/Y/H/i/s', time());
?>
- Y pedir la hora de la forma siguiente:
http://kio4.com/appinventor/php/fecha.php?contenido=America/Bogota
- En nuestro caso terminaría en Europe/Madrid.
_______________________________
|