---
# System prepended metadata

title: Temperature and Relative Humidity measurement device for apartment
tags: [Pycom, DHT11, Pybytes, Atom, Tutorial]

---

#  Temperature and Relative Humidity measurement device for apartment

###### tags: `Tutorial` `Pycom` `Pybytes` `Atom` `DHT11`

> Student name: Axel Bolmvall
> Student username: ab225va
> August 2021

This project is about taking temperature and relative humidity measurements and store them in a database called Pybytes. The device that is used is Pycom lopy4 which will be connected to WiFi and programmed in Atom. The sensor that was used to take the measurements was dht11 which is a digital temperature and humidity sensor. 

This is a relatively uncomplicated project but for an inexperienced person (who I am) this takes approximately 3-4 hours. 
## Objective

The ventilation in my apartment is not the best, before I go to sleep I make sure I open the window to let the fresh air in. Due to a road right outside the apartment building, I cannot sleep with the window open. When I wake up it is always hot and the air quality is the worst. Therefore, the idea of this project popped up, and due to lack of time this summer (and knowledge of IoT) I only chose to focus on the temperature and relative humidity measurement.

The purpose of the measurement readings will be to have proof that the quality of the air might not be the best in the mornings. 

This project will also give insights into the measurement levels during the whole day and how they change.

## Material
### List of material
* LoPy4 with headers (Basic Bundle)
    * This device is used in order to be able to take measurements and it can connect to WiFi
* Expansion board (Basic Bundle)
    * This makes it easier to connect the sensors
* Breadboard
    * This makes it easier to manage cables and sensors
* Cables
* Antennae (Basic Bundle)
    * The antenna gives you better signal strength when connecting to WiFi
* USB cable (Basic Bundle) 
* DHT11 - a digital temperature and humidity sensor
    * This sensor is used because it is cheap and relatively good 
* Battery holder 3xAAA with switch and JST-connector
    * The battery holder is not necessary for the project, but it is used when I do not want to have the system connected to the computer. 

### Cost & Where to buy the components


| Part | SEK | Purchased |
| -------- | -------- | -------- |
|   LNU - 1DT305 Tillämpad IoT - LoPy4 Basic bundle   | 849.00     | [https://www.electrokit.com/en/product/lnu-1dt305-tillampad-iot-lopy4-basic-bundle/](https://www.electrokit.com/en/product/lnu-1dt305-tillampad-iot-lopy4-basic-bundle/)     |
|Digital temperature and humidity sensor DHT11| 49.00 |  https://www.electrokit.com/en/product/digital-temperature-and-humidity-sensor-dht11/|
|Battery holder 3xAAA with switch and JST-connector| 29.00 |https://www.electrokit.com/en/product/battery-holder-3xaaa-with-switch-and-jst-connector/ |
|Breadboard|34.00|https://cdon.se/bygg-verktyg/kopplingsdack-breadboard-protoboard-400-punkter-p49343576?gclid=Cj0KCQjw6ZOIBhDdARIsAMf8YyFRR1RZnHEZZLDJQjjOO7_aiO5zFTNl7p0F2FtKQaU8djxu0Y0pnuAaAiL-EALw_wcB&gclsrc=aw.ds|
|Cables|29.00 |https://cdon.se/bygg-verktyg/10-cm-flatkabel-med-hane-hane-kontakter-40-kablar-bred-passar-kopplingsdack-p49769846|


## Computer setup
The things that I needed to be done is the following:
1. Install an IDE and make it work
2. Install pymakr extension
3. Make a Pybytes account and update the firmware on Pycom Lopy4
4. Install library for DHT11 sensor
5. Test the system


To be able to program my device I need an Integrated Development Environment (IDE). The IDE that I chose for this project was Atom. It is a free source code editor developed by GitHub. I chose this because it was easy to use and to install pymakr package which is a package that allows me to communicate and upload code to my Pycom board. 

When Atom was downloaded from [atom.io](https://atom.io/) and installed on my windows computer I went into problems when I tried to install Pymakr. This was solved by installing [Node.js](https://nodejs.org/en/), the latest version of [python](https://www.python.org/downloads/), and a [visual studio workload](https://docs.microsoft.com/en-us/visualstudio/install/install-visual-studio?view=vs-2019#step-3---install-the-visual-studio-installer). The workload I went with was *Desktop development with C++* which can be seen in the figure below. Then a restart of the computer made everything work.

![Desktop development with C++](https://i.imgur.com/GFnHGky.png)

When all the software was installed on my computer it was time to set up my hardware. To upgrade the firmware would make it easier to connect to Pybytes. Pybytes is a free could-based platform management for Pycom devices, and when I had made an account there I could upgrade my Lopy4 Pycom. First I downloaded the [firmware](https://docs.pycom.io/updatefirmware/device/) and ran the installer and clicked my way through, but note that I checked *Forced update Pybytes registration*, see figure below. 

![COM4 - communication](https://i.imgur.com/ciexO6H.png)

Then I had to generate a Pybytes activation token which was done on Pybytes website, see figure below. 

![pybytes activision token](https://i.imgur.com/xeArcj5.png)

This code was then pasted into the Pycom upgrade installer which can be seen below, and the registration was successful.


![pybytes registration successfull](https://i.imgur.com/oFcrIXd.png)

I now had installed everything and upgraded the firmware, the last step that I knew beforehand that I was going to need was the library for my sensor which was downloaded from [GitLab](https://gitlab.lnu.se/1dt305/sensor-libs). The setup for everything was now done and I could start to put everything together.

## Putting everything together

![Circuit diagram](https://i.imgur.com/hXQjL0S.png)

In the figure above you can see the circuit diagram which consists of Pycom lopy4 with an expansion board, a breadboard, temperature, and humidity sensor DHT11, and a 4.7 kΩ resistor. The datasheet of the sensor can be found [here](https://www.electrokit.com/uploads/productfile/41015/DHT11.pdf). The reason for having a resistor is because I use cables that are shorter than 20 meters, and the datasheet states that a 5kΩ resistor is recommended if the cable is shorter than that. The sensor can be connected to both 5V and 3V so I just chose one of them. 

## Platform
As I wrote above I chose to work with Pybytes due to its convenience of connecting Pycom devices with WiFi and it is free. If I would have done a bigger project I might consider another platform but for this project, I think Pybytes works just fine. Even if I would like to expand, I am able to have several devices connected to Pybytes which is a good thing. One way to expand the project could be to add more sensors such as an air quality sensor that could measure eCO2 as well. A bigger project could also result in a casing to my devices that could be either bought or 3D-printed. 

## The code
I have four files of code in my program which can be seen in the figure below. A boot file including my WiFi settings, keys file with my WiFi information, main file with the main code, and lastly a dht file which is the library for my sensor. 
![](https://i.imgur.com/kVkgEBH.png)



### boot.py 
This code connects my device to WiFi and was inspired by Pycom's documentation found [here](https://docs.pycom.io/updatefirmware/device/). I have stored the ssid and password in the keys.py file as variables.
```h=
from network import WLAN
import machine
import keys
wlan = WLAN(mode=WLAN.STA)

nets = wlan.scan()
for net in nets:
    if net.ssid == keys.wifi_ssid:
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, keys.wifi_password), timeout=5000)
        while not wlan.isconnected():
            machine.idle() # save power while waiting
        print('WLAN connection succeeded!')
        print(wlan.ifconfig())
        break
```

### dht.py (library)
This library creates two classes: DHTResult and DHT. These are the classes that made it able to read the data from the sensor. I have not changed any code in this file. The library can be downloaded [here](https://gitlab.lnu.se/1dt305/sensor-libs).

### main.py
I got a lot of help with my code from the library imported from GitLab which already had a testing code including in it. So I wanted to take measurements with my sensor, send them to Pybytes so I could store data without having my device connected to my computer all the time. Then I wanted the led lamp in at the Pycom device to light up when the temperature is below or above a certain value, below 18 and above 28 which are the minimum and maximum allowed in my rental apartment. If it is outside these limits I want the led to be red and notify me.

So, the following code reads the data from my dht11 sensor and prints it and sends the resulting data as two signals, 1 and 2, to Pybytes. 
```h= 
while True:
    result = th.read()
    while not result.is_valid():
        time.sleep(.5)
        result = th.read()
    print('Temp:', result.temperature)
    print('RH:', result.humidity)
    pybytes.send_signal(1,result.temperature)
    pybytes.send_signal(2,result.humidity)
```

Then there is the if statement that tells the led to shine red if the temperature is above or below a certain value, else the led should be green. Note that this code is still within the while loop. The last line says that the device should sleep for 2 seconds and then go through the while loop again. 
```H=10 
    if result.temperature <= 18 or result.temperature >= 28 :
        pycom.rgbled(0xFF0000)  # Red
    else:
        pycom.rgbled(0x00FF00)  # Green
    time.sleep(2)
```


## Transmitting data / connectivity
As stated in the last line of code the data is sent every other second, this was because I wanted to see the result directly on short notice. Otherwise, for this project, it would not be necessary to take measurements that often. If the function of my project is to measure the room temperature and relative humidity I think it is enough with taking measurements and send them once every hour. So in a day, it should have a nice graph of how the temperature change throughout the day. 

I chose to use my WiFi as a wireless protocol because it is a convenient way of sending the data to the server because the system is in my apartment. The transport protocol used is MQTT because this is, how I understood it, what is used when sending data to Pybytes.

## Presenting the data
Here is the dashboard of the presented data which is accessible through the ordinary browser but also through an application on the phone. As you can see in the graph and table data is collected every few seconds, as I programed. To collect data every other second drains a lot of battery power as well which also is one reason to only collect data once every hour. 
![Temperature dashboard](https://i.imgur.com/a8TTZU5.png)


![RH dashboard](https://i.imgur.com/y6GSzCJ.png)

## Finalizing the design
This is my final design of the system, you can see the sensor and if you look closely you can see the resistor right below the sensor. This is a quite simple design with opportunities for improvement. If I would continue with this project I would add an air quality sensor, which adds one variable to my measurement readings to be able to see how good the ventilation of the apartment is. 

I have gotten the result I wanted and are happy with them. I have learned a lot in the process and got introduced to the world of programming/coding which is a path I am likely to cross a lot of times in the future. 
![Final design](https://i.imgur.com/sbmH2lO.jpg)
