---
# System prepended metadata

title: 'Tutorial: Thermometer & humidity sensor'

---

# Tutorial: Thermometer & humidity sensor

##### Martin Andersson (ma225qm)

This project is an IoT-device which measures the temperature and humidity once every minute, sends the data to a platform on which the data then is presented. This project may be a good first project to get an insight of the world of IoT. 

###### Approximate time duration: **2 h**

## Objective

* Why i chose this project
I chose this project because i believe it is really straight-forward and thought it would make a gentle way for me into IoT-projects. 

* What purpose it serves
The purpose of this project will firstly serve as a thermometer and measure the humidity, but I also believe that is is a good first step towards doing more advanced IoT-devices. There are great opportunities to connect other devices or sensors to this device. That could for example be connecting it to a fan, and then start that fan if it's over a certain temperature, or start a humidifier if the humidity-level in the air is below a certain level. 

* What insights you think it will give
I think this project will bring some basic knowledge about implementing an IoT-project, but also I hope that it creates a deeper interest around Internet of Things and doing your own IoT-project. 

## Material

Here comes a table of the material used for this project. The price of an items is also a link to where you can buy it.

| Item                | Specification                                                      | Price                                                                                       |
| ------------------- |:------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- |
| LoPy4               | Micropython-programmable board that works with WiFi, Bluetooth, Sigfox and LoRa.                                                               | [€34.95](https://pycom.io/product/lopy4/) |
| Expansion board 3.0 | Expansion board that compatible with LoPy4. Enables connecting LoPy4 to a computer via USB.                                                               | [€16.00](https://pycom.io/product/expansion-board-3-0/)                                     |
| Breadboard          | Size: 82 x 55mm. 400 connections.                                                                | [59 SEK ~ €6](https://www.electrokit.com/produkt/kopplingsdack-400-anslutningar/)           |
| DHT11               | Temperature and humidity sensor module. Temperature range is 0°C - 50°C with an accuracy of +-2°C. Humidity range of 20% - 90% RH with an accuracy of +-5% RH.                                                               | [ 49 SEK ~ €5](https://www.electrokit.com/produkt/digital-temperatur-och-fuktsensor-dht11/) |
| Wires               | Male/male wires connecting the expansion board with the breadboard. | [29 SEK ~ €3](https://www.electrokit.com/produkt/labbsladd-20-pin-15cm-hane-hane/)          |
| USB cable           | Micro USB male to USB A male.                                      | [39 SEK ~ €4](https://www.electrokit.com/produkt/usb-kabel-a-hane-micro-b-5p-hane-1m/)      |
|                     | **Total:**                                                         | **~ €69**                                                                                   |
![LoPy4](https://i.imgur.com/LYCKfnH.png)
**LoPy4**



## Computer setup

#### IDE
I have used Atom for this project, which can be downloaded from [here](https://atom.io/). The pymakr package will also need to be installed to your Atom. The pymakr package can be found [here](https://atom.io/packages/pymakr).

#### Uploading code
Testing the code when the LoPy4 is connected to the computer via USB can be done by pressing `ctrl+alt+r` to run a specific file. 
The code can be uploaded to the device directly in the pymakr plugin in Atom by pressing `ctrl+alt+s`.

#### Steps for computer
If you are using Windows you might have to install drivers, which you can do from [here](https://docs.pycom.io/gettingstarted/installation/drivers/). When first connecting the LoPy4 to the computer it is strongly recommended that you update the firmware. A guide to that can be found [here](https://docs.pycom.io/gettingstarted/installation/firmwaretool/).

## Putting everything together
![](https://i.imgur.com/dEfyx7F.png)
On the expansion board the yellow (data) wire is connected to P9, the red (VCC) is connected to 3V3 and the black (ground) is connected to GND. The LoPy4 is powered through a micro USB - USB A cable that may be connected to a computer or a power brick to the wall. 

## Platform
For this project [Pybytes](https://pybytes.pycom.io/) is the platform on which the data is sent to and also presented to the user. 

## Code
```
# main.py -- put your code here!

import machine
import dht
from machine import Pin
import _thread

th = DHT(Pin('P9', mode=Pin.OPEN_DRAIN), 0)
#time.sleep(2)

# Takes celsius as a parameter and returns that temperature converted to fahrenheit
def celsius_to_fahrenheit(temp_in_celsius):
    return (temp_in_celsius * 1.8) + 32

# Reads a value from the DHT sensor.
# If the result isn't valid it continues to read values from the DHT sensor until a result is valid.
# It prints the temperature, humidity and temperature converted to fahrenheit.
# It sends a signal (1) for temperature.
# It sends a signal (2) for humidity.
# It sends a signal (3) for temperature in fahrenheit, it is formatted so it only sends the result with one decimal.
# The thread is delayed for 60 seconds to execute the program (it waits for 60 seconds untill continuing running the program).
def send_env_data():
    while True:
        result = th.read()
        while not result.is_valid():
            time.sleep(.5)
            result = th.read()
        print('Temp:', result.temperature)
        print('RH:', result.humidity)
        print('Temp in fahrenheit: ', celsius_to_fahrenheit(result.temperature))
        pybytes.send_signal(1,result.temperature)
        pybytes.send_signal(2,result.humidity)
        pybytes.send_signal(3,"{:.1f}".format(celsius_to_fahrenheit(result.temperature)))
        time.sleep(60)

_thread.start_new_thread(send_env_data, ())
```

## Connectivity
The data in sent wireless through WiFi. The transport protocol used is MQTT. With the Pybytes platform the data is automatically stored in the cloud. 

Code-wise the data is sent through the `pybytes.send_signal()` command. For example `pybytes.send_signal(1,result.temperature)` sends a signal [1] with the value of [result.temperature]. In Pybytes you can then define that signal 1 is *Temperature* with the unit *C* for example. 

## Data presentation
![](https://i.imgur.com/BJFcXrH.png)
Here the dashboard is displayed. In Pybytes you can add tables, bar charts and line charts displaying the data. In this project I have as shown in the picture above chosen to display three line charts. One for the temperature in Celsius, one for the temperature in Fahrenheit and one for the humidity level. In the picture the graphs are showing data for the latest three hours. Normally I would show the data for the latest 24 hours, but in this case the system had only been live for less than so. The dashboard also shows the location of the LoPy4 device and the amount of data sent for the latest hour and 24-hour period. 

The data is stored in the database for one month, and the database is updated with new data every time the devise sends a signal to it, which in this case is one time every minute. 

## Finalizing the design
In the end I think the project went well. As always when learning something completely new you "stumble in the dark" a bit in the beginning but by trial and error everything eventually everything connect. I would really liked to get started earlier with the project so I could have developed it further by now, but that is something i plan to do in the near future. :)

### Here comes a few pictures!
![](https://i.imgur.com/RQdECmu.jpg)
![](https://i.imgur.com/RmMXIsu.jpg)
These two images above shows how the LoPy4 with expansion board looks when connected to the DHT11 sensor on the breadboard. For this simple setup the breadboard wouldn't be necessary, but it makes it easy to work with in my opinion. 

![](https://i.imgur.com/oE4EO0m.png)
The picture above shows how Atom and the pymakr package looks when connected via USB to the LoPy4 and running the code. 




## Further development
I am very positive to the idea of taking this project to the next level and develop it further. An idea of what that could be that I have thought about doing would be to retrieve weather data from an API (SMHI for example) and then check the correlation between the forecast and the actual temperature measured by my device's temperature sensor. 