---
# System prepended metadata

title: Karolin Pettersson Project report IOT
tags: [school project IOT]

---

# Karolin Pettersson Project report IOT

###### tags: `school project IOT`

Name: Karolin Pettersson 
Student credentials: kp222pj

# Tutorial on how to build a knocking sensor for your front door

## Overview

This tutorial on how to build a knocking sensor that you can place at your front door. The purpose is to know if someone came to visit you while you weren't home. This project was made within the course of IOT Introduction at Linné University of Sweden.  Estimated time for this project is 80 hours but of course it can vary depending on your skillset.

## Objective
I chose this project because I have recently moved in to a new apartment complex and want to know if someone came knocking on my door while I was not there. Another reason is also because if I am home I want to know if someone came knocking and I did not hear it, like when you have home deliveries that you might have missed. So the purpose of this project is to store data on the knocks you have had on your front door in order to give you more insight on who came to see you or if you missed and when. The project has given me an insight in how to build IOT solutions compared to my previous courses where we only discussed its implications seeing that I have studied Interaction Design.

## Material
**I bought these two products from Electrokit:**
1. 995 kr https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/
2. 299 kr https://www.electrokit.com/produkt/sensor-kit-26-moduler/

Looking back I could have bought much less but I think they will be fun to have for future projects.

**From what I bought I used:**
- LoPy4 with headers (development board and wireless radios)
- Expansion board (allows for fast and easy connection to the development board and power)
- Antennae (wifi antennae)
- Micro USB cable (connect to computer)
- Breadboard (makes it easier to connect sensors)
- 3 wires (connects the sensor to the expansion board)
- Knocking sensor (senses vibrations and knocking): https://www.electrokit.com/en/product/knock-sensor/)

## Computer setup
I used my own MacBook Pro (Early 2015) for this project. I used Visual Studio Code because that is the IDE that I am used to. I installed Pymkr and had Python3 already installed on my computer.

Installation of Pymkr:
1. Go to Visual studio codes marketplace. 
2. Go to the plugin for Pymkr, direct link: https://marketplace.visualstudio.com/items?itemName=pycom.Pymakr
3. Install the plugin
4. It went smoothly for me but if you have problems you can go to: https://code.visualstudio.com/docs/editor/extension-gallery

Uploading the code:
I upload my code by clicking on the three dots in the right corner. *See picture.* Start with some generic code in order to know its working correct. I learned that in Visual studio code, maybe others as well, it can be a red line under some code but that does not neccessarily mean it's something wrong so try to upload anyhow and then start investigating.
![](https://i.imgur.com/x5Ll3kT.png)

## Putting everything together
I have connected everything as the picture shows below.

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

This is a development setup even though my ambition was to 3D print a case and have it on my front door but due to life getting in the way, I have to make that outside of this course.

Make sure you look at the datasheet of the sensor in order to know how to connect it. Here you can find the  datasheet: https://www.electrokit.com/uploads/productfile/41015/41015735%20-%20Vibration%20Shake%20Sensor.pdf 

Observe that the datasheet is for Arduino. By teacher instruction I used Pin 16 on my Lopy4 Pycom device for data. I was really close on mixing up the power and ground wiring which could have been problematic to say the least so be careful of reading the instructions. I used 3V3 and that worked fine but according to the datasheet it is 5 volt. 

## Platform
I used Pybytes as the platform where the data is stored in the cloud and the protocol is MQTT. I chose the free subscription because it had everything I needed. I set up signals that I then displayed on the dashboard. If I where to scale this idea, like for selling it, I would need to create maybe an application to make it more accessable on the market.

I had some trouble connecting my device to it so make sure you are doing everything in the right order:
1. Add your network (make sure it is a real network and the password is correct)
2. Remember to deploy the configuration.
3. Then go to provisioning and choose how you want to activate.

The mistake I did was that I changed the network credentials and forgot to deploy and then spend a couple of hours on the activation part which obviously did not work...

## The code
```python
# imports modules
import _thread # makes launching of threads available
from machine import Pin # needed in order to select which pin is current
import time # in order to use functions related to time
import utime # --

p_in = Pin('P16', mode = Pin.IN) # assigns the variable p_in with the correct pin

def convert(seconds): # function for converting seconds in to hours, minutes and seconds
    seconds = seconds % (24 * 3600)
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60
    return "%d:%02d:%02d" % (hour, minutes, seconds)

def send_env_data(): # function for sending the data
    timeout = 60 # see comment on line 20
    timeout_start = time.time() # see comment on line 20
    while time.time() < timeout_start + timeout: # Change this to 'while True:'' if you do not want a time limit and put # before the two lines above
        value = p_in() # assigns the variable 'value' with either 0 or 1 depending on the value of the sensor
        n = utime.time() # assigns 'n' with a time stamp in seconds
        currentTime = convert(n) # converting the seconds by using the function convert as mentioned above
        print(currentTime) # printing out the current time (not neccessary unless in development mode)
        if value == 0: # if value is 0 then execute the two following lines
            pybytes.send_signal(0,currentTime) # sends signal '0' to pybytes with the value of the variable 'currentTime'
            print("A knock was detected") # printing out a string (not neccessary unless in development mode)
        else: # if the value was not 0 then nothing is being sent
            print("Silence...") # printing out a string (not neccessary unless in development mode)
        time.sleep(0.1) # wait for 0,1 seconds before continuing to execute the code

_thread.start_new_thread(send_env_data, ()) # starts a new thread and return its identifier, executing 'send_env_data'
```

## Transmitting the data / connectivity

- If there is data to be sent, it is sent every 0,1 seconds. I found that 1 second was a bit to long for a knock. It sends a signal containing a 0 and a value to Pybytes over wifi. The size of each signal is 11 Bytes.
- As I mentioned before, a knock doesn't always last a second which is why the interval had to be shortened. I found that you could have  a separate thread that would be constantly listening for knocks and updating an internal variable whenever it detected a knock. My main program could then ask the other thread if it had detected a knock within the second, which would reset the variable. This solution was a bit too complicated to implement me but that is what I would have prefered.
- I used WiFi as the wireless protocol because when I am finished with the final product it would be the easiest way for me to maintain it and also because it would be used on short range. 
- I used MQTT as the transport protocol to send signals to Pybytes.

## Presenting the data
I first sent both the detected knocks and every occasion where there wasn't a knock. *See picture below.* 
![](https://i.imgur.com/heQ7ovD.png)

I quickly realized that this would be to much data if it where on for a while so then I changed it to just send data when there was a knock. *See picture below.* 

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

The value I send with it is a time stamp that says for how long after I turned on the device, the knock came. I built the dashboard by using the built in functions in Pybytes, by creating signals and putting them on the dashboard and then reorganized the dashboard. If there is a continuous knock, data will be saved every 0,1 seconds in the database but will be presented within the same second. 

The time limit is 1 month in Pybytes but there is integrations available. There is also a maximum limit of 5MB data. But the way this is intended to use, as long as you are not away from your home for months it is fairly easy to reset the data once you've looked at it to see if someone came by.

## Finalizing the design
It was overall interesting but some parts were harder and/or took longer time than other. I think it will go alot faster now that I have done it once. It was surprisingly easy to get started by using example code etc. but when it was time for me to start on the project and for transmitting the data it took a little more of my time to get it right.

The final result in the frame of this course:
![](https://i.imgur.com/m1IaNHu.jpg)

My goal is to print one of these with my 3D printer in order to hang it on the door: https://www.thingiverse.com/thing:3655877

And work on tidying up in the code and making the transmitting of the data a bit more efficient.

Overall, it was a hard but interesting course and I learned alot of new stuff. My goal with this course was to learn how some lines of code can make something blink or do something which I feel like I have learned.

---

*Thank you for reading!*