|
Aviso acceso con ESP8266
14-2-2016
Por unos 5€ podemos hacernos un aparato que a través de nuestra wifi nos notifique en el twitter de nuestro tlf, mediante mensajes emergentes tipo Whatsapp si alguien entra en nuestra casa y la temperatura de esta.
En el fuente que adjunto vienen unas someras instrucciones y los enlaces a los sitios de donde he cogido el codigo para hacer el programa.
Supongo que ya sabes programar el ESP8266 para funcionar en modo autonomo desde el entorno Arduino.
Si no, lo tienes aqui: https://www.youtube.com/watch?v=NwkDKhC0M6M
/***************************************************************************************
* by eb4cak@gmail.com Antonio
* 10-2-16 Este programa envía avisos por twitter al movil cuando se abre la puerta de casa o garaje. También da la temperatura.
1 PIN para magnetico puerta.
1 PIN 18B20
Al encenderse manda tweet de aviso con temp.
Si se abre la puerta manda tweet avisando y con temp.
Si la temperatura varía mucho en poco tiempo, avisa con tweet. (ejem 3º/h)
13-2-16 V4 Añado que suba las temperaturas a thingspeak. Desded ahi se pueden programar acciones y avisos.
El ESP8266 es autonomo. Solo se necesitan:
-ESP8266 ESP-01 o superior
-Sensor magnetico
-Sensor temperatura 18B20
Pines:
GPIO 0 En modo pruebas, conectado al PC aqui ponemos el Sensor magentico (directamente entre masa y este pin), en uso definitivo, va al aire. Esto es pq si este pin va a masa el ESP8266 arranca en modo programacion y no ejecuta tu codigo.
GPIO 2 Sensor temperatura (con su resistencia entre vcc y masa)
RX es GPIO3 Va al PC para programar y una vez programado lo usaremos para el Sensor magentico (directamente entre masa y este pin)
TX es GPIO1
VCC 3,3v NUNCA 5v o se romperá.
GND
RX es GPIO3
TX es GPIO1
*
* Fuentes de:
* Temperatura: http://fabricadigital.org/2015/11/construye-un-nodo-wifi-de-temperatura-con-el-esp8266-y-el-dallas-ds18b20/
* Tweeters: https://github.com/jconenna/ESP8266-Tweets-using-Arduino-IDE-and-ESP8266WiFi.h/commit/a428f99e154bdd96d76791a333b1a5fce5d496cd
* Subir a Thingspeak: http://www.arduinesp.com/thingspeak
*
*****************************************************************************************/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2 // El bus de datos del Dallas está en el pin 2
#define TEMPERATURE_PRECISION 12 // Precisión al máximo.
// Crea un objeto OneWire para comunicar con dispositivos OneWire (no solo Dallas DS18B20)
OneWire oneWire(ONE_WIRE_BUS);
// Crea un objeto de la clase DallasTemperature
DallasTemperature sensors(&oneWire);
// Crear una cuenta en thingspeak.com y copiar aqui la clave DE LOS ENVIOS A TWITTER y no otra.
String API = "M8YQ7CFKVO09SV80"; // API Key de envios a twitter OJO PON AQUI LA TUYA
String apiKey = "P6ODJG93N3JUHT8V"; // API Key de escritura de datos OJO PON AQUI LA TUYA
const char* ssid = "AquiElNombreDeTuWifi"; // OJO PON AQUI TU WIFI
const char* password = "AquiPasswordDeTuWifi"; // OJO, PON AQUI PASSWORD DE TU WIFI
ESP8266WebServer server(80); // Crea un objeto de la clase ESP8266WebServer
const char* server2 = "api.thingspeak.com";
WiFiClient client; // open client
const int SensorPin = 3; // Pin del Sensor Magnetico de la apertura de la puerta de entrada a la casa. GPIO3 es el pin de RX. OJO, ESTA LINEA LA ACTIVO PARA PROGRAMAR EL ESP8266 DEFINITIVO. PARA QUE NO QUEDE EN MODO PROGRAMACION
//const int SensorPin = 0; // Pin del Sensor Magnetico de la apertura de la puerta de entrada a la casa. OJO, ESTA LINEA LA ACTIVO PARA PROGRAMAR EL ESP8266 Y DEPURARLO. PARA QUE ENTRE EN MODO PROGRAMACION
int Sensor=0; // Valor del sensor magetico
// Mensaje de inicio al encenderse.
String tweet = "D%20@MiTwitt%20Recien%20encendido.%20Posible%20fin%20de%20corte%20de%20luz."; // OJO, AQUI PONER TU ID DE TWEETER TRAS LA @
void setup() {
//Serial.begin(9600); //OJO, solo para depuracion
pinMode(SensorPin, INPUT_PULLUP); // Sensor magentico puerta. Si no ponemos pullup hay que ponerlo por hardware.
// connect to wifi
WiFi.begin(ssid, password);
// allow time to make connection
while (WiFi.status() != WL_CONNECTED)
delay(500);
// MDNS hace que el esp8266 se encarge de asignarse su nombre en la red. Asi no lo hace el router.
if (MDNS.begin("MiEsp8266")) {
//Serial.println("MDNS responder started");
}
// Cosas del servidor www
server.on("/", handleRoot);
server.on("/inline", [](){
server.send(200, "text/plain", "Esto funciona bien.");
});
server.onNotFound(handleNotFound);
server.begin(); // Aqui ya hemos arrancado el servidor HTTP
sensors.begin(); // Inicialización del Dallas DS18B20
//sensors.setWaitForConversion(false); // Para lectura asincrona, para no tener que esperar.
//sensors.setResolution(Direc_temp01, TEMPERATURE_PRECISION); // Ponemos sensores temp dallas a la precisión elegida
sensors.requestTemperatures(); // Solicita las temperaturas
tweet += "Temp:%20";
tweet += sensors.getTempCByIndex(0); // Añade la temperatura a la respuesta
tweet += "%20C";
// Serial.println(WiFi.localIP()); // Imprime la IP del ESP8266
// Serial.println(tweet);
// Aqui nos conectamos a thingspeak.com y enviamos un tweet.
if (client.connect("184.106.153.149", 80))
{
client.print("GET /apps/thingtweet/1/statuses/update?key=" + API + "&status=" + tweet + " HTTP/1.1\r\n");
client.print("Host: api.thingspeak.com\r\n");
client.print("Accept: */*\r\n");
client.print("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n");
client.print("\r\n");
}
delay(2000);
}// Fin setup
int antirebotes=1; // Para la apertura de la puerta
unsigned long tiempo=0; // Para la grafica de temp a la nube
void loop()
{
server.handleClient();
if(digitalRead(SensorPin)){ // Si se abre la puerta. Cesa el contacto y deja de estar a masa, por lo que da 1 y envíamos un aviso.
if(antirebotes){ // Si el contacto permanece abierto solo enviamos una vez
envia();
//Serial.println(antirebotes);
delay(250);
antirebotes=0;
}
} else antirebotes=1; // Al cesar el contacto volvemos a habilitar los envios.
if((tiempo - millis()) > 10000){ // 5000 = Cada 5 seg enviamos temperatura a la nube
thingspeak();
}
/*
unsigned long rebotes=0;
if(digitalRead(SensorPin) && (rebotes-millis() > 1000)){ // Si cesa el contacto envíamos un aviso.
envia();
rebotes=millis();
}
*/
//Serial.println(tweet);
//delay(300);
}
/* *******************************************************************************************************
* Esta función sube datos a ThingSpeak para poder ejecutar acciones y ver los datos en graficas monas *
* *******************************************************************************************************/
void thingspeak(){
sensors.requestTemperatures(); // Solicita la temperatura
float t = sensors.getTempCByIndex(0); // La copiamos en t
/* Submos temperatura a la red*/
if (client.connect(server2,80)) { // "184.106.153.149" or api.thingspeak.com
String postStr = apiKey;
postStr +="&field1=";
postStr += String(t);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
}
client.stop();
}
/* *******************************************************************************************************
* Esta función envía un tweet de aviso de puerta abierta al destinatario "D @tuIDdeTwitter mensaje" *
* *******************************************************************************************************/
void envia(){
String tweet = "D%20@MiTwitt%20Puerta%20abierta.%20%20"; // OJO, aqui hay que poner el @TuTwitter de cada uno.
sensors.requestTemperatures(); // Solicita las temperaturas
tweet += "Temp:%20";
tweet += sensors.getTempCByIndex(0); // Añade la temperatura a la respuesta
tweet += "%20C";
// allow time to make connection
while (WiFi.status() != WL_CONNECTED)
delay(500);
// if connection to thingspeak.com is successful, send your tweet!
if (client.connect("184.106.153.149", 80))
{
client.print("GET /apps/thingtweet/1/statuses/update?key=" + API + "&status=" + tweet + " HTTP/1.1\r\n");
client.print("Host: api.thingspeak.com\r\n");
client.print("Accept: */*\r\n");
client.print("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n");
client.print("\r\n");
}
} //Fin de envia()
void handleRoot() {
String cadena= "La Temperatura es de: ";
sensors.requestTemperatures(); // Solicita las temperaturas
cadena += sensors.getTempCByIndex(0); // Añade la temperatura a la respuesta
cadena += " C";
server.send(200, "text/plain", cadena );
}
void handleNotFound(){
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);
}
Hoy habia 2 visitantes (8 clics a subpáginas) ¡Aqui en esta página!
|
|