Arduino Project Beginners (80+ New Arduino Hacks 2019)

Arduino Project Beginners 2018

Arduino Project Beginners 2018: A Simple Alarm System with Arduino 

In this blog, we build a simple alarm system that will be activated whenever motion is detected by a sensor. we designed a simple alarm with the buzzer sound with red LED that attach with the motion detector. The user will also be able to start and stop the alarm by pressing a button.

 

alarm

We are going to do the following on this blog:

  • Check the hardware and software requirements for this project
  • Then, how to assemble the hardware parts for Alarm
  • After that, we will configure our alarm using the Arduino IDE

 

Hardware and software requirements

First, let's see what the required components for this project are. As this is the first blog of the blog, we will spend a bit more time here to detail the different components, as these are components that we will be using in the whole blog.

 

The first component that will be central to the project is the Arduino Uno board:

In all the projects, I will be using the official Arduino Uno R3 board. However, you can use an equivalent board from another brand or another Arduino board, such as an Arduino Mega board.

 

Another crucial component of our alarm system will be the buzzer:

This is a very simple component that is used to make simple sounds with Arduino. You couldn't play an MP3 with it but it's just fine for an alarm system. You can, of course, use any buzzer that is available; the goal is to just make a sound.

 

After that, we are going to need a motion detector:

Here, I used a very simple PIR motion detector. This sensor will measure the infrared (IR) light that is emitted by moving objects in its field of view, for example, people moving around.

 

It is really easy and quite cheap to interface with Arduino. You can use any brand that you want for this sensor; it just needs a voltage level of 5V in order to be compatible with the Arduino Uno board.

 

Finally, here is the list of all the components that we will use in this project: Arduino Uno (https://www.sparkfun.com/products/11021)

Arduino Project Beginners

Buzzer (https://www.sparkfun.com/products/7950)

PIR (https://www.sparkfun.com/products/13285)

LED (https://www.sparkfun.com/products/9590)

330 Ohm resistor (https://www.sparkfun.com/products/8377)

Button (https://www.sparkfun.com/products/97)

1k Ohm resistor (https://www.sparkfun.com/products/8980)

Breadboard (https://www.sparkfun.com/products/12002)

Jumper wires (https://www.sparkfun.com/products/8431)

 

On the software side, the only thing that we will need in the first blog is the latest version of the Arduino IDE that you can download from the following URL: https://www.arduino.cc/en/main/software. Note that we are going to use the Arduino IDE in all the projects of this blog, so make sure to install the latest version.

 

Hardware configuration

arduino_alarm

We are now going to assemble the hardware for this project. As this is the first project of this blog, it will be quite simple. However, there are quite a lot of components, so be sure to follow all the steps. Here is a schematic to help you out during the process:

 

Let's start by putting all the components on the board. Place the buzzer, button, and LED on the board first, according to the schematics. Then, place the 330 Ohm resistor in series with the LED anode (the longest pin) and connect the 1k Ohm resistor to one pin of the push button.

 

This is how it should look at this stage: Now we are going to connect each component to the Arduino board.

Let's start with the power supply. Connect the 5V pin of the Arduino board to one red power rail of the breadboard, and the GND pin of the Arduino board to one blue power rail of the breadboard. 

 

Then, we are going to connect the buzzer. Connect one pin of the buzzer to pin number 5 of the Arduino board and the other pin to the blue power rail of the breadboard.

 

 After that, let's connect the LED. Connect the free pin of the resistor to pin number 6 of the Arduino board and the free pin of the LED (the cathode) to the ground via the blue power rail.

 

Let's also connect the push button to our Arduino board. Refer to the schematic to be sure about the connections since it is a bit more complex.

 

Basically, you need to connect the free pin of the resistor to the ground and connect the pin that is connected to the button to the 5V pin via the red power rail. Finally, connect the other side of the button to pin 12 of the Arduino board.

 

Finally, let's connect the PIR motion sensor to the Arduino board. Connect the VCC pin of the motion sensor to the red power rail and the GND pin to the blue power rail. Finally, connect the SIG pin (or OUT pin) to Arduino pin number 7.

 

The following is the final result:

If your project looks similar to this picture, congratulations, you just assembled your first secret agent project! You can now go on to the next section.

 

Configuring the alarm system

alarm_circuit

Now that the hardware for our project is ready, we can write down the code for the project so that we have a usable alarm system. The goal is to make the buzzer produce a sound whenever motion is detected and also to make the LED flash. However, whenever the button is pressed, the alarm will be switched off.

 

Here is the complete code for this project:

// Code for the simple alarm system
// Pins
const int alarm_pin = 5;
const int led_pin = 6;
const int motion_pin = 7;
const int button_pin = 12;
// Alarm
boolean alarm_mode = false;
// Variables for the flashing LED int ledState = LOW;
long previousMillis = 0;
long interval = 100; // Interval at which to blink (milliseconds)
void setup()
{
// Set pins to output
pinMode(led_pin,OUTPUT); pinMode(alarm_pin,OUTPUT);
// Set button pin to input pinMode(button_pin, INPUT);
// Wait before starting the alarm delay(5000);
}
void loop()
{
// Motion detected ?
if (digitalRead(motion_pin)) {
alarm_mode = true;
}
// If alarm mode is on, flash the LED and make the alarm ring if (alarm_mode){
unsigned long currentMillis = millis(); if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis; if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// Switch the LED digitalWrite(led_pin, ledState);
}
tone(alarm_pin,1000);
}
// If alarm is off
if (alarm_mode == false) {
// No tone & LED off noTone(alarm_pin); digitalWrite(led_pin, LOW);
}
// If button is pressed, set alarm off
int button_state = digitalRead(button_pin);
if (button_state) {alarm_mode = false;}
}

 

We are now going to see, in more detail, the different parts of the code. It starts by declaring which pins are connected to different elements of the project, such as the alarm buzzer:

const int alarm_pin = 5;

const int led_pin = 6;
const int motion_pin = 7;
const int button_pin = 12;
After that, in the setup() function of the sketch, we declare these pins as either inputs or outputs, as follows:
// Set pins to output
pinMode(led_pin,OUTPUT); pinMode(alarm_pin,OUTPUT);
// Set button pin to input pinMode(button_pin, INPUT);
Then, in the loop() function of the sketch, we check whether the alarm was switched on by checking the state of the motion sensor:
if (digitalRead(motion_pin)) {
alarm_mode = true;
}

Note that if we detect some motion, we immediately set the alarm_mode variable to true. We will see how the code makes use of this variable right now.

 

Now, if the alarm_mode variable is true, we have to enable the alarm, make the buzzer emit a sound, and also flash the LED. This is done by the following code snippet:

if (alarm_mode){
unsigned long currentMillis = millis(); if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// Switch the LED digitalWrite(led_pin, ledState);
}
tone(alarm_pin,1000);
}
Also, if alarm_mode is returning false, we need to deactivate the alarm immediately by stopping the sound from being emitted and shutting down the LED. This is done with the following code:
if (alarm_mode == false) {
// No tone & LED off noTone(alarm_pin); digitalWrite(led_pin, LOW);
}

Finally, we continuously read the state of the push button. If the button is pressed, we will immediately set the alarm off:

  • int button_state = digitalRead(button_pin);
  • if (button_state) {alarm_mode = false;}

 

Usually, we should take care of the bounce effect of the button in order to make sure that we don't have erratic readings when the button is pressed. However, here we only care about the button actually being pressed so we do not need to add an additional debouncing code for the button.

Now that we have written down the code for the project, it's time to get to the most exciting part of the blog: testing the alarm system!

 

Testing the alarm system

alarm

We are now ready to test our simple alarm system. Just grab the code for this project (either from the preceding code or the GitHub repository of the blog) and put it into your Arduino IDE.

 

In the IDE, choose the right board type (for example, Arduino Uno) and also the correct serial port. You can now upload the code to the board. Once it is done, simply pass your hand in front of the PIR motion sensor; the alarm should go off immediately. Then, simply press the push button to stop it.

 

To illustrate the behavior of the alarm, I simply used a battery pack to make it work when it is not connected to my computer. The following is the result when the alarm goes off: 

 

If this works as expected, congratulations, you just built your first secret agent project: a simple alarm system based on Arduino! If it doesn't work well at this point, there are several things you can check. First, go through the hardware configuration part again to make sure that your project is correctly configured.

 

Also, you can verify that when you pass your hand in front of the PIR sensorit goes red. If this is not the case, most probably your PIR motion sensor has a problem and must be replaced.

 

Burglar Alarm 

Firstly, we will create a plan for how we are going to go about catching the culprit. Of course, it is not enough to simply sound an alarm when a thief is caught in the act; you also want to have evidence. You see where this is going, right? Yes, we will be using a wireless camera to get a mugshot of the culprit.

 

This blog does use a fair share of code but, in addition to that, it requires quite a few components. Learning to use them in unison is the ultimate goal of this blog. It is divided into the following sections:

  • The PIR sensor
  • Testing the camera
  • Communicating with a smartphone
  • The burglar alarm

 

I promised you in previous blogs that I would try to teach you as much I possibly could about the Arduino. Bluetooth is very reliable and inexpensive but it is short-range and usually needs a host to gather or send data.

 

The following are the components you'll need, to create a high-tech burglar alarm:

  • 1 x Arduino UNO board
  • 1 x USB cable A to B (aka the printer cable)
  • 1 x PIR sensor
  • 1 x wireless IP camera (a netcam360 is used in this blog)
  • 1 x HC-06 module (Bluetooth)
  • 1 x wireless router (with accessible settings)
  • 1 x PC with inbuilt Bluetooth or a Bluetooth USB module

 

What is a passive infrared sensor?

passive infrared sensor (PIR) is an electronic sensor that uses infrared radiation to detect variations in its field of view. They are most commonly used as motion sensors.

 

For example, they are used to minimize power consumption by switching off lights and utilities if nobody is at home. They are also used in state-of-the-art burglar alarm systems to trigger a switch when motion is detected.

 

If you would like to learn more about how they work, you should refer to this page (https://learn.adafruit.com/ pir-passive-infrared-proximity-motion-sensor/) at Adafruit. Adafruit and Ladyada are really good resources for building Arduino projects.

 

A mini PIR-Arduino alarm

mini_alarm

Let's get started. We are going to create a setup in which an LED flashes when motion is detected by the PIR sensor. This is what the setup should look like when connecting the Arduino to the PIR Sensor:

Basically, the connections are as follows:

  • GND → GND
  • VCC → 5V
  • OUT → D02 (digital pin 2)

 

Digital pins are denoted using D and analog pins are denoted by A. So digital pin 13 is D13 and analog pin 2 is A02.

 

Open Arduino and load the sketch called PIR_LED.ino, or copy this:

int ledPin = 13; // use the onboard LED
int pirPin = 2; // 'out' of PIR connected to digital pin 2
int pirState = LOW; // start the state of the PIR to be low (no motion)
int pirValue = 0; // variable to store change in PIR value
void setup() {
pinMode(ledPin, OUTPUT); // declare the LED as output pinMode(pirPin, INPUT); // declare the PIR as input Serial.begin(9600); // begin the Serial port at baud 9600
}
void loop() {
pirValue = digitalRead(pirPin); // read PIR value
if ((pirValue == HIGH)&&(pirState==LOW)) { // check if motion has occured
digitalWrite(ledPin, HIGH); // turn on LED
Serial.println("Motion detected!");
pirState = HIGH; // set the PIR state to ON/HIGH delay(1000); // wait for a second
}
else { // if there is no motion digitalWrite(ledPin, LOW); // turn off LED if(pirState == HIGH) {
// prints only if motion has happened in the first place Serial.println("No more motion!\n");
pirState = LOW; // sets the PIR state to OFF/LOW delay(200); // small delay before proceeding
}
}
}

Run the code and open up the Serial Monitor and set the baud rate to 9600. This is a simple program that switches on the LED when motion is detected and powers it off when there is no motion.

 

See it in action by moving your hand in front of the PIR sensor. See how the LED glows when the PIR detects motion? PIR sensors are very sensitive to variations in light, which is why they are often used in motion detectors. This was pretty straightforward so far, right? Good! Let's now move on to the camera.

 

Testing the camera

An IP camera (or Internet Protocol camera) is a camera that you can access on your wireless network provided that it is configured correctly. The configuration procedure depends on which IP camera you bought and who the manufacturer is, but they should all be pretty similar.

 

Installing the camera on the network

Go to http://netcam360.com/enindex.html and download IP camera for PC.

 

You should also be able to find a PC installation manual on the same webpage. Follow the instructions provided. I will not go into detail because there is a high chance that you have not purchased the same IP Camera.

 

It is highly recommended that you create a password for your camera to keep prying eyes away. Also, do remember the password because we will need it in the steps to come.

 

Setting up the mugshot URL

Go back to http://netcam360.com/enindex.html and download the IP camera search tool or use the file of the same name located in the Useful Files folder that comes with this blog. I believe that this tool can be used, irrespective of the manufacturer, to find IP cameras on your network.

 

Run it and Note down the IP address at the top. In this case, it is 192.168.0.111:81, where 81 is the port number.

Open a new browser window and, in the address bar, paste the following: http://<your ip>/snapshot.cgi?user=admin&pwd=<your_password>

For example: http://192.168.0.111:81/snapshot.cgi?user=admin&pwd=password

 

You should be able to see a snapshot of what your camera is seeing in real time. You can try refreshing the page while moving the camera to test different camera positions. We are going to use this link later in the blog to fetch the image file to catch the burglar.

 

Putting it together

As I mentioned before, we will be using a Bluetooth module to communicate with the Arduino. The specific model is the HC-06 module, which is one of the cheapest Arduino communications modules and is widely used.

 

We could just try to hook it up to our smartphone and send an alert directly to it, but what if you aren't at home? That is a drawback of using Bluetooth.

 

But fret not. We will capitalize on what we can do using just the Bluetooth. I think this is a good time to explain the plan before diving into the details.

 

We use the PIR sensor to check if there is any motion detected. This data is transmitted through the HC-06 Bluetooth module to a host computer through a Bluetooth channel. A script (program) running on the computer takes a snapshot of the culprit using the wireless IP camera's URL and saves it as an image.

 

It then uploads the image to an image-sharing website and fetches the link. Finally, an alert is sent to the user saying that the alarm has been set off. The user can then open the link on a smartphone to see the culprit. I hope that wasn't too hard to follow. First, let's get the script ready.

 

An introduction to Python

Wait! What? I did not sign up for this! Hold on there. We are not going to study Python too much. That is outside the scope of this blog. To be honest, I think this particular section is the furthest you will deviate from the field of Arduino.

 

But you must understand that, to create something really powerful, you need to make the most out of the resources we have. We are just going to use its basic functionalities to achieve our intended plan.

 

What are you even talking about? What is PythonWhy are we talking about a snake? Python is a very powerful, but easy to use, languages like C or Java. We will be using it to get a snapshot from the camera, upload it to the Web, and send a notification to your smartphone. The following image is the best way to describe it:

 

You should be warned that this section is going to be a bit difficult, but you should try to be patient. Once Python is installed, it is going to stay there forever. Let's go ahead and install it. There are two popular versions of Python, namely 2.7 and 3.4. We are going to use 2.7 since it is older and has a lot more libraries that work with it.

 

Yes, libraries, similar to the ones that you used earlier with the Arduino.

Download Python from https://www.python.org/download/releases/2.7.8/ according to your operating system. Note that 32-bit is x86 and 64-bit is x64.

 

Install it somewhere convenient. Most OS X and Linux computers come with Python pre-installed.

 

Next, we need to download and install an interface for writing your codes. I recommend Eclipse because it is easy to use for newcomers to Python. Since Eclipse is Java-based, you should update Java by going to http://www.java.com/en/ and installing/updating Java on your system.

 

You can download Eclipse from http://www.eclipse.org/downloads/. Select Eclipse Classic and install it, or rather extract it, into a convenient location, as with Arduino. If you have used Python before, you can simply choose your own interface. Geany is one commonly used Python IDE.

 

Open Eclipse. If you get a Java error, use this resource to solve the problem:

http://stackoverflow.com/questions/2030434/eclipse-no-java-jre-jdk-no-virtual-machine. It will ask you for a workspace. Use something like C:\ MyScripts or choose anything similar. Then close the welcome screen. You will see something like this:

 

Ignore PyDev Package Explorer on the left in the screenshot. I am starting from the beginning so that you can set it up.

 

1. Go to Help | Install New Software. You will see this dialog box:

2. Click Add….

3. For Name, type pydev and for Location, type http://pydev.org/updates.

4. Press OK. Wait for it to load.

 

5. Select the first option (PyDev) and click Next >. Accept the terms and conditions and let it install. If it asks you whether you trust this application, just select Yes. It will ask you to restart Eclipse. Allow it. Wait for it to launch by itself. You're almost done.

 

6. Go to Window | Preferences. In that dialog, expand PyDev | Interpreters | Python Interpreter.

7. Click on New….

8. For the Interpreter Name, type Python27.

And for Interpreter Executable, you can browse to select C:\Python27\ python.exe or you can simply paste that without quotations. Click OK. It will load a lot of files. Ensure all are checked and hit OK.

 

9. Hit OK again. One last thing: on the Eclipse Interface on the top right. Select PyDev instead of Java.

 

10. Now, in PyDev Package Explorer, right-click and create a new project.

11. Choose General | Project.

 

12. Click Next >.

Call your project something like MyProject or HelloWorld, or whatever you like, and let it use the default location to store the files. Click Finish when you're ready.

 

13. Right-click on MyProject | New | File.

 

14. Call it HelloWorld.py and press Finish. Remember to use .py and not just HelloWorld, so that Eclipse understands what to associate it with. Type: print("Hello World!")

 

15. Press Run (the green bubble with a right-pointing triangle). It will bring up the following window every time you run a new script:

16. Simply select Python Run and press OK.

 

If everything works as expected, you will see this in the Console window on the right side:

Hurray! You have just written your very first Python script! You should be proud of yourself because you have just been introduced to one of the most powerful programming tools in the history of programming.

 

When you are done with this blog, I recommend you look up some Python tutorials to see what it can do. But now, we must keep moving. Let's now focus on setting up the Bluetooth network.

 

Hooking up the Bluetooth module

The HC-06 is a simple, low-powered Bluetooth module that works very well with Arduino. Go ahead and create this circuit:

The connections are as follows

GND → GND

VCC → 3.3 V

RXD → D01 (TX)

TXD → D00 (RX)

Note that, before uploading codes where RX and TX pins are used, unplug those pins. Reconnect them once the uploading process is complete.

 

1. Plug the Arduino into the USB hub to power the HC-06 chip. Now, in your system tray, right-click on the Bluetooth icon and click Add a Device.

 

2. Let the computer search until it finds HC-06. If nothing shows up, try using an Android phone to connect to it. If it doesn't show up even then, check your connections.

 

3. Click Next. Here, type in the device's pairing code, which is 1234 by default.

 

4. It will now install the HC-06 on your computer. If everything works well, when you open up Device Manager and go to Ports (COM & LPT), Note down these three COM values (they will be different for different users).

 

5. Finally, you are ready to program the Bluetooth module.

 

Open up a new Arduino sketch and load the ard_BL_led.ino file or paste in the following code:

char bluetoothVal; //value sent over via bluetooth
char lastValue; //stores last state of device (on/off)
int ledPin = 13;
void setup() {
Serial.begin(9600); // begin communication on baud 9600 pinMode(ledPin, OUTPUT); // set the led pin to output
}
void loop() {
if(Serial.available()) // searches for available data {//if there is data being recieved
bluetoothVal=Serial.read(); //read it
}
if (bluetoothVal=='1')
{//if value from bluetooth serial is '1'
digitalWrite(ledPin,HIGH); // turn on LED
if (lastValue!='1')
Serial.println(F("LED ON")); //print LED is on
lastValue = bluetoothVal;
}
else if (bluetoothVal=='0')
{//if value from bluetooth serial is '0'
digitalWrite(ledPin,LOW); //turn off LED
if (lastValue!='0')
Serial.println(F("LED OFF")); //print LED is off lastValue = bluetoothVal;
}
delay(1000);
}

Again, before uploading, make sure you disconnect the RX and TX wires. Connect them after the upload is completed.

To test this code, we will use some popular software called Tera Term. OS X and Linux systems come with terminal emulators so this is not necessary.

 

It is mainly used as a terminal emulator (a fake terminal, in plain language) to communicate with different devices/servers/ports. You can download it from http://en.osdn.jp/ projects/ttssh2/releases/. Install it to someplace convenient.

 

Launch it and select Serial, and select the COM port that is associated with Bluetooth. Start by using the lower COM port number. If that doesn't work, the other one should.

 

Hit OK. Give it some time to connect. The title of the terminal window will change to COM36:9600baud if everything works correctly.

Type 1 and hit enter. What do you see? Now try 0. Give Tera Term some time to connect to Bluetooth. 1 or 0 are not displayed when you type them. Just the LED status will be displayed.

 

You have now successfully controlled an LED via Bluetooth! This effect would be a lot cooler if you used a battery to power the Arduino so that there was no wired connection between the Arduino and the computer. Anyway, let's not get carried away, there is much to be done.

 

Before bringing everything together, there are two things left to be done: dealing with the image (mugshot) upload and sending a notification to your smart device. We'll start with the former, in the following blog.

 

So far, we have configured the camera, the Bluetooth, and Python. In this blog section, we will be going through the following topics:

  • Obtaining and processing the image of the intruder
  • Uploading the image to a convenient website
  •  Sending the URL to your smartphone

So, shall we get right to it?

 

Dealing with the image

As discussed before, when Arduino sends a message to Python, it is going to take a snapshot using the camera and save it to the computer. What do we do with it, then? How do we upload it to a file-sharing platform?

 

There are several ways to do this, but in this blog, we will be using Imgur. Yes, the same Imgur that you have been using, knowingly or unknowingly, on Reddit or 9gag.

Go to http://imgur.com/ and sign up for a new account.

 

Once you have verified your account, go to https://api.imgur.com/oauth2/ and client to add a new application so that Imgur permits you to post images using a script. Use the following information:

 

  • Application name: Arduino burglar alarm
  • Authorization type: OAuth 2 authorization without callback URL
  • Email: <your email>
  • Description: Using Arduino to catch the cookie thieves

 

Now proceed, and you will get a page like this:

Imgur will give you the Client ID and Client secret. Save them in a safe location as we will need them later.

Let us try testing the automatic image uploading functionality. However, before that, we need to install the Imgur library for Python. To do this, firstly, we need to install a simple Python library installer called pip, which is used to download other libraries. Yeah! Welcome to Python!

 

Go to https://pip.pypa.io/en/latest/installing.html and download get-pip.py, or you could just use get-pip.py that is in the Useful Files folder that came with this blog. Save it or copy it to C:\Python27. Go to your C directory and Shift + right-click on Python27. Then, select Open command window here:

 

Type python get-pip.py, hit Enter, and let it install pip to your computer.

Navigate to C:\Python27 and Shift+ right-click on Scripts. Open the command window and type pip install pyimgur in that command window to install the Imgur library. Your terminal window will look like this:

 

Let's test this newly installed library. Open Eclipse and create a new file called imgur_test.py, and paste the following or simply load the imgur_test.py file from the code attached to this blog:

import pyimgur # imgur library
import urllib # url fetching default library
import time # time library to add delay like in Arduino
CLIENT_ID = "<your client ID>" # imgur client ID
# retrieve the snapshot from the camera and save it as an image in the chosen directory
urllib.urlretrieve("http://<your ip : port>/snapshot. cgi?user=admin&pwd=password", "mug_shot.jpg") time.sleep(2)
PATH = "C:\\<your python project name>\\mug_shot.jpg" # location where the image is saved
im = pyimgur.Imgur(CLIENT_ID) # authenticates into the imgur platform using the client ID
uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur")
# uploads the image privately
print(uploaded_image.link) # fetches the link of the image URL

 

Change <your client ID> to the ID that you saved when you created an application on Imgur; change <your ip : your port> to your camera URL; change <your python project name> to the folder where all your python codes are saved. For example, if you look at your Eclipse IDE:

 

My project name is HelloWorld, and in the C drive, I have a folder called HelloWorld where all the Python files are saved. So, set your PATH to correspond to that directory. For me, it will be C:\\helloworld\\mug_shot.jpg where mug_shot.jpg is the name of the saved file.

 

Once you have changed everything and ensured that your camera is on the wireless network, run the code. Run it using Python as you did in the hello world.py example in the previous blog and you should get a result with an Imgur link:

 

Copy and paste this link in a new browser window and you should have something like this:

Try refreshing the page and see what happens. Nothing! Exactly! This is why we took all the trouble of saving the image and then uploading it to a file sharing server. Because once the snapshot has been taken, it will not change.

 

Be mindful while using this method to upload images to Imgur. Do not abuse the system to upload too many images, because then your account will be banned. Now, it is time to deal with sending a notification to your smart device.

 

Sending a notification to a smart device

There are many ways a notification can be sent to your smart device (e-mail, SMS, or via an app). During the course of writing this blog, I realized that an e-mail is not the most efficient way to alert the user of an emergency (a burglar in this case), and there is no single global SMS notification service that can be used by people from different parts of the world.

Hence, we are going to use yet another really powerful push messaging app called Pushover.

 

It works by communicating over the Internet, and conveniently there is a Python library associated with it that we will use to send notifications to the Pushover app on our smart device. 

 

Go to https://pushover.net/login and create a new account. By default, you get a 7-day trial, which is sufficient for completing this blog. If you like the software, you can go ahead and purchase it, as you can use it for future projects.

 

Once you have verified your e-mail ID, look up Pushover on the iTunes App store (https://itunes.apple.com/en/app/pushover-notifications/ id506088175?mt=8) or on the Google Play store (https://play.google.com/store/apps/details?id=net.superblock.pushover&hl=en) and download the app. Log in with the same credentials.

 

It is important to allow push notifications for this app because that is going to be its sole purpose.

 

Now, when you go back to https://pushover.net/ and log in, you should be able to see your devices listed.

Note down your user key as we will need it while we create a script. For now, let us test the app. Under Send a notification, fill in the following:

 

Now, hit the Send Notification button. Wait for a couple of seconds and you should see a message that pops up on your smart device with the title Hello World:

 

Now, go ahead and register a new application on the Pushover website:

 

4. Go to C:\Python27 and Shift + right-click on Scripts; open a command window and type the following: pip install python-pushover

5. Hit Enter. This will install the python-pushover library for you.

 

6. Open Eclipse and create a new script, and call it pushover_test.py. Copy the following code into it, or load the pushover_test.py file that came with this blog:

from pushover import init, Client

init("<token>")

client = Client("<user-key>").send_message("Hello!", title="Hello")

 

7. As you did for the Imgur tutorial, change <token> to your API Token/Key. Also, change <user-key> to your user key that is available when you sign in to your account at https://pushover.net/.

 

 Run the script. Wait for a few seconds and you should get a similar notification as you got before. Fascinating stuff, if I say so myself.

 

Finally, we have finished working with and understanding the elements that will go into creating the entire compound. We are now going to put them all together.

 

Putting the pieces together. Go ahead and create this circuit for Arduino:

The connections are as follows:

PIR → Arduino
GND → GND
OUT → D02
VCC → 5V
HC-06 → Arduino
VCC → 3.3V
GND → GND
TXD → D10
RXD → D11

Don't get mad, but there is one last library that you need to install in order to allow Arduino to communicate with Python: pySerial. Go to https://pypi.python. org/pypi/pyserial, download pyserial-2.7.win32.exe, and install it just like you install any other software. Then, we are ready.

 

Open Arduino and load the alarm_bluetooth.ino file that came with this blog. It is recommended that you have the most up-to-date Arduino software before proceeding:

#include <SoftwareSerial.h> // serial library used for communication
SoftwareSerial burg_alarm(10, 11); // communicates via TX, RX at 10, 11 respectively
int ledPin = 13; // in built LED to show status changes int pirPIN = 2; // signal of the PIR sensor goes to pin 2
int pirState = LOW; // initiate the PIR status to LOW (no motion)
int pirVal = 0; // variable for storing the PIR status
void setup() {
burg_alarm.begin(9600); // communication begins on baud 9600 pinMode(ledPin, OUTPUT); // sets the LED pin as output delay(5000); // waits 5 seconds for motion to die down
}
void loop(){
pirVal = digitalRead(pirPIN); // read input from the sensor
if (pirVal == HIGH) { // if input is HIGH (motion detected)
digitalWrite(ledPin, HIGH); // turn LED ON
delay(150); // small delay
if (pirState == LOW) { // checks if the PIR state is LOW while the input is HIGH
// this means, there wasn't motion before, but there is something happening now
Serial.println("Motion detected!"); // prints out an Alert burg_alarm.println('1'); // sends out '1' for when motion is
detected via Bluetooth to python
pirState = HIGH; // sets the pirState to HIGH (motion detected)
}
} else { // no motion detected
digitalWrite(ledPin, LOW); // turn LED OFF
delay(300); // small delay
if (pirState == HIGH){ // if there was motion, but isn't any now Serial.println("Motion ended!");
burg_alarm.println('0'); // sends a '0' when the motion has
ended
pirState = LOW; // sets the state to LOW (no motion)
}
}
}

Make sure you unplug the TX and RX wires before uploading the code and then attach them back. Now, unplug the Arduino while we create a Python script.

 

Open Eclipse and load the alarm_bluetooth.py file, or just copy the following:

import serial
import pyimgur
import urllib
import time
from pushover import init, Client
print("Burglar Alarm Program Initializing")
init("< your push overtoken>")
CLIENT_ID = "<your client ID>"
PATH = "C:\\<your python folder>\\mug_shot.jpg"
im = pyimgur.Imgur(CLIENT_ID)
mug_shot_ctr = 0
serial_status = 0
camera_status = 0
try:
print("\nAttempting to connect to Bluetooth module...")
ser = serial.Serial('COM36', 9600) #Tried with and without the last 3 parameters, and also at 1Mbps, same happens.
time.sleep(3)
serial_status = 1
print('Bluetooth connection successful!')
except:
print('Bluetooth Connection Error! \nPlease check if bluetooth is connected.')
mug_shot_ctr = 4
try:
print("\nChecking IP Camera Status...") urllib.urlretrieve("http://<your ip>/snapshot.
cgi?user=admin&pwd=<your password>", "mug_shot.jpg")
time.sleep(2)
print("Camera Status OK")
camera_status = 1
except:
print("Camera not connected!\nPlease check if camera is connected.")
mug_shot_ctr = 4
if((serial_status==1)&(camera_status==1)):
print("\nBurglar Alarm armed!")
while mug_shot_ctr < 3:
line = ser.readline()
if(line[0]=='1'):
print('\nMotion Detected!') print('Capturing Mug Shot') urllib.urlretrieve("http://<your ip>/snapshot.
cgi?user=admin&pwd=<your password>", "mug_shot.jpg")
time.sleep(2)
print('Uploading image to Imgur')
uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur - Mugshot")
print(uploaded_image.link)
print('Sending notification to device.')
Client("<your imgur ID>").send_message("Mug Shot: "+ uploaded_ image.link, title="Intruder Alert!")
print('Notification sent!')
mug_shot_ctr = mug_shot_ctr + 1
if(serial_status ==1):
ser.close()
print('\nProgram Ended')

Remember to change the tokens, keys, ports, the path, the camera IPand the client ID (highlighted) to your specifics. The good thing about this code is that it checks whether the camera and Bluetooth are working as expected.

 

 If not, it gives an error message with which you can tell if something is wrong. Note that if you are not getting your camera IP to work, go back to the IP Camera Search Tool at www.netcam360.com to find the IP of your camera. It changes sometimes if it has been restarted.

 

What this code does is…well, everything! It first gathers all the libraries that you have used so far. It then checks and connects to the Bluetooth module followed by the IP camera.

 

Then, it waits for Arduino to send a message (1) saying motion has been detected. The script immediately fetches a snapshot from the IP camera's URL and uploads it to Imgur.

 

Then, it uses Pushover to send the user an alert saying that motion has been detected, along with the Imgur URL that the user can open to see who the culprit is. The script will send three simultaneous images to give a better chance of catching the thief in action. This value can be changed by changing mug_shot_ctr.

 

Power your camera and your Arduino. Let's test this out and run the program. Move your hand in front of the PIR sensor and you will get an output like this:

 

The only thing left to do now is to position your camera in such an area where it keeps an eye on a possible entry point. The Arduino, with the PIR sensor and Bluetooth, needs to be placed close to the entry point so that the PIR sensor can detect when a door or window is opened.

 

It is advisable to use a 2.1mm 9-12V DC adapter to power the Arduino. Also, instead of using Eclipse, now that the code has been prepared, you can navigate to C:\<your Python project directory> and double-click on alarm_bluetooth.py to run it directly. 

 

Done! You are finally done! You have created your very own high-tech burglar alarm system using Arduino, Bluetooth, Python, Imgur, and Pushover. If you have reached this point, I want to congratulate you.

 

It has not been an easy journey, but it is definitely worth the patience and hard work. Your home is now secure. "However, what if we want to do this without the need for a computer?"

 

We would have to use something such as a Raspberry Pi, but that is beyond the scope of this blog. If you are adventurous, I am not going to stop you from trying to make this project standalone.

 

Arduino Lock Door 2018

Arduino Lock Door with SMS

In this blog, we are going to build another great application for secret agents: opening a door lock simply by sending an SMS! You'll just need to send a message to a given number and then you'll be able to control a door lock or any other kind of on/off the digital device, such as an alarm.

 

For that, we are going to take a number of steps, as follows:

First, we are going to use Arduino and the FONA shield from Adafruit in order to be able to receive and process text messages Then, we'll connect this to a relay and LED to see whether we can actually control a device by sending an SMS. Finally, we'll see how to connect an actual electronic lock to the system. Let's start!

 

Hardware and software requirements

Arduino Lock Door

First, let's see what the required components for this project are. The most important parts are related to GSM functionalities, which is the central piece in our project. We'll need an antenna in order to be able to connect to the local GSM network.

 

For this project, a flat uFL antenna is used:

Then, you'll need a way to actually use a SIM card, connect to the GSM network, and process the information with Arduino. There are many boards that can do this.

 

However, I recommend the Adafruit FONA shield, which is very convenient to configure and use with Arduino. The following is the image of the Adafruit FONA shield along with the flat GSM antenna.

 

Then, you will need a battery to power the FONA shield, as the Arduino Uno board doesn't allow to power the chip that is at the core of the FONA shield (it can use up to 2A at a time!). For this, I used a 3.7 LiPo battery along with a micro USB battery charger:

 

A very important part of the project is the SIM card that you need to place in the FONA shield. You need a normal SIM card (not micro or nano), which is activated, not locked by a PIN, and is able to receive text messages. You can get one at any of your local mobile network operators.

 

Then, to test the functionalities of the project, we'll also use a simple LED (along with a 330 Ohm resistor) and a 5V relay. This will mimic the behavior of the real electronic lock.

Lock_door

Finally, you'll need an electronic lock. This part is optional as you can completely test everything without the lock and it is quite complicated to set up. For this, you'll need an Adafruit electronic lock, a 1K Ohm resistor, and a power transistor.

Finally, here is the list of all the components that we will use in this project:

Arduino Uno (https://www.sparkfun.com/products/11021)

Adafruit Fona 808 shield (http://www.adafruit.com/product/2542)

GSM uFL antenna (http://www.adafruit.com/products/1991)

GSM SIM card

3.7V LiPo battery (http://www.adafruit.com/products/328)

LiPo battery charger (http://www.adafruit.com/products/1904)

LED (https://www.sparkfun.com/products/9590)

330 Ohm resistor (https://www.sparkfun.com/products/8377)

5V relay (https://www.pololu.com/product/2480)

Optional: Adafruit electrical lock (http://www.adafruit.com/ products/1512)

Optional: Rectifier diode (https://www.sparkfun.com/products/8589)

Optional: Power transistor (http://www.adafruit.com/products/976)

Optional: 1K Ohm resistor (https://www.sparkfun.com/products/8980)

Optional: 12V power supply (https://www.sparkfun.com/products/9442)

Optional: DC jack adapter (https://www.sparkfun.com/products/10288)

Breadboard (https://www.sparkfun.com/products/12002)

Jumper wires (https://www.sparkfun.com/products/8431)

 

On the software side, you'll only need the latest version of the Arduino IDE and the Adafruit FONA library. You can install this library using the Arduino IDE library manager.

 

Hardware configuration

Door_lock

It's now the time to assemble the hardware for the project. We'll first connect the Adafruit FONA shield and then the other components. Before assembling the hardware, make sure that you have inserted the SIM card into the FONA shield.

 

Note that the location of the pins can be different on your FONA shield, as there are many versions available. Also, note that the relay is not represented on this schematic. Here are the steps that you need to take in order to assemble the hardware:

 

1. First, connect the power supply to the breadboard. Connect the 5V pin from the Arduino board to the red power line on the breadboard and the GND pin to the blue power line.

 

2. Then, place the FONA shield on the breadboard. Connect the VIO pin to the red power line and the GND and key pins to the blue power line.

 

3. After that, connect the RST pin to Arduino pin 4, TX to Arduino pin 3, and RX to Arduino pin 2. Also, connect the 3.7V LiPo battery and antenna to the FONA shield.

 

4. Finally, connect the relay and the LED to the Arduino board. Connect the relay VCC and GND pin to the power supply on the breadboard and the EN pin to pin 7 of the Arduino board.

 

5. For the LED, place it in series with a 330 Ohm resistor on the breadboard, with the longest side of the LED connected to the resistor. Then, connect the other pin of the resistor to pin 8 of the Arduino board. Also, connect the other pin of the LED to the ground. The following is an image of the completed project, with a zoom around the FONA shield and Arduino board:

 

Testing the FONA shield

Now that our hardware is ready, we are going to test the FONA shield to see whether it is correctly connected and can connect to the network. As a test, we will send an SMS to the shield and also read all the messages present in the SIM card.

 

This is the complete Arduino sketch for this part, minus some helper functions that won't be detailed here:

// Include library #include "Adafruit_FONA.h" #include <SoftwareSerial.h>
// Pins
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
// Buffer for replies char replybuffer[255];
// Software serial
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); SoftwareSerial *fonaSerial = &fonaSS;
// Fona
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
// Readline function
uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);
void setup() {
// Start Serial while (!Serial); Serial.begin(115200); Serial.println(F("FONA basic test")); Serial.println(F("Initializing....(May take 3 seconds)"));
// Init FONA
fonaSerial->begin(4800);
if (! fona.begin(*fonaSerial)) {
Serial.println(F("Couldn't find FONA"));
while(1);
}
Serial.println(F("FONA is OK"));
// Print SIM card IMEI number.
char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
uint8_t imeiLen = fona.getIMEI(imei);
if (imeiLen > 0) {
Serial.print("SIM card IMEI: "); Serial.println(imei);
}
}
void loop() {
// Get number of SMS
int8_t smsnum = fona.getNumSMS();
if (smsnum < 0) {
Serial.println(F("Could not read # SMS"));
} else { Serial.print(smsnum);
Serial.println(F(" SMS's on SIM card!"));
}
// Read last SMS flushSerial(); Serial.print(F("Read #")); uint8_t smsn = smsnum;
Serial.print(F("\n\rReading SMS #")); Serial.println(smsn);
// Retrieve SMS sender address/phone number.
if (! fona.getSMSSender(smsn, replybuffer, 250)) { Serial.println("Failed!");
}
Serial.print(F("FROM: ")); Serial.println(replybuffer);
// Retrieve SMS value. uint16_t smslen;
if (! fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in
buffer and max len!
Serial.println("Failed!");
}
Serial.print(F("***** SMS #")); Serial.print(smsn);
Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes
*****"));
Serial.println(replybuffer);
Serial.println(F("*****"));
// Flush input flushSerial();
while (fona.available()) { Serial.write(fona.read());
}
// Wait
delay(10000);
}
Now, let's see the details of this sketch. It starts by including the required libraries:
#include "Adafruit_FONA.h"
#include <SoftwareSerial.h>
Then, we will define the pins on which the FONA shield is connected:
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
We will also define a buffer that will contain the SMS that we will read from the shield:
char replybuffer[255];
Then, we'll use a SoftwareSerial instance to communicate with the shield:
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); SoftwareSerial *fonaSerial = andfonaSS;
We will also create an instance of the FONA library:
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
Then, in the setup() function of the sketch, we will start the Serial object for the purpose of debugging and print a welcome message:
while (!Serial);
Serial.begin(115200);
Serial.println(F("FONA basic test"));
Serial.println(F("Initializing....(May take 3 seconds)"));
After that, we will initialize the FONA shield:
fonaSerial->begin(4800);
if (! fona.begin(*fonaSerial)) {
Serial.println(F("Couldn't find FONA"));
while(1);
}
Serial.println(F("FONA is OK"));
Then, we will read the IMEI of the SIM card in order to check whether the shield is working and whether a card is present:
char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
uint8_t imeiLen = fona.getIMEI(imei);
if (imeiLen > 0) {
Serial.print("SIM card IMEI: "); Serial.println(imei);
}
Now, in the loop() function of the sketch, we will first count the number of text messages present in the card:
int8_t smsnum = fona.getNumSMS();
if (smsnum < 0) {
Serial.println(F("Could not read # SMS")); } else {
Serial.print(smsnum);
Serial.println(F(" SMS's on SIM card!"));
}
Then, we will also read the last one and print it on the serial monitor:
// Read last SMS flushSerial(); Serial.print(F("Read #")); uint8_t smsn = smsnum;
Serial.print(F("\n\rReading SMS #")); Serial.println(smsn);
// Retrieve SMS sender address/phone number.
if (! fona.getSMSSender(smsn, replybuffer, 250)) { Serial.println("Failed!");
}
Serial.print(F("FROM: ")); Serial.println(replybuffer);
// Retrieve SMS value. uint16_t smslen;
if (! fona.readSMS(smsn, replybuffer, 250, &smslen)) { // pass in buffer and max len!
Serial.println("Failed!");
}
Serial.print(F("***** SMS #")); Serial.print(smsn);
Serial.print(" ("); Serial.print(smslen); Serial.println(F(") bytes
*****"));
Serial.println(replybuffer);
Serial.println(F("*****"));
Once that's done, we will flush the SoftwareSerial instance and wait for 10 seconds until the next read:
// Flush input flushSerial();
while (fona.available()) { Serial.write(fona.read());
}
// Wait
delay(10000);

Note that the complete code for this section can be found on the GitHub repository of the blog at https://github.com/ marcoschwartz/Arduino-secret-agents.

 

It's now the time to test the FONA shield. Make sure that you get all the code and open it in your Arduino IDE. Then, upload the code to the board and open the serial monitor. You should see the following screenshot:

 

If everything is working fine, you should see the IMEI number of the SIM card and then the latest SMS in the card. You can test it by sending a message to the phone number of the SIM card; it should immediately show in the next reading of the SIM card. If this works, congratulations! You can now move to the next section.

 

Controlling the relay

In this part, we are going to program the Arduino board to remotely control the relay and LED that are connected to the board by sending an SMS to the FONA shield.

 

As most of the code is similar to the code that we saw in the previous section, I'll only detail the new elements of code here.

 

We need to define the pins on which the relay and the LED are connected:

#define RELAY_PIN 7
#define LED_PIN 8
Then, we'll define a set of variables for a counter for the relay/lock. This is needed because after we open a lock, for example, we will want it to close automatically after a given amount of time for the purpose of safety. Here, we use a delay of 5 seconds:
bool lock_state = false;
int init_counter = 0;
int lock_counter = 0;
int lock_delay = 5000;
Then, we will define variables to count the number of SMS stored in the card:
int8_t smsnum = 0;
int8_t smsnum_old = 0;
We will also set two "passwords" to activate or deactivate the relay. I used very simple passphrases here; however, you can use the one that you want:
String password_on = "open";
String password_off = "close";
Then, in the setup() function of the sketch, we will set the relay and LED pins as output:
pinMode(RELAY_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
In the loop() function of the sketch, we will get the total number of SMS stored in the SIM card:
smsnum = fona.getNumSMS();
Basically, what we want is to check whether a new SMS has been received by the shield. To do that, we will compare this new reading to the old number of SMS stored in the SIM card:
if (smsnum > smsnum_old) {
If that's the case, we store the message in a String object so that we can conduct some operations on it:
String message = String(replybuffer);
Then, if the received message matches with the "On" password that we set earlier, we will activate the relay and LED, and also start the counter:
if (message.indexOf(password_on) > -1) {
Serial.println("Lock OPEN");
digitalWrite(RELAY_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
lock_state = true;
init_counter = millis();
}
We would do something similar if we received an "Off" message:
if (message.indexOf(password_off) > -1) {
Serial.println("Lock CLOSE");
digitalWrite(RELAY_PIN, LOW);
digitalWrite(LED_PIN, LOW);
lock_state = false;
}
After that, we will update the counter:
lock_counter = millis();
Then, we check whether the delay has already passed since the last time the relay/ lock was activated. If that's the case, we will deactivate the relay/close the lock automatically:
if (lock_state == true andand (lock_counter - init_counter) > lock_ delay) {
Serial.println("Lock CLOSE");
digitalWrite(RELAY_PIN, LOW);
digitalWrite(LED_PIN, LOW);
lock_state = false;
}
Finally, we will store the current number of received text messages in the smsnum_old variable:
smsnum_old = smsnum;

Note that the complete code can be found in the GitHub repository of the project at https://github.com/marcoschwartz/arduino-secret-agents. It's time to test the project. Grab all the code and paste it in the Arduino IDE. Make sure that you change the on/off passwords in the code as well.

 

Then, upload the code to the board and open the serial monitor. You should see the shield being initialized and then waiting for a new text message. Now, send a text message to the shield with the message corresponding to the "On" password that you defined earlier. The following screenshot is what you should see:

 

You should also see the LED turn on and the relay is activated. You can either wait until the system deactivates itself or you can simply send the "Off" passphrase again.

 

Now that we managed to actually control the relay and the LED by sending text messages to the FONA shieldwe can connect the actual lock. This last step of the project is optional as you already tested the main functionality of the project and connecting the electronic door lock is a bit more technical. This is an image of the lock that I used:

 

First, you'll need to cut the JST connector from the electronic lock in order to be able to connect it the breadboard. I soldered some 2-pin header at the end of the electronic lock to make it compatible with my breadboard.

 

Let's see how to assemble these components together. First, place all the components on the breadboard. Then, connect the digital pin 7 of the Arduino board to the base of the transistor via the 1K Ohm resistor.

 

Also, connect the emitter of the transistor to the ground of the project. Then, connect the electronic door lock between the collector of the transistor and the 12V power supply. Finally, mount the rectifier diode parallel to the door lock, with the orientation defined on the schematic.

 

Then, it's time to test the project again. You can use the exact same code as in the previous section. Congratulations, you can now control a door lock by sending a secret passphrase via SMS!

 

Automatic door lock system or Bluetooth door lock

This will be the first project of this blog in which we'll take everything we learned so far and integrate it to make a complete Internet of Things project you can actually use in your life.

 

For this project, we are going to build a door lock that we can control from anywhere on the planet using the ESP8266 Wi-Fi chip. We are also going to see how to integrate notifications right into the software you'll build, so you will receive a push notification in case anyone opens the door lock. Let's start!

 

Hardware and software requirements

Arduino Lock Door 2018

For this project, you will, of course, need an ESP8266 chip. As for most of this blog, I used the Adafruit Huzzah ESP8266 module, but any ESP8266 module will work fine here.

 

For the lock, I used a 12V DC solenoid-based door lock. You can, of course, use any other equivalent lock on the market. You will need a few components to use the lock: an NPN transistor, a protection diode, and a 1K Ohm resistor.

 

I included the reference for all those components in this section. You will also need a 12V DC power supply that you can connect to a breadboard.

 

You will also need a 3.3V/5V FTDI USB module to program the ESP8266 chip. Finally, you will also need some jumper wires and a breadboard. This is a list of all the components that will be used in this blog:

 

Adafruit ES8266 module (https://www.adafruit.com/products/2471)

FTDI USB module (https://www.adafruit.com/products/284)
Lock Style Solenoid (https://www.adafruit.com/products/1512)
NPN transistor (https://www.sparkfun.com/products/13689)
Resistor (https://www.sparkfun.com/products/8980)
Diode (https://www.sparkfun.com/products/8589)
Breadboard (https://www.sparkfun.com/products/12002)
Jumper wires (https://www.sparkfun.com/products/9194)

 

For the software, if it's not been done yet, you will need to install the latest version of the Arduino IDE, which you can get from here: http://www.arduino.cc/en/Main/Software

Then, for the last part of the blog, you will also need an IFTTT account. If you don't have one, please refer to the Blog 5, Interacting With Web Services to learn how to create your IFTTT account.

 

Configuring the hardware

sensor_lock

Let's now configure the hardware for this project. The configuration for this project is quite complex, which was why I included a schematic to help you out:

This schematic represents how you should connect the lock to the ESP8266. First, place the transistor on the breadboard, and connect the base of the transistor to the ESP8266 via the 1K Ohm resistor.

 

Then, connect the emitter of the transistor to the ground of the ESP8266. After that, connect the door lock to the 12V DC power supply and to the remaining pin of the transistor.

 

 Finally, connect the diode in parallel to the lock, as indicated on the schematics. Note that on the diode, the cathode is usually marked with a grey stripe, corresponding to the schematics.

 

This is how it should look at the end:

 

Configuring the ESP8266 board

It's now time to configure the ESP8266 Wi-Fi chip so it can accept commands coming from the cloud. This is something we already saw earlier, but it's always good to remember the basics, as we'll make a more complicated sketch later in this blog:

 

1. We first need to include the required libraries:

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <aREST.h>
2. Then, we declare a Wi-Fi client and PubSub (MQTT) client:WiFiClient espClient;
PubSubClient client(espClient);
3. After that, we create an instance of the aREST library:
aREST rest = aREST(client);
4. You also need to enter your Wi-Fi name and password into the sketch:
const char* ssid = "wifi-ssid";
const char* password = "wifi-pass";
5. You can also give a name to your device:
rest.set_id(device_id);
rest.set_name("door_lock");
6. Finally, in the loop() function of the sketch, we handle the connection coming from the cloud:
rest.handle(client);

It's now time to configure the board! Simply grab the code from the GitHub repository for the blog, make sure to modify the Wi-Fi settings and password, upload the code to the board, and leave it there; we'll use a dashboard to actually control the lock.

 

Controlling the lock from the cloud

It's now time to see how to control our door lock from the cloud. Again, we'll use the dashboard feature of aREST to rapidly build a cloud dashboard for our project:

1. Simply go to: http://dashboard.arest.io/

2. After creating an account, you'll be able to create your first dashboard:

3. Once it's been created, simply click on the name of the new dashboard:

 

4. From there, you'll be able to create a new element. As we simply want on/off buttons here, configure your dashboard with the following settings: name the element Lock, enter the device ID of the project, and select the correct digital pin (5). 

 

5. Of course, make sure to replace the device ID with the one from your own device. Once that's done, you should see your new control inside the dashboard:

 

You can now finally try the project; simply click on the On button and the lock should immediately be activated. You can now lock or unlock a door from anywhere in the world! Just make sure that you are not clicking on different buttons too quickly; unlike an LED, for example, the door lock takes some time (one or two seconds) to respond.

 

Receiving notifications when the lock is opened

1. First, go to IFTTT, and add two channels if that's not been done yet: the Maker channel and the Pushover channel. Also install the Pushover app on your smartphone. 

 

2. Then, create a new recipe, and choose the Maker channel as the trigger:

3. We need to use the Maker channel here, as it will allow us to use custom projects like ours with IFTTT. As the trigger for the channel, put the lock_opened event:

 

4. As the action, simply look for the Pushover channel, which we will again use to receive notifications from IFTTT:

5. Then, select the notification type of your choice:

 

6. This will simply indicate to IFTTT whether it should send normal or high-priority notifications to your Pushover app. After that, put the message you want to receive every time an event is received:

 

7. Finally, confirm the creation of the channel:

 

8. Let's now see what we need to add to the previous code to integrate the notifications. First, we need to define two variables to store the current status of the lock:

  • bool lockStatus;
  • bool previousLockStatus;

 

9. Then, inside the setup() function of the sketch, we read data from pin number 5, to check whether the lock is initially activated or not:

  • lock status = digitalRead(5);
  • previousLockStatus = lockStatus;

 

10. After that, inside the loop() function, we again read the state from pin number 5:

lock status = digitalRead(5);

 

11. If it has changed compared to the last read, and if the lock is open (which means that there is a LOW status on the pin), we send a notification via IFTTT:

if (lockStatus != previousLockStatus && lockStatus == 0) {
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return;
}
// We now create a URI for the request
String url = "/trigger/";
url += eventName;
url += "/with/key/";
url += key;
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
int timeout = millis() + 5000; while (client.available() == 0) {
if (timeout - millis() < 0) { Serial.println(">>> Client Timeout !"); client.stop();
return;
}
}
// Read all the lines of the reply from server and print them to Serial
while(client.available()){
String line = client.readStringUntil('\r'); Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
// Set previous status previousLockStatus = lockStatus;
}

To learn more about how to send notifications via IFTTT, please check out Next Blog, Sending Notifications from the ESP8266.

 

12. It's now time to test the project! Upload the code to the board, and then go back to the online dashboard that you used before to control the lock. This time, every time you open the lock, you should immediately get a notification on your smartphone.

This way, even if you shared your dashboard with somebody else, you will be informed when they open the door lock.

Recommend