While working at your desk, suddenly you hear a distant noise. Did someone just come home? My car is parked in front of my house, did someone break into my car? Don't you wish you got notification on your phone or at your desk so you can decide whether or not to investigate? Well question no more! R-PiAlerts is here!

What is R-PiAlerts?
R-PiAlerts is a Raspberry Pi3 based security system built around Firebase's Cloud. If movement is detected, the system will notify the user of a potential break-in with a text message and a blinking LED display (silent visual alarm of sorts). Once user receives a notification, he or she can investigate. All detected movement will be logged to the Firebase database. Besides viewing the movement log on a web browser, the user can also access the movement log via an iOS app. I decided to build this due to the recent rise in break-ins to both vehicles and homes around my area.

Why the Pi3?
I needed something small that can detect movement and run off of a battery if needed. Then, I can hide the unit behind a door or in a car. Also the unit needs to be able to send me notifications or alerts. The Pi3 can do all these things with the built in wifi and its ability to run off an USB battery pack. Other reasons on why I chose the Pi3:

  • The Pi is relatively inexpensive
  • Its easy to deploy and scale up
  • Its configurable from the software standpoint
  • Ability to use displays and sensors. This project will use the SenseHat
  • Operate Headless (without monitor, keyboard or mouse)

How Does it Work

  • Ideally the user will need 2 Raspberry Pis connected to the Firebase database, but a single Pi will work also.
  • Utilizing the SenseHat, the first Pi (Pi1) will detect movement with the accelerometer while the second Pi (Pi2) will display notifications of movement.
  • When the Pi1 detects motion, it does 3 things
    • log movement to the database
    • create a notification entry on the database for Pi2 to display
    • send the user a text message notifying the user of movement.
  • When Pi2 detects a notification to display from the database, two things happen
    • Pi2's LED display will show the notification continuously
    • User can clear the notification by press down on Pi2 SenseHat's button. This will also clear the notification entry on the database.
  • With the iOS app, the user can
    • access the database; read and delete the movement log
    • the user can send Pi1 to display a message on Pi1's LED display.

Practical Applications

  1. If you street park your car within wifi range. Attach a battery pack to Pi1 (see pic). Hide Pi1 in your car. Place Pi2 somewhere easily viewable such as next to your desk (see pic).
  2. Another application is to place Pi1 in your house to the side of a door. The Pi is so tiny that most people will not notice it especially if its behind the hinge side (see pic). Then place your Pi2 at your work desk.
  3. Dog getting into a spot in the house it's not suppose to? Place a Pi1 in that area. Make sure you put the Pi in a sturdy box so your dog doesn't chew it up.

As long as your Pis are in wifi range, they can alert or notify you of movement. If you don't have a second Pi, you can just use Pi1 to detect movement and receive SMS notifications via your cell phone.

Bill of Materials

  • Two(2) Raspberry Pi 3s running Raspbian (Raspberry Pi 2 will work too with a wifi dongle)
  • Two(2) SenseHats
  • Mac and iOS device

Software Needed

  • Pyrebase library (connecting to Firebase)
  • SenseHat library (for accessing accelerometer and LED display)
  • Twilio library (for sending SMS)
  • Python 3, built in with latest Raspbian
  • Raspbian with IDLE
  • Xcode8 and Cocoapods on your Mac
  • Willingness to learn and explore

Side Note
This is not the only Pi based security solution. If you have any ideas, suggestions, or just want to refactor my code, please leave a comment below! =)

Step 1: Setup Firebase and Twilio Accounts

First off, before we start fiddling with our Pis, we need to setup Firebase and Twilio. Firebase is Google's backend as a service. Firebase includes such features such as database, cloud messaging, authentication, storage, etc. For this project, we will only need to use Firebase's realtime database and authentication. Authentication will be needed to read and write to the your Firebase database. To setup Firebase:

  1. Register for a free Firebase account
  2. Go to the console. Create a new project and give it a name.
  3. Under the left menu, click on the "Overview"
  4. Click "Add Firebase to your web app", copy your APIKey and projectid (not the url). Project ID is located in the different URLs such as the database: https://projectid.firebaseio.com/
  5. Under the left menu, click on the "Authentication". Go to "Sign in Method" and enable "Email/Password"
  6. Under "User" create a new user account with email/password of your choice. You will use this credential to log into the database.
  7. Under the left menu, go to the "Database"
  8. This is your Database. It is empty right now. When filled, it will be in JSON format. The URL should be the same as the one you saw earlier.

Twilio allows developers to send messages to their customers. We will use it to send SMS to your phone when the Pi detects movement. Twilio will provide you with a phone number to send out SMS. To setup Twilio:

  1. Sign up for a free account at Twilio's site
  2. Copy your accountSID and authToken
  3. Click on "Trial Restrictions" and select "get your first Twilio phone number"
  4. Copy your new phone number

Step 2: Set Up Your Pis

Before we can start programming the Pis, we need to do some setup. Make sure you have a password login for your Pis. First we will physically connect the SenseHat boards to the Pis. Next, we will install the necessary SenseHat, Twilio and Pyrebase libraries. Firebase real time database was designed for mobile devices or websites. However, we can read and write the cloud database through the Rest API with a helper library like Pyrebase.

Connect the SenseHat
Make sure the SenseHats are connected to your Pis. If you have an unusual case, you may need to remove the Pi before connecting the SenseHat.

Installing Libraries
All the library installations will be done in the Terminal

  • Boot up your Pis if you havn't already.
  • Upon bootup, you get this colorful LED rainbow on your SenseHat! (see pic)
  • Go to terminal and update/dist-upgrade, type:
    • sudo apt-get update
    • sudo apt-get dist-upgrade
  • After upgrades are done, type the following to install SenseHat libraries:
    • sudo apt-get install sense-hat
  • To install Pyrebase, type:
    • sudo pip install pyrebase
  • Lastly, install Twilio
    • sudo pip install twilio

Step 3: Python Script for Pi1

As we mentioned earlier, Pi1 will be the Pi that will be used to detect movement. The SenseHat's accelerometer's values will be used to determine movement. Thus, the code for Pi1 will be around accessing the accelerometer g force values and logging the motions detected to the Firebase Database. Here is a overview of process flow:

  • If Pi1 detects movement, it will add an entry to the "alerts" child in the Firebase DB.
  • Pi1 will also update the "notifypi2" child with a notification message regarding the movement.
  • Pi2, then reads "notifypi2" and display the notification on its LED matrix display.

I've included the Pi1 Python script for you to follow. Comments in the script explain what the code is doing.

Additional notes and insights for the Pi1 script

  • For Firebase and Twilio setup. Fill in the appropriate API keys, IDs, passwords, etc that you copied from the previous steps.
  • Regarding Firebase authentication, for extra security, you can ask for user input instead of hard coding these credentials. Each time we write or read from the database, we will need to include
    with the
    get(), push(), set() 
  • CPU temperature is needed so we can intervene in case the Pi overheats in a car or a closed environment.
  • We also take the absolute value of the G forces since we do not need to know negative values. We only need to know if there are G forces.
  • If statement will check the accelerometer's values. If G forces are greater than 1 in any direction, Pi1 will log the movement time and display an exclamation mark on its own LED display. It will also update the "notifypi2" child. When "notifypi2" is updated, Pi2 will read it and display "!!!" on its LED display to notify the user of possible movement/break-in. Pi1 will also send the user a SMS notification of movement.
  • When using the push() method, Firebase will autogenerate a child with a new entry. This needed so the logged movement data will be unique. the set() method on the other hand will overwrite previous data.
  • 10 second loop to check the database is necessary so your Pi doesn't repeatedly request data from Firebase. If you continuously spam Firebase, Google will log you out in about 10 mins.
  • Firebase will also kick the user out every 60 mins if the token is not refreshed. I have the refresh set to 1800 seconds (30 mins).

Step 4: Python Script for Pi2

If you look at the photo, that is of Pi2 displaying a notification of possible movement.

Pi2's script is pretty much exactly the same as Pi1 except the script does not detect movement. Pi2 only displays or resets notification messages from the "notifypi2" child. Since thats the only difference, I will explain that below.

  • Every 10 seconds, Pi2 will check "notifypi2" to display. If there is a notification message to display, the Pi2 will display it continuously so the user sees it.
  • Only the user intervention of pressing the joystick button will the message clear and reset on the database side.

Step 5: Test the Pis

Time to test the Pis.

  • Run the scripts for the respectively Pis.
  • Log into Firebase and go to your projects database section.
  • Shake your Pi1, you should see a red exclamation mark on the Pi1 LED display. You should also get a SMS message.
  • Check the database, alert entries should start showing up. "notifypi2" should also be updated.
  • Take a look at Pi2. You should also scrolling "!!!" To clear this notification message, just press on the joystick. "notifypi2" should be resetted. Check your Firebase to confirm.
  • If you find the Pi1 too sensitive to movement, increase the threshold to greater than 1G in the Pi1 script.

If all goes well, your scripts will not crash. Now, you have a working notification system. Once Pi1 detects movements or vibrations, you will get a SMS message notification and a visual LED notification on Pi2.

Step 6: Building the R-PiAlerts IOS App

Time to build the iOS app! App will be fairly simple. It will have a LoginViewController and a ItemsTableViewController. ItemsTableViewController will display alert notifications from the "alerts" child. One can also delete database entries from the app. To save you some headache, if you plan to look at online tutorials for Firebase, make sure you look for tutorials dated after March 2016 as there were major changes last year around that time. Anything before March 2016 will be legacy. I've you're interested in the swift files, please review the comments in the code. If you want a detail tutorial on how to build a Firebase app that reads the database, check out Ray Wunderlich's tutorial.

Set Up Your iOS Project Overview

  • Create a single view iOS project in Xcode.
  • Copy the bundle identifer
  • Go to your Firebase project on the website and create a info.plist file with the bundle identifier.
  • Add the GoogleService-info.plist file to your project. This info.plist only works with the specific Firebase Project you've created.
  • Close out of Xcode and install Firebase via Cocoapods. Make sure to install Auth and Database.
  • Restart Xcode, then configure your AppDelegate.swift for Firebase. It only takes 2 lines of code.
    Import Firebase
    . Optionally, Firebase has a persistence feature that only takes 1 line of code:
    FIRDatabase.database().persistenceEnabled = true 
  • Detail installation steps can be found on Firebase's Website

How the App Interacts with the Firebase Database:

  • The app will need to authenticate the user.
  • Once authenticated, the app takes a snapshot of the Firebase database and stores it as an "Item" object.
  • Said object will fill an array. Said array will be used to fill the tableview.
  • An observer will watch for changes to the Firebase database and create a snapshot.
  • Once changes are detected, array will be appended from the new snapshot.
  • Tableview will then be reloaded to show the changes.

General Outline on How to Build the App

  • Take a look at image on how the app is laid out in Xcode's interface builder.
  • Create a ViewController in interface builder and point the custom class to LoginViewController.swift.
  • Add textfields for email and password. Don't forget to turn on "Secure Text Entry" for the password field. Add a login button.
  • Link up the textfields and button to the LoginViewController.swift. LoginViewController.swift will handle the authentication.
  • Add a Navigation Controller in interface builder. Create a segue from the LoginViewController to the Navigation Controller. Make sure to give the segue an identifier.
  • Set the custom class of the new tableview that came with the navigation controller to point ItemsTableViewController.swift. I also have 2 buttons on the ItemsTableViewController: Logout and an Add button. Link up the buttons to ItemsTableViewController.swift.
  • Regarding the LoginViewController.swift code. The user will input the login credentials and Firebase will return an user. If an user is present, it will perform a segue with the identifier. (see code attached)
  • Add the Item.swift class (see code attached)
  • Regarding ItemsTableViewController code, it's pretty standard tableview code. There will be an observer to monitor changes to your database saved as a snapshot as an Item object. Then the Item object will append the array to fill the tableview. The Add button sets an entry in the Firebase database for Pi1 to read and display. For giggles, I also added code (see attached code)

Step 7: Test the App

Run your app!

  • Login and shake your Pi1. You should start seeing new alert notifications show up.
  • Tap the add button and watch your Pi1 display your message.
  • Swipe left, see "Alerts" entries get removed.
  • Receiving too many notifications in rapid succession? adjust the accelerometer threshold or increase the sleep time in the Pi1 script.

Step 8: Conclusion

Awesome! Now we have Pis that can detect movement and send you notifications of movements. On top that, you can manage on your alert message log with your iOS device! Time to deploy the Pis. Put Pi1 next to your door and Pi2 around your work area. Next time someone comes in, you can check out the situation! Or better yet, try to hide at Pi in your car with a battery pack. Slam the doors a few times, see what happens!

This is only a beginning to the possibilities on what you can do with a Raspberry Pi and Firebase. The SenseHat also includes environmental sensors, gyros, and a compass. You can set up your Pis to log certain changes to the environment. Want to step up your game? When your Pi detects movements, use a camera capture images and have the Pi text you the photos. Also try to use a computer vision algorithm to recognize faces. if its a face of someone you know, you can get notified! Have fun!

<p>So yes, you are using your (wear-with-all) and imagination, to create cool things, NICE!!! Major KUDOS!!!!</p><p>To be sure I thought I saw a couple months ago a script that allows you to detect movement from your camera attached to the pi??? now with twillo setup you get sms to your cell.... Tech that rocks!!!! Rules!!</p><p>not to brag but, I have two pi zeros, one orange pi (knock off from china), and a pi 2, and pi 3, and Pine64....just did the pi zero, (altoids retro pi rig ) but mine is totally modular,so I can put the pi zero in something else if I want.. way cool.....</p>
<p>Wow this is definitely something I will be making, I have 4 Pi's and was looking for something like this to use so really appreciate your efforts. <br>I will tweak it a little, but all in all I will use what you have made here to great use.<br><br>Oh and BTW, love the Bruce Lee Avatar! He is one hero of mine &quot;<i style="">If you spend too much time thinking about a thing, you'll never get it done&quot; </i>so on that note (a B.Lee quote) I will get it done....</p>
<p> Looking for a instruct able where I can get a wifi or just plain remote sense of someone coming down my driveway.Its around 800 feet long that sets back into a somewhat wooded area . I can purchase a sonar type device but would prefer to educate myself .I have seen where a device is set at the road side of the driveway ,when a vehicle enters it signals a device in the home. Also another device that would send a signal using a Surveillance camera wireless to send a picture in the same manner.Any ideas would be great and educational. </p>
<p>Isn't </p><p>-&gt; getting robbed </p><p>and </p><p>-&gt; getting notification about getting robbed as well as getting robbed</p><p>amount to the same thing?</p><p>.... ding *picks up phone*</p><p>&quot;You have been robbed&quot;.</p><p>Nice.</p>
<p>yes, but at least you have a chance to either stop the thief, or use the data to report the incident to the police</p>
can i know how much all this things for this project costs in malaysian money RM?<br>
<p>You can do money conversions with the calculator at:<br></p><p>http://www.xe.com/.</p>
Why not use a nodemcu for the sensors and run all the database and signaling programs on a raspberry pi 2 with a WiFi dongle. In my opinion that is a lot cheaper and more energy efficient. (A pi3 uses a lot more power than a pi2 and a node MCU even less and that has also WiFi on board.)
<p>Really nice project! It's a clever use of a Raspberry Pi board! <br>Some thinking about it: </p><p>For Pi1 you could use a PiZero W and a simple accelerometer sensor. This would cut costs a lot, doing almost the same things (apart from the notification display when a moving is detected, but you should reallly need this just on Pi2). It could also be much more compact.</p><p>You could do something similar for Pi2, thinking about a small addon board for the display.</p><p>Just for personal taste, I prefer using Telegram for the notifications. It's free and you can have some extra feature compared to sms, but any method is good as long as you can receive the notifications...</p><p>If you wish to capture images when a movement is detected, maybe it would be better to use another RPi in a fixed position as the &quot;moving&quot; RPi could get unuseful pictures (depends on where you use it, of course).</p><p>P.s.If you need a simple code to use a camera for motion detect, I just wrote a small post on my blog: <a href="https://rpihome.blogspot.com/2017/03/detecting-motion-with-rpi.html" rel="nofollow">https://rpihome.blogspot.com/2017/03/detecting-mot...</a></p>
<p>Thanks for checking out this Instructable!</p><p>Pi Zero W would be great! Too bad it just came out before I bought the Pi3. I took a look at your post, I was planning to add image capture with OpenCV. I just havn't had the time to get to playing around with my picamera yet. I may update this instructable in the future to support image capture, or build a different project that includes the camera. </p>
Gotta agree with Mascal, two RPi3? That's probably 60+ $/&euro;.... Even an RPi Zero with WiFi dongle would make sense, not only when it comes to pricing, but also to battery lifetime. Or you just get an arduino clone with additional or built-in WiFi for less than 5 $/&euro; from China. And the battery lifetime would again increase significantly.
<p>Hello! You don't need to use 2 Pis. One would work also. The reason I included 2 Pis is to show how easy one could scale this. Consider covering your house with with Pis. </p>
<p>This project can be surely made using from PiZero to Pi3 (and also other boards). Despite what you are using I think it's a great idea.</p><p>And you are just right, if the Pi is hidden somewhere it's not possible to use pir or camera. That's why I love it!</p>
<p>Nice project. Even nicer iOS app instructions. Thank you!</p><p>One thing that really surprised me is why you chose to use an accelerometer instead of a PIR motion sensor to detect motion. No need for an expensive HAT, just wire it directly to the GPIO pin (preferably with a Pi-Zero)</p>
<p>I chose the SenseHat because its aspirational. Consider its range of other sensors and joystick that can be used. While not discussed in the Instructables explicitly, there are other applications one could apply to what I've built. If you have a room that needs to be temperature controlled and you want to monitor the flow of traffic via the vibrations, the SenseHat can do it. Then you can grab the logged data and compare the movement against temperature changes. If you create a program with multiple security profiles, you can select them with the joystick. The choice of using the accelerometer is it's omnidirectional and can detect movement in multiple rooms. One could use a &lt;$10 PIR sensor, but that only works with line of sight. If the unit was hidden, then its not too useful.</p>
<p>Excellent instructable. This really shows how you can scale and add much more to this setup. I read the &quot;overkill&quot; comments, but they maybe missing the idea of what you proposed here. <br>Keep up the good work and thank you for sharing.</p>
<p>Right! This project could be done in several different ways of course, but it's the idea that is quite smart! I would have never thought to make a movement detection system by using accelerometer...<br>Despite of what we can use to make it, this would be surely useful in several situation.</p>
<p>Step 0: At least minimally secure the Pi itself (http://raspberrypi.stackexchange.com/questions/7133/how-to-change-pi-sudo-permissions). Using the Raspbian default user when it has no effective password authentication for running root commands is asking for trouble.</p>
<p>you're right, I didnt include that step. I would assume people use passwords</p>
<p>Very interesting use of the senseHAT to make a security system without a camera! Sure there are cheaper ways to do this, but think of all the messages you could send to the person who stole your car!! Mount it so it's somewhat visible from the drivers seat, yet not very visible from the outside. </p>
<p>Thats a good use case! if one is comfortable with their car, they can hardwire the Pi into the car and have it hidden somewhere. Thanks for reading!</p>
<p>Could tell them the police are coming and have it flash red and blue lights!</p>
<p>A PIR sensor would be a lot cheaper and more effective than a sense hat.</p>
<p>ditto. with esp8266, the cost would be &lt; $10. </p>
An Esp8266 could also do the trick. Much cheaper, with deep sleep so energy efficient and smaller.
<p>I have ESP8266 board and really want to setup a door trip system to tell me when door was opened. I have not had any success yet though. Do you have any tips or tutorials that could help me?</p>
<p>Wow thanks, deep sleep is very interesting and sounds prefect for my application. I know some new home security devices in stores can run for over a year on just 2xAA batt so hopefully I can get similar results. Thanks. </p>
<p>While this may be true, most people have never heard of the ESP8266. I have now, and thank you for that. So when somebody who's looking to get into micro-controller programming, but doesn't know too much about it and just bought a Pi, they will Google search for the more ubiquitous thing (and probably the only thing they've heard of). If you're a seasoned programmer with lots of experience and knowledge of various ways of more efficiently doing things, then by ball means, you do you! But can this ESP8266 also be turned into an arcade or media player? </p><p>Seriously, thanks for the tip. I think I'm going to look into getting some of these!</p>
<p>Also the ESP8266 is only $5 to $10 - very cheap when ordered from China</p>
<p>Sorry, but you kill a fly with a big grenade launcher. </p><p><a href="https://www.instructables.com/member/mjager3" rel="nofollow">mjager3</a> is correct!</p>
<p>I think you've both missed the point.</p>
<p>This is really cool! There's very few breakins in my area, but me and my brother constantly enjoy &quot;locking down&quot; our upstairs with a giant baricade made from boxes and pillows. I try to set up my phone to set of an alarm when it detects movement, but it never seems to work. Now that there's this, I can successfully create a security system for my pillow wall! Thank you very much!</p>
<p>Sounds good! to be secure from the thieves</p>

About This Instructable




More by imjasonc:R-PiAlerts: Build a WiFi Based Security System With Raspberry Pis Easy Configurable Cargo Blocks for Your Car Trunk DIY $10 10-Stop Neutral Density (ND) Filter 
Add instructable to: