Amidala Hoffmén
Student credentials: ah226gq
## Project overview
This is a simple IoT project that detects when the kitchen cabinet door is opened using a digital hall sensor and a magnet. When the sensor stops detecting the magnet, it means that the cabinet door has been opened. It notifies you by email when it detects that the cabinet door has been opened.
The estimated time to complete this project is 1-3 hours depending on how much experience you have with coding and with IoT.
## Objective
My cat is very smart and has learned how to open the kitchen cabinet, because she knows her food is in there. She now knows how to open the cabinet and steal food without anyone knowing. This project aims to notify me when she opens the cabinet, enabling me to prevent her from overeating.
Monitoring a cat's food intake is crucial, and this project will assist me in tracking her food consumption. I can adjust her portion sizes and feeding schedule by knowing when the kitchen cabinet has been opened when it shouldn't have been.
I track when the door gets opened, which means I can learn about when my cat wants to eat food. I could start to give her smaller portions more often, based on which times she most likely is to open the kitchen cabinet.
Additionally, this project could be used on any door, not just kitchen cabinets. You could apply this project on which ever door you wish to monitor.
## Material
| Item | Description | Price and link | Picture |
| ---- | ----------- | -------------- |---------|
|Hall-effect sensor digital|A sensor used to detect magnetism. When the sensor no longer detects a magnet, it indicates that the door (in this case) is open.| 39.00 SEK <br /> [Electrokit](https://www.electrokit.com/en/product/hall-effect-sensor-digital/)| |
|Raspberry Pi Pico W|A wireless microcontroller. |98.00 SEK <br /> [Electrokit](https://www.electrokit.com/produkt/raspberry-pi-pico-w/) | |
|Breadboard|A solderless breadboard with 840 tie-points. A smaller board could also be used for this project.|69.00 SEK <br /> [Electrokit](https://www.electrokit.com/en/product/solderless-breadboard-840-tie-points-2/) |  |
|USB cable A-male – microB-male 1.8m|A USB 2.0 cable, USB A to USB B micro, used to connect the microcontroller to a computer and powerbank.|39.00 SEK <br /> [Electrokit](https://www.electrokit.com/produkt/usb-kabel-a-hane-micro-b-5p-hane-1-8m/) |  |
|Jumper wires 40-pin 30cm male/male|40-pin jumper wire with connectors on both ends, used to connect the sensors to the microcontroller.|49.00 SEK <br /> [Electrokit](https://www.electrokit.com/en/product/jumper-wires-40-pin-30cm-male-male/) |  |
|Jumper wires 40-pin 30cm female/male|40-pin jumper wire with connectors in both ends for use with breadboards and headers. |49.00 SEK <br /> [Electrokit](https://www.electrokit.com/en/product/jumper-wires-40-pin-30cm-female-female-2/) |  |
|Magnet Neo35 Ø5mm x 5mm |Magnet used with the digital hall sensor |11.00 SEK <br /> [Electrokit](https://www.electrokit.com/en/product/magnet-neo35-o5mm-x-5mm-2/) |  |
## Computer setup
There are steps that needs to be followed for the computer setup. The first thing we need to do is chose an IDE to use. I chose Visual Studio Code as my IDE. I use a computer with Windows 10, so the installation can vary depending on which computer you have.
**Step 1: Installing Visual Studio Code and Pymakr Plugin**
Follow these steps to install Visual Studio code as your IDE and to install the pymakr plugin.
1. Download and install [Node Js](https://nodejs.org/en)
2. Download and install [Visual Studio Code](https://code.visualstudio.com/Download
3. Launch Visual Studio Code
4. Click on the Extensions icon on the left sidebar (or press Ctrl+Shift+X).
5. Search for "Pymakr" in the Extensions Marketplace.
6. Click "Install" to install the Pymakr plugin.
7. Close and reopen Visual Studio Code to apply the changes.
A more detailed tutorial can be found [here](https://hackmd.io/@lnu-iot/rkiTJj8O9)
**Step 2: Downloading and Updating Firmware on Raspberry Pi Pico W**
Follow these steps to download and update the firmware on you Raspberry Pi Pico W Board, and also test the board.
1. Download the MicroPython firmware for the Raspberry Pi Pico W from the official [MicroPython website](https://micropython.org/download/rp2-pico-w/).
2. Connect your USB cable to the Raspberry Pie Pico.
3. Press and hold the BOOTSEL button on the Raspberry Pi Pico W.
4. While holding the BOOTSEL button, connect the USB cable to your computer.
5. Release the BOOTSEL button.
6. You should see a new USB drive named "RPI-RP2" on your computer.
7. Copy the downloaded MicroPython firmware (UF2 file) to the "RPI-RP2" drive.
10. Wait until your board automatically disconnects and reconnects.
11. Test your board by putting in this snipped of code after the >>> symbols <br /> ``` print("Good luck with your studies, from LNU!") ```
12. The same text should be responded back to you.
A more detailed tutorial can be found [here](https://hackmd.io/@lnu-iot/rkFw7gao_)
**Step 3: Creating a New Project in Visual Studio Code**
Create a new project in Visual Studio Code.
1. Open Visual Studio Code.
2. Click on the "Explorer" icon on the left sidebar (or press Ctrl+Shift+E).
3. Click on the "New Folder" icon to create a new folder for your project.
4. Open the newly created folder.
5. Right-click in the empty space and select "New File" to create a new file.
6. Name the file "main.py".
7. Add your development device to the new project.
A more detailed tutorial can be found [here](https://hackmd.io/@lnu-iot/B1T1_KM83)
## Putting everything together
I connected the sensors and microcontroller on the breadboard like this image shows:

Use male-to-male jumper wires to connect the Raspberry Pi Pico to the breadboard (red, blue, and black wires). The green, white, and gray wires are male-to-female jumper wires. The reason for using male-to-female wires is to have the sensor placed outside the breadboard, allowing it to be taped inside the cabinet.
## Platform
The platform that was chosen was Ubidots [(link here)](https://ubidots.com/). I am using the free trial of Ubidots, but there is also a free version called Ubidots STEM. After the free trial, the version I am using will cost $49 / month. I have not tried Ubidots STEM, but it could work similarly. I chose Ubidots because of its user-friendliness and because of the option to send out an email whenever an event occurs. You get 100 free emails a month with the free trial version of Ubidots. Ubidots also allows users to visualize the data easily with different dashboards.
## The code
The code is contained in a single file named `main.py`.
In this file, I am setting up the wireless internet connection, and also connecting to Ubidots and sending the data to Ubidots.
**Important things to change in this code:**
- The TOKEN variable should be replaced with your Ubidots token, which you can obtain from Ubidots by clicking on your profile picture in the top-right corner, selecting "API Credentials," and copying your token from there.
- DEVICE_LABEL should be what you chose to name your device on Ubidots.
- VARIABLE_LABEL should be what you chose to label your sensor on Ubidots.
- WIFI_SSID should be the SSID of your network.
- WIFI_PASS should be the password of your network.
```python=
import network
import urequests as requests
import machine
from time import sleep
import random
TOKEN = "Your_Ubidots_Token" #Put here your TOKEN
DEVICE_LABEL = "Your_Device_Name" # Assign the device label desire to be send
VARIABLE_LABEL = "Your_Sensor_Name" # Assign the variable label desire to be send
WIFI_SSID = "Your_WiFi_SSID" # Assign your the SSID of your network
WIFI_PASS = "Your_WiFi_Password" # Assign your the password of your network
DELAY = 5 # Delay in seconds
# Function for WiFi connection
def connect():
wlan = network.WLAN(network.STA_IF) # Put modem on Station mode
if not wlan.isconnected(): # Check if already connected
print('connecting to network...')
wlan.active(True) # Activate network interface
# set power mode to get WiFi power-saving off (if needed)
wlan.config(pm = 0xa11140)
wlan.connect(WIFI_SSID, WIFI_PASS) # Your WiFi Credential
print('Waiting for connection...', end='')
# Check if it is connected otherwise wait
while not wlan.isconnected() and wlan.status() >= 0:
print('.', end='')
sleep(1)
# Print the IP assigned by router
ip = wlan.ifconfig()[0]
print('\nConnected on {}'.format(ip))
return ip
# Builds the json to send the request
def build_json(variable, value):
try:
data = {variable: {"value": value}}
return data
except:
return None
# Random number generator
def random_integer(upper_bound):
return random.getrandbits(32) % upper_bound
# Sending data to Ubidots Restful Webserice
def sendData(device, variable, value):
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(variable, value)
if data is not None:
print(data)
req = requests.post(url=url, headers=headers, json=data)
return req.json()
else:
pass
except:
pass
# Connect to the WiFi
connect()
# Your device
hallSensor = machine.Pin(28, machine.Pin.IN)
led = machine.Pin("LED", machine.Pin.OUT)
while True:
val = hallSensor.value()
if val == 1:
led.value(1)
else:
led.value(0)
returnValue = sendData(DEVICE_LABEL, VARIABLE_LABEL, val)
sleep(5)
```
Rows 69-77 contain the code that returns either 1 or 0 every 5 seconds. A value of 1 indicates that the sensor is detecting a magnet, indicating that the cabinet is closed. A value of 0 means that the sensor is not detecting a magnet, indicating that the cabinet door is open. The LED is used to visualize the sensor value on the microcontroller but is not necessary for the project to function. You can remove the LED-related code to simplify it to this instead:
```python=
while True:
val = hallSensor.value()
returnValue = sendData(DEVICE_LABEL, VARIABLE_LABEL, val)
sleep(5)
```
It would not make much of a difference except that the led on the microcontroller will not turn on and off depending on the value of the hallSensor.
## Transmitting data / connectivity
The data is transmitted with WiFi protocols, because the cabinet is at home, I did not need to use a LoRa device for example. WiFi has limited reach, but this project does not need long range communication.
The data is sent over to my dashboard on Ubidots with HTTP requests (REST API). The data is sent every 10 seconds, which feels like enough to check if the cabinet is open. It is never opened for less that 10 seconds when its my cat that is opening it, and it doesnt matter if it misses sometimes when I am opening it for just a few seconds. If I wanted to track how often I open the cabinet, I would have the data get sent more often.
## Presenting the data
I am using Ubidots dashboards. I have one dashboard which is a gauge widget. It shows if the data is either 0 or 1. If it is on 1, it means that the cabinet door is open, as you can see on the image below. If it is on 0, it means that the cabinet door is closed.

I can also explore the data using the "Explore Data" option on Ubidots. This shows the average value of the sensor over a chosen period, helping me identify when the cabinet is opened most frequently.

The higher the line goes, the more frequently the cabinet is open during that time. This visualization helps me identify the times when the cabinet is opened most frequently. The data is preserved for 30 days.
When the value of the sensor is 1, I get sent an email. This is happening because of an event i made in Ubidots. The downside of this is that I also get sent an email whenever I open the cabinet.

## Finalizing the design
To ensure proper functioning, I taped the digital hall sensor inside the cabinet where the magnet is close enough for the sensor to detect when the cabinet is closed. I positioned the sensor as shown in the image below:

The magnet is placed on the inside of the cabinet door, as depicted here:

This means that when the cabinet door gets closed, the magnet is close enough for the sensor to detect it, and when the door gets opened, the sensor can not detect the magnet anymore.
For future improvements, it would be beneficial to detect in some way if its me that has opened the cabinet, or if its my cat. I could have added a vibration sensor by the cats food, which would remove a lot data from when its me that opened the cabinet.
Something else that could have been done is to use a 3D-printer to hide the setup more and make it look better.
