---
# System prepended metadata

title: Home Security System Tutorial

---

# Home Security System Tutorial



![](https://i.imgur.com/73nbVvN.jpg)

By: Andréas Jansson - aj224py
Date: 2021-08-02

This is a tutorial to build and code a home security system which monitors the status of your front door using the lopy4 platform. Estimated time to build the device is 6h.

# Objective

When deciding on the project I wanted to build something that has an actual use for myself. Being a student who lives in a student apartment, safety for yourself and your belongings is something that pops to mind every now and then. 

I therefore chose to build a device which monitors the state of my door. The data is sent to pybytes at the moment and lets me know if something unexpected has transpired.




# Material

Here is a list of all the materia I purchased. 

**Pycom Kit**
The Pycom kit was purchased from electrokit.com with a cost of 849kr. It contains the Pycom device called the Lopy4, an expansion board(version 3.0), an antenna and a micro USB to USB A. It is a microcontroller with multiple I/O pins, allowing great freedom when building your devices.
![](https://i.imgur.com/SN47ZbQ.png)



**Bread board**
The breadboard was purchased from cdon.com with a cost of 34kr. The breadboard has 400 connections and exist to simplify connecting sensors to the pycom device.
![](https://i.imgur.com/SoOhyyP.jpg)



**Wires (m2m)**
The wires were purchased from electrokit.com with a cost of 29kr. The length is 15cm and the contacts are male to male.
![](https://i.imgur.com/9dZRJ5W.jpg)


**Led lights**
The led lights were included in the sensor kit purchased from electrokit.com with a cost of 299kr. They come in different colours, Red, Yellow and Green were used in this project.

**Resistor**
The resistors were included in the sensor kit purchased from electrokit.com with a cost of 299kr. The one in use is 110 Ohm in order to pull current through the LEDs.

![](https://i.imgur.com/m7GU288.jpg)



**Ultrasonic sensor**
The ultrasonic sensor was purchased from electrokit.com with a cost of 59kr. It is of model HC-SR04 and can measure distances up to 4m.
![](https://i.imgur.com/t6grbHD.jpg)



**Joystick**
The joystick sensor was included in the sensor kit purchased from electrokit.com with a cost of 299kr. 

![](https://i.imgur.com/yWZ7ZjG.jpg)


**Battery case**
The AAA battery case was purchased from electrokit.com with a cost of 19kr.
![](https://i.imgur.com/GDC0SfP.jpg)



**Casing - Lego**
The lego was purchased from webhallen.com with a cost of 2999kr. This was a previous purchase and I do not recommend buying it for the sole purpose of building a case.
![](https://i.imgur.com/7ZNb0xX.jpg)



# Computer Setup
The computer used for the project is a Macbook Pro 2016 13" and running MacOS Big Sur version 11.3. 

The text editor Atom is used for connection and coding the onboard logic. Open the editor and click Atom > Preferences > Install. Search for "Pymakr" and install it.

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




The Pycom firmware updater was used to update the firmware and pair the device to pybytes. Start the program and enter the following settings, make sure to select the correct COM port.



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


Once this is done, you are able to write your code and upload it to the device!


# Putting everything together

Let's assemble the device. First we need to connect the Lop4 to the expansion board by lining up the pins. 

Once that is complete we can connect the WIFI antenna to the port shown in the diagram.

To connect the breadboard, we will connect one wire from the Vin pin to a + row and a wire from the ground pin to the - row. From these we will be able to easily power multiple devices on the breadboard.

**Ultrasonic sensor**
Let's start off with the ultrasonic sensor. It has 4 pins named Vcc, Trig, Echo and Gnd. 

The Vcc pin is connected to the + row on the breadboard in order to receive power. 

The Trig pin is connected to pin 22 on the expansion board. 

The Echo pin is connected to pin 21 on the expansion board. 

The Gnd pin is connected to the - row on the breadboard. 

**Joystick sensor**
The joystick sensor has five pins named Gnd, +5V, URX, URY and SW.

The Gnd pin is connected to the - row on the breadboard.

The +5V pin is connected to the + row on the breadboard.

The URX pin is connected to pin 18 on the expansion board.

The URY pin is connected to pin 19 on the expansion board.

The SW pin is unconnected since it is not being used by our device.

**LED**
The green LEDs input pin is connected to pin 7 on the expansion board. The out pin is connected to a 110 Ohm resistor.

The yellow LEDs input pin is connected to pin 6 on the expansion board. The out pin is connected to a 110 Ohm resistor.

The red LEDs input pin is connected to pin 5 on the expansion board. The out pin is connected to a 110 Ohm resistor.

**Battery**
The battery pack is optional and is connected to the power input socket on the expansion board. 

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



# Platform

The platform I've decided to use is the pybytes platform. It is simple to use and meets the requirements for this device. The device only sends 4 different messages, startup, config, reset and breach. This makes it very simple and doesn't need a more robust database solution. Pybytes is a cloud platform which makes it easy to connect and maintain.


# The Code

**Main Logic**

1. Gets median distance 

2. Checks if the joystick is pressed up or if the boot flag is true.

3. If either is true then a message is sent to pybytes and the current median distance is set to the default value.

4. If the distance is larger than the default value, the alarm triggers by enabling the red LED and sending an alert message to pybytes. It will stay in this state until you either press the joystick up to reconfigure the default distance or down to exit the alert loop.

The green LED is active when the alarm is active but not triggered. The red LED is active once the alarm has been triggered. The Yellow LED is active during configuration of the default distance. 

```
    distance = dist_average() #Calculate the median distance
    
    #Enters config mode if joystick is pressed up or boot flag is true
    if y_axis() > 300 or status_boot == 1:
        pybytes.send_signal(1, code_config)
        calibrated_value = config(distance)
        time.sleep(1)
    #If distance is larger than default distance, alarm triggers
    elif distance > calibrated_value:
        pybytes.send_signal(1, code_breach)
        while True:
            alert()
            print('dist: ' + str(distance) + ' conf dist: ' + str(calibrated_value))
            #Press joystick down to return to main loop
            if x_axis() < 50:
                pybytes.send_signal(1, code_reset)
                reset()
                break
            #Press up to set new default value
            elif y_axis() > 300:
                pybytes.send_signal(1, code_config)
                calibrated_value = config(distance)
                break
```


**Distance Calculation**
This function is responsible for calculating the distance from the ultrasonic sensor.

It sets the trig pin to 0 in order for the sensor the send a pulse and counts the number of ms that has elapsed since system start. When it receives the pulse it does the same and calculates the difference. The elapsed time can then be calculated with this formula: (time * 0.034) / 2. The 0.034 comes from the speed of sound being 343 m/s and the division by two is to get the one way distance.


```
def dist():
    trig.value(0) 
    utime.sleep_us(2)
    trig.value(1)
    utime.sleep_us(10)
    trig.value(0)

    while echo() == 0:
        continue
    start_time = utime.ticks_us()

    while echo() == 1:
        continue
    finish_time = utime.ticks_us()

    utime.sleep_ms(20)

    distance = ((utime.ticks_diff(finish_time, start_time)) * .034) / 2

    return distance

```


**Average Distance**
The Sensor and device can sometimes transmit spiky results for various reasons. This function takes 10 measurements and sorts them. It then picks the middle value to reduce the risk of faulty readings.
```
def dist_average():
    dist_list = []

    for i in range(10):
        dist_list.append(int(dist()))

    dist_list = sorted(dist_list)
    dist_average = dist_list[5]

    return dist_average
```


# Transmitting the Data / Connectivity



The data is transmitted to Pybytes cloud solution using WIFI using the MQTT protocol since this is a "smart" home device. Range and power isnt our largest concern,  but rather compatibility for most users.

The following code carries out the operation. Data is sent on startup as default, otherwise it will only send data when the alarm triggers or the joystick is being used.

```
pybytes.send_signal(signal, message)
```


# Presenting the data


The dashboard simply shows the latest inputs from the device. The users can look at these to see the current state of the device. The four status messages are startup, config, reset and breach.

Startup simply indicates that the device has booted up.

Config is entered after the bootup or when the joystick is pressed up.

Reset indicates someone has pressed the joystick down in order to exit the alarm loop.

Breach indicates that someone has opened your door and you should probably call the police.






# Finalizing the Design



Building this device has been a lot of fun and shown me that you can create quite functional and advanced devices rather quickly using lop4 and micropython. 

This project is quite simple but effective. There are of course ways to improve it, such as requiring a special sequence from the joystick in order to turn off the alarm, adding a speaker and so forth. I hope this tutorial can help or inspire others to build cooler builds!  üü


![](https://i.imgur.com/JEQdsvq.jpg)


