# Disco air safety system for Grandpa
By Mimmi Andersson (ma226ep)
A home system that alerts to critical air humidity and also supports the regulation process by tracking irrigation of nearby plants and vegetation. The project is using the Micropython-programmable microcontroller Lopy4 to connect air and soil humidity sensors through wi-fi.
Estimated time for the project:
- About 5-10h for hardware- and software setup. It is provided that all the listed material is available.
## Objective
The project idea arose when I visited my lovely grandfather during the summer (2021) and noticed how deplorable ventilation capacity he had in his home. Since this indoor climate can cause increased health problems for him, I immediately did a search for free house tricks that could help to reduce the humidity. The experts on the internet claimed that high and enriched vegetation is the best trick to effect the air, so I decided to follow their advice and to fill his bedroom with a lot of plants. [PING sound] With a moisture sensor in one hand and that night's party shoes in the other, the term *Disco air safety system for Grandpa* was coined.
The main purpose of this project is to design a supportive security system, as my dear grandfather tends to forget a lot these days. The system is intended to alert him when the humidity in his bedroom is critically high, and then also check that he responds to the alarm by active watering of the connected flowers.
The project is designed in it's simplest form, but the hope is to gain insight into how connected sensors can function as a support for individuals with cognitive impairment. Furthermore, it might also gain insight on how to make use of stored sensor data in terms of machine learning and empirical research in the field.
## Material
|Nmr| Item | Link to product | Supplier | Price |
| - | ---------------------------- |:-------------------------------- | ------------- |------ |
| 1 | Micro controller LoPy4 | [:link:][Electro-Sensor-Bundle] |electro:kit |849 SEK (including item 1-3)|
| 2 | Expansion board 3.1 | [:link:][Electro-Sensor-Bundle] |electro:kit |- |
| 3 | USB cable | [:link:][Electro-Sensor-Bundle] |electro:kit |- |
| 4 | Breadboard | [:link:][RS] |RS |50 SEK |
| 5 | Jumping wires (20 pcs) | [:link:][Electro-wires] |electro:kit |29 SEK |
| 6 | Temperature sensor (DHT11) | [:link:][Electro-temp] |electro:kit |49 SEK |
| 7 | Soil Moister sensor (FC28) | [:link:][Electro-moisture] |electro:kit |29 SEK |
[Electro-Sensor-Bundle]: https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-basic-bundle/
[RS]: https://se.rs-online.com/web/p/raspberry-pi-hats-add-ons/2222162/?cm_mmc=SE-PLA-DS3A-_-google-_-CSS_SE_EN_Raspberry_Pi_%26_Arduino_%26_Development_Tools_Whoop-_-(SE:Whoop!)+Raspberry+Pi+HATs+%26+Add-ons-_-2222162&matchtype=&pla-374265978167&gclid=CjwKCAjwuvmHBhAxEiwAWAYj-M_WfN6NvcEF3MnrXxJVR6GdQuHCBJHf6PT2HUvOVUXQD58MRVZ0GRoCL5IQAvD_BwE&gclsrc=aw.ds
[Electro-wires]: https://www.electrokit.com/produkt/labbsladd-20-pin-15cm-hona-hona/
[Electro-temp]: https://www.electrokit.com/produkt/digital-temperatur-och-fuktsensor-dht11/
[Electro-moisture]: https://www.electrokit.com/produkt/jordfuktighetssensor/
### Item description:
**1-3. Microcontroller LoPy4 / Expansion board 3.1 / USB cable**
The LoPy4 is a tiny development device as a Micropython-programmable microcontroller. It offers 4 different network connectivity options as LoRA, Sigfox, Wi-Fi, and Bluetooth. The compatible expansion board 3.1 allows one to create and connect IoT projects as sensors via the different pinouts for analog and digital values. In this project, the module gets its power via the USB plugin. Alternatively, the module can also be charged using a portable battery via the battery plugin.
 
**4-5. Breadboard / Jumping wires (20 pcs)**
The breadboard is used to hold the electronic components and create circuits with several sensors. The jumping wires help one to quickly create electrical connections between the sensors and the development device (Lopy4 in this case). In this project, a minimum of 10 wires is recommended in order to create connectivity for the two sensors in use.

**6. Temperature sensor (DHT11)**
This is a basic digital temperature and humidity sensor which measures the surrounding air.

**7. Soil Moister sensor (FC28)**
This is a sensor for measuring the amount of liquid in soil. It measures the resistance between the two legs and converts it to voltage using an analog or digital signal. The drier soil the higher is the resistance between the two legs.

## Computer setup
- Step 1: If your expansion board is purchased second-hand it might have an outdated version. It's therefore recommended to update its firmware by [following this guide.](https://docs.pycom.io/updatefirmware/expansionboard/) This update is not required for new expansion boards.
- Step 2: Connect the LoPy4 module and the expansion board. The layout of output pins (at the back of the Lopy4 module) is exactly the same as the plugins on the expansion board. Make sure that each pin is connected and orient the LED/reset button on the Lopy4 right above the USB connector on the expansion board.
- Step 3: Connect the hardware module to your computer by using the USB cable. The USB connector on the expansion board is sensitive, therefore, do not remove this side of the cable when you disconnect the device further on.
- Step 4: Download **Node.js** on your computer by [following this guide.](https://nodejs.org/en/) In this project, a computer with the operating system (OS) macOS is used. The Node.js platform is required and is basically used to easily build fast and scalable network applications.
- Step 5: Download an integrated development environment (IDE) as **Visual Studio Code** (VSC) or **Atom** on your computer. This is in order to create projects and write code for your microcontroller by using the programming language *Micropython*. In this project, the open source editor *Visual Studio Code* is used.
- Step 6: Install the **PyMakr plugin** to easy run, upload and run your code. If VSC is used, this can easily be done in the extension tab directly available in the user interface. However, no matter choice of IDE [this guide](https://docs.pycom.io/index.html) can be followed in order to install the plugin.
- Step 7: Check that the softwares and extensions above is successfully downloaded by connecting the LoPy4 to the computer port. Information about the connection can be read in the PyMakr terminal window and should be established before continuing.
- Step 8: Learn how to use **VSC** and **PyMakr plugin** in order to upload and run MicroPython code on the microcontroller. by creating a first simple project using [This guide](https://docs.pycom.io/gettingstarted/) shows how to create a simple project that activates the LED (by flashing in different colors) on the microcontroller. Also make sure to understand the [required folder structure](https://docs.pycom.io/docnotes/micropython/) in order for PyMakr to interpret the IoT-project, as well as MicroPython [syntax](https://docs.pycom.io/docnotes/syntax/) and modules.
## Putting everything togheter
The connection in the circuit diagram is based on a user guide provided by the sensor supplier ([DHT11](https://www.electrokit.com/uploads/productfile/41015/41015738_-_Soil_Moisture_Sensor.pdf) & [FC-28](https://www.electrokit.com/uploads/productfile/41015/41015728_-_Digital_Temperature_Humidity_Sensor.pdf)). The connection might differ for other similar sensors, so make sure that the exact same sensors are used if this curciut diagram is used.

The FC-28 sensor gives both analog and digital output. In this project the analog output (A0) is used, which gives a value between 0 - 1023 as 10 bits. The DHT11 sensor gives a digital signal with 16 bits and takes a temperature range between 0°C to 50°C as well as a humidity range from 20 to 90.
When connecting the sensors to the pins at the extension board it's important to be aware of the different functionalities for each pin. P18 supports analog signal and is therefore connected to the FC-28 sensor. More information about the functionalities for each pin can be studied in this [schematic](https://docs.pycom.io/gitbook/assets/lopy4-pinout.pdf).
Furthermore, both sensors supplies a voltage of 5V and is therefore connected to VIN.
## Platform
This project is using [PyBytes online platform](https://pybytes.pycom.io/) in order to send and store data in to the cloud via wifi-connection. The platform is build for Pycom devices and is very simple and intuitive to use by following [this guide](https://docs.pycom.io/pybytes/gettingstarted/).
The platform is free and provides many great tools in order to visualize realtime sensor data into different charts and diagrams. Since the alarming function in this project is only using the wi-fi connection to the LED light, the PyBytes platform can be considered as a intuitive choice. However, if one is aiming to develope alarming functions that need to send data over a longer distance (as email sending or mobile notifications) it might be a better choice to consider other platforms, as for example the [Ubidots.com](https://ubidots.com/).
## The code
### Folder structure and external libraries
The program of this IoT project is simple and follows the main design of the PyMakr folder structure. The lib folder includes a DHT library that was downloaded from GitLab in order to read temperature and humidity from the DHT11 sensor. The boot.py is not used in this project and is therefore empty.

### Main programme (main.py)
The read_from_pin function takes the input of the temperature and the moisture sensor objects and runs until it gets manually interrupted.
The function, as a simple alarming safety system, reads the voltage of air humidity and soil humidity every third second, calculates the relative values (percent values), and turns the LoPy LED into different colors depending on the humidity status.
When the function is running, the LED lamp is activated to a constant green light if the air humidity is within an approved percentage (below 60) and switches to red light if the value exceeds this maximum threshold.
In this case, the function takes the connected plant into account and shifts the LED to yellow light if it gets watered (thus when the soil humidity decreases). Finally, if the air humidity decreases back to an approved value (below 60 percent), the LED light turns back to green.
For more details read the comments next to each code line.
```python=16
def read_from_pin(th_pin, mo_pin):
h_max = 90 #Air humidity maximum value
h_min = 20 #Air humidity mininum value
m_max = 3210 #Soil humidity value measured in air
m_min = 1628 #Soil humidity value measured in water
trigger = False #Initializing trigger. If False the light LED-light will turn Green otherwise Red.
soi_moi = m_min #Initializing soil moister value for the first loop
air_moi = h_min #Initializing air moisture value for the first loop
while True:
soi_mo_previous = soi_moi #Updating previous soil moisture value
air_mo_previous = air_moi #Updating previous air moisture value
th_data = th_pin.read() #Read from DHT11 sensor object
soi_moi = mo_pin.voltage() #Read from FC-28 sensor object
air_moi = th_data.humidity
air_temp = th_data.temperature
humidity_percentage = (air_moi-h_min)/(h_max-h_min)*100 #Calculating of air humidity percentage
moisture_percentage = (soi_moi-m_min)/(m_max-m_min)*100 #Calculating of soil moister percentage
#----- Triggers -----
if humidity_percentage > 60: #To high air humidity. Not recommended
trigger = True
pycom.rgbled(0xFF0000) #Red as warning light
print("ALERT! Air humidity is to high. Water your plants in the bedroom immediately to achieve better air quality!")
if soi_moi < soi_mo_previous: #Detection of improvement as more water in the plant.
#Decrease in soil humidity for plants in the same room helps to decrease the air humidity.
print("Good job Grandpa! Continue to water your plants!")
pycom.rgbled(0xFFFF00) #Yellow as improvement light
else if air_moi < air_mo_previous: #Detection of improvement as increasing air humidity.
print("Almost there Grandpa! Air humidity decreases!")
else: #The value of the air humidity is not critical.
pycom.rgbled(0x00FF00) #Green as safe light
if trigger == True: #The air humidity went from critical to safe.
print('We made it Grandpa! Now you can sleep safely tonight! :D ')
trigger = False #Resetting trigger value
```
## Transmitting the data / connectivity
The project is a secure system for indoor environments and plants, which limits the required range of accurate data transmission. It's therefore intuitive to use the wi-fi protocol for connectivity and data sending. Each data point is formatted and loaded by the standard layers (MAC, internet, transport, application) and the packet is then sent to the online server and platform PyBytes. This is easily done by a predefined signal function with two input arguments (signal value and a sensor value), which is provided in their API.
The packet that is sent through wi-fi is large compared to other optional protocols, which requires high power consumption. The LoPy4 is therefore powered by a wall socket through the USB cable instead of a portable battery.
## Presenting the data
The PyBytes platform supports many different functions in order to visualize the data in a customized way.
Below is a dashboard with different charts for the signals air humidity, soil humidity, and temperature is shown. The line charts shows 60 data points for the last hour.
The purpose of this dashboard design is to be able to evaluate if my Grandpa is taken the system seriously. By analyzing the correlation between the air and soil humidity, it is possible to ensure that Grandpa responds to the alarm if the air humidity gets too high.

*Example 1* Graph and values of increasing air humidity and inverted soil humidity curve.

*Figure 2.* Example of temparute values during one hour.
The charts receive a new data point every minute, which is the smallest possible interval in order to illustrate the effect of irrigation during a day. The PyBytes platform provides free data storage of 1MB, which for 3 8-bits datapoints/minute will store the data for almost a month (1024000/(3*8*60*24)=29 days), which is much more than needed for this purpose.
## Finalizing the design
I think the project was really fun and worked out great without any major technical problems. I believe that there are many fun ways to improve and scale this type of security system. To mention a few examples it would be nice to try other alarming features as alarming noise, email sending, or mobile notification. It would also be fun to scale the project and connect several flowers in the room in order to increase soil impact on the air humidity. In this project, the concept of using flowers as a household trick was limited to only one moisture sensor and one flower, which is not enough to affect the air.
Below are some pictures that illustrates the three different modes of green, red and yellow light.

*Mode 1.* Green LED for approved air humidity.

*Mode 2.* Red LED for increasing and critical air humidity.

*Mode 3.* Yellow LED for decrease in soil humidity. (Illustrates the concept of watering the flower.)