# Build a Public Locker Alarm :lock::loudspeaker: **Author:** Mika Persson - mp223tz ![](https://i.imgur.com/s5R4mEb.jpg) This tutorial aims at explaining how you can build your own public locker alarm using IoT. In short, the device consists of a microcontroller that has a PIR sensor that detects human motion which, after being triggered, sets off an alarm through a passive buzzer that is also connected to the microcontroller. After being triggered, the controller also sends a notification to the users cellphone in order for the user to quickly confront the potential thief. All the needed materials are given below and a step-by-step guide explains how to then construct the device with these, plus some theory. The project takes approximately three hours to complete. The project is part of the course [Introduction to applied Internet of Things](https://lnu.se/en/course/introduction-to-applied-internet-of-things/distance-international-part-time-summer/) given by Linneaus Univeristy. **(OBS: The reader is assumed to be somewhat comfortable with microcontrollers or at least have worked with it before, but the project can still be done by a complete beginner. Furthermore, one has to have [Sigfox coverage](https://www.sigfox.com/en/coverage))** ## Objective Except from learning how to create an IoT device, the reason why I chose to do this specific project was because I often find myself in situations where I leave my personal belongings unattended in public lockers, for example at the gym or swimming pool. The device decreases the risk of ones belongings belong stolen becaus of the built in alarm in the device, at the same time as one gets notified in an attempt of theft. Some of the insights one may gain by doing this project is how hard it is to make the PIR sensor work as one imagines how it should work, how to send and use information using the internet of things (Sigfox) and how exciting the field of IoT is. ## Material The IoT device used in this project is the Pycom LoPy4, which is suitable for IoT applications as it has multiple digital and analog general purpose input/output pins which one can connect sensors to, at the same time as the device can be connected through LoRa, Sigfox, WiFi and Bluetooth. With this, and exponsion board is used to simplify the usage of the LoPy4 device. It is assumed that the person following the project has a computer, so it is not contained in the material table below. The following table summarizes materials needed for the project: | Material | Price | Purchase link | Information | | -------- | -------- | -------- | -------- | | LoPy4 | 38€ | [Link](https://pycom.io/product/lopy4/) | Microcontroller (the brain) | Expansion board | 18€ | [Link](https://pycom.io/product/expansion-board-3-0) | Simplifies operating the LoPy4 | 37 in 1 sensor kit | 30€ | [Link](https://www.amazon.co.uk/ELEGOO-Upgraded-Tutorial-Compatible-MEGA2560/dp/B01M3TOXZN/ref=sr_1_1_sspa?dchild=1&keywords=37+sensor&qid=1627830012&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFOOUVOVFQ1R05RQUgmZW5jcnlwdGVkSWQ9QTA5NjIzMzU2MzdTQzg2UDEzN0kmZW5jcnlwdGVkQWRJZD1BMDg5MDYyNjJETlNYSVA3M08zMkgmd2lkZ2V0TmFtZT1zcF9hdGYmYWN0aW9uPWNsaWNrUmVkaXJlY3QmZG9Ob3RMb2dDbGljaz10cnVl) | Contains PIR sensor, passive buzzer and plenty more | Micro-USB cable | 4€ | [Link](https://www.amazon.com/Micro-USB-to-Cable/dp/B004GETLY2) | For powering the device. | Dupont wires | 6€ | [Link](https://www.amazon.com/Elegoo-EL-CP-004-Multicolored-Breadboard-arduino/dp/B01EV70C78/ref=sr_1_1_sspa?dchild=1&keywords=dupont+cables&qid=1627830311&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFYNDZSR1VNRDlUR1EmZW5jcnlwdGVkSWQ9QTAwMjQzNTAxWElMNDQwQlZUN0MzJmVuY3J5cHRlZEFkSWQ9QTA1MzE4NDczTE44VUNWVTFINDhEJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==) | For connecting the LoPy4 with the sensors. | Battery case | 7€ | [Link](https://www.amazon.com/LAMPVPATH-Battery-Holder-Switch-Leads/dp/B07C6XC3MP/ref=sr_1_2_sspa?dchild=1&keywords=battery+holder+3+AA&qid=1627830425&sr=8-2-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUExNVJUNzc4RlFTRjNZJmVuY3J5cHRlZElkPUEwMzQ0ODMwMkpCWE5YRVpBQVFMQiZlbmNyeXB0ZWRBZElkPUEwMDIzMTI2M09MNUpEV1ZFUERSMiZ3aWRnZXROYW1lPXNwX2F0ZiZhY3Rpb249Y2xpY2tSZWRpcmVjdCZkb05vdExvZ0NsaWNrPXRydWU=) | Makes the device portable | Antenna | 10€ | [Link](https://www.sparkfun.com/products/14676) | Enables connection with the internet of things | AA batteries | 4€ | [Link](https://www.apotea.se/varta-batteri-aa-longlife-power-10-st?gclid=CjwKCAjwjJmIBhA4EiwAQdCbxjlBJvTKlAmBPZMYDWMIeSJlbcaXLXUjAQ8nhUoWBbTo9kfaxTqh8BoCRV4QAvD_BwE) | For powering the device | Breadboard **(optional)**| 3€ | [Link](https://cdon.se/bygg-verktyg/kopplingsdack-breadboard-protoboard-400-punkter-p49343576?gclid=CjwKCAjwjJmIBhA4EiwAQdCbxlIWFwgYp8RDQstuE457EriddrUH8QANRirGPUY94LHATUnJzz5X2hoCIWQQAvD_BwE&gclsrc=aw.ds) | Simplifies the sensor-LoPy4 connections | Crimping tool set **(optional)**| 20€ | [Link](https://www.amazon.se/gp/product/B07DXM3GND/ref=ppx_yo_dt_b_asin_title_o03_s01?ie=UTF8&psc=1) | Makes the battery case connection to the LoPy4 more robust | **Total**: | **~114-137€** Note that it is not necessary to use a breadboard or battery case, but the breadboard simplifies the dupont wire connections and one may use a powerbank or computer instead of a battery case. Furthermore, the PIR sensor and the passive buzzer may be bought independently from a sensor kit. ## Computer setup The following steps walks through the setup of the connection between the LoPy4 and your computer, but also the sending of data through Sigfox and setting up the alarm notifier. To get familiarized with the LoPy4 and the expansion board, please see the following two resources: * [LoPy4](https://docs.pycom.io/datasheets/development/lopy4/) * [Expansion board](https://docs.pycom.io/datasheets/expansionboards/expansion3/) In order to prevent this tutorial from becoming to lengthy, several references are made to other guides. ### Step 0: Flash the expansion board If you have the *Expansion board V3.1* (this can be seen on the back of the board), you do not need to flash it. If not, then follow the steps in the steps in the following guide: [updating expansion board firmware](https://docs.pycom.io/updatefirmware/expansionboard/). ### Step 1: Getting started with Pybytes Pybytes is a cloud-based device management platform that will be used in this project. On their website you will create an account in order to manage your device, for example present data sent from your device. To get started, follow steps 1 and 2 in [this tutorial](https://docs.pycom.io/pybytes/gettingstarted/) and in step 2.3, choose the *Sigfox* network option. Step 3 where you provision your device will be covered further down in this tutorial. ### Step 2: Connect the LoPy4 to a computer Connect the LoPy4 and the expansion board as seen in the picture below. At the top of the figure, the onboard LED of the LoPy4 can be seen, make sure that the orientation of the boards are correct before connecting them. Under the onboard LED, connect the micro USB cable to the expansion board and your computer. ![](https://i.imgur.com/z9RRGCV.png "connect lopy4 and expansion board") ### Step 3: Update the firmware of the LoPy4 In short, *firmware* can be described as a specific computer software that provides the low-level control of a device's specific hardware. In order to update the firmware of the LoPy4, you first have to download the Pycom updater, which can be found [here](https://docs.pycom.io/updatefirmware/device/), choose the appropriate one for your operating system. On the same webpage, follow the steps given under the subtitle *Updating Device Firmware* and choose `Pybytes` at step 5. You will discover that you must supply a `Pybytes activation token`, this you can obtain from your Pybytes device profile under the `PROVISIONING` tab (this is step 2.5 from the *Getting started with Pybytes tutorial*), then selecting the `OFFLINE FIRMWARE UPDATER` option and the generate your token. This is the token you have to supply to the Pycom updater, after that you proceed by pressing `Continue` until you reach the screen looking like the one below. In order to connect to Sigfox, you have to use the given `Sigfox ID` and `Sigfox PAC` as seen in the figure below. This will be done later. If there is any problems with the drivers, you can eventually fix those problems by following [this guide](https://docs.pycom.io/gettingstarted/software/drivers/). ![](https://i.imgur.com/qNGt5Uh.png) ### Step 4: Setting up the IDE and testing the device In order to write code that will determine how the device works, a so called integrated developement environment (IDE) can be of great help. In this project, the VS Code IDE will be used to write the code, but the Atom IDE works equally fine, although it is not covered in this tutorial. In this step you will download VS Code, setup Pymakr and download NodeJS, which Pymakr needs in order to work. An easy step-by-step guide can be followed [here](https://docs.pycom.io/gettingstarted/software/vscode/). Afterwards, in the so called Read Evaluate Print Loop (REPL), also called terminal, you can test to see if your device functions correctly by running the following lines in the REPL: ```python >>> import pycom >>> pycom.heartbeat(False) >>> pycom.rgbled(0x330033) ``` these lines will turn the onboard LED of the LoPy4 purple. ### Step 5: Create a Sigfox account In order to use Sigfox, a Sigfox account has to be created. To create an account, follow the guide under the subtitle **Creating account at Sigfox backend** in [this link](https://docs.pycom.io/gettingstarted/registration/sigfox/). As a `Business Name`, you can enter anything. ### Step 6: Add Sigfox device to Pybytes In this step, a connection is made between Sigfox and Pybytes, this is done by creating Sigfox API credentials for Pybytes. Follow the steps in [this guide](https://docs.pycom.io/pybytes/networks/sigfox/) in order to do this. The communication should now be working. ### Step 7: Verify the network communication is working (optional) If you would like, you could test creating a new directory in your file explorer and open it in VS Code. In this directory, create a file `main.py` and insert the following block of code in it (note the indentation): ```python import time while True: #Select a value to send, #perhaps before this you've read from a sensor value = 5 #Send the value pybytes.send_signal(1, value) print("sending: {}".format(value)) #Sending data once every 11 minutes time.sleep(60 * 11) ``` Connect the antenna to the LoPy4 according to the picture shown in the image below. ![](https://i.imgur.com/p3CtPwH.png) If VS Code has connected to your device (seen in the REPL), press `Upload`, the button seen at the bottom of the figure below. If this generates an error message in the REPL, then try to press `ctrl+C` to generate a `Keyboard interruption` until you at least see `>>>` in the REPL, then press `Upload` again and it should work. If this still does not work, try pulling out and plugging in the USB cable from you computer or turning off and on VS Code before pressing `Upload` again. ![](https://i.imgur.com/rrqJGB5.png) ## Pytting everything together The final product should look something like the circuit diagram below + the antenna, it shows how the LoPy4/Expansion board is connected to the battery case and sensors using dupont wires. ![](https://i.imgur.com/BIpmR6l.png) ### Electric circuits in general An electric circuit is a path, or rather a closed loop, for transmitting electric current (electrons moving), which often includes electronic components as for example sensors that uses the current in the path and batteries that gives electric energy to the path. As the current travels in one direction exclusively as a consequence of the electrons travelling to a positive charge because of their inherited negative charge, the ends of the path may be refered to plus (+) and negative (-). The flow of the electric current is measured in amperes (A), which is related to the voltage (V) and resistance ( R ) of the electric circuit by Ohm's law: **V = I * R**, nicely illustrated in the picture below. ![](https://i.imgur.com/BPe9vWQ.jpg) As seen in the picture, the higher the voltage, the higher the electric energy in the circuit, and the resistance is, you guessed it, the resistance the electrons have to face in the path. In relation to the circuit diagram of the device above, one may like to visualize the electrons travelling from + to - (even though it is the other way around), hence from the red wires to the black ones called ground (**GND**). These two wires (red and black) are used for powering the electronic components. How much power the electrical components can often be found in the datasheets. In the case of this project, we need to look up the datasheets for the PIR sensor HC-SR501 and passive buzzer, these can be found easily by Googling. From these, one learns how to connect the sensors and how much voltage that should be supplied. Aside from the wires used for powering the electronic components, wires can also be used for reading and sending data. In the circuit diagram above, these are marked as **SIGNAL** wires. In our case, they are used for sending information if motion has been detected and which frequency to play for the PIR sensor and passive buzzer respectively. ### Using the PIR sensor (HC-SR501) The passive infrared sensor (PIR) is used for motion detection. Under the white globe (Fresnel lens) of the PIR sensor, there are a couple of manual customizations one can do in order to make the PIR sensor work as one wishes. These three customizations can be seen in the figure below: **Time Delay Adjust**, **Sensitivity Adjust** (two potentiometers) and **Trigger Selection Jumper**. Furthermore, one sees the pinout (how to connect the PIR sensor, which wire goes where). ![](https://i.imgur.com/EhnVFXP.png) The area of detection is presented in the following figure: ![](https://i.imgur.com/rHdCamD.png) Adjusting the **Sensitivity Adjust** is explained by the following figure: ![](https://i.imgur.com/buC3Ife.png) In our case, this will be set to three meters since the distance between the device and the potential thief will be less than a meter since the device will just need to detect motion right outside the locker. Adjusting the **Time Delay Adjust** is explained by the following figure: ![](https://i.imgur.com/PQY259n.png) The time delay determines how long the output of the PIR sensor module will remain high after detection motion. The range is from about three seconds to five minutes. In our case, this will be set to 3 seconds in order to make sure that a possible thief is caught and because a theft from a public locker is relatively quick. All motion detection is blocked during this three second period. Adjusting the **Trigger Selection Jumper** is explained by the following figure: ![](https://i.imgur.com/KVVjUv7.png) In this project, the trigger will be set to **Single Trigger Mode**, it does not actually matter which mode it is set to in this project. However, the single trigger mode would be a more robust solution in the sense that it would resend packages of data to Sigfox, which would decrease the risk of no notification being sent as a consequence of sent packages being lost. ### Using the passive buzzer The working principle of the passive buzzer is using PWM generating audio to make the air vibrate and which frequency it plays is determined by the user and sent through the **Signal** to the LoPy4 as mentioned above. ### Using a breadboard (optional) A breadboard has internal connections for making wiring easier. The picture below illustrates how the breadboard looks both outside and on the inside. One notes that the copper clips on the right half of the figure shows how one can connect wires with each other in order to create a circuit. ![](https://i.imgur.com/1vgI6IO.png) ### Making dupont wires out of the battery case wires (optional) To simplify the connections from the battery case to the expansion board, the batter case wires can be made into dupont wires using a crimping tool. Because the battery case wires are fragile and frayed, they are not so easy to manage, therefore it is desirable to make these into easy-to-use dupont wires. The following video gives a tutorial on how to do this: [create dupont wires](https://www.youtube.com/watch?v=ARAm0fJLib0). ## Platform In order to get notifications from the device, the free service If This Then That ([IFTTT](https://ifttt.com/home)) was used. One can briefly describe this service as a tool for managing responses to events that happen in the world, everything from different results in the Olympic Games to motion detection from the device in this project. After our device has detected motion, it sends this information to Sigfox, and then further more to IFTTT using a webhook (discussed later). The choice of this platform was because it is easy to set up such a notifier and there is not any redundancies in the storage or sending of data. ## The code The following flowchart illustrates the anatomy of the code. The Github repository for this project can be found [here](https://github.com/mikapersson/PublicLockerAlarm). ![](https://i.imgur.com/CDyBx81.png) The file hierarchy of the project is the following: ![](https://i.imgur.com/L4Klirk.png) where the project directory is named `PUBLICLOCKERALARM` and the `lib` directory contains the libraries, these are files that manage the electric components and general help methods which makes the `main.py` file more readable and not so cluttered. The table below shows briefly explains each of the relevant files: | File | Description| | -------- | -------- | buzzer | Library that manages the buzzer, both by bookkeeping each note-frequency pair and sending the commands to the buzzer to play. | onboard_LED | Library that contains commands (functions) for managing the LoPy4 onboard LED. | pir | Library that contains the function for reading the PIR input for motion detection. | main | Contains the main code, illustrated in the flowchart above. | The rest of the files that were not mentioned are not relevant for the end product of the project and can thus be removed. The `boot` file is the file that is first executed when the LoPy4 is powered, here, as an example, a network connection to WiFi can be established, but since Sigfox is connected to automatically without having to use any specific lines of code, the `boot` file can be empty in our case. Only the source code for the `main` file will be shown, the rest can be seen in the project Github repository linked above. ### The `main` file The main parts of this file has already been discussed, but the comments in the source code may give some more detailed explanations. ```python from onboard_LED import LED_alarm, LED_off, LED_sleeping from buzzer import play_alarm from machine import Pin from onboard_LED import * import time """ Main Code """ LED_off() print("Sleeping") LED_sleeping() time.sleep(10) # sleep for ten seconds, this gives enough time to close the locker # IDEA: Talk to the pycom through a phone in order to determine if the alarm should be ready or not LED_off() # Some constants pir_pin = Pin("P17", mode=Pin.IN) # Main Loop while True: # Check the input from the PIR sensor motion_detected = pir_pin() # If the PIR sensor detects motion, the alarm goes of and a notification is sent to the owner if motion_detected: print("DETECTED SOMETHING") LED_alarm() # Sending data through Sigfox to Pybytes and then to IFTTT through webhook pybytes.send_signal(3, motion_detected) print("Sent detection to Pybytes") # Play alarm play_alarm() LED_off() time.sleep(2) ``` ## Transmitting the data / connectivity As mentioned, when the PIR sensor detects motion, the device send this PIR reading, the number 1 as in `True`, to the Sigfox network. Thus, the wireless protocol that is used is Sigfox. What makes Sigfox suitable for this project is that the user does not manually have to access the WiFi of the gym or train station for example in order to set up a connection between the device and that specific local WiFi. Instead, the device can be used anywhere where there is Sigfox coverage, which is quite effective (as long as there is coverage). Hopefully, data is not sent so frequently because this would indicate that there has been an attempt of theft in one's locker. Ideally, the device only sends one signal to Sigfox, which is when a connection has been established after the device has been turned on. Because the size of the data sent from the device to Sigfox is so small, the energy consumption of the device is better preserved. The antenna design may affect the battery consumption and the there may be some large path loss since the device will operate inside a locker which is inside a building, meaning that there may be some disturbances in the propagation from the device to the base station receiver. Because of this challenge, the device should maybe have used WiFi instead of Sigfox since a WiFi connection may be more robust for the device's purpose. More information on this can be found [here](https://build.sigfox.com/antennas). ### Setting up IFTTT and webhook to Sigfox The transport protocol between Sigfox and IFTTT is webhook. Through this webhook, Sigfox forwards the received data from the device to IFTTT. Afterwards, IFTTT sends a notification to the mobile app where the user can get notified. The following steps goes through everything from the setup of the IFTTT account to the setup of the notifier. ### Step 1: Create an IFTTT account You have to [create an account](https://ifttt.com/join?psu_=1) at the IFTTT website in order to setup the webhook and notifier. ### Step 2: Create an Applet At the top right corner of homepage of IFTTT, press the **Create** button to the left of your user profile logo, you will then see the following screen: ![](https://i.imgur.com/TkWA0o0.png) Press the large black button **If This Add**, you will then choose a service to use. In the **Search services** textbox, enter `Webhooks` and press it's logo after it popped up. You will then choose one of two possible triggers, choose the left one saying **Receive a web request** and then enter an **Event Name** which suitable describes the event. This could for example be "PIR_detection". Now you have created an "If", next you should create an "Then That" by pressing the large black button **Then That** which was gray before and is below the now blue **If** button. As before you should choose a service. Because we would like to receive a notification when the trigger in the "If" statement has been triggered, we choose the service `Notifications`. The action that is then choosed is the one to the left saying **Send a notification from the IFTTT app**, afterwards you can enter a suitable notification message. This message could for example be "The alarm has been triggered!". Next, you press the large black button saying **Continue** and then you are done setting up the applet. ### Step 3: Get URL pattern To create a callback in Sigfox, an URL pattern has to be supplied to the callback, this is where the data will be forwarded. In our case, this will be the webhook that was created in IFTTT earlier. There, on the IFTTT homepage, go to **My services** shown in the picture below. ![](https://i.imgur.com/FRU4GQX.png) Your services will then be shown, choose **Webhooks** and then press **Documentations**. This will open up a new tab in your web browser which will look the picture below. ![](https://i.imgur.com/qn0et7N.png) What is of interest here is the URL displayed below **Make a POST or GET web request to:**. Copy this, as it will be used in the next step. ### Step 4: Create callback in Sigfox backend Go to the Sigfox backend website, click on the **Device** button at the top of the screen and then click on your device type below **Device type** shown in the figure below: ![](https://i.imgur.com/r944me1.png) Next, click on the **CALLBACK** button to the left as seen in the figure below: ![](https://i.imgur.com/LVxJ19V.png) We would now like to create a new callback, therefore press **New** at the top right corner of the screen as seen in the following figure: ![](https://i.imgur.com/xa1rRIr.png) You will then choose **Custom callback** and choose the dropdown boxes as seen in the figure below and enter your URL pattern that you obtained in step 3 above: ![](https://i.imgur.com/qlDnCBV.png) Then press the **Ok** at the bottom. ### Step 5: Download the mobile IFTTT app Download the IFTTT on your phone and enable the app to send notifications. ## Presenting the data The data is presented in a Pybytes dashboard, for a tutorial on how to setup your own dashboard in Pybytes, follow [this tutorial](https://docs.pycom.io/pybytes/dashboard/). The picture below illustrates what the data looks like. As one can see, only data points with a value of 1 is sent, this is because the device only sends data when the PIR sensor detects motion and sends this value as a 1, corresponding to the boolean value `True` in python. ![](https://i.imgur.com/xCp4A8f.png) ## Finalizing the design The device has not gone through a thorough testing in order to optimize it for practical usage in real environments as a gym locker room for example. Because of this, the device might still need some polishing in the form of the code, since this determines how the device works with the input (PIR) and output (buzzer and data sending). As for now, at least the device works as an alarm for protecting one's food from other people living in the same home, the youtube video below illustrates this :smile: (although WiFi could have been used in stead of Sigfox in this case, but that is for another tutorial) <iframe width="560" height="315" src="https://www.youtube.com/embed/Y95Zn9cd7b0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> Except from running experiments in actual public lockers, in the future, it would be nice to construct and print a 3D printed case for the device so that the device becomes easier to use and more robust. Other approaches would be to replace the PIR sensor with a light sensor since it would make the device less complex and the light sensor would respond to someone opening the locker, letting light into the locker. One could maybe also have used a distance sensor that would be triggered if someone opens the locker as a consequence of the greater distance between the sensor and the locker door. However, this last approach may fail if the thief stands at the same distance as the the locker door, but this of course depends on how one implements the device.