Brayan Andrés Bermúdez
Published © GPL3+

Security system and temperature monitor for your home

This system sends alerts to your smartphone when there is movement in the house, also allows monitoring the temperature of the place.

EasyFull instructions provided10 hours1,969
Security system and temperature monitor for your home

Things used in this project

Story

Read more

Schematics

Schematic

Untitled sketch bb11 3uk2xmdwau

PSoC Analog Cooprocessor

Cooprocesorcopy 01 b35pblzl5n

Code

PSoC Creator Code

C/C++
/******************************************************************************
* Project Name      : CE211301_PIR_Motion_Sensing
* Version           : 1.0
* Device Used       : CY8C4A45LQI-L483
* Software Used     : PSoC Creator 3.3 CP3
* Compiler Used     : ARM GCC 4.9.3 
* Related Hardware  : CY8CKIT-048 PSoC Analog Coprocessor Pioneer Kit 
*******************************************************************************
* Copyright (2016), Cypress Semiconductor Corporation.
*******************************************************************************
* This software, including source code, documentation and related materials
* ("Software") is owned by Cypress Semiconductor Corporation (Cypress) and is
* protected by and subject to worldwide patent protection (United States and 
* foreign), United States copyright laws and international treaty provisions. 
* Cypress hereby grants to licensee a personal, non-exclusive, non-transferable
* license to copy, use, modify, create derivative works of, and compile the 
* Cypress source code and derivative works for the sole purpose of creating 
* custom software in support of licensee product, such licensee product to be
* used only in conjunction with Cypress's integrated circuit as specified in the
* applicable agreement. Any reproduction, modification, translation, compilation,
* or representation of this Software except as specified above is prohibited 
* without the express written permission of Cypress.
* 
* Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND, 
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED 
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
* Cypress reserves the right to make changes to the Software without notice. 
* Cypress does not assume any liability arising out of the application or use
* of Software or any product or circuit described in the Software. Cypress does
* not authorize its products for use as critical components in any products 
* where a malfunction or failure may reasonably be expected to result in 
* significant injury or death ("ACTIVE Risk Product"). By including Cypress's 
* product in a ACTIVE Risk Product, the manufacturer of such system or application
* assumes all risk of such use and in doing so indemnifies Cypress against all
* liability. Use of this Software may be limited by and subject to the applicable
* Cypress software license agreement.
*******************************************************************************/
/*******************************************************************************
* Theory of Operation: This example demonstrates how to implement an analog front end 
* (AFE) for a Pyroelectric Infrared (PIR) motion sensor using PSoC Analog Coprocessor.
* The code example is designed to measure the voltage signal from a PIR sensor to detect 
* the movement of IR emitting object. The sensor data is communicated over I2C. 
* Also, RGB LED is also turned ON once the motion is detected.
*******************************************************************************/

/* Header File Includes */
#include <project.h>
#include <stdio.h>
#include <stdlib.h>
#include "LiquidCrystal_I2C.h"

#define LED_ON                      (0u)
#define LED_OFF                     (1u)
#define MOTION_DETECTED             (1u)
#define MOTION_NOT_DETECTED         (0u)
#define THREE_FEET                  (3u)
#define TEN_FEET                    (10u)
#define TWENTY_FEET                 (20u)
#define ADC_CHANNEL_PIR             (0u)
#define SENSOR_RAW_INITIAL          (0)
/* EzI2C Read/Write Boundary */
#define READ_WRITE_BOUNDARY         (1u)

/* High and low thresholds for the motion detection are determined 
	through experiments */ 
	
/* High Threshold for 3 feet detection (80% of positive peak count) */
#define PIR_WINDOW_HIGH_3FT         (1200)
/* Low Threshold for 3 feet detection (80% of negative peak count) */
#define PIR_WINDOW_LOW_3FT          (-1200)   
/* High Threshold for 10 feet detection (80% of positive peak count) */
#define PIR_WINDOW_HIGH_10FT        (600)
/* Low Threshold for 10 feet detection (80% of negative peak count) */
#define PIR_WINDOW_LOW_10FT         (-600)
/* High Threshold for 20 feet detection (80% of positive peak count) */    
#define PIR_WINDOW_HIGH_20FT        (1200)
/* Low Threshold for 20 feet detection (80% of negative peak count) */   
#define PIR_WINDOW_LOW_20FT         (-1200)
	
/* Structure that holds the sensor values                                        */
/* Use __attribute__((packed)) for GCC and MDK compilers to pack structures      */
/* For other compilers use the corresponding directive.                          */
/* For example, for IAR use the following directive                              */
/* typedef __packed struct {..}struct_name;                                      */
typedef struct __attribute__((packed))
{
    uint8 detectionDistance;      	/* PIR detection distance */
	int16 sensorRawValue;        	/* ADC result */
	int16 highThreshold;		    /* High threshold for motion detection */
	int16 lowThreshold;			    /* Low threshold for motion detection */
    uint8 motionDetected;		    /* Motion detection flag */
}pir_sensor_data;


/* Function Prototypes */
void InitResources(void );
CY_ISR(TIMEBASE_ISR);

/* Declare the i2cBuffer to exchange sensor data between Bridge Control Panel (BCP) and PSoC Analog Coprocessor */
pir_sensor_data i2cBuffer = {THREE_FEET, SENSOR_RAW_INITIAL, 
                             PIR_WINDOW_HIGH_3FT, PIR_WINDOW_LOW_3FT, 
                             MOTION_NOT_DETECTED};

/*******************************************************************************
* Function Name: main
********************************************************************************
*
* Summary:
*  This function initializes all the resources, and in an infinite loop, performs tasks to measure all the sensor
*  parameters from sensors and to send the data over I2C.
*
* Parameters:
*  None
*
* Return:
*  int
*
* Side Effects:
*   None
*******************************************************************************/

/*****************************************
    inicializacion de componentes del termistor
    ******************************************/
    int32 vTherm,vRef; // variables correspondientes a los voltajes de referencia y termistor
    int32 Termresis,Termtemp; // variables correspondientes a resistencia y temperatura de termistor
    float TermistorResis,TermistorTemp;// variables para la correccin del formato de resistencia y temperatura
    char str[12];// variable para imprimir
    int16 filterOutputVref=0;
    int16 filterOutputVth=0;
    
    /* Variables to hold calculated resistance and temperature */
    int16 thermistorResistance, temperature;
    int16 estadopir=0;
    uint32_t Addr = 0x3F;
    
    int pir = 0;
    


CY_ISR(leerTemp)
{
    
     
        sprintf(str,"A%dB%d",temperature,estadopir);
        
        UART_UartPutString(str);
        
        sprintf(str,"%.2f C",(temperature/100.00));
        setCursor(6,1);
        LCD_print(str);
       
        if(estadopir==1)
        {
            setCursor(0,3);
            LCD_print("     Movement!!");
        }else{
            setCursor(0,3);
            LCD_print("                    ");
        }
        
        // ADC_StartConvert();
        
        Timer_Stop();
        Timer_Start();
        LED_Prueba_Write(!LED_Prueba_Read());
        
}




int main()
{
    
    
    UART_Start();
    Timer_Start();
    isrLeerTemp_StartEx(leerTemp);
    
    
    
    I2C_Start();
    
    LiquidCrystal_I2C_init(Addr,20,4,0);
    begin();
    
    LCD_print("Temperature Monitor");
    setCursor(0,2);
    LCD_print("     PIR : ");
    LCD_print("OFF ");
    setCursor(0,2);
    
	/* Sensor raw value */
	int16 sensorRawValue = 0;
	
	/* Motion detection thresholds */
	int16 highThreshold = PIR_WINDOW_HIGH_3FT;		                           
	int16 lowThreshold = PIR_WINDOW_LOW_3FT;
	
    /* Variable that stores the previous detection distance, used for checking if 
        the detection distance is changed by the master(BCP) */
    uint8 prevDetectionDistance = THREE_FEET;
    
    /* Variable to store the status returned by CyEnterCriticalSection() */
    uint8 interruptState = 0;
    
    /* Enable global interrupts */
    CyGlobalIntEnable;
    
    /* Initialize all the hardware resources */
    InitResources();
    
    /* Infinite Loop */
    for(;;)
    {        
        /* If the master(BCP) changed the detection distance, change the second stage 
            amplifier (PGA) gain and the thresholds for the required detection distance*/
        if (i2cBuffer.detectionDistance != prevDetectionDistance)
        {
            prevDetectionDistance = i2cBuffer.detectionDistance;
            
            /* Set the required detection distance */
            switch (i2cBuffer.detectionDistance)
            {
                case THREE_FEET:
                    /* Set second stage PGA gain and thresholds that gives 
                        3 feet detection distance */
                    PIRAmplifierStage2_SetGain(PIRAmplifierStage2_GAIN_1);
                    highThreshold = PIR_WINDOW_HIGH_3FT;
                    lowThreshold = PIR_WINDOW_LOW_3FT;
                    break;
                case TEN_FEET:
                    /* Set second stage PGA gain and thresholds that gives 
                        10 feet detection distance */
                    PIRAmplifierStage2_SetGain(PIRAmplifierStage2_GAIN_2);
                    highThreshold = PIR_WINDOW_HIGH_10FT;
                    lowThreshold = PIR_WINDOW_LOW_10FT;
                    break;
                case TWENTY_FEET:
                    /* Set second stage PGA gain and thresholds that gives 
                        20 feet detection distance */
                    PIRAmplifierStage2_SetGain(PIRAmplifierStage2_GAIN_32);
                    highThreshold = PIR_WINDOW_HIGH_20FT;
                    lowThreshold = PIR_WINDOW_LOW_20FT;
                    break;
                default:
                    /* Set second stage PGA gain and thresholds that gives 
                        3 feet detection distance */
                    PIRAmplifierStage2_SetGain(PIRAmplifierStage2_GAIN_1);
                    highThreshold = PIR_WINDOW_HIGH_3FT;
                    lowThreshold = PIR_WINDOW_LOW_3FT;
                    break;
            }
        }            
        /* Check if ADC data is ready */
        if(ADC_IsEndConversion(ADC_RETURN_STATUS))
        {
            /* Read ADC result */
            sensorRawValue = ADC_GetResult16(ADC_CHANNEL_PIR);
            
            /* Check if motion is detected */
            if((sensorRawValue > highThreshold) || 
               (sensorRawValue < lowThreshold))
            {
                /* Once the motion is detected, the RGB LED is driven with RED color for 5s
                   and the motion detected variable in I2C buffer is latched to '1' for 5s.
                   If another motion is detected before 5s elapsed the timer is restarted 
                   to maintain 5s time window */
               	
				/* Stop the timer */
                Timebase5s_Stop();
				
				/* Reload the counter */
				Timebase5s_WriteCounter(Timebase5s_TC_PERIOD_VALUE);
				
				/* Start the 5s timer */
                Timebase5s_Start();
				
				/* Update the status of motion detection */
				i2cBuffer.motionDetected = MOTION_DETECTED;
				
				/* Turn ON the LED */
                Pin_LED_Write(LED_ON);
                estadopir=1;
                /*
                UART_UartPutChar('1');
                UART_UartPutChar('\n');
                UART_UartPutChar('\r');
                */
            }
        } 
		
		/* Enter critical section to check if I2C bus is busy or not */
        interruptState = CyEnterCriticalSection();
    /*        
        if(!(EzI2C_EzI2CGetActivity() & EzI2C_EZI2C_STATUS_BUSY))
        {
           // Update the I2C buffer
            i2cBuffer.sensorRawValue = sensorRawValue;
			i2cBuffer.highThreshold = highThreshold;
			i2cBuffer.lowThreshold = lowThreshold;							
        }
	*/	
		/* Exit critical section */
        CyExitCriticalSection(interruptState);	
        
        /****************************************
        Programa termistor
        *****************************************/
        
        //ADC_IsEndConversion(ADC_WAIT_FOR_RESULT);// Esperar por un resultado
        vTherm = ADC_GetResult16(2);// Guardar resultado en la variable Vtherm
        //ADC_StopConvert();// Parar conversiones del ADC
        
        //ADC_StartConvert();//Empezar conversiones del ADC
        //ADC_IsEndConversion(ADC_WAIT_FOR_RESULT);//Esperar por un resultado
        vRef = ADC_GetResult16(1);// Guardar resultado en la variable Vref
        //ADC_StopConvert();// parar conversiones del ADC
        
        /* Low pass filter the measured ADC counts of Vref */            
            filterOutputVref = (vRef + (32u - 1) * filterOutputVref) / 32u;
                    
            /* Low pass filter the measured ADC counts of Vth */         
            filterOutputVth = (vTherm + (32u - 1) * filterOutputVth) / 32u;
                        
            /* Calculate thermistor resistance */
            thermistorResistance = Thermistor_GetResistance(filterOutputVref, filterOutputVth);           
            
            /* Calculate temperature in degree Celsius using the Component API */
            temperature = Thermistor_GetTemperature(thermistorResistance);
        
        TermistorResis=Termresis/1000.000;// correcion del formato para la resitencia
        TermistorTemp = Termtemp/100.00;// correccion del formato para el termistor
       
        
    }    
}

/*******************************************************************************
* Function Name: void InitResources(void)
********************************************************************************
*
* Summary:
*  This function initializes all the hardware resources
*
* Parameters:
*  None
*
* Return:
*  None
*
* Side Effects:
*   None
*******************************************************************************/
void InitResources(void)
{
    /* Start EZI2C Slave Component and initialize buffer */
    //EzI2C_Start();
    //EzI2C_EzI2CSetBuffer1(sizeof(i2cBuffer), READ_WRITE_BOUNDARY, (uint8*)&i2cBuffer);
    
    /* Enable LED timebase ISR */
    isr_Timebase5s_Start();
    isr_Timebase5s_StartEx(TIMEBASE_ISR);   
    
    /* Start the Scanning SAR ADC Component and start conversion */
    ADC_Start();
    ADC_StartConvert();
    
    /* Start the Reference Buffer */
    RefBuffer_Start();
    
    /* Start Programmable Voltage Reference */
    PVref_Start();
    
    /* Enable Programmable Voltage Reference */
    PVref_Enable();
    
    /* Start the first stage amplifier */
    PIRAmplifierStage1_Start();
    
    /* Start the second stage amplifier (PGA) */
    PIRAmplifierStage2_Start();    
 }

/*******************************************************************************
* Function Name: CY_ISR(TIMEBASE_ISR)
********************************************************************************
*
* Summary:
*  This function implements the ISR for 5s timebase
* 
* Parameters:
*  None
*
* Return:
*  None
*
* Side Effects:
*   None
*******************************************************************************/
CY_ISR(TIMEBASE_ISR)
{
   	/* Reset the motion detection flag */
    i2cBuffer.motionDetected = MOTION_NOT_DETECTED;
    /* Turn OFF the LED */
    Pin_LED_Write(LED_OFF);
    estadopir=0;
    /*
    UART_UartPutChar('0');
    UART_UartPutChar('\n');
    UART_UartPutChar('\r');
    */
    /* Stop the 5s timer */
    Timebase5s_Stop();
}
/* [] END OF FILE */

Arduino code

Arduino
/**************************************************************
 * Blynk is a platform with iOS and Android apps to control
 * Arduino, Raspberry Pi and the likes over the Internet.
 * You can easily build graphic interfaces for all your
 * projects by simply dragging and dropping widgets.
 *
 *   Downloads, docs, tutorials: http://www.blynk.cc
 *   Blynk community:            http://community.blynk.cc
 *   Social networks:            http://www.fb.com/blynkapp
 *                               http://twitter.com/blynk_app
 *
 * Blynk library is licensed under MIT license
 * This example code is in public domain.
 *
 **************************************************************
 * This example runs directly on ESP8266 chip.
 *
 * Note: This requires ESP8266 support package:
 *   https://github.com/esp8266/Arduino
 *
 * Please be sure to select the right ESP8266 module
 * in the Tools -> Board menu!
 *
 * Change WiFi ssid, pass, and Blynk auth token to run :)
 *
 **************************************************************/

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "ef3449684be14bc6bcb303a40f68f1d1";

SimpleTimer timer;

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Lilith4";
char pass[] = "AeroTallica.1";

int llaveescritura=0;
char inChar;
char num1[10];
char num2[10];
String string1="";
int val1=0;
int val2=0;
String string2="";
int i=0;
int string1l =0;
int string2l =0;

WidgetLED ledmovimiento(V2);

void myTimerEvent()
{
  if (val2==1)
  {
    ledmovimiento.on();
    Blynk.notify("Heey....!! Hay movimiento en tu casa!");
    Blynk.email("Subject: PIR Sensor", "Hay movimiento en la casa...");
    
  }else{
    ledmovimiento.off();
  }
}



  
void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, myTimerEvent);
}

void loop()
{
  Blynk.run();
  timer.run();
  
    if (Serial.available()){
    //Lectura de caracteres   
       inChar = Serial.read();
    //Suma de caracteres en variable string
      if(llaveescritura==1)
      {
        string1+=inChar;
      }
      if(llaveescritura==2)
      {
        string2+=inChar;
      }
    
      if(inChar=='A')
      {
        string1l=string1.length();
        string2l=string2.length();

        for (int a = 0; a<=string1l-2; a++)
          {
            num1[a]=string1.charAt(a); 
          }
        for (int a = 0; a<=string2l-2; a++)
          {
            num2[a]=string2.charAt(a); 
          }
        val1 = atoi(num1);
        val2 = atoi(num2);
        Serial.print("Val1: ");
        Serial.println(val1);
        Serial.print("val2: ");
        Serial.println(val2);

        Blynk.virtualWrite(V1,val1/100.00); //actualizando temperatura
        Blynk.virtualWrite(V3,val1/100.00);
        Blynk.virtualWrite(V0,val1/100.00);
        
        string1="";
        string2="";
        num1[0]='\0';num1[1]='\0';num1[2]='\0';num1[3]='\0';num1[4]='\0';num1[5]='\0';num1[6]='\0';num1[7]='\0';num1[8]='\0';num1[9]='\0';
        num2[0]='\0';num2[1]='\0';num2[2]='\0';num2[3]='\0';num2[4]='\0';num2[5]='\0';num2[6]='\0';num2[7]='\0';num2[8]='\0';num2[9]='\0';
        
        llaveescritura = 1;
        
      }
      if(inChar=='B')
      {
        llaveescritura = 2;
        
      }



    
      }
      
    
    
  
  
}

PSoC Creator Files

Blynk Library

Simple Timer Library

Credits

Brayan Andrés Bermúdez

Brayan Andrés Bermúdez

9 projects • 17 followers

Comments