---
# System prepended metadata

title: Gate notification system with a built-in weathersystem

---

# Gate notification system with a built-in weathersystem

> Written by Simon Nevby (sn223fx)

This tutorial describes how to build a gate notification system with a built-in weather system using Pycom devices and Pybytes as back-end. Replicating the system while following this tutorial should take approximately 4-6 hours.

### Objective

The idea to create this system came about when trying to fix an old analog gate notification system. It was basically just a motion detector which sent a signal to a device which played a tune. It had a few problems with it including but not limited to:
* It often gave false positives (when windy, or when someone passed by the receiver would sound)
* It was limited to one receiver which sounded
* You had to be close to the receiver to hear the sound

The system solves the problems by using a Reed switch module connected to a Pycom device which in turn is connected to WiFi and Pybytes (more on this later). 

The idea is that a reed sensor is placed where the gate door is closed (or locked into place) and a magnet is placed at the edge of the gate door. When closed the two (the sensor on the magnet) will be at most 2cm away from each other making the sensor go off. When the gate opens the connection will be broken.

This new system will serve to replace and improve the old one and to add a "weather station" functionality. The data will give insight in a sense as to the current and past local weather as well as a more precise and robust gate notification system. 


---

### Material

#### List of modules from PLAYKNOWLOGY

| Material | Description | Brand    | Cost (kr)| Place of purchase |
| -------- | --------    | -------- | -------- | -------- |
| DHT11     | Temperature and humidity sensor | PLAYKNOWLOGY | * | [Kjell & Company](https://www.kjell.com/se/produkter/el-verktyg/arduino/moduler/playknowlogy-stora-modul-paketet-for-arduino-p87291) |
| Reed Switch Module | Magnetic field sensor | PLAYKNOWLOGY | * | [Kjell & Company](https://www.kjell.com/se/produkter/el-verktyg/arduino/moduler/playknowlogy-stora-modul-paketet-for-arduino-p87291) |
| RGB LED Module | LED Light | PLAYKNOWLOGY | * | [Kjell & Company](https://www.kjell.com/se/produkter/el-verktyg/arduino/moduler/playknowlogy-stora-modul-paketet-for-arduino-p87291) |
\* All modules/sensors were bought as part of the [Playknowlogy Stora modul-paketet för Arduino](https://www.kjell.com/se/produkter/el-verktyg/arduino/moduler/playknowlogy-stora-modul-paketet-for-arduino-p87291) from [Kjell & Company](https://www.kjell.com/se) Cost 499 kr. (For this tutorial it is unnecessary to buy the whole kit)
![](https://i.imgur.com/HmPf8p8.png)
*Image 1 - [Playknowlogy Stora modul-paketet för Arduino](https://www.kjell.com/se/produkter/el-verktyg/arduino/moduler/playknowlogy-stora-modul-paketet-for-arduino-p87291) from [Kjell & Company](https://www.kjell.com/se)*

#### List of components from Pycom

| Material | Description | Brand    | Cost (kr)| Place of purchase |
| -------- | --------    | -------- | -------- | -------- |
| Pycom fipy module | Micropython device | Pycom | 560 | [Pycom.io](https://pycom.io/product/fipy/) |
| Pycom expansionboard 3.1 | Makes connections to the fipy module easier | Pycom | 170 | [Pycom.io](https://pycom.io/product/expansion-board-3-0/) |
| External WiFi Antenna | Antenna for WiFi connection | Pycom | 80 | [Pycom.io](https://pycom.io/product/external-wifi-antenna/) |
| MicroUSB cable | MicroUSB charging cable | Any | 50-200 | Found at home |
![fipy / expansionboard 3](https://i.imgur.com/4LpaiQU.png) 
*Image 2 - fipi on the expansionboard 3.1 from Pycom*
 
 
#### List of miscellaneous from PLAYKNOWLOGY

| Material | Description | Brand    | Cost (kr)| Place of purchase |
| -------- | --------    | -------- | -------- | -------- |
| Breadboard | Makes wireconnections easy | PLAYKNOWLOGY | * | [Kjell & Company](https://www.kjell.com/se/produkter/el-verktyg/arduino/arduino-kit/playknowlogy-komponent-kit-for-experimentering-med-arduino-p87293) |
| Wires | Wires | PLAYKNOWLOGY | * | [Kjell & Company](https://www.kjell.com/se/produkter/el-verktyg/arduino/arduino-kit/playknowlogy-komponent-kit-for-experimentering-med-arduino-p87293) |
| Magnets | Any kind of magnets | Any | - | Found at home |
| Battery | 9V for powering the breadboard | Any | - | Found at home |

\* The items were bought as part of the [Playknowlogy Komponent-kit för experimentering med Arduino](https://www.kjell.com/se/produkter/el-verktyg/arduino/arduino-kit/playknowlogy-komponent-kit-for-experimentering-med-arduino-p87293), Cost 299 kr.

![Playknowlogy Komponent-kit för experimentering med Arduino](https://i.imgur.com/xi6O77j.jpg)
*Image 3 - Playknowlogy Komponent-kit för experimentering med Arduino*


---

### Computer setup

These instructions are for Windows 10. For other operating systems, refer to the docs on [pycom.io](https://docs.pycom.io/pytrackpysense/installation/firmware/)

#### 1. Update Firmware on the expansion board 3.1


For this you need to download the [DFU util tools](http://dfu-util.sourceforge.net/releases/dfu-util-0.9-win64.zip), the installer tool [Zadig](http://zadig.akeo.ie/) as well as the latest expansionboard firmware [Expansion Board DFU v3.1](https://software.pycom.io/findupgrade?key=expansion31.dfu&type=all&redirect=true). When downloaded and extracted put the DFU files, firmware and the Zadig Application in the same directory, then unplug the expansion board and click on the Zadig.exe file. 

Now you need to hold down the "s1" button on the expansion board and plug it in to your computer. In the Zadig program you should see your device pop up. Select the libusbK driver and press install within 7 seconds. Image 4 shows how it should look like upon completion. Note that the expansion board v3 has the code 0xEF99 for DFU bootloader (update mode) and 0xEF98 for normal mode.

![](https://i.imgur.com/oVcBIFF.png)
*Image 4 - source: https://docs.pycom.io/pytrackpysense/installation/firmware/*

To confirm successful installation go to device manager and check if the device is visible. See right side of image 4.

You can find a more detailed description of this process at [docs.pycom.io](https://docs.pycom.io/pytrackpysense/installation/firmware/)

#### 2. Connect the FIPY to the expansion board

Now you are ready to connect the FIPY to your expansion board. Make sure the reset button is on the same side as the microUSB connector and press it firmly into place. The WiFi antenna is optional and is only needed if a stronger connection is needed. More information on that can be found on [docs.pycom.io](https://docs.pycom.io/firmwareapi/pycom/network/wlan/)

#### 3. Update FIPY Firmware

Next step is download the firmware update tool. For windows press [here](https://software.pycom.io/findupgrade?product=pycom-firmware-updater&type=all&platform=win32&redirect=true). For other OS see [docs.pycom.io](https://docs.pycom.io/gettingstarted/installation/firmwaretool/). After download click the exe file and follow the instructions. After successful installation disconnect and reconnect the fipy/expansion board to your computer. If there are any issues during the installation refer to the [pycom docs](https://docs.pycom.io/gettingstarted/installation/), otherwise your device should be ready for use.


#### 4. IDE - Atom and Pymakr
The IDE i chose for this project is [Atom](https://atom.io/) with the [Pymakr](https://docs.pycom.io/gettingstarted/installation/pymakr/) plugin. The software can be used on Linux, Mac or Windows OS. Make sure your Node.js version is installed and up-to-date ([Node.js](https://nodejs.org/en/)). There is a complete installation guide on [pycom](https://docs.pycom.io/pymakr/installation/atom/) but here is the basic steps. 
1. Follow [this link](https://atom.io/) to atom's webpage. 
2. Then download the corresponding version for your computer. 
3. Run the exe file and follow the instructions. When completed open Atom. 
4. Go to File -> settings, then press on the install button
5. In the text field, enter "pymakr"
6. Press install


![](https://i.imgur.com/LCN8xFT.png)
*Image 5 - If the steps were followed correctly it should look like this. Source: https://docs.pycom.io/pymakr/installation/atom/*

#### 5. Connecting Pymakr to your device via Serial USB

If step 1 though 4 were completed successfully, you should now be able to connect the Pymakr plugin to your device. Make sure the fipy/expansion board is connected via the microUSB cable to your computer. Then click the "Connect Device" dropdown in the Pymakr plugin in Atom. There you should be able to find your device connection like in the image.

![](https://i.imgur.com/JBjsq4Q.png)
*Image 6 - Source: https://docs.pycom.io/pymakr/installation/atom/*

In a few moments after clicking on your device you should see three arrows which means there was a successful connection! You can press the "get device info" button to confirm.


#### 6. Uploading code to your device

First off you will need a project to upload to your device. Start by creating a empty folder and open it in Atom. This is done by clicking on File -> Open, then select your empty folder. Now press the "download from device" button in the Pymakr plugin. Your project should now contain a boot.py and a main.py file - both empty. It is in the main.py file where the code should be added.

When the code has been added press the "upload to device" button in pymakr and the code will added to your device.

More on creating your first project can be found on [Pycom docs](https://docs.pycom.io/gettingstarted/programming/first-project/).

---


### Putting everything together


#### Circuit diagram

![](https://i.imgur.com/GHEjTOJ.png)
*Image 7 - Circuit diagram with the FIPY/Expansion board v3.1 in the middle, the RGB LED module to the left, the reed switch module on the top and the DHT11 temperature and humidity sensor to the right*

#### Explaining the circuit diagram

##### RGB LED MODULE
To the left on the diagram the RGB LED module is shown. The color of the LED is determined by what rgb values is sent to it. It has the following connections
1. The red connection goes from "R" on the module to P6 on the expansion board. The module receives via PIN.OUT the value for red on the LED. min: 0, max 255.
2. The green connection goes from "G" on the module to P7 on the expansion board. The module receives via PIN.OUT the value for green on the LED. min: 0, max 255.
3. The blue connection goes from "B" on the module to P8 on the expansion board. The module receives via PIN.OUT the value for blue on the LED. min: 0, max 255.
4. The fourth pin is connected via the breadboard to the ground (GND) on the expansion board.

##### REED SWITCH MODULE
On the top of the diagram we have the Reed Switch Module. It detects magnetic fields and will return a 0 or 1 via the Digital Output (DO) Pin shown i gray. It has the following connections
1. The black connection is connected via the breadboard to the ground (GND) on the expansion board.
2. The red connection is connected to the expansion boards power output (VIN)
3. The gray connection is the DO connected to the P3 Pin mode Pin.IN, Pin.PULL_UP.

##### DHT11 Temperature / Humidity Sensor
To the right in the circuit diagram is the DHT11 sensor. It returns the current temperature and humidity. It has the following connections
1. The black connection is connected via the breadboard to the ground (GND) on the expansion board.
2. The red connection is connected to the power output (3V3) on the expansion board
3. The gray connection goes from the data pin on the DHT11 sensor to P23 with Pin.OPEN_DRAIN mode.



---

### Platform - Pybytes


The platform used in this tutorial is a free subscription of Pybytes. It is a easy-to-use cloud device management platform for micropython devices. It works by provisioning (connecting) the Pycom device and sending/receiving signals which are visualized in the dashboard ([pybytes docs](https://docs.pycom.io/pybytes/)). For example to send the temperature from the DHT11 sensor to Pybytes the following code is used: 
```python=
pybytes.send_signal(1,result.temperature)
```
How it is visualized is shown below in the "transmitting the data" section of the tutorial.

Going forward I would use something like Google Cloud IOT and Firebase BAAS to easily access and use the data in a mobile application, where the data could be visualized and notifications could be shown whenever the gate opens/closes.

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

### The code

```python=

import time
from machine import Pin
import _thread
from dht import DHT

#Defining a DHT object from the lib/DHT class with the pin P23
th = DHT(Pin('P23', mode=Pin.OPEN_DRAIN), 0)

#Defining the "gate open/gate closed" or reed switch value pin P3
p_reed = Pin('P3', Pin.IN, Pin.PULL_UP)

#Pins for setting the red, green and blue values of the RGB LED Light
p_r = Pin('P6', Pin.OUT)
p_g = Pin('P7', Pin.OUT)
p_b = Pin('P8', Pin.OUT)

time.sleep(2)

#Function that sends temperature/humidity data to the pybytes backend
def send_temp_hum_data():
    set_color(255,255,255)

    while True:
        #Reading values from the P23 pin
        result = th.read()
        while not result.is_valid():
            time.sleep(.5)
            result = th.read()
            
        #Printing temperature/humidity values for debugging
        print('Temp:', result.temperature)
        print('RH:', result.humidity)
        
        #Sending temperature/humidity values to pybytes the platform
        pybytes.send_signal(1,result.temperature)
        pybytes.send_signal(2,result.humidity)
        
        set_color_after_temperature(result.temperature)
        
        #Values sent to backend every 20 minutes
        time.sleep(1200)

#Function to determine the color of the visual feedback temperature LED
#(The color is based on temperature, purple = coldest, red = hottest)
def set_color_after_temperature(temp):
    if temp > 27:
        set_color(255,0,0) # red
    elif temp <= 27 and temp > 20:
        set_color(255,178,102) # orange
    elif temp <= 20 and temp > 10:
        set_color(255,255,50) # yellow
    elif temp <= 10 and temp > 5:
        set_color(0,255,255) # light blue
    elif temp <= 5 and temp > 0:
        set_color(0,0, 255) # blue
    elif temp <= 0:
        set_color(255,0,255) # purple

#Function that sets the rgb values of the LED module
def set_color(r,g,b):
    p_r.value(r)
    p_g.value(g)
    p_b.value(b)

#Function that determines if the front gate is open or closed. 
#Sends signal to pybytes when opened or closed
def gate_handler():
    global p_reed
    while True:
        value1 = p_reed.value()
        time.sleep(0.1)
        value2 = p_reed.value()
        if value1 and not value2:
            print("Front Gate Open")
            pybytes.send_signal(3, 1)
        elif not value1 and value2:
            print("Front Gate Closed")
            pybytes.send_signal(3, 0)

#Starting the threads
_thread.start_new_thread(gate_handler, ())
_thread.start_new_thread(send_temp_hum_data, ())
```

---

### Transmitting the data / connectivity

The temperature and humidity data is sent once every 1200 seconds, i.e. every 20 minutes, while the gate open/gate closed signal is sent once when the gate is opened and once every time it is closed.

The data is set over WiFi with the MQTT protocol with the pybytes built-in library. 

Both wireless and transport protocols were chosen because of simplicity and not how well they would fit the project. Optimally LoRa should be used to save battery and for range. Unfortunately there was not enough time in this project.  



---

### Presenting the data

The visual presentation of the data takes place in the Pybytes dashboard as shown in the following images 8-11.

For now the data is preserved on Pybytes for one month. The environment data is saved once every 20 minutes and the gate data is saved once every time the gate is opened or closed.



---

![](https://i.imgur.com/wrqipW8.png)
*Image 8 - Bar chart showing when the gate is closed (0) and the gate is opened (1)*


---


![](https://i.imgur.com/xF90xJz.png)
*Image 9 - Line chart with humidity data points*


---


![](https://i.imgur.com/W6nuE6s.png)
*Image 10 - Line chart with temperature data points (currently inside -> constant temperature)*



---

![](https://i.imgur.com/AUF47IB.png)
*Image 11 - The Pybytes dashboard showing all charts*


---


### Finalizing the design


![](https://i.imgur.com/f7eIv6S.jpg)
*Image 12 - Image showing the final setup*

The final results of the project is no more than a proof-of-concept or a prototype. Had I had more time with it and if the goal had been to create a finished product quite the few things would have changed. 

As mentioned before, on the user end-point I would have liked to create an app showing the data and notifying the user if the gate is opened/closed. I would have added sensors such as an air quality sensor, brightness sensor and perhaps an UV-sensor. It would also use the LoRa protocol instead of WiFi. On top of that some soldering and and a waterproof case would be involved. 

All in all a successful prototype with a lot of potential for further development.

![](https://i.imgur.com/i1mOGRA.jpg)
*Image 13 - The reed switch module sensing the magnetic field from the magnets (red light in the circle is on) signifying that the gate is closed*

![](https://i.imgur.com/J6AVYkt.jpg)
*Image 13 - The reed switch module not sensing the magnetic field from the magnets (red light in the circle is off) signifying that the gate is open*

