Anti-Theft System using Ultrasonic Sensor and HC-05/ESP-01 with Blynk Mobile App

Overview:

Additional security in our homes and/or belongings not only aids in ensuring one’s safety but also reduces additional damage to our property. The most important aspect of a security system is its ability to maintain a wireless connection.  A system that is able to notify through our phones when there’s an intrusion is also most convenient for ease in monitoring. Thus, this project will introduce a simple anti-theft system using our Upgraded Arduino Uno Starter Kit with an integrated Blynk Application.

Hardware:

Software:

Application Discussion

Wireless access, especially when it comes to security system, is important because this allows constant monitoring and control. Such functionalities can be achieved by our security system by using modules which enables wireless communication.

As such, this project introduces the use of wireless communication using either of the two modules: HC-05 or ESP-01. The security system generally consists of the Ultrasonic Sensor as an obstruction detector with LED lights, as well as a buzzer, as indicators.

Ultrasonic Sensor (HC-SR04)

The ultrasonic sensor is a sensor that is able to measure distances. It uses SONAR (Sound Navigation and Ranging) in order to determine the distance of an object. It also allows non-contact range detection. This is quite useful for security system because it minimizes the chance of damage on the actual system.

The connection of the ultrasonic sensor to the Arduino can be viewed in the table below:

ULTRASONIC SENSOR PIN

ARDUINO CONNECTION

Vcc

5V

Trig

9

Echo

10

GND

GND

 

HC-05 Bluetooth Module

There are several ways in achieving wireless communication and one of it is through Bluetooth. The HC-05 Bluetooth module uses serial communication which is commonly used in most electronics projects. It is also quite affordable for a device that enables a master-slave behavior. Such behavior allows wireless communication between two microcontrollers or any device with a Bluetooth functionality.

For this project, the HC-05 is used to receive information from the ultrasonic sensor and then relay it to the Blynk App. For the pins of the HC-05, the following connections are used:

BLUETOOTH MODULE PIN

ARDUINO CONNECTION

State

Not connected

RX

12

TX

11

GND

GND

VCC

5V

EN

Not Connected

 **This is viewed top to bottom from the product photo above—Pin label can also be found at the back of the Bluetooth module       .

ESP-01 Wi-Fi Module (ESP8266-01)



Aside from the HC-05 it is also possible to use a Wi-Fi Module to achieve wireless communication. The ESP8266-01 is a Wi-Fi module which allows microcontrollers to have access to a Wi-Fi network. It can also be reprogrammed to act as a standalone Wi-Fi connected device just by adding power! This module is quite versatile and is also affordable much like the HC-05.

Before proceeding with the ESP-01 route, the module MUST be configured first.

To configure the ESP-01, click HERE.

This module is an alternative route in creating this project. Wireless connection can be obtained using either the HC-05 or the ESP-01. The ESP-01 consists of 8 pins in total. Its corresponding connection with the Arduino, in this project can be viewed below.

1
GND

2
GPIO2

3
GPIO0

4
GPIO3

5
GPIO1

6
CHIP_EN

7
RESET

8
VCC

*Arrangement of the pins is referenced from the above photo

WI-FI MODULE PIN

ARDUINO CONNECTION

GND

 GND

GPIO2

 Not connected

GPIO0

 Not connected

GPIO3 (RX)

11 

GPIO1 (TX)

 12

CHIP_EN (CHIP ENABLE)

3.3 V 

RESET

 Not connected

VCC

 3.3 V

 

Set-up the hardware

There will be two (2) hardware setup for this project. The first project will utilize HC-05 as its means for wireless communication while the other will use ESP-01.

Using the HC-05:

 

Using ESP-01:

 

Blynk App Setup

Download the Blynk App for your smartphone on Google Play or App Store.

Opening the application will immediately direct to the Log in page. User may opt to log in with their Facebook, Create a New Account, or Log in if they have an existing account already. Choose whichever option works best and once that’s done, we begin by creating a ‘New Project’.

The photos below show which options to select according to their respective module used. Bluetooth for the HC-05 option and Wi-Fi for the ESP-01. This is step is quite crucial to ensure seamless work experience with the Blynk App and the project.

After that, there will be an authentication token sent to the registered email address, make sure to check that. It the mail cannot be seen in the inbox folder make sure to also check the spam folder.

The next part will be the adding of components or widgets to achieve a good visual display for the project.

The next step is connecting to our Bluetooth/Wi-Fi module

For Bluetooth Connection

For Wi-Fi Connection

Change the connection type to Wi-Fi and it will automatically notify that a new device is connected. 



Just like in the bluetooth connection, the next step is adding of components or widgets to achieve a good visual display for the project.

With the Blynk App installed and ready to use, all that’s left is to setup the software side of our system.

Set-up the software

Open the Arduino IDE and upload the code on the Arduino. The codes can also be found on GitHub here.

Code for HC-05

#define trigPin 9
#define echoPin 10
#define onLED 4
#define detectLED 3
#define detectBuzz 7
/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

#include <SoftwareSerial.h>
SoftwareSerial SwSerial(11, 12); // RX, TX

#include <BlynkSimpleSerialBLE.h>

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

long duration;
int distance;

int acquiredValue;
int notifyVar = 0;

BlynkTimer timer1;
BlynkTimer timer2;

void myNormalTimerEvent()
{
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, "System is ON");
}

void myDetectedTimerEvent()
{
  // You can send any value at any time.
  // Please don't send more that 10 values per second.
  Blynk.virtualWrite(V5, "Obstruction Detected");
}

void setup() {
  // put your setup code here, to run once:
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(onLED, OUTPUT);
  pinMode(detectLED, OUTPUT);
  pinMode(detectBuzz, OUTPUT);
  
  digitalWrite(onLED, HIGH);
  
  SwSerial.begin(9600);
  Serial.begin(9600);
  Blynk.begin(SwSerial, auth);
  Serial.println("Waiting for connections...");

  // Setup a function to be called every second
  timer1.setInterval(1000L, myNormalTimerEvent);
timer1.run(); } void loop() { Blynk.run(); ultrasonicFunction(); if (distance < 50) { digitalWrite(onLED, LOW); digitalWrite(detectLED, HIGH); tone(detectBuzz, 1000); if (notifyVar == 0) { notifyVar++; Blynk.notify("!!Obstruction Detected!!"); // Setup a function to be called every second timer2.setInterval(1000L, myDetectedTimerEvent); timer2.run(); } } if (acquiredValue == 1) { digitalWrite(onLED, HIGH); digitalWrite(detectLED, LOW); noTone(detectBuzz); notifyVar--; acquiredValue = 0; Blynk.notify("System Reset"); // Setup a function to be cal led every second timer1.setInterval(1000L, myNormalTimerEvent); timer1.run(); } } void ultrasonicFunction() { // Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH); // Calculating the distance distance= duration*0.034/2; // Prints the distance on the Serial Monitor Serial.print("Distance: "); Serial.println(distance); } BLYNK_WRITE(V1) { acquiredValue = param.asInt(); // assigning incoming value from pin V1 to a variable }

Code Breakdown

The code for controlling using the Blynk app is based on the Blynk Example Browser.

Make sure to input the Board as Arduino UNO and the Connection as HC05 or HC06. Afterwards, input the Auth Token that could be found in your Blynk App by pressing the nut icon on your project screen.

You can now browse the Examples provided. For this project, we will be using the Get Data to listen if you have pressed the button in the App and the Push Data to change the display in our Blynk App.

  • Setting up the Bluetooth connection to Blynk
#include <SoftwareSerial.h>
SoftwareSerial SwSerial(11, 12); // RX, TX

#include <BlynkSimpleSerialBLE.h>

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

This is what you'll see in the Blynk Example Browser. Make sure to input this in your void setup() afterwards to turn on communication of the HC-05 and start communicating with your Blynk App.

SwSerial.begin(9600);
Blynk.begin(SwSerial, auth);
  •  void myNormalTimerEvent()

This function is from the Push Data example from the Blynk Example Browser. In this case, it was renamed to myNormalTimerEvent(). This will utilize the BlynkTimer function and for this function, it will be named timer1. This function will changed the label on virtual pin 5 (V5) of the Blynk App to "System is ON". It will only work if it is called in the code with:

timer1.setInterval(1000L, myNormalTimerEvent);
timer1.run();
  • void myDetectedTimerEvent()

This function is like the myNormalTimerEvent() and will only activate if the ultrasonic sensor detected an obstruction. In this case, it was renamed to myDetectedTimerEvent(). This will utilize the BlynkTimer function and for this function, it will be named timer2. This function will changed the label on virtual pin 5 (V5) of the Blynk App to "Obstruction Detected". It will only work if it is called in the code with:

timer2.setInterval(1000L, myDetectedTimerEvent);
timer2.run();
  • BLYNK_WRITE(V1)

This function is from the Get Data example from the Blynk Example Browser. This function is checking if the button on your Blynk App that was assigned on virtual pin 1 (V1) has been pressed or not. We get this by using the function param.asInt() and storing it in a variable called acquiredValue. This variable will be equal to 1 if pressed.

  • void setup()
This is a default Arduino function that runs once the system is turned on. All the defined pins will be declared as INPUT or OUTPUT depending on their function. The green LED or the onLED pin will also be set to high to tell the user that the sensor have not detected any obstruction and the system is turned on. Next, turn on the bluetooth communication by inputting SwSerial.begin(9600) and the Blynk.begin(SwSerial, auth) to begin communicating with the Blynk App. Finally, add the myNormalTimerEvent() timer to make the label in the Blynk App into "System is ON" to once again indicate to the user that the sensor have not detected any obstruction and the system is turned on.
  • void loop()

This is also a default Arduino function that runs repeatedly after running the setup() function has ran once. Input Blynk.run() first to make sure that the Blynk App will be communicating with the Arduino.

Next, call the ultrasonicFunction() function to make the ultrasonic sensor start detecting.

Then add an if statement checking that if once there is something obstructing within 50 centimeters of the sensor, the green LED will turn off, the red LED named detectLED will turn on, and the buzzer named detectBuzz will turn on at 1000 Hz frequency. Still inside this if statement, we add another if statement that checks if the variable notifyVar is equal to zero. This if statement is responsible for making sure that the user will only get notified ONCE when an obstruction is detected. This is done by using the Blynk.notify() function and setting the notifyVar equal to 1 to make sure it will only be run once. The timer for the myDetectedTimerEvent() will also be run here to make sure the label in the app will changed to "Obstruction Detected".

Finally, add another if statement with the condition acquiredValue == 1 to check if the Reset button in the App has been pressed or not. Once the reset button has been pressed: the green LED will turn on, the red LED will turn off, and the buzzer will turn off. The variable notifyVar will be equal to 0 to allow the user to get a notification when another obstruction is detected that was discussed in the previous paragraph, the user will also get a notification that the system has been reset, and the myNormalTimerEvent() will also run to make sure that the label in the app will be changed back to "System is ON".

  • void ultrasonicFunction()

This function is responsible for making the ultrasonic sensor work. As discussed earlier, this sensor emits ultrasound (using the TRIG pin) and also detects the bouncing ultrasound from an object (using the ECHO pin). Using this description, this function first turns the TRIG pin OFF for a few microseconds then turns the TRIG pin ON to emit the ultrasound. Afterwards, the TRIG pin will once again be turned OFF and the ECHO pin will be turned ON, allowing the sensor to detect the bouncing ultrasound that it emitted from the TRIG pin to get the duration in microseconds.

Finally,  it calculates the distance in centimeters utilizing the duration variable and the speed of sound.

Code for ESP-01


#define BLYNK_PRINT Serial

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

#define trigPin 9
#define echoPin 10
#define onLED 4
#define detectLED 3
#define detectBuzz 7

long duration;
int distance;

int acquiredValue;
int notifyVar = 0;

/* Comment this out to disable prints and save space */
#include 
SoftwareSerial EspSerial(12, 11); // RX, TX

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

// Your WiFi credentials.
// Set password to "" for open networks.
//Replace the ---- with your SSID and Password
char ssid[] = "------"; 
char pass[] = "------";

// Your ESP8266 baud rate:
#define ESP8266_BAUD 9600

ESP8266 wifi(&EspSerial);

void setup() {
  // put your setup code here, to run once:

  // Debug console
  Serial.begin(9600);
  delay(10);
  
  EspSerial.begin(ESP8266_BAUD);
  delay(10);

  Blynk.begin(auth, wifi, ssid, pass);
  Blynk.virtualWrite(V5, "System is ON");

  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(onLED, OUTPUT);
  pinMode(detectLED, OUTPUT);
  pinMode(detectBuzz, OUTPUT);
  
  digitalWrite(onLED, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Blynk.connected()) {
    Blynk.run();
    ultrasonicFunction();

    if (distance < 50) {
      digitalWrite(onLED, LOW);
      digitalWrite(detectLED, HIGH);
  
      tone(detectBuzz, 1000);
  
      if (notifyVar == 0) {
        notifyVar++;
  
        Blynk.notify("!!Obstruction Detected!!");
        Blynk.virtualWrite(V5, "Obstruction Detected");
      }
    }
    if (acquiredValue == 1) {
      digitalWrite(onLED, HIGH);
      digitalWrite(detectLED, LOW);
  
      noTone(detectBuzz);
  
      notifyVar--;
  
      acquiredValue = 0;
      Blynk.notify("System Reset");
      Blynk.virtualWrite(V5, "System is ON");
    }
  }
}

void ultrasonicFunction() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance= duration*0.034/2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}

BLYNK_WRITE(V1)
{
  acquiredValue = param.asInt(); // assigning incoming value from pin V1 to a variable
}

Code Breakdown

 The code for controlling using the Blynk app is based on the Blynk Example Browser.

Make sure to input the Board as Arduino UNO and the Connection as ESP8266 WiFi Shield. Afterwards, input the Auth Token that could be found in your Blynk App by pressing the nut icon on your project screen.

Copy the sketch from the Blynk Example browser and comment out #define EspSerial Serial1 and uncomment the following while changing the EspSerial to (12,11).

#include <SoftwareSerial.h> 
SoftwareSerial EspSerial(12, 11); // RX, TX

Make sure to configure your ESP-01s to 9600 baud rate. Otherwise, the default would be 115200 baud rate.

You can now browse the Examples provided. For this project, we will be using the Get Data to listen if you have pressed the button in the App, and unlike the Bluetooth output, we won't be using timers in this project. Instead, we will utilize Blynk.write().

  • BLYNK_WRITE(V1)

This function is from the Get Data example from the Blynk Example Browser. This function is checking if the button on your Blynk App that was assigned on virtual pin 1 (V1) has been pressed or not. We get this by using the function param.asInt() and storing it in a variable called acquiredValue. This variable will be equal to 1 if pressed.

  • void setup()
This is a default Arduino function. Make sure to input EspSerial.begin(ESP8266_BAUD) to begin communication of the ESP-01s module and also Blynk.begin(auth, wifi, ssid, pass) to begin communication from your ESP-01s to the Blynk app. Add Blynk.virtualWrite(V5, "System is ON") to change the label in the Blynk App. Afterwards, indicate the other pins as either OUTPUT or INPUT, and then turn the green LED on using digitalWrite().
  • void loop()

This is also a default Arduino function. The void loop() will have the same content as the Bluetooth except that there will be no more timer and the whole code will be inside an if (Blynk.connected()) so that the loop will only commence if your system is connected to the Blynk App. The timers will be replaced with Blynk.virtualWrite(V5, "System is ON") and Blynk.virtualWrite(V5, "Obstruction Detected").

  • void ultrasonicFunction()

This function is responsible for making the ultrasonic sensor work. As discussed earlier, this sensor emits ultrasound (using the TRIG pin) and also detects the bouncing ultrasound from an object (using the ECHO pin). Using this description, this function first turns the TRIG pin OFF for a few microseconds then turns the TRIG pin ON to emit the ultrasound. Afterwards, the TRIG pin will once again be turned OFF and the ECHO pin will be turned ON, allowing the sensor to detect the bouncing ultrasound that it emitted from the TRIG pin to get the duration in microseconds.

Finally,  it calculates the distance in centimeters utilizing the duration variable and the speed of sound.

Output

for Bluetooth (HC-05)

Once the code has been uploaded go back to your Blynk App. The prompt should say that the system is ON and will send you a notification if an obstruction is detected. The reset button will switch off the alarm and await for another detected obstruction.

 

for Wi-Fi Module (ESP-01)


Conclusion

Upon working on the simple anti-theft system, we were able to explore two ways in achieving a wireless communication. The two options we explored were the Bluetooth route which used the HC-05 module and the Wi-Fi route which made use of the ESP-01. Not only that, we also utilized various components such as the ultrasonic sensor, the LED, and the buzzer. This simple anti-theft system cannot be commercially used however such knowledge may be applied in higher-scale projects or applications.

To find more useful and fun projects for you to try, you may head on to KnowledgeBase and Tutorials.

References

www.microchip.ua/wireless/esp01.pdf

https://components101.com/wireless/hc-05-bluetooth-module

https://randomnerdtutorials.com/complete-guide-for-ultrasonic-sensor-hc-sr04/

Anti-theftArduino unoBluetoothBlynkBuzzerEsp01Esp8266Hc-05LedUltrasonic sensorWi-fi

Leave a comment

All comments are moderated before being published