Build a surveillance system using Raspberry Pi, NodeJS and Pir sensor
Tags: raspberrypi3, node, iot, diy
Published: 2020-12-08 14:44:43

On February 2018 my interest in embedded systems began after reading couple of articles on the topic and discussing with some friends of mine that had an idea on it. That been the case nothing really caught my interest than when I saw that JavaScript, a language I was very familiar with, was also in the embedded space through NodeJs( Server side JavaScript).

In the article I would be showing you how I used the Raspberry Pi 3, NodeJs, Pir sensor to create a monitoring system. This system depends on the internet to send notifications and hence can be regarded as an IoT system.

**Disclaimer: In this article I am assuming you have already set up the NodeJS environment in the raspberry pi and have everything installed and set up ready to run. If not please check out tutorials on setting up the Raspberry Pi 3 and NodeJs**

## **Tools we would be needing**

The following below are the tools, packages, services I used to carry out this project:

1. Raspberry Pi 3: The Raspberry Pi is a series of small single board computer developed in the United Kingdom by the Raspberry Pi Foundation to promote teaching of basic computer science schools and in developing countries. I used it here as our mini computer system.
2. Pir Motion Sensor: Pyroelectric (“Passive”) Infrared Sensors allows you to sense motion, almost always used to detect whether a human has moved in or out of the sensors range. I used it here to detect motion
3. Nodemailer: A node package for sending mails, I used it to send mails
4. onoff: A node package which has GPIO access and interrupt detection with Node.js, I used it here to interface with the Raspberry Pi GPIO pins.
5. RGB Led Light: Used as a signal system here to show when motion has been detected. It consist of three colors red, green and blue.
6. Breadboard: A breadboard is a solderless device for temporary prototype with electronics and test circuit designs. Most electronic components in electronic circuits can be interconnected by inserting their leads or terminals into the holes and then making connections through wires where appropriate. I used it here to connect some of my hardware.
7. Jumper wires(Female to male and Female to Female): These are electronic wires I used to connect my hardware's.

## **Work time**
Time to get our hands dirty!

### **Setting up hardware to board**

1. Setting up the RGB Led Light: Insert the three output legs of the RGB Led Light to the breadboard. Then insert the female-to-male jumper wire(male end) to the breadboard parallel to each leg of the RGB, attach the opposite ends of these jumper wire(female end) to any GPIO pins in the Pi you would want to use, in this article we would be using 2,4,17.
2. Setting up the PIR Sensor : The sensor should likely have three ends, one for power, one for ground and one for output . Depending on the one you purchase, see a guide online on how to connect it to the pi board. In this article we would be using the GPIO pin 27 for output.

### **Setting up the mailer module**

1. First create a folder we would be working in and move into it, create a package.json file by running **_npm init_** and following the prompt, then install the node package by running this code:
    ```javascript
      npm install nodemailer
    ```
    This would add the nodemailer to the node modules directory as 
    one of our dependencies.

2. Create a new file called mailer.js and open it in any text editor of your choice, we would be writing the mailing function needed in this file.
    ```javascript
      const nodemailer = require("nodemailer");

      const transporter = nodemailer.createTransport({

      service:"Gmail",

       auth:{

        user:"yourmail@yourmail.com",

        pass:"password"

       }

     });

     module.exports.sendEmail=function() {

     if(timerId)return;

     timerId=setTimeout(function() {

      clearTimeout(timerId);

      timerId=null;

      },10000);

      const mailOptions={

       from:"SMART SURVIELLANCE ",

       to:"yourmail@yourmail.com",

       subject:"[Pi Bot] Intruder Detected",
       html:
       "Mr/Mrs/Miss. Your name ,


       Someone is trying to steal your raspberry pi 3.


       At : "+
       Date()+

       " 
        Love,
        Pi Bot"

       };

       console.log("Sending an Email now..");

       transporter.sendMail(mailOptions,
         function(error,info) {

          if(error) {

            console.log(error);

          }else{

            console.log("Message sent: "+info.response);

          }

        });

       };
    ```
    First and foremost we import the nodemailer package into our 
code(line 1), then we add our credentials using the nodemailer 
createTransport method(line 3–15).

    We then initialize a variable that is used to delay the execution of mail sending until after 10 seconds of motion detection occurrence, so as to prevent multiple mails been sent when motion is detected at close intervals(line 21–27).

    The next section simply uses a variable mailOptions to store the details of the mail to be sent(line 29–50), while the transporter.sendMail method proceeds to send the actual mail, we use a callback here to check if the message was sent or not and then show the corresponding message in the console(line 54–67).

    The module is then exported using the in built NodeJs exports method as sendEmail

### **Making the system functional**

Create an index.js file located in the same path as the mailer.js file created earlier. This file would be the default entry file for our NodeJs application. As usual I would be pasting the code and then proceed to explain
```javascript
const Gpio = require("onoff").Gpio;
const LED1 = new Gpio(2, "out");
const LED2 = new Gpio(4, "out");
const LED3 = new Gpio(17, "out");
let state = 2;

const pir = new Gpio(27, "in", "both");

pir.watch(function(err, value) {
  if (err) exit();
  let blinkInterval = setInterval(blinkLED, 250);

  console.log("Intruder detected");
  console.log("Pi Bot deployed successfully!");
  console.log("Guarding the raspberry pi 3...");

  if (value == 1) require("./mailer").sendEmail();

  setTimeout(endBlink, 15000);

  function endBlink() {
    clearInterval(blinkInterval);
    LED1.writeSync(0);
    LED1.unexport();
    LED2.writeSync(0);
    LED2.unexport();
    LED3.writeSync(0);
    LED3.unexport();

    //included when we are working with sensors
    pir.unexport();
    process.exit();
  }
});

function blinkLED() {
  if (state == 2) {
    if (LED1.readSync() === 0) {
      LED1.writeSync(1);
    } else {
      LED1.writeSync(0);
      state = 4;
    }
  } else if (state == 4) {
    if (LED2.readSync() === 0) {
      LED2.writeSync(1);
    } else {
      LED2.writeSync(0);
      state = 6;
    }
  } else {
    if (LED3.readSync() === 0) {
      LED3.writeSync(1);
    } else {
      LED3.writeSync(0);
      state = 2;
    }
  }
}
```

Firstly we import the onoff package and then use the GPIO method(line 1). Then we assign the three output of the RGB light to three variables and also initialize a state variable that would be used to know the current color in the RGB Led Light been shown(line 2–5).

We also assign the Pir motion sensor on the Raspberry Pi pin 27 to a variable(line 7). After which we write a pir.watch function that watches for false positive from the Pir motion sensor(line 9). If there is an error we exit from executing the code, if not, meaning a valid motion was detected, we proceed to call a function that blinks the RGB light at 250 milliseconds interval(line 11). This function simply uses the state variable to know the color of the led light currently showing and then shows the next color at the next interval.

We also import the sendEmail module from our mailer.js file and call it (line 17), after which we stop the blinking light after 15 seconds, clean up the program and exit(line 19–34).

And wolla!, we have built a very easy yet effective monitoring system by just writing a few lines of code, that goes to show the immense power of NodeJS when combined with the elegance of the Raspberry Pi 3.


## **Conclusion**

You can do all sorts of things with this setup . You can even [receive an sms](https://docs.clickatell.com/channels/one-api/one-api-reference/) or have [Twilio](https://www.twilio.com/) call you whenever the alarm is tripped off!

Let me know what did with this setup and this amazing chip in the comments!