Signaling with own hands. Alarm ESP8266 + HC SR501 + Blynk

Signaling with own hands. Alarm
ESP8266 Board and PIR motion Sensor HC SR501

https://youtu.be/-llWS6OZquI

Screenshot_2017-04-28-12-22-21

Link to the sketch and setting up widgets https://yadi.sk/d/CECHM4Jb3S5Bu9

Link to Russian version
Ссылка на Русскую версию https://youtu.be/8kFRyxRLF6M

code

/*****************************************************************************
 * 
 * Author: Obushenkov Alexey Andreevich    
 * Group in VK https://vk.com/engineer24
 * YouTube channel https://www.youtube.com/channel/UCih0Gcl9IEdkR8deDJCiodg
 * Inzhenerki Engineering room
 * 
 ***************************************************************************** 
 * A sketch is assembled on site http://docs.blynk.cc/
 *****************************************************************************
 * Modules in the project
 * ESP8266 NodeMCU Lua WIFI V3 (3,75 $) https://goo.gl/GFDYq0
 * NodeMCU L293D Motor Shield Board for ESP-12E (1.68 $) https://goo.gl/T0WwT6
 * Infrared PIR motion sensor HC - SR501 (0,95 $) https://goo.gl/0mCfOL
 * 1-channel relay control the High and Low levels (0,99 $) https://goo.gl/SnFuXY
 * Passive Buzzer the Buzzer (0,50 $) https://goo.gl/clKuKb
 * 
 *****************************************************************************
 * What is the essence of the sketch
 * Simplest alarm
 * Triggered by the Infrared motion sensor PIR sensor (HC SR501) is in security mode
 * Blink sends notifications to a Mobile device as a PUSH notification and an email
 * plus relay to activate anything.
 * Takes the protection of just using the widget Button mode SWITCH she is disarmed.
 * That we would know under protection or not PIN D4 (sedit LED) under protection will glow,
 * Without protection will be off. 
 * Depending on the condition of the system, changing its appearance
 * sent messages, etc.
 * 
 *****************************************************************************
 * V1 - Widget LED (Color led) (although in my case, it is not particularly needed)
 * V2 - Widget BUTTON (the Button arm and disarm of the alarm)
 * V10 - Widget Value Display or Labeled Value (a Reflection of the status of the system)
 * V11 - Widget Value Display or Labeled Value (the Reflection from the thermometer)
 * 
 * also nugene widgets (they can be unused, but need to remember to disable it in the code
 * otherwise, for stability do not meet)
 * RTC real time Clock
 * 
 * Notification - notification Pushup
 * Mail - E-Mail
 * Twitter - Twitter
 *****************************************************************************
 *
 */

// If sousie line raskomentiruyte performance drops to 10 TIMES!!!
// After debugging the project to zakommentirovat
// #define BLYNK_PRINT Serial
// #define BLYNK_DEBUG 

// By default, the Maximum allowed email + subject + message length is 120 characters.
// However, you can increase this limit if needed. 
// ESP for example, you can set it to 1200 (don't know how it will affect performance)
// By the way Russian characters guzzle two times more than English
#define BLYNK_MAX_SENDBYTES 600 

// Library ESP and Blynk
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

// Library for firmware ESP by air
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

// Library for real-time clock
#include <TimeLib.h>
#include <WidgetRTC.h>

// Assignable inputs and outputs
#define PIR D1 // gpio 5 here plug-in infrared sensor
#define LED D4 // gpio 2 here can connect the led, but on the Board he already has (But it's inverted)

// D8 = gpio 15 here we catch relay which is driven by a high level
// if you have a relay with it's low clings through NPN transistor
// for example like this http://amperka.ru/product/bipolar-transistor
#define RELAY D8 // D8 = gpio 15

#define BUZZER D7 // D7 = gpio 13 here we catch the Squeaker

// color for LEDs and the color of the letters
#define BLYNK_GREEN "#23C48E"
#define BLYNK_BLUE "#04C0F8"
#define BLYNK_YELLOW "#ED9D00"
#define BLYNK_RED "#D3435C"
#define BLYNK_DARK_BLUE "#5F7CD8"
#define BLYNK_WHITE "#FFFFFF"


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

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

char Mail[] = "sib.eng124@gmail.com"; // Your e-mail
String Subject = "Subject: Security ESP "; // subject of email
    
WidgetRTC rtc; // initialize widget real time clock

BlynkTimer timer; // initialize the timer
int timerSpeak_ID; // initialize a variable to hold the timer ID Tweeters
int timerPIRSensor_ID; // initialize a variable to hold the timer ID of the motion Sensor

WidgetLED led1(V1); // registreren widget LED

bool isFirstConnect = true; // Variable for storing state of the first time whether the established connection

bool pirState = false; // initialize variable to store the status Srabatyvaet alarm motion sensor

// initialize variable to store the Alarm condition
// false / off 
// true included
bool flagProtection = false;
bool intruderState = LOW; // Variable that stores the triggering of the alarm
int securityStateX = 0; // number of the alarm condition

float B; // initialize variable to store data plavusa point sensor option 2

//************************************************************************************//
// Here starts the code of the program                            //
//************************************************************************************//

BLYNK_CONNECTED()// If has installed the first time, sinhroniziruete all widgets
{
  if (isFirstConnect) {
    Blynk.syncAll(); // syngenesiae all widgets
    
    // Make string with time and date and dobavlaet to the message
    String currentTime = String(hour()) + ":" + minute() + ":" + second();
    String currentDate = String(day()) + "/" + month() + "/" + year() + " ";

    String Notif = "Hardware Running" + currentDate + "" + currentTime;
    
    Blynk.notify(Notif);
    
    //I think the extra sending mail on startup
    //Blynk.email(Mail, Subject, Notif); // my sketch to send better this way
    //Blynk.email("sib.eng24@gmail.com", "Subject: Security ESP ", "Hardware Running"); // standard sending on soap
    isFirstConnect = false;
    
  }
}

void readPIRSensor() // function to read motion sensor
{ 
  static int pir = LOW; // declare variable to store 
                        // information about the state of digital input PIR
 /*The static keyword is used to create a variable,
  *which is visible to only one function. However, unlike local variables,
  *which are created and destroyed with each function call,
  *static variables remain after the function call, preserving their values between calls. 
 */ 
                       
  if (flagProtection == true && pirState == LOW) // If alarm enabled
  {pir = digitalRead(PIR);} // read the value from a digital input
                              // we are not interested in the state of the sensor while
                              // protection not included
  if (flagProtection == true && pir == HIGH && pirState == LOW) // If alarm is Enabled (ON) and Motion Sensor is triggered
  {pirState = HIGH; // This flag can be reset only by disabling the alarm
   digitalWrite(LED, !pirState); // turn on the led on the Board
  }                        
                                            
  if (flagProtection == false && pirState == HIGH) // If alarm is Off (OFF) and Blile drawdown
  {pirState = LOW; // Reset the flag
   digitalWrite(LED, !pirState); // turn off led
  }                                   

// I'm trying to write this function so that it once again nothing happened

} //readPIRSensor


BLYNK_WRITE(V2) // Read the state of the button (Widget Button) and save the value in flagProtection
{
  flagProtection = param.asInt(); // Read the button state

   if (flagProtection) // if flag is raised
  {timer.enable(timerPIRSensor_ID);} // Enable the timer function readPIRSensor
  else // otherwise
  {timer.disable(timerPIRSensor_ID); // Disable timer function readPIRSensor
  timer.setTimeout(50, readPIRSensor);} // Pull the Motion Sensor function
                                           // once with a delay of 50 Millisecond
  
}

void messeg() // function for sending messages, depending on the status of the Alarm (securityState)
{
  String Notif; // Variable for storing messages

  // The Respondent RTC and make a string to send
  String currentTime = String(hour()) + ":" + minute() + ":" + second();
  String currentDate = String(day()) + "/" + month() + "/" + year() + " ";

 // depending on the condition of alarm select the desired text
 // and add the date and time
 switch (securityStateX) {
 case 1:
    Notif = "a Strange OBJECT" + currentDate + "" + currentTime;
    break;
 case 2:
    Notif = "Protected" + currentDate + "" + currentTime;
    break;
 case 3:
    Notif = "disarmed after obnoruzheniya OFFENDER" + currentDate + "" + currentTime;
    break;
 case 4:
    Notif = "disarmed" + currentDate + "" + currentTime;
    break;    
 
 //default:
    // code to execute
  }

 static int i = 1; // variable and structure of if else needed for
                   // serial send delay

 // there is a message to be sent
 // you can just zakommentirovat 
 // not the desired method of communication 
 if (i == 3) {Blynk.notify(Notif); i=1;
 }
 
 else if (i == 2) {Blynk.email(Mail, Subject, Notif); i++;
 }
 
 else if (i == 1) {Blynk.tweet(Notif); i++;
 }
 
}

// Custom widgets (change colors displaying a message), depending on the status of the Alarm (securityState)
void Setting (String color, String Text) 
{
 // variable and the design of the if else is needed to
 // serial send delay 
 static int i = 1;
  
 if (i == 4) {led1.setColor(color); i=1;} // Change color LED V1

 else if (i == 3) {Blynk.setProperty(V10, "color", color); i++;}// Change the color of the widget V10

 else if (i == 2) {Blynk.setProperty(V2, "color", color); i++;}// Change the color of the widget V2

 else if (i == 1) {Blynk.virtualWrite(V10, Text); i++;} // Print a message Value Display
  
}

void sendSetting() // Send settings, depending on the status of the Alarm (securityState)
{
  
  String Notif; // Variable for storing messages
  String color; // Variable to store color
  
  // then choose a setting depending on the system state
 switch (securityStateX) {
 case 1:
    Notif = "a Stranger on the OBJECT";
    color = BLYNK_RED;
    break;
 case 2:
    Notif = "Protected";
    color = BLYNK_GREEN;
    break;
 case 3:
    Notif = "disarmed was the Offender";
    color = BLYNK_BLUE;
    break;
 case 4:
    Notif = "disarmed";
    color = BLYNK_BLUE;
    break;    
 
 //default:
    // code to execute
  }

  // call the function Setting and substitute the data
  Setting(color, Notif); // Custom widgets (change colors displaying a message)  
}

void securityState () // Define the Alarm status and the corresponding actions produce
{
 
// State 1 // "If the system is armed" and "sensor Tripped" and "Not Able 1"
// Code executed once
    if (flagProtection == true && pirState == true && securityStateX != 1) 
  {   
      securityStateX=1; // number of the status of the alarm 1
      intruderState = HIGH;// the Alarm went off
      
      timer.setTimer(1000, messeg, 3); // call funkciu messeg 3 times, with an interval of 1 second
        
      digitalWrite(RELAY, intruderState); // relay

      timer.setTimer(200, sendSetting, 4); // call funkciu sendSetting 4 times, with an interval of 0.2 seconds
                                            
      timer.enable(timerSpeak_ID); // Enable the timer function Speak Squeaker                                           
                     

  } // State 1 //
  
// State 2 // "If the system is armed" and "Sensor is Tripped" and "Not in Condition 2"    
// Code executed once
  else if (flagProtection == true && pirState == false && securityStateX != 2) 
  { 
      securityStateX=2; // Number of alarm condition 2
      
      timer.setTimer(1000, messeg, 3); // call funkciu messeg 3 times, with an interval of 1 second

      timer.setTimer(200, sendSetting, 4); // call funkciu sendSetting 4 times, with an interval of 0.2 seconds

      timer.disable(timerSpeak_ID); // Disable timer function Speak Squeaker
      

  } // State 2 //

// Condition 3 // "If security is turned Off" and "Alarm" and "Condition 3"
// Code executed once
  else if (flagProtection == false && intruderState == HIGH && securityStateX != 3) 
  {
      securityStateX=3; // number of the status alarm 3
      intruderState = LOW; // Reset the flag triggering the Alarm
      
      timer.setTimer(1000, messeg, 3); // call funkciu messeg 3 times, with an interval of 1 second
      
      digitalWrite(RELAY, intruderState); // turn Off relay

      timer.setTimer(200, sendSetting, 4); // call funkciu sendSetting 4 times, with an interval of 0.2 seconds
      
      timer.disable(timerSpeak_ID); // Disable timer function Speak Squeaker
            
   } // State 3 //
   
// State 4 // "If security is Disabled" and "No Alarm" and "Status 4"
// Code executed once   
   else if (flagProtection == false && intruderState == LOW && securityStateX != 4) 
   {
    if (securityStateX !=3) // if previous state is not equal to 3 then
    {securityStateX=4; // Number of alarm condition 4
    
    timer.setTimer(1000, messeg, 3); // call funkciu messeg 3 times, with an interval of 1 second
    
    timer.setTimer(200, sendSetting, 4); // call funkciu sendSetting 4 times, with an interval of 0.2 seconds
    
    timer.disable(timerSpeak_ID); // Disable timer function Speak Squeaker

    } 

  } // State 4 //

} //securityState


void Speak() // Function for Buzzer Buzzer (Chants)
{
  // Set frequency and duration for the tweeters
tone(BUZZER, 3500, 50);
} // Speak

//**Start*******************the Send data option 1******************
// Sending data to Blynk. In the Widget settings
// find REDIN RATE and set PUSH. !!!!Only!!!!PUSH!!!!
// otherwise will depart from online

void readSensorB() // function to read sensor B
{
  
//*********The code for getting random values*******************
//**************************Beginning********************************
  static int x = random (100, 200);
  static int i = 2000;
  if (i > -1) {
    i = i + x;
    B=(float)i/100;
    if (i >= 4000) x = -random (100, 200); // switching control to the maximum
    if (i <= 2000) x = random (100, 200); // switching control to the maximum
    }
//*********The code for getting random values*******************
//**************************End*********************************        

//**************************The send data option 1******************
// Sending data to Blynk in the Widget settings
// find REDIN RATE and set PUSH. !!!!Only!!!!PUSH!!!!
// otherwise will depart from online
  Blynk.virtualWrite(V11, B); 
  
//***Depending on the sensor you can change the color and the inscription***  
  //Serial.println(B); // print values to serial monitor
  static int hotState = 0;
  if (B > 32 && hotState != 1)
  {hotState = 1;
   Blynk.setProperty(V11, "label", "OPASNOSTI OVERHEAT");// Change the name of the widget V11 (understands only English)
   Blynk.setProperty(V11, "color", BLYNK_RED); // Change the color of the widget V11 red
  }
  else if (B <= 32 && hotState != 2)
  {hotState = 2;
   Blynk.setProperty(V11, "label", "Temperature NORMAL"); // Change the name of the widget V11 (understands only English)
   Blynk.setProperty(V11, "color", BLYNK_WHITE); // Change the color of the widget V11 on white
  }
}
//The bottom line is that in this case we obnavljam data with the frequency which was prescribed
//timer B. This line is
//void setup() 
//timer.setInterval(1000L, readSensorB);
//ie update data in the widget manages Our iron (ESP8266)
//**End********************the Send data option 1******************





void reconnectBlynk() // function which checks the connection
{
  if (!Blynk.connected()) { //if there is no connection then 
    if (Blynk.connect()) { // conectica
      BLYNK_LOG("Reconnected"); // print in log   
    
    } else {
      BLYNK_LOG("Not reconnected"); // print in log     
    }
  }
  
} // reconnectBlynk

void setup()
{
   
// Debug console
  Serial.begin(19200);
  Serial.println(" ");
  Serial.println("Launch");
  
// Custom inputs and outputs
  pinMode (LED,OUTPUT);
  digitalWrite(LED, HIGH);
  pinMode (RELAY,OUTPUT);
  pinMode (PIR,INPUT);
  pinMode (BUZZER,OUTPUT);

  delay(1000);
  for (int i=0; i <= 3; i++)
  {tone(BUZZER, 300, 50);
  delay(80);}

  // Blynk.begin(auth, ssid, pass);
  // Usually, we use the construction from above but from
  // ESP8266 for it hangs when trying to install a WiFi connection
  Blynk.config(auth); // so configurable connection
  Blynk.disconnect(); //terminate the connection
  Blynk.connect(); // and then try to have to concretise


//Custom timers
  timerPIRSensor_ID = timer.setInterval(1000L, readPIRSensor); // Pull the motion sensor function every six seconds.
  timerSpeak_ID = timer.setInterval(500L, Speak); // Pull the function 
  timer.disable(timerPIRSensor_ID); // disable timer Motion Sensor
  timer.disable(timerSpeak_ID); // disable timer Tweeters

  timer.setInterval(3000L, securityState); // Pull the function of protection Status once a second
  
  timer.setInterval(30000L, reconnectBlynk); // check every 30 seconds if still connected to the server 
  timer.setInterval(2000L, readSensorB); // read data from sensor B times a second (Pull function)


  rtc.begin(); // run clock widget real-time
  
//Custom widgets
  // Turn on the LED for that would change the color of the Led's were visible
  led1.on();

  // Change the name of the widget V10 (Value Display)(only understands English)
  Blynk.setProperty(V10, "label", "Status"); // Custom title for the Widget

//************************
  ArduinoOTA.setHostname("Security01"); //OTA Set the name of the network port
  ArduinoOTA.setPassword((const char *)"0000"); //OTA Set access password for remote firmware
  ArduinoOTA.begin(); //Initialize OTA OTA
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
//***********************

if (Blynk.connected()) { // If has established communication, then twice a Squeaker will Paknam
  for (int i=0; i <= 2; i++)
  {tone(BUZZER, 200, 50);
  delay(100);}
}
  else {
    for (int i=0; i <= 10; i++) // If not connected then 10 times the Beeper will Paknam
  {tone(BUZZER, 100, 50);
  delay(80);}
  }
  
} //setup

void loop()
{
  ArduinoOTA.handle(); // OTA Always ready to be flashed wirelessly

   if (Blynk.connected()) {
    Blynk.run(); // Startup blink
   }
  
  timer.run(); // start the timer
} // loop
6 Likes

Continuing the discussion from Signaling with own hands. Alarm ESP8266 + HC SR501 + Blynk:

Hello,
this is a very nice sketch. I added the possibility to control 6 RF-plugs, one of them is activated when alarm is triggered and “ext.horn” switch (V3) is on.
The modifications are commented like “// xxxxxxxxxxxxxxx”, so they are easy to find.
You need to add an RF-transmitter at pin D8 (check the other pins for buzzer & relay, numbers are changed).
In the beginning I had some problem when the connection with the blynk-server was interrupted, it didn’t reconnect, so I disabled line 568 and 572 in the loop and then it worked perfectly. The PIR-alarm is active and can send command to RFswitch even while
the unit is offline.
Here is the modified scetch:

/*****************************************************************************

   Author: Obushenkov Alexey Andreevich
   Group in VK https://vk.com/engineer24
   YouTube channel https://www.youtube.com/channel/UCih0Gcl9IEdkR8deDJCiodg
   Inzhenerki Engineering room

 *****************************************************************************
   A sketch is assembled on site http://docs.blynk.cc/
 *****************************************************************************
   Modules in the project
   ESP8266 NodeMCU Lua WIFI V3 (3,75 $) https://goo.gl/GFDYq0
   NodeMCU L293D Motor Shield Board for ESP-12E (1.68 $) https://goo.gl/T0WwT6
   Infrared PIR motion sensor HC - SR501 (0,95 $) https://goo.gl/0mCfOL
   1-channel relay control the High and Low levels (0,99 $) https://goo.gl/SnFuXY
   Passive Buzzer the Buzzer (0,50 $) https://goo.gl/clKuKb

 *****************************************************************************
   What is the essence of the sketch
   Simplest alarm
   Triggered by the Infrared motion sensor PIR sensor (HC SR501) is in security mode
   Blink sends notifications to a Mobile device as a PUSH notification and an email
   plus relay to activate anything.
   Takes the protection of just using the widget Button mode SWITCH she is disarmed.
   That we would know under protection or not PIN D4 (sedit LED) under protection will glow,
   Without protection will be off.
   Depending on the condition of the system, changing its appearance
   sent messages, etc.

 *****************************************************************************
   V1 - Widget LED (Color led) (although in my case, it is not particularly needed)
   V2 - Widget BUTTON (the Button arm and disarm of the alarm)
   V3 = Widget BUTTON (switch for ext. horn)
   V10 - Widget Value Display or Labeled Value (a Reflection of the status of the system)
   V11 - Widget Value Display or Labeled Value (the Reflection from the thermometer)

   also nugene widgets (they can be unused, but need to remember to disable it in the code
   otherwise, for stability do not meet)
   RTC real time Clock

   Notification - notification Pushup
   Mail - E-Mail
   Twitter - Twitter
 *****************************************************************************

*/

// If sousie line raskomentiruyte performance drops to 10 TIMES!!!
// After debugging the project to zakommentirovat
// #define BLYNK_PRINT Serial
// #define BLYNK_DEBUG

// By default, the Maximum allowed email + subject + message length is 120 characters.
// However, you can increase this limit if needed.
// ESP for example, you can set it to 1200 (don't know how it will affect performance)
// By the way Russian characters guzzle two times more than English
#define BLYNK_MAX_SENDBYTES 600

// Library ESP and Blynk
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

// Library for firmware ESP by air
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

// Library for real-time clock
#include <TimeLib.h>
#include <WidgetRTC.h>

// Library for rcswitch           // xxxxxxxxxxxxxxxxx
#include <RCSwitch.h>             // xxxxxxxxxxxxxxxxx
RCSwitch mySwitch = RCSwitch();   // xxxxxxxxxxxxxxxxx

// Assignable inputs and outputs
#define PIR D1 // gpio 5 here plug-in infrared sensor
#define LED D2 // gpio 2 here can connect the led, but on the Board he already has (But it's inverted)

// D7 =  here we catch relay which is driven by a high level
// if you have a relay with it's low clings through NPN transistor
// for example like this http://amperka.ru/product/bipolar-transistor

#define RELAY D5 // D5

#define BUZZER D6 // D6 =  here we catch the Squeaker


// color for LEDs and the color of the letters
#define BLYNK_GREEN "#23C48E"
#define BLYNK_BLUE "#04C0F8"
#define BLYNK_YELLOW "#ED9D00"
#define BLYNK_RED "#D3435C"
#define BLYNK_DARK_BLUE "#5F7CD8"
#define BLYNK_WHITE "#FFFFFF"

// Area identity ;-P
// You should get the Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "60901879425940718e7c8c3bd2444a8c";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "xxxxxxxxxxxxx";
char pass[] = "xxxxxxxxxxxxxx";

char Mail[] = "xxxxxxx@yyy.com"; // Your e-mail
String Subject = "Subject: Security ESP "; // subject of email

WidgetRTC rtc; // initialize widget real time clock

BlynkTimer timer; // initialize the timer
int timerSpeak_ID; // initialize a variable to hold the timer ID Tweeters
int timerPIRSensor_ID; // initialize a variable to hold the timer ID of the motion Sensor

WidgetLED led1(V1); // registreren widget LED

bool isFirstConnect = true; // Variable for storing state of the first time whether the established connection

bool pirState = false; // initialize variable to store the status Srabatyvaet alarm motion sensor

// initialize variable to store the Alarm condition
// false / off
// true included
bool flagProtection = false;
bool intruderState = LOW; // Variable that stores the triggering of the alarm

bool hornEnable = false;  // Variable that stores ext.horn on-off  xxxxxxxxxxxxxxxxx

int securityStateX = 0; // number of the alarm condition

float B; // initialize variable to store data plavusa point sensor option 2

//************************************************************************************//
// Here starts the code of the program                            //
//************************************************************************************//

BLYNK_CONNECTED()// If has installed the first time, sinhroniziruete all widgets
{
  if (isFirstConnect) {
    Blynk.syncAll(); // syngenesiae all widgets

    // Make string with time and date and dobavlaet to the message
    String currentTime = String(hour()) + ":" + minute() + ":" + second();
    String currentDate = String(day()) + "/" + month() + "/" + year() + " ";

    String Notif = "Hardware Running" + currentDate + "" + currentTime;

    Blynk.notify(Notif);


    //I think the extra sending mail on startup
    //Blynk.email(Mail, Subject, Notif); // my sketch to send better this way
    //Blynk.email("sib.eng24@gmail.com", "Subject: Security ESP ", "Hardware Running"); // standard sending on soap
    isFirstConnect = false;

  }
}


BLYNK_WRITE(V3) // Read the state of the Horn button (Widget Button V3) and save the value in hornEnable   xxxxxxxxxxxxxxxxxxxxxxxx
{
  hornEnable = param.asInt(); // Read the button state
}


void readPIRSensor() // function to read motion sensor
{
  static int pir = LOW; // declare variable to store


  /*The static keyword is used to create a variable,
    which is visible to only one function. However, unlike local variables,
    which are created and destroyed with each function call,
    static variables remain after the function call, preserving their values between calls.
  */

  {
    if (flagProtection == true && pirState == LOW) // If alarm enabled
    {
      pir = digitalRead(PIR); // read the value from a digital input
    }
    // we are not interested in the state of the sensor while
    // protection not included


    if (flagProtection == true && pir == HIGH && pirState == LOW) // If alarm is Enabled (ON) and Motion Sensor is triggered
    { pirState = HIGH; // This flag can be reset only by disabling the alarm
      digitalWrite(LED, !pirState); // turn on the led on the Board

      if (hornEnable == HIGH)
      {
        mySwitch.send(6611, 24); // 433mhz alarm, >>send code to RFswitch_6 > ext.alarm on (also when unit is offline) xxxxxxxxxxxxxxxxxxxx
      }

    }

    if (flagProtection == false && pirState == HIGH) // If alarm is Off (OFF) and Blile drawdown
    { pirState = LOW; // Reset the flag
      digitalWrite(LED, !pirState); // turn off led

      if (hornEnable == HIGH)
      {
        mySwitch.send(6600, 24); // 433mhz alarm, >>send code to RFswitch_6 > ext.alarm off   xxxxxxxxxxxxxxxxxxxx
      }

    }

    // I'm trying to write this function so that it once again nothing happened

  }
} //readPIRSensor


BLYNK_WRITE(V2) // Read the state of the button (Widget Button) and save the value in flagProtection
{
  flagProtection = param.asInt(); // Read the button state

  if (flagProtection) // if flag is raised
  {
    timer.enable(timerPIRSensor_ID); // Enable the timer function readPIRSensor
  }
  else // otherwise
  { timer.disable(timerPIRSensor_ID); // Disable timer function readPIRSensor
    timer.setTimeout(50, readPIRSensor);
  } // Pull the Motion Sensor function
  // once with a delay of 50 Millisecond

}

void messeg() // function for sending messages, depending on the status of the Alarm (securityState)
{
  String Notif; // Variable for storing messages

  // The Respondent RTC and make a string to send
  String currentTime = String(hour()) + ":" + minute() + ":" + second();
  String currentDate = String(day()) + "/" + month() + "/" + year() + " ";

  // depending on the condition of alarm select the desired text
  // and add the date and time
  switch (securityStateX) {
    case 1:
      Notif = "a Strange OBJECT" + currentDate + "" + currentTime;
      break;
    case 2:
      Notif = "Protected" + currentDate + "" + currentTime;
      break;
    case 3:
      Notif = "disarmed (Alarm stopped)" + currentDate + "" + currentTime;
      break;
    case 4:
      Notif = "disarmed" + currentDate + "" + currentTime;
      break;

      //default:
      // code to execute
  }

  static int i = 1; // variable and structure of if else needed for
  // serial send delay

  // there is a message to be sent
  // you can just zakommentirovat
  // not the desired method of communication
  if (i == 3) {
    Blynk.notify(Notif); i = 1;
  }

  else if (i == 2) {
    Blynk.email(Mail, Subject, Notif); i++;
  }

  else if (i == 1) {
    Blynk.tweet(Notif); i++;
  }

}

// Custom widgets (change colors displaying a message), depending on the status of the Alarm (securityState)
void Setting (String color, String Text)
{
  // variable and the design of the if else is needed to
  // serial send delay
  static int i = 1;

  if (i == 4) {
    led1.setColor(color);  // Change color LED V1
    i = 1;
  }

  else if (i == 3) {
    Blynk.setProperty(V10, "color", color);  // Change the color of the widget V10
    i++;
  }

  else if (i == 2) {
    Blynk.setProperty(V2, "color", color);  // Change the color of the widget V2
    i++;
  }

  else if (i == 1) {
    Blynk.virtualWrite(V10, Text);  // Print a message Value Display
    i++;
  }

}

void sendSetting() // Send settings, depending on the status of the Alarm (securityState)
{

  String Notif; // Variable for storing messages
  String color; // Variable to store color

  // then choose a setting depending on the system state
  switch (securityStateX) {
    case 1:
      Notif = "a Strange OBJECT";
      color = BLYNK_RED;
      break;
    case 2:
      Notif = "Protected";
      color = BLYNK_GREEN;
      break;
    case 3:
      Notif = "disarmed (Alarm stopped)";
      color = BLYNK_BLUE;
      break;
    case 4:
      Notif = "disarmed";
      color = BLYNK_BLUE;
      break;

      //default:
      // code to execute
  }

  // call the function Setting and substitute the data
  Setting(color, Notif); // Custom widgets (change colors displaying a message)
}

void securityState () // Define the Alarm status and the corresponding actions produce
{

  // State 1 // "If the system is armed" and "sensor Tripped" and "Not Able 1"
  // Code executed once
  if (flagProtection == true && pirState == true && securityStateX != 1)
  {
    securityStateX = 1; // number of the status of the alarm 1
    intruderState = HIGH;// the Alarm went off

    timer.setTimer(1000, messeg, 3); // call funkciu messeg 3 times, with an interval of 1 second

    digitalWrite(RELAY, intruderState); // relay

    timer.setTimer(200, sendSetting, 4); // call funkciu sendSetting 4 times, with an interval of 0.2 seconds

    timer.enable(timerSpeak_ID); // Enable the timer function Speak Squeaker


  } // State 1 //

  // State 2 // "If the system is armed" and "Sensor is Tripped" and "Not in Condition 2"
  // Code executed once
  else if (flagProtection == true && pirState == false && securityStateX != 2)
  {
    securityStateX = 2; // Number of alarm condition 2

    timer.setTimer(1000, messeg, 3); // call funkciu messeg 3 times, with an interval of 1 second

    timer.setTimer(200, sendSetting, 4); // call funkciu sendSetting 4 times, with an interval of 0.2 seconds

    timer.disable(timerSpeak_ID); // Disable timer function Speak Squeaker


  } // State 2 //

  // Condition 3 // "If security is turned Off" and "Alarm" and "Condition 3"
  // Code executed once
  else if (flagProtection == false && intruderState == HIGH && securityStateX != 3)
  {
    securityStateX = 3; // number of the status alarm 3
    intruderState = LOW; // Reset the flag triggering the Alarm

    timer.setTimer(1000, messeg, 3); // call funkciu messeg 3 times, with an interval of 1 second

    digitalWrite(RELAY, intruderState); // turn Off relay

    timer.setTimer(200, sendSetting, 4); // call funkciu sendSetting 4 times, with an interval of 0.2 seconds

    timer.disable(timerSpeak_ID); // Disable timer function Speak Squeaker

  } // State 3 //

  // State 4 // "If security is Disabled" and "No Alarm" and "Status 4"
  // Code executed once
  else if (flagProtection == false && intruderState == LOW && securityStateX != 4)
  {
    if (securityStateX != 3) // if previous state is not equal to 3 then
    { securityStateX = 4; // Number of alarm condition 4

      timer.setTimer(1000, messeg, 3); // call funkciu messeg 3 times, with an interval of 1 second

      timer.setTimer(200, sendSetting, 4); // call funkciu sendSetting 4 times, with an interval of 0.2 seconds

      timer.disable(timerSpeak_ID); // Disable timer function Speak Squeaker

    }

  } // State 4 //

} //securityState


void Speak() // Function for Buzzer Buzzer (Chants)
{
  // Set frequency and duration for the tweeters
  tone(BUZZER, 3500, 50);
} // Speak

//**Start*******************the Send data option 1******************
// Sending data to Blynk. In the Widget settings
// find REDIN RATE and set PUSH. !!!!Only!!!!PUSH!!!!
// otherwise will depart from online

void readSensorB() // function to read sensor B
{

  //*********The code for getting random values*******************
  //**************************Beginning********************************
  static int x = random (100, 200);
  static int i = 2000;
  if (i > -1) {
    i = i + x;
    B = (float)i / 100;
    if (i >= 4000) x = -random (100, 200); // switching control to the maximum
    if (i <= 2000) x = random (100, 200); // switching control to the maximum
  }
  //*********The code for getting random values*******************
  //**************************End*********************************

  //**************************The send data option 1******************
  // Sending data to Blynk in the Widget settings
  // find REDIN RATE and set PUSH. !!!!Only!!!!PUSH!!!!
  // otherwise will depart from online
  Blynk.virtualWrite(V11, B);

  //***Depending on the sensor you can change the color and the inscription***
  //Serial.println(B); // print values to serial monitor
  static int hotState = 0;
  if (B > 32 && hotState != 1)
  { hotState = 1;
    Blynk.setProperty(V11, "label", "OPASNOSTI OVERHEAT");// Change the name of the widget V11 (understands only English)
    Blynk.setProperty(V11, "color", BLYNK_RED); // Change the color of the widget V11 red
  }
  else if (B <= 32 && hotState != 2)
  { hotState = 2;
    Blynk.setProperty(V11, "label", "Temperature NORMAL"); // Change the name of the widget V11 (understands only English)
    Blynk.setProperty(V11, "color", BLYNK_WHITE); // Change the color of the widget V11 on white
  }
}
//The bottom line is that in this case we obnavljam data with the frequency which was prescribed
//timer B. This line is
//void setup()
//timer.setInterval(1000L, readSensorB);
//ie update data in the widget manages Our iron (ESP8266)
//**End********************the Send data option 1******************





void reconnectBlynk() // function which checks the connection
{
  if (!Blynk.connected()) { //if there is no connection then
    if (Blynk.connect()) { // conectica
      BLYNK_LOG("Reconnected"); // print in log

    } else {
      BLYNK_LOG("Not reconnected"); // print in log
    }
  }

} // reconnectBlynk

void setup()

{
  // Debug console
  // Serial.begin(19200);
  // Serial.println(" ");
  // Serial.println("Launch");

  // Custom inputs and outputs
  pinMode (LED, OUTPUT);
  digitalWrite(LED, HIGH);
  pinMode (RELAY, OUTPUT);
  digitalWrite (RELAY, HIGH);
  pinMode (PIR, INPUT);
  pinMode (BUZZER, OUTPUT);

  digitalWrite (D7, HIGH);  // Custom relay button D7

  delay(1000);
  for (int i = 0; i <= 3; i++)
  { tone(BUZZER, 300, 50);
    delay(80);
  }

  // Blynk.begin(auth, ssid, pass);
  // Usually, we use the construction from above but from
  // ESP8266 for it hangs when trying to install a WiFi connection
  Blynk.config(auth); // so configurable connection
  Blynk.disconnect(); //terminate the connection
  Blynk.connect(); // and then try to have to concretise


  //Custom timers
  timerPIRSensor_ID = timer.setInterval(1000L, readPIRSensor); // Pull the motion sensor function every six seconds.
  timerSpeak_ID = timer.setInterval(500L, Speak); // Pull the function
  timer.disable(timerPIRSensor_ID); // disable timer Motion Sensor
  timer.disable(timerSpeak_ID); // disable timer Tweeters

  timer.setInterval(3000L, securityState); // Pull the function of protection Status once a second

  timer.setInterval(60000L, reconnectBlynk); // check every 60 seconds if still connected to the server
  timer.setInterval(2000L, readSensorB); // read data from sensor B times a second (Pull function)


  rtc.begin(); // run clock widget real-time

  //Custom widgets
  // Turn on the LED for that would change the color of the Led's were visible
  led1.on();

  // Change the name of the widget V10 (Value Display)(only understands English)
  Blynk.setProperty(V10, "label", "Status"); // Custom title for the Widget

  //************************
  ArduinoOTA.setHostname("Security01"); //OTA Set the name of the network port
  ArduinoOTA.setPassword((const char *)""); //OTA Set access password for remote firmware
  ArduinoOTA.begin(); //Initialize OTA OTA
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  //***********************

  if (Blynk.connected()) { // If has established communication, then twice a Squeaker will Paknam
    for (int i = 0; i <= 2; i++)
    { tone(BUZZER, 200, 50);
      delay(100);
    }
  }
  else {
    for (int i = 0; i <= 10; i++) // If not connected then 10 times the Beeper will Paknam
    { tone(BUZZER, 100, 50);
      delay(80);
    }
  }

  mySwitch.enableTransmit(D8); // the rf-transmitter is connected to D8   xxxxxxxxxxxxxxxxxxxxxxxxx

}
void loop()

{
  ArduinoOTA.handle(); // OTA Always ready to be flashed wirelessly

// if (Blynk.connected()) {           //this line is disabled because of reconnection-issue      xxxxxxxxxxxxxxxxx
    Blynk.run(); // Startup blink

    timer.run(); // start the timer
//  }                                 //this line is disabled because of reconnection-issue      xxxxxxxxxxxxxxxxx
} // loop

// -------rcswitch------

/*
RFswitch commands. Each command is assinged to a virtual pin. Unless you have self-learning switches you will need a rf-serial sniffer to obtain the commands for each switch.
example: mySwitch.send(xxxx, 24);
each switch needs two commands; on and off. in the Blynk-app I use two push buttons for on and off because I can't see the state of the switch.
*/

BLYNK_WRITE(100) {  //virtual pin 100
  mySwitch.send(1111, 24); // RFswitch_1 on
}

BLYNK_WRITE(101) {
  mySwitch.send(1100, 24); // RFswitch_1 off
}

BLYNK_WRITE(102) {
  mySwitch.send(2211, 24); // RFswitch_2 on
}

BLYNK_WRITE(103) {
  mySwitch.send(2200, 24); // RFswitch_2 off
}

BLYNK_WRITE(104) {
  mySwitch.send(3311, 24); // RFswitch_3 on
}

BLYNK_WRITE(105) {
  mySwitch.send(3300, 24); // RFswitch_3 off
}

BLYNK_WRITE(106) {
  mySwitch.send(4411, 24); // RFswitch_4 on
}

BLYNK_WRITE(107) {
  mySwitch.send(4400, 24); // RFswitch_4 off
}

BLYNK_WRITE(108) {
  mySwitch.send(5511, 24);   // RFswitch_5 on
}

BLYNK_WRITE(109) {
  mySwitch.send(5500, 24); // RFswitch_5 off
}

BLYNK_WRITE(110) {
  mySwitch.send(6611, 24); // RFswitch_6 on
}

BLYNK_WRITE(111) {
  mySwitch.send(6600, 24); // RFswitch_6 off
}
2 Likes

Oh thanks. Glad you liked my sketch.

I did the same thing like this. Send the QR code of your application. and What RF devices do you use? Give links.
Your code additions are studying. )))

if (Blynk.connected()) {
Blynk.run(); // Startup blink
}
timer.run(); // start the timer

That is more correct. There is an error here. )))

I loaded it and made the settings, but when I activated the alarm, the buzzer was always on.