Secret Knocking

download Secret Knocking

of 22

description

Proyecto de IoT, en donde una puerta anuncia por correo electrónico y SMS al dueño de la casa que alguien está tocando.

Transcript of Secret Knocking

  • Contenido

    Descripcin General .......................................................................................................... 1

    Listado de Componentes ................................................................................................... 2

    Proceso de Construccin ................................................................................................... 2

    Diagramas elctricos ......................................................................................................... 5

    Explicacin de la programacin ......................................................................................... 5

    Tweeting ........................................................................................................................ 6

    Mailing .......................................................................................................................... 12

    Conclusiones ................................................................................................................... 19

    Bibliografa ....................................................................................................................... 20

  • 1

    Descripcin General

    En la actualidad se est acrecentando la necesidad de estar en lnea. Las personas utilizan

    sus celulares para hablar con personas, ver fotos de sus amigos en redes sociales,

    compartir pensamientos en mensajes cortos o incluso tomarle una foto a la comida que

    estn a punto de devorar o un video gracioso de un perro haciendo un truco y todo lo anterior

    es posible gracias al internet. Ahora bien, por qu no llevar el internet a un nivel diferente?

    Creemos que podemos empezar por las casas, las personas pasan la mayor parte de su

    tiempo en casa ya sea durmiendo, viendo tele, cocinando, platicando, limpiando,

    estudiando, trabajando y una infinidad de diversas actividades. Y es desde hace 2 dcadas

    que el internet est tratando de ser llevado a los hogares de todo el mundo y avanza

    rpidamente, por lo tanto en una casa lo que normalmente se encuentra en lnea son las

    computadoras, impresoras, cmaras de seguridad y celulares aunque recientemente se

    empezaron a conectar las televisiones y se obtuvieron resultados sorprendentes de esta

    ltima conexin. Entonces, por qu no empezar a conectar ms aparatos domsticos a la

    red?

    A partir de la pregunta surgieron ideas de que se poda conectar a la casa y se propusieron

    desde timbres, celulares, casas de perros, aviarios hasta los sistemas de control de

    temperatura y luces. Pero de toda la lluvia de ideas se nos ocurri por qu no conectar la

    puerta? Por milenios se han utilizado las puertas para separar nuestra propiedad privada

    del exterior, de los desconocidos, de lo inseguro, pero siempre hemos estado limitados a

    estar presentes fsicamente para saber quin toca la puerta y poder abrirla. Ahora con el

    desarrollo de nuevos microprocesadores y sensores podemos evitarnos la presencia fsica

    y as poder obtener informacin de nuestra puerta y lograr control de la misma pero a

    distancia gracias a la conexin a internet.

    Este proyecto consiste en utilizar un nuevo producto de la marca Arduino, el Yn. Esta

    nueva tablilla cuenta con conexin a Wi-Fi, microprocesador Atheros AR9331 y el

    microcontrolador ATmega32u4. Esta tablilla se montara junto con un sensor piezoelctrico

    y un motor a pasos para controlar el estado de abierto o cerrado de una puerta y adems

    mandar informacin en vivo a un dispositivo mvil.

    El proyecto funciona de la siguiente manera. Primero es necesario determinar si la puerta

    se debe abrir o no y eso se logra con el sensor piezoelctrico. La puerta solo se abrir

    cuando se toque a la puerta con un ritmo secreto que fue grabado previamente en la

  • 2

    memoria del procesador. El sensor piezoelctrico es capaz de captar cada uno de los

    golpes en la puerta y el Yn procesa los tiempos que hay entre golpes consecutivos y

    determina si el ritmo es suficientemente parecido al guardado previamente. Si el ritmo es

    correcto entonces el motor mueva la chapa de la puerta para poder abrirla y si est

    equivocado entonces manda una alarma de que un ritmo incorrecto fue tratado de

    introducir. Adems de mover el motor, el Yn manda informacin al dispositivo mvil por

    correo electrnico, SMS o tweet sobre el estado en el que se encuentra la puerta y lo

    anterior es logrado a travs de los Choreos de Temboo.

    Listado de Componentes

    Los componentes que fueron utilizados para la construccin del montaje mecnico son:

    1. 1.5 metros de tubo de PVC de pulgada

    2. 3 ngulos de 90 para tubo de PVC de pulgada

    3. 2 conectores en T para tubo de PVC de pulgada

    4. 3 chupones de plstico de 1 pulgada

    5. 8 stand-off con base adhesiva

    6. 1 caja para proyectos electrnicos tamao mediana

    Y los componentes utilizados para la parte electrnica son:

    1. 1 Arduino Yn

    2. 1 motor a pasos 28BYJ-48

    3. 1 sensor piezoelctrico

    4. 1 circuito integrado con transistores en configuracin Darlington (ULN2003A)

    5. 1 LED rojo

    6. 1 LED verde

    7. 2 botones NC

    8. 1 pila de 9V

    9. 1 tablilla para soldar

    Proceso de Construccin

    Para hacer la parte mecnica se hicieron los cortes de los tubos de PVC a las medidas

    requeridas para poder ensamblarse con la puerta. Despus se hicieron los agujeros en los

  • 3

    tubos de PVC en donde se iban a colocar los tornillos que iban a sostener el motor a pasos

    y quedo la siguiente estructura.

    Figura 1 Estructura para el montaje del motor

    Al mismo tiempo se mand a hacer una puerta con una chapa montada con un carpintero

    y qued de la siguiente manera:

    Figura 2 Puerta con su marco y chapa montada

  • 4

    Ahora para la parte electrnica se soldaron todos los componentes necesarios para poder

    colocar todo en una caja para proyectos. Adems a la caja se le hicieron agujeros para

    poder montar los botones y LEDs necesarios y qued de la siguiente manera:

    Figura 3 Caja para colocar el Yn y la tablilla con las conexiones

    Una vez terminada cada una de las partes individuales se continu con la integracin de

    todos los componentes y qued de la siguiente forma:

    Figura 4 Montaje final del proyecto

  • 5

    Diagramas elctricos

    El diagrama fue realizado con el software Fritzing. Podemos observar grficamente como

    quedaron distribuidas las IO del Yn y las conexiones que se hicieron en la tablilla para

    soldar. Aunque no es una representacin exacta del modelo final, demuestra grficamente

    cmo deben quedar conectados todos los elementos para que funcione el proyecto.

    Figura 5 Conexin de todos los componentes electrnicos del proyecto

    Explicacin de la programacin

    Antes de empezar con la explicacin de la programacin, es importante aclarar que el

    software utilizado para programar la plataforma Yn es diferente al utilizado para

    plataformas tradicionales como el Uno, Mega, Leonardo, etc. Se utiliza el software Arduino

    1.5.6 que es una versin creada para programar especficamente el nuevo set de

    plataformas que est lanzando la compaa Arduino. No existe diferencia en el ambiente

    de programacin en el software 1.5.6, por lo tanto se puede entender el cdigo si se ha

    tenido experiencia previa con programacin de cualquier tipo de Arduino.

  • 6

    Tweeting

    El primer programa que se explicar es el de Twitter. Este programa tiene la capacidad de

    lanzar un tweet en una cuenta predeterminada cuando el ritmo de los toques coincide con

    el del Yn. El programa usa las libreras Temboo y manda a llamar el Choreo Statuses

    Update. Para poder utilizar la librera y el choreo se tuvieron que hacer otras actividades

    aparte de la programacin cmo: dar de alta una API Key para la cuenta de Twitter que se

    fuera utilizar, dar de alta una cuenta en la pgina de Temboo y crear un archivo H junto con

    el programa principal para guardar los datos de la cuenta de Temboo. El programa que se

    utiliz fue el siguiente y partes del cdigo vienen explicadas para su comprensin adems

    de que las partes subrayadas con amarillo son aquellas que tienen relacin directa con la

    conexin a internet1:

    /* Detects patterns of knocks and triggers a motor to unlock it if the pattern is correct. By Gerardo Hernndez, Jesus Lorias, Edgar Cervantes, and Yobain de Haro */ #include // Includes the library to control stepper motors #include #include // Includes the library to make calls to Temboo #include "TembooAccount.h" // Includes Temboo account information // In the next lines we declare the tokens and APIs that belong to my own twitter account const String TWITTER_ACCESS_TOKEN = "XXXXX"; const String TWITTER_ACCESS_TOKEN_SECRET = "XXXXX"; const String TWITTER_API_KEY = "XXXXX"; const String TWITTER_API_SECRET = "XXXXX"; // Pin definitions const int knockSensor = 0; // Piezo sensor on pin 0. const int programSwitch = 2; // If this is high we program a new code. const int closeDoor = 3; //If this is high the door gets closed const int redLED = 4; // Status LED const int greenLED = 5; // Status LED const int in1Pin = 12; //First output for stepper motor const int in2Pin = 11; //Second output for stepper motor const int in3Pin = 10; //Third output for stepper motor const int in4Pin = 9; //Fourth output for stepper motor const int turns = 512; //Declare the instance for the stepper motor

    1 Las tokens de twitter y los nmeros API fueron eliminados por cuestiones de seguridad de la cuenta

  • 7

    Stepper motor(2048,in1Pin, in2Pin, in3Pin, in4Pin); // Tuning constants. Could be made vars and hoooked to potentiometers for soft configuration, etc. const int threshold = 30; // Minimum signal from the piezo to register as a knock const int rejectValue = 35; // If an individual knock is off by this percentage of a knock we don't unlock.. const int averageRejectValue = 30; // If the average timing of the knocks is off by this percent we don't unlock. const int knockFadeTime = 150; // milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.) const int maximumKnocks = 20; // Maximum number of knocks to listen for. const int knockComplete = 1200; // Longest time to wait for a knock before we assume that it's finished. // Variables. int secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Initial setup: "Shave and a Hair Cut, two bits." int knockReadings[maximumKnocks]; // When someone knocks this array fills with delays between knocks. int knockSensorValue = 0; // Last reading of the knock sensor. int programButtonPressed = false; // Flag so we remember the programming button setting at the end of the cycle. boolean lockStatus = true; // Flag to remember if door is open or closed void setup() { // pinMode(lockMotor, OUTPUT); pinMode(in1Pin, OUTPUT); pinMode(in2Pin, OUTPUT); pinMode(in3Pin, OUTPUT); pinMode(in4Pin, OUTPUT); pinMode(redLED, OUTPUT); pinMode(greenLED, OUTPUT); pinMode(programSwitch, INPUT); pinMode(closeDoor,INPUT); motor.setSpeed(3); //The stepper motor speed is set to 3 RPM Bridge.begin(); digitalWrite(greenLED, HIGH); // Green LED on, everything is go. } void loop() { // Listen for any knock at all. knockSensorValue = analogRead(knockSensor); if (digitalRead(programSwitch)==LOW){ // is the program button pressed? programButtonPressed = true; // Yes, so lets save that state digitalWrite(redLED, HIGH); // and turn on the red light too so we know we're programming.

  • 8

    } else { programButtonPressed = false; digitalWrite(redLED, LOW); } if (digitalRead(closeDoor)==LOW && lockStatus==false){ motor.step(-turns); lockStatus=true; } if (knockSensorValue >=threshold){ listenToSecretKnock(); } } // Records the timing of knocks. void listenToSecretKnock(){ int i = 0; // First lets reset the listening array. for (i=0;i

  • 9

    if (programButtonPressed==true){ digitalWrite(redLED, LOW); // and the red one too if we're programming a new knock. } delay(knockFadeTime); // again, a little delay to let the knock decay. digitalWrite(greenLED, HIGH); if (programButtonPressed==true){ digitalWrite(redLED, HIGH); } } now=millis(); //did we timeout or run out of knocks? } while ((now-startTime < knockComplete) && (currentKnockNumber < maximumKnocks)); //we've got our knock recorded, lets see if it's valid if (programButtonPressed==false){ // only if we're not in progrmaing mode. if (validateKnock() == true && lockStatus == true){ triggerDoorUnlock(); } else { digitalWrite(greenLED, LOW); // We didn't unlock, so blink the red LED as visual feedback. for (i=0;i

  • 10

    void triggerDoorUnlock(){ int i=0; lockStatus = false; digitalWrite(greenLED, HIGH); // Turn the green LED on motor.step(turns); // and the lock too. // Blink the green LED a few times for more visual feedback. for (i=0; i < 5; i++){ digitalWrite(greenLED, LOW); delay(100); digitalWrite(greenLED, HIGH); delay(100); } // The next lines call Temboo to update my twitter account String tweetText("Someone opened the door! (" + String(millis()) + ")"); // This sets the string that will be tweeted TembooChoreo StatusesUpdateChoreo; // invoke the Temboo client // NOTE that the client must be reinvoked, and repopulated with // appropriate arguments, each time its run() method is called. StatusesUpdateChoreo.begin(); // set Temboo account credentials StatusesUpdateChoreo.setAccountName(TEMBOO_ACCOUNT); StatusesUpdateChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); StatusesUpdateChoreo.setAppKey(TEMBOO_APP_KEY); // identify the Temboo Library choreo to run (Twitter > Tweets > StatusesUpdate) StatusesUpdateChoreo.setChoreo("/Library/Twitter/Tweets/StatusesUpdate"); // set the required choreo inputs // add the Twitter account information StatusesUpdateChoreo.addInput("AccessToken", TWITTER_ACCESS_TOKEN); StatusesUpdateChoreo.addInput("AccessTokenSecret", TWITTER_ACCESS_TOKEN_SECRET); StatusesUpdateChoreo.addInput("ConsumerKey", TWITTER_API_KEY); StatusesUpdateChoreo.addInput("ConsumerSecret", TWITTER_API_SECRET); // and the tweet we want to send StatusesUpdateChoreo.addInput("StatusUpdate", tweetText); StatusesUpdateChoreo.close(); } // Sees if our knock matches the secret. // returns true if it's a good knock, false if it's not. boolean validateKnock(){

  • 11

    int i=0; // simplest check first: Did we get the right number of knocks? int currentKnockCount = 0; int secretKnockCount = 0; int maxKnockInterval = 0; // We use this later to normalize the times. for (i=0;i 0){ currentKnockCount++; } if (secretCode[i] > 0){ //todo: precalculate this. secretKnockCount++; } if (knockReadings[i] > maxKnockInterval){ // collect normalization data while we're looping. maxKnockInterval = knockReadings[i]; } } // If we're recording a new knock, save the info and get out of here. if (programButtonPressed==true){ for (i=0;i 0){ delay( map(secretCode[i],0, 100, 0, maxKnockInterval)); // Expand the time back out to what it was. Roughly. digitalWrite(greenLED, HIGH); digitalWrite(redLED, HIGH); } delay(50); } return false; // We don't unlock the door when we are recording a new knock. } if (currentKnockCount != secretKnockCount){ return false; }

  • 12

    /* Now we compare the relative intervals of our knocks, not the absolute time between them. (ie: if you do the same pattern slow or fast it should still open the door.) This makes it less picky, which while making it less secure can also make it less of a pain to use if you're tempo is a little slow or fast. */ int totaltimeDifferences=0; int timeDiff=0; for (i=0;i rejectValue){ // Individual value too far out of whack return false; } totaltimeDifferences += timeDiff; } // It can also fail if the whole thing is too inaccurate. if (totaltimeDifferences/secretKnockCount>averageRejectValue){ return false; } return true; }

    Mailing

    El segundo programa manda un mail cada vez que la puerta es abierta con xito o cuando

    se toca la puerta de manera errnea. Al igual que en el programa anterior tambin se utiliza

    la librera de Temboo pero ahora utilizando el Choreo SendEmail. Tambin es necesario

    otras actividades previas para hacer que funcione la programacin cmo: dar de alta una

    cuenta en Temboo y crear un archivo H junto con el programa principal para guardar los

    datos de la cuenta de Temboo. El programa que se utiliz fue el siguiente y partes del

    cdigo vienen explicadas para su compresin adems de que las partes subrayadas con

    amarillo son aquellas que tienen relacin directa con la conexin a internet2:

    /* Detects patterns of knocks and triggers a motor to unlock it if the pattern is correct. By Gerardo Hernndez, Jesus Lorias, Edgar Cervantes, Yobain de Haro */ #include // Includes the library to control stepper motors

    2 Se elimin el correo electrnico y su contrasea por cuestiones de seguridad

  • 13

    #include #include // Includes the library to make calls to Temboo #include "TembooAccount.h" // Includes Temboo account information // In the next lines we include all the information of the gmail account const String GMAIL_USER_NAME = "XXXXX"; // your Gmail username, formatted as a complete email address, eg "[email protected]" const String GMAIL_PASSWORD = "XXXXX"; // your Gmail password const String TO_EMAIL_ADDRESS = "XXXXX"; // the email address you want to send the email to, eg "[email protected]" // Pin definitions const int knockSensor = 0; // Piezo sensor on pin 0. const int programSwitch = 2; // If this is high we program a new code. const int closeDoor = 3; //If this is high the door gets closed const int redLED = 4; // Status LED const int greenLED = 5; // Status LED const int in1Pin = 12; //First output for stepper motor const int in2Pin = 11; //Second output for stepper motor const int in3Pin = 10; //Third output for stepper motor const int in4Pin = 9; //Fourth output for stepper motor const int turns = 512; //Declare the instance for the stepper motor Stepper motor(2048,in1Pin, in2Pin, in3Pin, in4Pin); // Tuning constants. Could be made vars and hoooked to potentiometers for soft configuration, etc. const int threshold = 30; // Minimum signal from the piezo to register as a knock const int rejectValue = 35; // If an individual knock is off by this percentage of a knock we don't unlock.. const int averageRejectValue = 30; // If the average timing of the knocks is off by this percent we don't unlock. const int knockFadeTime = 150; // milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.) const int maximumKnocks = 20; // Maximum number of knocks to listen for. const int knockComplete = 1200; // Longest time to wait for a knock before we assume that it's finished. // Variables. int secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Initial setup: "Shave and a Hair Cut, two bits." int knockReadings[maximumKnocks]; // When someone knocks this array fills with delays between knocks. int knockSensorValue = 0; // Last reading of the knock sensor. int programButtonPressed = false; // Flag so we remember the programming button setting at the end of the cycle. boolean lockStatus = true; // Flag to remember if door is open or closed boolean success = false; // Flag to be used when sending an email

  • 14

    void setup() { // pinMode(lockMotor, OUTPUT); pinMode(in1Pin, OUTPUT); pinMode(in2Pin, OUTPUT); pinMode(in3Pin, OUTPUT); pinMode(in4Pin, OUTPUT); pinMode(redLED, OUTPUT); pinMode(greenLED, OUTPUT); pinMode(programSwitch, INPUT); pinMode(closeDoor,INPUT); motor.setSpeed(3); //The stepper motor speed is set to 3 RPM Bridge.begin(); digitalWrite(greenLED, HIGH); // Green LED on, everything is go. } void loop() { // Listen for any knock at all. knockSensorValue = analogRead(knockSensor); if (digitalRead(programSwitch)==LOW){ // is the program button pressed? programButtonPressed = true; // Yes, so lets save that state digitalWrite(redLED, HIGH); // and turn on the red light too so we know we're programming. } else { programButtonPressed = false; digitalWrite(redLED, LOW); } if (digitalRead(closeDoor)==LOW && lockStatus==false){ motor.step(-turns); lockStatus=true; } if (knockSensorValue >=threshold){ listenToSecretKnock(); } } // Records the timing of knocks. void listenToSecretKnock(){ int i = 0; // First lets reset the listening array. for (i=0;i

  • 15

    int startTime=millis(); // Reference for when this knock started. int now=millis(); digitalWrite(greenLED, LOW); // we blink the LED for a bit as a visual indicator of the knock. if (programButtonPressed==true){ digitalWrite(redLED, LOW); // and the red one too if we're programming a new knock. } delay(knockFadeTime); // wait for this peak to fade before we listen to the next one. digitalWrite(greenLED, HIGH); if (programButtonPressed==true){ digitalWrite(redLED, HIGH); } do { //listen for the next knock or wait for it to timeout. knockSensorValue = analogRead(knockSensor); if (knockSensorValue >=threshold){ //got another knock... //record the delay time. now=millis(); knockReadings[currentKnockNumber] = now-startTime; currentKnockNumber ++; //increment the counter startTime=now; // and reset our timer for the next knock digitalWrite(greenLED, LOW); if (programButtonPressed==true){ digitalWrite(redLED, LOW); // and the red one too if we're programming a new knock. } delay(knockFadeTime); // again, a little delay to let the knock decay. digitalWrite(greenLED, HIGH); if (programButtonPressed==true){ digitalWrite(redLED, HIGH); } } now=millis(); //did we timeout or run out of knocks? } while ((now-startTime < knockComplete) && (currentKnockNumber < maximumKnocks)); //we've got our knock recorded, lets see if it's valid if (programButtonPressed==false){ // only if we're not in programming mode. if (validateKnock() == true && lockStatus == true){ triggerDoorUnlock(); } else { digitalWrite(greenLED, LOW); // We didn't unlock, so blink the red LED as visual feedback. for (i=0;i

  • 16

    delay(100); digitalWrite(redLED, LOW); delay(100); } digitalWrite(greenLED, HIGH); // Send an email alerting that someone has just introduced a wrong knock if (!success){ TembooChoreo SendEmailChoreo; SendEmailChoreo.begin(); SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT); SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); SendEmailChoreo.setAppKey(TEMBOO_APP_KEY); SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail"); SendEmailChoreo.addInput("Username", GMAIL_USER_NAME); SendEmailChoreo.addInput("Password", GMAIL_PASSWORD); SendEmailChoreo.addInput("ToAddress", TO_EMAIL_ADDRESS); SendEmailChoreo.addInput("Subject", "ALERT: Door Notification!"); SendEmailChoreo.addInput("MessageBody", "Hey! Somebody just knocked incorrectly on your door!"); unsigned int returnCode = SendEmailChoreo.run(); if (returnCode == 0){ success = true; } SendEmailChoreo.close(); } success = false; // Make variable false for future emails } } else { // if we're in programming mode we still validate the lock, we just don't do anything with the lock validateKnock(); // and we blink the green and red alternately to show that program is complete. digitalWrite(redLED, LOW); digitalWrite(greenLED, HIGH); for (i=0;i

  • 17

    digitalWrite(greenLED, HIGH); // Turn the green LED on motor.step(turns); // and the lock too. // Blink the green LED a few times for more visual feedback. for (i=0; i < 5; i++){ digitalWrite(greenLED, LOW); delay(100); digitalWrite(greenLED, HIGH); delay(100); } // The next lines call Temboo to sent an email to myself if (!success){ TembooChoreo SendEmailChoreo; // invoke the Temboo client // NOTE that the client must be reinvoked, and repopulated with // appropriate arguments, each time its run() method is called. SendEmailChoreo.begin(); // set Temboo account credentials SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT); SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME); SendEmailChoreo.setAppKey(TEMBOO_APP_KEY); // identify the Temboo Library choreo to run (Google > Gmail > SendEmail) SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail"); // set the required choreo inputs // the first input is your Gmail email address SendEmailChoreo.addInput("Username", GMAIL_USER_NAME); // next is your Gmail password. SendEmailChoreo.addInput("Password", GMAIL_PASSWORD); // who to send the email to SendEmailChoreo.addInput("ToAddress", TO_EMAIL_ADDRESS); // then a subject line SendEmailChoreo.addInput("Subject", "ALERT: Door Notification!"); // next comes the message body, the main content of the email SendEmailChoreo.addInput("MessageBody", "Hey! Somebody just managed to open the door of your house!"); // Tell the Choreo to run and wait for the results. The // return code will tell us either the Temboo client was able to send our request to the Temboo servers unsigned int returnCode = SendEmailChoreo.run(); // a return code of 0 means everything worked if (returnCode == 0)

  • 18

    { success = true; } SendEmailChoreo.close(); } // make variable success false again for the next email success = false; } // Sees if our knock matches the secret. // returns true if it's a good knock, false if it's not. boolean validateKnock(){ int i=0; // simplest check first: Did we get the right number of knocks? int currentKnockCount = 0; int secretKnockCount = 0; int maxKnockInterval = 0; // We use this later to normalize the times. for (i=0;i 0){ currentKnockCount++; } if (secretCode[i] > 0){ //todo: precalculate this. secretKnockCount++; } if (knockReadings[i] > maxKnockInterval){ // collect normalization data while we're looping. maxKnockInterval = knockReadings[i]; } } // If we're recording a new knock, save the info and get out of here. if (programButtonPressed==true){ for (i=0;i 0){

  • 19

    delay( map(secretCode[i],0, 100, 0, maxKnockInterval)); // Expand the time back out to what it was. Roughly. digitalWrite(greenLED, HIGH); digitalWrite(redLED, HIGH); } delay(50); } return false; // We don't unlock the door when we are recording a new knock. } if (currentKnockCount != secretKnockCount){ return false; } /* Now we compare the relative intervals of our knocks, not the absolute time between them. (ie: if you do the same pattern slow or fast it should still open the door.) This makes it less picky, which while making it less secure can also make it less of a pain to use if you're tempo is a little slow or fast. */ int totaltimeDifferences=0; int timeDiff=0; for (i=0;i rejectValue){ // Individual value too far out of whack return false; } totaltimeDifferences += timeDiff; } // It can also fail if the whole thing is too inaccurate. if (totaltimeDifferences/secretKnockCount>averageRejectValue){ return false; } return true; }

    Conclusiones

    A lo largo de la construccin del proyecto logramos conocer las ventajas que presenta una

    tablilla con Wi-Fi integrado y toda la gama de proyectos posibles que se puede lograr con

    esta. Este tipo de tablillas son ms potentes y estn abiertas a programacin ms compleja

    y pueden ser la solucin de muchos problemas de domtica. Sin embargo, son slo ms

    que un microcontrolador por lo que ahora no basta con programar nicamente en lenguaje

    C, sino que tambin se debe de involucrar programacin en Java o Python para poder

    ejecutar aplicaciones en lnea. De cualquier forma es una herramienta ms poderosa para

  • 20

    que un ingeniero pueda desarrollar aplicaciones ms complejas y que puedan satisfacer las

    nuevas necesidades que van surgiendo en esta sociedad cambiante y hambrienta por

    nueva tecnologa.

    Bibliografa

    Adafruit. (s.f.). Adafruit. Obtenido de Arduino Lesson 16. Stepper Motors:

    https://learn.adafruit.com/adafruit-arduino-lesson-16-stepper-motors/breadboard-

    layout

    Arduino. (s.f.). Arduino. Obtenido de Knock Sensor:

    http://www.arduino.cc/en/pmwiki.php?n=Tutorial/KnockSensor

    Temboo. (s.f.). Arduino Yn :: Temboo. Obtenido de Making your Yn send email is a

    breeze: https://temboo.com/arduino/yun/send-an-email

    Temboo. (s.f.). Arduino Yn :: Temboo. Obtenido de Post updates to Twitter from your Yn:

    https://temboo.com/arduino/yun/tweet