# Building a simple magnet detector that can be used for home security by Minsun Jung (mj224vw) ## Project Description A simple magnet detector with alarm function that can be used for home security. ESP32 development board is the microcontroller for this project. We are using Arduino IDE and it's programmed by c++. (Unfortunately, Arduino IDE does not support MicroPython). WiFi is wireless protocol and MQTT is the transport protocol. The cloud platform Ubidots is used for data visualization. Estimated time: 10-20 hours (depending on your previous experience with IoT). ## Objective One of my neighbors got a new balcony door and was very happy until she discovered that it can be opened from outside. The issue was solved by adding an extra lock. However, it motivated me to build this magnet detector. It turned out to be a good choice for me as I had no experience with IoT before but was curious to know how the Internet of Things actaully works. The purpose of this project is to monitor door for security. Logic of this project is very simple: 1. Hall sensor detects the magnetic field and sends the data. (Door status: closed) 2. If the sensor does not detect the magnetic field (Door status: open), the cloud platform (Ubidots) will trigger warning. 3. The user can be notified by email. In addition, given that ESP32 has many built-in features (e.g. WiFi, Bluetooth, Hall sensor, temperature sensor and led, etc.) with inexpensive price, it would make easy for beginners to try out IoT project and get exposed to modern technology in a fun way . ## List of material | Item | Picture | Description | Price & Link| | --------------- | ------------------------------------ | --- | ------------------ | | ESP32 DEVKIT DOIT | ![](https://i.imgur.com/Q8W0iwd.png) | Microcontroller ( with built-in Wi-Fi & Hall sensor) Hall sensor detects the magnetic field of its surrounding. | SEK 94 & Sizable [(here)](https://sizable.se/P.CE9S1/ESP32) | | Micro USB cable | ![](https://i.imgur.com/nxDdLWO.png) | A data transferrable USB cable. It is used to power the device. | SEK 18 & Sizable [(here)](https://sizable.se/P.VC1YX/Micro-USB-kabel-50-cm) | | Magnet | ![](https://i.imgur.com/3dhsG1k.png) | Magnet is used for the detection of the magnetic field by Hall sensor | SEK 89,90 & [(here)](https://www.clasohlson.com/se/Neodymmagnet/p/31-1467) | | Total | | | SEK 202 | ## Computer setup Some setups are required in order to start programming on your ESP32. **Step 1 Installation of board driver** **Purpose**: To let our computer recognize ESP32 board and communicate with it **How to install**: Go to [this link](https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers) and download the CP21Ox driver for your operating system. Note that the operating system used in this project is Windows. (We can find the guideline for other operating systems in the aforementioned link.) Check your Windows Device Manager. If succesfully installed, it should include a port as seen in the image below: ![](https://i.imgur.com/fGmXH7B.png) **Step 2 Installation of Arduino IDE** **Purpose**: To let us (humans) communicate with our microcontroller IDE stands for 'integrated development environment' and the role of IDE for this project is basically to write code and flash program onto our microcontroller. (e.g. We type codes => We execute codes => We got the codes that we wrote on IDE (on PC) onto our ESP32) We need to check if our choice of IDE supports the language we want to use. The original idea for this project is to program in Micropython as it is known to be ideal for beginners. When tried installing some IDEs that support micropython (for example Atom and Thonny), bugs occurred randomly and repeatedly. Due to such instability, Arduino IDE is chosen for this project. Except that Arduino IDE does not support Micropython, Arduino IDE was the best choice for this project. The following points may summarize why: 1. Compatibility with ESP32 2. An easy access to its library for Wi-Fi and HTTP/MQTT protocol. 3. Stability: bugging issues didn't occur at all. Alright! It's time to get going! **How to install** 1) **Arduino IDE** The latest version can be downloaded from Arduino's official website [(here)](https://www.arduino.cc/en/software) and detailed instruction for installation can be found [(here)](https://https://docs.arduino.cc/software/ide-v2/tutorials/getting-started/ide-v2-downloading-and-installing#the-arduino-ide-20). 2. **Add-on for ESP32 board** Once you are done with the above, you need to install add ESP32 add-on in Arduino IDE. Why this step is required? It is because Arduino IDE does not support ESP32 by default. However, through installing the add-on in Arduino IDE's board manager (which is very simple), Arduino IDE can work with ESP32. Do not forget to hold "Boot" button on ESP32 during the hole process. Otherwise, it does not work. Open the Arduino IDE => Go to [File] => Click [Preferences] ![](https://i.imgur.com/sQ0Mfqs.png) Type or copy/paste [this link](https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json) into the "Additional Board Manager URLs" field => Click [OK] ![](https://i.imgur.com/zOBzx0q.png) Go to [Tools] => [Board] => [Boards Manager] ![](https://i.imgur.com/QgwW6so.png) (image source: https://randomnerdtutorials.com) Search & Install ESP32 ![](https://i.imgur.com/hU6ZrTB.png) ![](https://i.imgur.com/GYj9XDr.png) (image source: https://randomnerdtutorials.com) That's it! We can now write code on Arduino IDE. ## Putting everything together ESP32 board has versatile built-in features and for this project, Wi-Fi, Hall sensor and led lights were used. (See the blue circle in the image. That's where the Hall sensor is located.) This powerful feature allows us to perform this project without assembling any circuit. Just connect your ESP32 to your PC with micro USB cable. ![](https://i.imgur.com/9MxEG9d.png) (image source: https://anantawijay.medium.com/discovering-its-true-potential-hall-effects-and-touch-sensor-in-esp32-1abca6b9d030) ## Platform In order that we can save, monitor and analyize the data transmitted by ESP32, we need to use either local server or online service. Choice of platform for this project is the cloud platform Ubidots. Another online service called 'Adafruit' was tested but Ubidots was appealing for this project. Why? See the below. 1. Beginer-frienldy and functional Dashboards 2. Simple way to 'create event' and 'get notified' via e-mail/sms 3. Individual Support: in case that we need assistance to send data from our device to Ubidots, 1:1 chat help can be offered For more information, click and visit their official website here: [Ubidots](https://ubidots.com/) & [Adafruit](https://io.adafruit.com/). In regards with the service fee, Ubidots offers both a free (called STEM) and paid subscription. To complete this project, STEM is enough as it covers the most. (e.g.: using dashboard, creating the event, being notified by e-mail/sms) Just be aware that there is limit on data ingestion(4,000 dots per day), extraction(500,000 dots per day) and retention (1 month). Check [here](https://help.ubidots.com/en/articles/639806-what-is-the-difference-between-ubidots-and-ubidots-stem) if you want to check the comparison between Ubidots STEM plan and Ubidots commercial license. ## The Code The code for this project can be found [here](https://github.com/vvvv0904/mj224vw/blob/main/(ESP32)%20building%20a%20simple%20magnetic%20detector%20for%20home%20security%20(door%20alarm)). The below chart shows the logic structure of this project. ![](https://i.imgur.com/XaSPJ4H.png) We are using WiFi as wireless protocol and MQTT as transport protocol. While WiFi library can easily be added with just a line of code: #include <WiFi.h>, PubSubClient library(that supports MQTT) can be imported by the following steps. On Arduino IDE'S menu bar: Go to [Sketch] => [Include Library] => [Manage Libraies] ![](https://i.imgur.com/FWVR1TQ.png) Then, search for PubSubClient and install it. ![](https://i.imgur.com/oSQrxcL.png) Once the installation is made, we can continue coding on Arduino IDE. ![](https://i.imgur.com/POD3OVB.png) It is important to type your WiFi ssid, password, Ubidots' Token, MQTT client name and device & variable API labels. As for the Ubidots token and device & variable's API labels, we can get them from our Ubidots accont. The guidelines are here: [[TOKEN]](https://help.ubidots.com/en/articles/590078-find-your-token-from-your-ubidots-account), [[Device & Variable API Label]](https://help.ubidots.com/en/articles/693566-where-can-i-find-the-variable-id) We can run the code on Arduino IDE by clicking [Verify 'V'] => [Upload '=>'] icon on the menu bar. Again it is important that we hold the "Boot" button on ESP32 until the uploading is done. ![](https://i.imgur.com/5ZPi501.png) We can test our code on Arduino IDE's serial monitor by clicking the magnifying glass icon on the right side of the menu bar. If sucessfully performed, we can get to see the below result. ![](https://i.imgur.com/z5zoaKT.png) ## Transmitting the data / connectivity There are various options for wireless technologies such as WiFi, Bluetooth, LoRa and Zigbee. For this project, WiFi has been chosen as the wireless protocol to connect to the internet. Why? 1. To make good use of ESP32's powerful built-in WiFi feature 2. It will be tested at home so it does not require long range communication 3. The device is powered via USB cable (not by batteries). So, no concern for unstable data transmission even though the data will be sent continuously. In regards with transport protocols, MQTT was chosen for this project. While HTTP is popular and widely used , a publish/subscribe model based MQTT is considered to be more suitale for Iot devices nowadays. Merits of MQTT is well explained on its official website [[mqtt.org]](https://mqtt.org/). ## Presenting the data **Dashboard** As previousl mentioned, Dashboard is very simpe to build on Ubidots. Click [HERE](https://help.ubidots.com/en/articles/2400308-create-dashboards-and-widgets) for the instruction. Here is the example of on how Ubidots' dashboard could look like. ![](https://i.imgur.com/lSzeaAA.png) As for widget, Gauge is chosen for hall sensor and switchs is chosen for LED. Otherwise, there are many other options to choose. If we click the plus sign on the right top of the dashboard page, we can get to see other variant of gadget. ![](https://i.imgur.com/WwlF3j9.png) We could have added a line chart as well but there is another way to view data on a line chart in stead of just adding new widget. ![](https://i.imgur.com/wziSYPQ.png) Go to [Devices] tab => Select our device (e.g. ESP32) => Select variable (e.g. Hall sensor). VoilĂ ! ![](https://i.imgur.com/ajznU7o.png) Data is saved every time we send data to Ubidots and the data is kept for 30 days without extra cost for STEM account users. This offers matches well to our project given that home security system requires continuous monitoring. **Event & Alert** Guide to create conditional events and alerts on Ubidots can be found [HERE](https://help.ubidots.com/en/articles/1445537-events-creating-conditional-events-and-alerts). For this project, the below event & alert is created. **Event** ![](https://i.imgur.com/64k2neX.png) **Alert** ![](https://i.imgur.com/5BTIN8V.png) We can get notified by e-mail as the below image shows when the value of Hall sensor is less than threshold value (20) [Which means that the Hall sensor does not detect magnetic field. Thus, door/window is open!] for 3 minutes. ![](https://i.imgur.com/Yuwt3y7.png) ## Finalizing the design One thing that could have been more interesting for this project is to finalize the design with using a 3d-printer. Nevertheless, the below result shows the concept of our project. ![](https://i.imgur.com/xbtL3f0.png) ** When the device is active (Door is closed) ![](https://i.imgur.com/8gbInp8.png) ** When the hall sensor does not sense the magnetic field (Door is open) ![](https://i.imgur.com/iUrI11I.png) ** A sample image of door alram system (image source: https://ee-paper.com/common-application-of-magnetic-sensor-in-internet-of-things/ ) This project was such an inspiring journey. I've learned about the complex stages of IoT archetecture, applied the knowledge by building the magnetic detector by my own and gained hands-on experience. Some parts could have been done in another way : * LoRa could have been tested as it allows long distance communication with low power consumption. When we need to monior remotely, could be a better decision than WiFi. * LED is blinked to show the different status of the Hall sensor. Even though it could be controlled from Ubidots manually, it would have been even better if LED had triggered automatically. The whole process wasn't completed smoothly but we all know about the basics: No pain, No gains! I am very pleased to get to explore the world of IoT and look forward moving forward from now!