---
# System prepended metadata

title: Turtorial on how to build motion detection device

---

# Turtorial on how to build motion detection device

Title: Personal Zone Protection 
Tamim Jabr, tj222kg

Overview: Detecting if someone enters my office room

Time needed to do: 4h

## Objective

I chose this project because I am so curious about if someone enters my office room while I am not at home. This project will help me protecting my personal zone. In addition, I am so interested in working with motion sensor, so this project seems to fit well.

## Material

1. Pycom LoPy4: a device that is a little device programmed by MicroPython and has several bands of connectivity (including wifi that I use in my project). The device has many digital and analog input and outputs and is well suited for an IoT project.

![](https://i.imgur.com/tBGu9HP.png)



2. The expansion board : makes it easier to connect things to LoPy4, as well as connecting my computer via micro USB, enabling me to plug the usb cable and start programming my LoPy4 

![](https://i.imgur.com/ewD9LOk.png)



3. Breadboard : Allowing me to connect my sensors to the breadboard and connect the breadboard to the LoPy4, making things easier when connecting several sensors.


![](https://i.imgur.com/xNkACHB.png)


4. Jumper wires male-male: easy to convert to female-male using a pair of nippers

![](https://i.imgur.com/2FkInal.png)

5. Push button: to start and end the program
![](https://i.imgur.com/exJxL6t.png)


6. Motion sensor : detecting the motion in the room

![](https://i.imgur.com/vYS2W35.png)

The material from 1 to 4 was included in IoT – LoPy4 and sensors bundle that I purchased from Electrokit and the price was 949 kr (about 93 euro) including many other things like resistors, temperature sensor...

The push button price was 19 kr (less than 2 euro)

The motion sensor price was 49 kr (less than 5 euro)

## Computer setup

1. When it comes to flashing the firmware, so everything worked well for me without doing that. But if you need to do that watch this video on pycom official youtube channel [How To Flash Your Pycom Devices With The Latest Firmware](https://www.youtube.com/watch?v=TEfiMnkvyyM)

2. I use Visual Studio Code because I already use it for web programming and I feel comfortable with it.

3. Make sure to install pymakr extension for VSC to be able to upload and download your code to and from your pycom device, as well as running your code.
    ![](https://i.imgur.com/ncdZXm1.png)
    
    ![](https://i.imgur.com/az6UFt2.png)



4. Edit the gloabl settings for your pymakr extension and make sure to enable auto connect for easier connection for your LoPy4

![](https://i.imgur.com/rHW2H1e.png)


5. Download Nodejs if you don't already have it on your computer because PyMakr uses Nodejs. [Nodejs-download](https://nodejs.org/en/download/)


## Putting everything together

![](https://i.imgur.com/X07O12i.png)


The figure shows how I connect the devices to each other. The white wires are connected to GND (ground), the red wire for the button is connected to the 3v3, but on the motion sensor to 5v. The green wires show that the button is connected to pin 10 and the motion sensor to pin 4 on the expansion board.

This set up is intended for development, but not production because it is easy to disconnect wires and devices when moving them. For production, it is a good idea to use 3D printer to create some kind of box where those devices can be fastened.

## Platform

I use [Pybytes](https://pybytes.pycom.io/) as platform to manage my device, because it gives me those features that I need ex. locating the device, savung singals sent from the device for one month without setting up a database myself and enabling me to save notifications (ex. when the battery level is low or when sending a specific amount of data). You can read more about [how to connect your Pycom devices to Pybytes](https://docs.pycom.io/pybytes/connect/#app) 

The installation is cloud based because singals and notifications are saved in the cloud in pybytes platform. I am not planning to use a paid subscription because I can add as many devices as I need without doing that.

In case I want to scale my application, so I need to set up a database connected to pybytes to store my data permanently because pybytes save the data sent from my devices only for one month.

## The code

```python=
import pycom
import time
from machine import Pin
from machine import Timer


powerOn = False
pycom.heartbeat(False)

p_in = Pin('P10', mode=Pin.IN)  # SENSOR BUTTON FORM ELEKTROKIT


while(1):
    val = p_in()  # get value, 0 or 1 from the button
    if val == 0:
        if (powerOn):
            powerOn = False
        else:
            powerOn = True

            motionDetected = 1
            noMotionDetected = 0
            pir = Pin('P4', mode=Pin.IN)

            chrono = Timer.Chrono()
            chrono.start()

            # notify when start detecting by logging and green light
            print("Starting Detection")
            pycom.rgbled(0x00FF00)  # Green
            time.sleep(1)
            pycom.rgbled(0x000000)
            while True:
                if pir() == motionDetected:
                    print(chrono.read(), "Motion Detected!")
                    # notify when detecting motion by sending data, logging and red light for 10sec
                    pybytes.send_signal(1, "Motion Detected!")
                    print("sending: Motion Detected!")
                    pycom.rgbled(0xFF0000)  # Red
                    time.sleep(10)

                if pir() == noMotionDetected:
                    pycom.rgbled(0x000000)
                    pass
                time.sleep(1)
                val2 = p_in()
                if val2 == 0:
                    powerOn = False
                    print("Stop detection")
                    pycom.rgbled(0x0000FF)  # Blue
                    time.sleep(1)
                    pycom.rgbled(0x000000)
                    break
    time.sleep(1)

```

The code is waiting until someone hold the button until the green led flashes to start detection and once the sensor detects motion we send data to pybytes via wifi, log that motion detected and light red led for 10 seconds. When we want to stop detection, we have to hold the button until the blue led flashes.


## Transmitting the data / connectivity

Data is transmitted to the internet using wifi and sent on every motion detection and the transport protocols that is used is MQTT because pybytes runs over an open MQTT broker.

## Presenting the data

The Dashboard show signals for the past hour and past day, as well as the location of the device.

![](https://i.imgur.com/Plm3GTW.png)

Signals are saved in Pybytes for one month and they are deleted after that.

![](https://i.imgur.com/GJ3h4kV.png)

I save notifications when the total amount of transfered data exceeds 19 bytes within 1 minute, so in result I got notification when someone enters the room. I I also have notification when the battery level is lower than 20% (because I am planning to use batteries instead of connecting the device via usb). Even the notifications have an archive for the last 30 days.
 
 ![](https://i.imgur.com/faPjPkg.png)



## Finalizing the design

The final result is a device that detects if someone enters my office room while I am not at home. It works fine but there are some points that could be improved:

1. Use 3D printer for making the device more user-friendly
2. Use database to store data sent from the device
3. Send e-mail or sms notifications for instantly notification when motion is detected

 [Here is a short video showing how the device works](https://www.youtube.com/watch?v=XYaL2JEY7UU)
 
 
## Source list for pictures:

1. Pycom.io, pictures of Lopy4 and expansion board
2. Electrokit.com, pictures of breadboard, wires, button and motion sensors
 