# Tutorial on how to build a motion triggered humidity and temperature sensor.
By: Ludwig Hurtig (lh224ap)
## Overview
This project will guide you through how to build a sensor for Temperature and Humidity that will send data when a change in pitch is detected by the accelerometer using the built in sensors on the Pysense device. It will also send a message through Discord to notify when motion is detected. Depending on previous experience with IoT this project will take between 5-15 hours.
## Objective
I chose this project because i recetly got a mailbox in the entrance to my building instead of a slot in my appartment door and i alway forget to check to see if i got mail. Therefore i wanted to take the opportunity and build a sensor that notifies me when i get mail.
I also want to learn how to connect and read data from the sensors. By collecting temperature and humidity data as well as data when i get mail, i want to get insights about how often i get mail and the temperature and humidity changes in my entrance.
I also wanted to learn how to trigger notifications using sensors.
The data will be sent from the pysense device to pybytes and visualized using their dashboard. notifications will be sent through Discord via a Webhook integration in pybytes.
## Material
As this is my first time working with IoT i chose to buy the [Fipy and sensor bundle](https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-fipy-and-sensors-bundle/) from ElectroKit. What i used from det bundle in this project was:
| Item | Description |
| ---- | ----------- |
FiPY| This is the microcontroller that reads the micropython code tha we put into it. it functions as the "brain" of our IoT device. It is also what enables us to connect the device through, in this case, WiFi. But you can also choose LTE, LoRa or Bluetooth if you want. |
| PySense  | This is a Sensor shield/expansion board for the Fipy which includes 5 sensors. this project i used the Accelerometer, Humidity and temeprature sensors. the pysense also has a micro usb port which is used to connect the device to a computer or battery. |
Wifi antennae|Used to extend the WiFi range. Connects to the FiPy.|
Breadboard|Used to connect wires to the fipy and pysense.
Jumperwires| wires to connect to the breadborad and sensors
There was a lot more included in the bundle an the total cost for everything was 1528 SEK. even though i did not use everything for this project im glad i had the option to try different things, and i can always use them later.
## Computer Setup
The device is programmed using MicroPython. Before we can start writing code we need to install a few things.
First you need to update the FiPy device firmware You can follow [this guide](https://hackmd.io/@lnu-iot/SJ91R_jSO#Part-1-Firmware-Update-amp-Running-Code-PyCom-Boards) for that. Then you have to set up your computer by:
1. Installing [Node.js](https://nodejs.org/en/).
2. Installing [Atom](https://atom.io) or your IDE of choice.
3. Install and then install the PyMakr plugin on your IDE.
[This](https://hackmd.io/@lnu-iot/SydH7MTcw) tutorial goes through all of the steps no matter what OS you are on.
To write and upload code in Atom you need to:
1. create and open a package. You can name it what you want.
2. Create a file in the package and name it, for example "main.py"
3. Then write or paste code in the file and save.
4. to upload the code to the device you click this button.

[This tutorial](https://hackmd.io/@lnu-iot/SJ91R_jSO#Mac-OS) goes in to more depth in how to flash your pycom device and also how to upload code to your device.
I use MacOS and chose Atom as my IDE for this project. I liked it alot. It was easy to use and understand and you can upload your code to the device with just a click which makes it easy to test your program step by step as you build it. In the linked tutorial they show you how to program a LED diod to blink and I recommend doing that just to see that everything works before continuing with this project.
## Putting everything together
Since this Project only uses the bult in sensors on the Pysense sensorshield we can simply connect the FiPy directly to the Pysense like the picture below: 
But i chose to use the separate breadboard because the FiPy gets hot and i think that will make the temperature data less accurate, therefore i cinnected the device like this: 
Please follow [this](https://hackmd.io/@lnu-iot/By-930cTu) guide if you want to connect the pysense via the breadboard. This enables all the sensors on the pysense to be used aswell.
## Platform
I chose to use Pybytes as my platform since in this project we only use the sensors from the Pysense and PyBytes is created by the same company Pycom. Everything is already suited for eachother in a neat way. Pybytes lets you chose your connection (In This case WI-fi) retrieves signals from your pysense which you the can use to display your data using widgets. All data is stored in their cloud for 30 days which means no local storage is needed and its also for free.
i tried using adafruit aswell because i had some trouble with understanding how to display data with the widgets on pyybytes, and i wanted to see if adafruit eould be easier. But i found it easier to use Pybytes nonetheless just because of how easy it was to setup the signals.
## The code
Most of my code for the sensors are taken from the [Pycom library](https://github.com/iot-lnu/applied-iot/tree/master/sensor-examples/Pycom%20-%20Pysense%20v1) for the pysense, except this line of code for when data should be sent to Pybytes:
```
last_pitch = current_pitch = math.floor(li.pitch())
while True:
print("Pitch: " + str(math.floor(li.pitch())))
current_pitch = math.floor(li.pitch())
if current_pitch != last_pitch:
print("Pitch changed")
last_pitch = current_pitch
if(pybytes_enabled):
pybytes.send_signal(1, mpp.pressure())
pybytes.send_signal(2, si.temperature())
pybytes.send_signal(3, si.humidity())
pybytes.send_signal(4, math.floor(li.pitch()))
print("Sent data to pybytes")
else:
print("Pybytes is not enabled")
time.sleep(10)
```
What this code does is reading the pitch from the accelerometer and comparing it to the last pitch, if its the same as before it goes to sleep for 10 seconds but if the pitch is different it will print "pitch changed" and if pybytes is enabled it will read and send data from the Temperature, Humidity and Pressure sensor and send this data to Pybytes, then it will go to sleep again for 10 seconds.
## Transmitting the data/Connectivity
The data is sent every time the pitch of the accelerometer is changed, so every 10 seconds is max, but that will not be the case. Data will be transmitted everytime i get a letter in the mailbox which triggers the accelerometers pitch. The wireless protocol i chose for this project is WiFi using MQTT transport protocols. When data is recevied in pybytes it sends a message to discord using WebHook.
## Presenting the data
This is what the dashboard shows in Pybytes:

*Fig 1. dashboard displaying the lastest reading of Temperature and humidity.*

*Fig 2. Line graph showing temperature changes through out the day.*

*Fig 3. Line graph showing humidity changes through out the week.*

*Fig 4. Bar graph displaying every time a pitch change is registered the last 12 hours.*
The data is automatically stored in Pybytes for 30 days as mentioned before.
##### Webhook: Discord.
I used an integration in Pybytes called Webhooks to make Pybytes send a message to a private discord server everytime data is sent to pybytes. use [this](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks) guide if you want to use webhooks with discord. Then go to settings in Pybytes and klick on "integration" then new inegration. Choose Webhook and paste the wbhook URL you got from discord. i followed the guide from [this tutorial](https://hackmd.io/@js225fg/B1wj3AmyF#Webhook-Discord) to set it up.
## Finalizing the design
Some pictures of the setup in the mailbox:

*Picture 1. 10000 mAh battery on the side of the box.*

*Picture 2. I taped the wiring to a cardboard which moves when a letter is inserted.*

*Picture 3. A slightly different angle.

*Picture 4. what it looks like from the outside.*
As you can see in the screenshots under the headline "presenting data" i managed to get the device to send data to pybytes whenever there is a motion detected which im super happy with! There still is some fine tuning needed on some aspects, for example the webhook messages in discord. every time data is sent to pybytes from the device i get one message per signal from the device, wich is four in total. This leads to some annoying spam every time the sensor react on a new pitch.
The pitch is also hard to set up in a way that it isnt too sensitive but still reacts to every letter that gets inserted in the mail slot. this is something i would try to finetune if i had more time. Something i will try to experiment with further after this project is the sleep time between cycles to se how often the iterations for the pitch is needed. Maybe every 10 minutes is enough as long as the device doesnt go back to some standard pitch after a few minutes hanging. I have som thoughts on a mechanism for that.
Over all i am super happy with what i learned and how it turned out. It was a fun project.