---
# System prepended metadata

title: Tutorial - Indoor air-quality sensor

---

# Tutorial - Indoor air-quality sensor

Samir Nazdrajic - sn222ck

This project is about indoor air-quality measurement. The measurement of temperature, humidity, pressure and VOC.

**Estimeted time**: 2 - 4 hours
**Estimeted price**: 1100 SEK (120 Euro)


---

## Objective

I have chosen this project because indoor air quality is an important part of our health. Being able to present measurements from the house's different rooms is important to be able to see how the house is feeling. If necessary, some changes can be made to make the house feel better.

In my case, I chose to install a fan in the bathroom to be activated when the humidity exceeds 70% and then I chose to use the sensor to check that the fan was activated at 70% humidity.

Only when we get facts about the condition of the house can we make an improvement.
I see control of the indoor environment as a great advantage in this project.

## Material



| Article  | Store    | Price |
| -------- | -------- | -------- |
| Sensor BME680     | [Electrokit.se ](https://www.electrokit.com/produkt/bme680-monterad-pa-kort/)   | 279 SEK     |
| Labsladd 1-pin hane-hane 150mm 10-pack | [Electrokit.se ](https://www.electrokit.com/produkt/labsladd-1-pin-hane-hane-150mm-10-pack/) | 29 SEK |
| USB-kabel A-hane – micro B 5p hane 1.8m | [Electrokit.se ](https://www.electrokit.com/produkt/usb-kabel-a-hane-micro-b-5p-hane-1-8m/) | 39 SEK |
| Pycase Clear | [Pycom.io ](https://pycom.io/product/pycase-clear/)  | 100 SEK |
| LoPy4 | [pycom.io ](https://pycom.io/product/lopy4/) | 400 SEK |
| Expansion Board 3.0 | [Pycom.io ](https://pycom.io/product/expansion-board-3-0/) | 200 SEK |

**Sensor BME680**
Low power gas, pressure, temperature, humidity sensor.

The most important component of the project, the sensor itself, which we will connect to the pycom expansion board.

![](https://i.imgur.com/3tBbeBm.jpg)



**Labsladd 1-pin hane-hane 150mm 10-pack**
Jump wires are simply wires that have contact pins at each end, so that they can be used to connect two points to each other without having to solder. Very handy to have, especially when prototyping.

![](https://i.imgur.com/XDhaiFA.jpg)



**USB-kabel A-hane – micro B 5p hane 1.8m**
Used to connect the expenson board to the computer. Power supply for expansion card / Lopy4 is via USB.

![](https://i.imgur.com/bn7rLKp.jpg)


**Pycase Clear**
PyCase can hold either LoPy, WiPy, FiPy, SiPy or GPy with an expansion board and attached antenna. Very handy to have.

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


**Lopy4**
The LoPy4 is a compact quadruple network MicroPython enabled development board (LoRa, Sigfox, WiFi, Bluetooth). It’s the perfect enterprise grade IoT platform for your connected Things. With the latest Espressif ESP32 chipset the LoPy4 offers a perfect combination of power, friendliness and flexibility. Create and connect you things everywhere. Fast.

![](https://i.imgur.com/Z38oDou.jpg)

**Expansion Board**

Provides pin connections so you easily can connect sensors. [Here](https://docs.pycom.io/datasheets/expansionboards/expansion3/) you can find data sheets for expansion board


![](https://i.imgur.com/vxo4aMF.jpg)


## Computer setup

**Steps that you need to do on your computer**

I have chosen to work with VS Code which is a free version and can be downloaded [here](https://code.visualstudio.com/).

IDE is the actual program used to communicate with lopy4 and IDE is used to write your own code to be uploaded to the Lopy4 device via the USB cable.

In addition to the installation of VS Code, you also need to install Node.js which you can download [here](https://nodejs.org/en/).
Run the installation straight through and it will be fine. Just make sure all the packages are marked to be installed.

One last thing that needs to be done is to install pymakr extensions inside VS Code. [Here](https://docs.pycom.io/gettingstarted/software/vscode/) you have a good "how to" do this.

1. Install Visual Studio Code
2. Install Node.js
3. Install pymakr extension inside the Visual Studio Code

**Firmware update (expension board and Lopy4)**

![](https://i.imgur.com/RlnmFom.jpg)


Now you can connect the expansion board to computer via USB and do a firmware upgrade of the expansion board. If you have bought a brand new device, it probably has the latest firmware. Here is a [guide](https://docs.pycom.io/updatefirmware/expansionboard/) on how to upgrade the firmware of the expansion board.

Lopy4 firmware can be upgraded using this [guide](https://docs.pycom.io/updatefirmware/).

Before you proceed, I recommend that you try to upload the finished code to see that the device is connected and working properly. You can do this via this [guide](https://docs.pycom.io/tutorials/basic/rgbled/).

1. Update firmware (expension board)
2. Update firmware (Lopy4 device)
3. Upload some code to see if everyting is working fine


## Putting everything together

![](https://i.imgur.com/SuJ59HR.jpg)

In my case, I did not need to use breadboard but I strongly recommend that you buy one to play with other sensors.

Even though it says on the sensor that it should be able to connect at 2-6 volts, it did not work until I switched to the 5V port(VIN) on the expansion board. In my case this is only for development and is not meant for production yet.

![](https://i.imgur.com/fpo7gpa.jpg)

## Platform

I have tested pybytes and ubidot's cloud platform and come to the conclusion that I have more use for ubidot's platform as it is able to give me nice graphs and a good overview of my data with more options like mail and sms triggers that i can activate. I can also filter data better (date, low, medium, high) with ubidots as opposed to pybytes. Ubidots is a better platform if the idea is to be developed.

![](https://i.imgur.com/aYavaTt.jpg)


## The code

![](https://i.imgur.com/V8kKZ8b.jpg)

Urequests under lib contains the code to be able to communicate with ubidots, the code in boot.py is also used for ubidots. Information and the code for it can be found in this [guide](https://help.ubidots.com/en/articles/961994-connect-any-pycom-board-to-ubidots-using-wi-fi-over-http).

The rest of the files in lib belongs to the sensor and are ready-made libraries that can be used freely. [Here](https://www.electrokit.com/produkt/bme680-monterad-pa-kort/) you will find data sheets and python libraries for the sensor.


Keys contains password, ssid and token which is unique to the account I created on ubidots.

You only need to change the keys file to get in touch with ubidots via your router.

TOKEN = Enter your token from ubidots.
NAME = Name of your home WiFi network (SSID).
PASS = Password for your WiFi connection

![](https://i.imgur.com/BQSpt11.jpg)

In the main file, a json object is created. This is used to save sensor data which is then sent to ubidots via the def post_var function.

```
from network import WLAN
import urequests as requests
import machine
import time
import keys
import _thread
from lib.bme import BME
import struct

TOKEN = keys.TOKEN #Put here your TOKEN
DELAY = 10  # Delay in seconds

wlan = WLAN(mode=WLAN.STA)
wlan.antenna(WLAN.INT_ANT)

# Assign your Wi-Fi credentials
wlan.connect(keys.NAME, auth=(WLAN.WPA2, keys.PASS), timeout=5000)

while not wlan.isconnected ():
    machine.idle()
print("Connected to Wifi\n")
bme = BME(('P9', 'P10'))

def build_json(variable1, value1 , variable2, value2, variable3, value3, variable4, value4):
    try:
        data = {variable1: {"value": value1},
                variable2: {"value": value2},
                variable3: {"value": value3},
                variable4: {"value": value4}}
        return data
    except:
        return None

# Sends the request. Please reference the REST API reference https://ubidots.com/docs/api/
def post_var(device, value1, value2, value3, value4):
    try:
        url = "https://industrial.api.ubidots.com/"
        url = url + "api/v1.6/devices/" + device
        headers = {"X-Auth-Token": keys.TOKEN, "Content-Type": "application/json"}
        data = build_json("Temperature", temp, "Humidity", humidity, "Pressure", pressure, "Air Quality", air_quality)
        if data is not None:
            print(data)
            req = requests.post(url=url, headers=headers, json=data)
            return req.json()
        else:
            pass
    except:
        pass

while True:

    temp, humidity, pressure, air_quality = bme.get_values()
    post_var("pycom", temp, humidity, pressure, air_quality)
    time.sleep(DELAY)
    
```



 


## Transmitting the data / connectivity

The data is sent every second in my case, although this can of course be changed. I chose to use WiFi from Lopy4 to send data to Ubidots via my router, this as Lora GW is not nearby.

This exchange of data takes place over the web via a "webhook URL". 

Ubidots provides great [guides](https://help.ubidots.com/en/articles/961994-connect-any-pycom-board-to-ubidots-using-wi-fi-over-http) on how to succeed in this. Once you have succeeded, you should actually be able to use the same code to send to other platforms by only exchanging the url and token.

In my case, LoRa would be a better method if the device is to be battery powered as the amount of data is very low and the temperature, humidity etc. do not need to be taken as often in my project



## Presenting the data

The data is saved in the database at 10 second intervals, mostly because I played with the humidity level and needed to have more frequent intervals.

Added triggers that will ensure that an email is sent to me when the air quality exceeds 100 for 5 min.


![](https://i.imgur.com/PYc5SmT.jpg)

![](https://i.imgur.com/IPMFzng.jpg)

![](https://i.imgur.com/CDaU6ML.jpg)







## Finalizing the design

The project went well, it would have been fun to test 3D printing and shape my own shell.

I would also recommend that everyone order battery holders at the beginning of the course. Unfortunately, Lora GW is not available everywhere but the next goal is to try to send data via the LoRa network instead.

![](https://i.imgur.com/ljZcBCo.jpg)

Final dashboard Ubidots

![](https://i.imgur.com/Mz8ou08.jpg)

