---
# System prepended metadata

title: Tutorial to create a small security system for your summer house

---

# Tutorial to create a small security system for your summer house

Author: Sandra Ljungberg - sl224gw

This tutorial will demonstrate how to create a small security system for your second home, for example your summer house, that is often left unattended during nights. An approximation of the time needed to assemble this project is 3-4 hours if all steps are included and you have no previous experience.

## Objective
The project consists of creating a system that will turn on a lamp when an unwanted visitor has been detected. This will hopefully scare the burglar off before you even get there (however the lamp will only turn on when its dark enough to have an impact)! As an extra precaution if the lamp does not do the trick, you will also recieve an alarm through email and can go and investigate yourself.

I chose this project since it covers a lot of different kinds of hardware which I was excited to test out. Hence this will give insights in how to use quite a few common components in electronic circuits, which will make it easier to create even more advanced IoT-projects in the future.  It also serves a good purpose since security in my summer house is non existent and this could solve that!   

The hardware used in this project will cover both the use of sensors as well as a relay that connects to a 6 volt lamp. This will give the knowledge of working with these components without having to work with electronics that run on the main current (230 volts). Therefore this project is a good  starting point for getting acquainted with home automation in a more safe environment. The project also includes sending the data to a platform (ubidots), where it will be displayed and visualised. The IoT-platform was chosen not only for its aesthetics and easy to use design, but also because it has functionality where alarms (triggers) can be set at specified thresholds and the user can be notified through email.      

## Material

| Material                   | Cost   | Usage                                                                                                                                                                         | Where to buy (link)                                                                    |
| -------------------------- |:------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |:-------------------------------------------------------------------------------------- |
| LoPy4                      | €38.45 | Is a quadruple bearer board that is programmable with micropython.                                                                                                            | :link:https://pycom.io/product/lopy4/                                                  |
| Expansion Board 3.0        | €17.60 | To place the LoPy4 on (to easier connect the sensors).                                                                                                                           | :link:https://pycom.io/product/expansion-board-3-0/                                    |
| Micro USB cable            | 39 SEK | To connect to LoPy4/expansion board to the laptop.                                                                                                                                             | :link:https://www.electrokit.com/produkt/usb-kabel-a-hane-micro-b-5p-hane-1m/          |
| Breadboard                 | 59 SEK | To have an easy way to connect sensors/components with the the LoPy4/expansion board.                                                                                                               | :link:https://www.electrokit.com/produkt/kopplingsdack-400-anslutningar/               |
| Jumper wires [female/male] | 29 SEK | To connect the relay to the breadboard.                                                                                                                                        | :link:https://www.electrokit.com/produkt/labbsladd-20-pin-15cm-hona-hane/              |
| Jumper wires [male/male]   | 29 SEK | To connect the sensors mounted on the breadboard to the pins on the LoPy4/expansion board.                                                                                                     | :link:https://www.electrokit.com/en/product/jumper-wires-20-pin-30cm-male-male/        |
| Resistor 10k Ohm                           |  3 SEK      |    Used together with the photo resistor sensor.                                                                                                                                                                           |      :link:https://www.electrokit.com/produkt/motstand-metallfilm-0-6w-1-1kohm-1k/                                                                                  |
| Photo resistor             | 8 SEK  | Used to measure light. When light increases then the resistance decreases.                                                                                                    | :link:https://www.electrokit.com/en/product/photo-resistor-cds-2-5-kohm/               |
| Motion detector PIR mini   | 59 SEK | Can detect when people move up to 3-5 meter in front of the sensor.                                                                                                           | :link:https://www.electrokit.com/en/product/rorelsedetektor-pir-mini-sr602/            |
| Relay module 5V            | 39 SEK | The relay is used to control the electronic circuit consisting of the lamp and the battery. The control signal can be 3.3V or 5V and it can control loads up to 250VAC / 10A. | :link:https://www.electrokit.com/en/product/relay-module-5v/                           |
| Light bulb 6V              | 9 SEK  | Lamp compatible with the battery size of 6V.                                                                                                                                  | :link:https://www.electrokit.com/en/product/glodlampa-e10-6v-0-1a-0-6w-glob/           |
| Lamp holder                | 15 SEK | Used to connect the lamp bulb with the electronic circuit.                                                                                                                     | :link:https://www.electrokit.com/en/product/lamp-holder-e10-black/                     |
| Battery holder 4xAA        | 10 SEK | Used to power the electronic circuit with the lamp.                                                                                                                           | :link:https://www.electrokit.com/en/product/batterihallare-4xaa-kabel-2/               |
| Batteries 4xAA             | 20 SEK | To use in the battery holder.                                                                                                                                                  | :link:https://www.clasohlson.com/se/Alkaliskt-batteri-AA-LR6-Clas-Ohlson/p/Pr365487004 |

You will also need a small screwdriver for the connections of the relay and the lamp holder. In the following picture some of the main components can be seen. On the top row from the left: relay, lamp holder, light bulb. On the bottom row from the left: photo resistor, motion detector PIR mini and resistor 10K Ohm.

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


## Computer and device setup

Before we start programming we need to do some computer setup and device setup. The hardware also needs to be assembled before we can start with the project. Start by mounting the LoPy4 to the expansion board and then adding the micro USB-cable to the micro USB port on the expansion board. The other end of the USB-cable will later be plugged into the laptop. The result should look like the following picture.

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

It is recommended to update the device firmware (on the LoPy4) before starting, this is to reduce potential bugs since pycom continously makes improvements and adds new features. To update the device firmware [follow this guide](https://docs.pycom.io/updatefirmware/device/). Now that the device firmware is updated it is time to set up your computer.

The communication with the LoPy4 is done through a chosen IDE, I chose Atom, but it would for example also be possible to use VScode or any other prefered IDE that has a pymakr plugin. To use the pymakr plugin in Atom we need to install some programs, I recommend doing the computer setup in the following order. **Observe that I have done this with a windows computer and the steps might differ if you use something else.**

1. Install Node.js 
    * Download it [from here](https://nodejs.org/en/)
    * Follow the installation guide
2. Install the latest version of Python
    * Download it [from here](https://www.python.org/)
    * Follow the installation guide **but make sure to tick the box "Add to Path"**
3. Install Visual Studio
    * Follow [this guide](https://docs.microsoft.com/en-us/visualstudio/install/install-visual-studio?view=vs-2019#step-3---install-the-visual-studio-installer) to install Visual Studio, **but make sure to tick the box with "Desktop development with C++"**
4. Install Atom
    * Download it [from here](https://atom.io/)
    * Follow the installation guide
5. Restart your computer
6. Install pymakr Plugin
    * Start Atom
    * Navigate to file->settings->install
    * Search for pymakr and click install

Now that the pymakr plugin is installed it is possible to start writing and uploading code to the device. Connect the USB-cable to the computer. In the terminal of the Atom window you will see that the device have connected. You can now run code on the device by clicking on the tilted triangle in the terminal, or uploading the code to the device by clicking on the icon with the arrow facing upwards.


## Putting everything together

Start with having the power supply (USB) unplugged. Connect 5V and ground from the LoPy4 to the breadboard with the plus and minus row. Add the photo resistor in series with a  resistor (10k Ohm) as seen in the circuit diagram. Mount the motion detection sensor on the breadboard and connect it to ground and the 5V row on the breadboard. Connect one side of the relay with jumper wires from the ground and 5V on the breadboard to the pins on the relay. The switch pin on the relay will go straight to the Lopy4.

The second part of the circuit is more or less seperate from the first part. This part of the circuit is running on its own power supply (the 6V battery) and is controlled through the relay. I am using the "normally open" pin on the relay since I want to be able to start the lamp by setting the switch pin on the relay to one (it would be the opposite if I had instead used the "normally closed" pin).

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

The finished product is only on a development setup, and to be used in production it would need further improvements. One of the main reasons for this is that the lamp is so small that it would most likely not be bright enough to have a great impact. The same principles could however be used even if the lamp is swiched out to one with a higher voltage, since the relay can control loads up to 250VAC/10A, **but this should only be done if you know what you are doing since using the main current can be dangerous.**

When you are done it should look something like this.

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



## Platform

The chosen platform is Ubidots (Ubidots STEM), which is a free platform for non-commercial use where you can connect up to three devices. The data is saved for 1 month in their cloud and the platform has the possibility to create dashboards that will present the data in very intuitive ways and it is very easy to use. This platform also comes with more fun alternatives for how to present the data compared to for example pybytes which has a more simple design. Ubidots also gives the alternative to create triggers for the data, which was well suited for this project. The platform is scalable if more devices should be added in the future, however if more than three devices are connected then a subscription is needed which will cost. 

## The code
The code that is doing the main functionality is located in the main file. The code that covers the transmission of data and the WiFi connectivity will be described in the next part of the tutorial.

The code in the main file is built into three  parts. First comes some pin configurations and other variable definitions. Then some functions are defined to make the code a bit more easily read, and lastly is a while true loop that will run indefinitely.

```python=
#The first and second part of the main.py file not including functions for data transmission

import machine
from machine import Pin
import time
import keys
from network import WLAN
import urequests as requests

#WIFI CONFIGURATIONS
TOKEN = keys.TOKEN #Put your TOKEN
 
#PIN CONFIGURATIONS
motionDetectionPin = Pin('P16', mode=Pin.IN)
adc = machine.ADC() # create an ADC object
lightPin = adc.channel(pin='P19')
lampPin = Pin('P21', mode=Pin.OUT)

#VARIABLE DEFINTIONS / START VALUES
intervalToSend = 60
lampOnTime = 60*0.25
lightThreshold = 80
clockCounter = 0
lampOn = 0
detection = 0

#SENSOR FUNCTIONS
def ReadDigitalValue(pin):
    return pin()

def ReadAnalogValue(pin):
    return pin.voltage()
```

The loop that will continously run when the device is active is built so that the device will read sensor measurements every second. These measurements are not all transmitted to the cloud on the platform since the data transmission only occur once per minute. The continous (every second) measurements are instead used in the automation of the lamp. If the light in the room is dim enough and a motion has been detected, the lamp will turn on for a fixed amount of seconds with the variable *lampOnTime*. To keep track on how long time has passed a variable *clockCounter* is also introduced. Since the device will sleep one second in the beginning of every loop it will also count clockCounter up one right after. However it should be noted that this does not give a reliable time counter since the time it takes to run one lap of the code is not counted here (it is only the time that the device sleeps that is counted).

```python=
#The while true loop
 
while True:
    try:
        time.sleep(1)
        clockCounter+=1 #One second has passed

        lightMeasurement = ReadAnalogValue(lightPin)
        motionDetectionMeasurement = ReadDigitalValue(motionDetectionPin)
        #The device will send that a detection has occured if it has detected it at least once since the last time data has been sent
        if motionDetectionMeasurement == 1: 
                detection = 1

        if (clockCounter == intervalToSend):
            send_data("pycom", lightMeasurement, detection)
            clockCounter = 0
            detection = 0

        #Turns on the lamp for the predefined amount of time
        if (motionDetectionMeasurement == 1 and lightMeasurement < lightThreshold and lampOn == 0):
            lampOn+=1
            lampPin(1)
        elif (lampOn != 0 and lampOn < lampOnTime):
            lampOn+=1
        else:
            lampOn = 0
            lampPin(0)

    except KeyboardInterrupt:
        print('interrupted!')
        lampPin(0)
        break
```

## Transmitting the data / connectivity

It is possible to transfer up to 4000 dots per day on the chosen platform (ubidots) as well as 1 request per second per token. The data is therefore chosen to be transferred in the same request and the time interval of one minute. The chosen interval will not be a problem for the light measurement since the purpose of checking the light is only to determine if it is dark enough that it would be worth turning on the lamp (if it is too bright in the room the lamp will not be powerful enough to make an impact anyway and it is therefore unnecessary to light it and waste battery). The light measurement does not need to be transmitted more often than that (however it is still checked locally on the device every second, but only one every sixty measurements are sent). The motion detection measurement might however become a problem if it is only sending one measurement once every minute. This is solved in the code so that it will check detection every second and once every minute it will send to the platform if at least ONE detection has happened during the time since the last time data was sent. This could still give a delay, from that the detection has been noted by the device until the alarm has been sent from ubidots. However this delay is small enough that it is counted to not matter much. 

Where I am located there is no coverage for  TTN, Helium or Sigfox, so the choice to use WiFi connection became easy. However, since the device will be located inside the summer house where there exist a good WiFi-connection, the choice to use WiFi would most likely be the best choice even if coverage for one of the others were avaliable.

To send the data through WiFi to the chosen platform [this guide](https://help.ubidots.com/en/articles/961994-connect-any-pycom-board-to-ubidots-using-wi-fi-over-http) was used. The following code is  based on the code provided in the guide. The transport protocol used are webhooks. I decided to place code that connects the device to WiFi in the *boot* file to seperate some of the code and make everything a bit more tidy. The WiFi credientials as well as the token was also added in a seperate file named *keys*. A library file was also used for the transmission to work, it was taken from the guide but the file can also be found [here](https://github.com/jotathebest/micropython-lib/blob/master/urequests/urequests.py).

```python=
#boot.py
import machine
from machine import UART
import os
from network import WLAN
import keys

uart = UART(0, baudrate=115200)
os.dupterm(uart)

#WIFI-CONNECTION
wlan = WLAN(mode=WLAN.STA)
wlan.antenna(WLAN.INT_ANT)

# Assign your Wi-Fi credentials
wlan.connect(keys.WIFI_NAME, auth=(WLAN.WPA2, keys.WIFI_PASS), timeout=5000)

while not wlan.isconnected ():
    machine.idle()
print("Connected to Wifi\n")
```

To send the data to the ubidots platform two more functions were used, one to send a request and one to build a json. Both of these functions are defined in the *main* file.

```python=
#main.py
def build_json(variable1, value1, variable2, value2): # Builds the json to send the request
    try:
        data = {variable1: {"value": value1},
                variable2: {"value": value2}}
        return data
    except:
        return None

def send_data(device, value1, value2): # Sends the request.
    try:
        url = "https://industrial.api.ubidots.com/"
        url = url + "api/v1.6/devices/" + device
        headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
        data = build_json("Light measurement", value1, "Motion detection measurement", value2)
        if data is not None:
            print(data)
            req = requests.post(url=url, headers=headers, json=data)
            return req.json()
        else:
            pass
    except:
        pass
```

The token used can be found if you are logged in on ubidots and then clicking on the user profile and then select API credentials. The token can then be copied and used.


## Presenting the data

The dashboard shows the two measurements: light and motion detection. The top row shows the historical values and the bottom row shows at-the-moment views. The motion detection measurement is only presented as 0 (not detected) and 1 (detected) and it is therefore presented with an indicator that is colour coordinated. If it is green it means it has detected something. The light is presented with a gauge so that it can easily be seen how bright the room is on a scale. The data is transmitted and saved once a minute and will stay on the platform for one month. 

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

The motion detection data also has a trigger that will send an email if the detection occurs three times in a row. This means that the device has spotted something at least once in between the transmissions, for three seperate transmissions. This is done by going into ubidots and clicking on *Data* and then *Events*. Click on *Create Event* and choose the motion detection variable and add the specifics. It should be equal to 1 for three minutes to give out an alarm. You can also customize what the email should say!

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


## Finalizing the design

I think the project went really well and the final result worked as expected!  It was a good project to get to try some different components without having to worry about working with the main current. However as has been discussed earlier, the project has some room for development. If it was to actually be implemented then the lamp would need to be bigger as well as a battery for the pycom board would need to be bought. At the moment it is only the lamp that is run on battery and the rest of the circuit is driven with the USB cable from the laptop which really limits its flexibility.

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


