---
# System prepended metadata

title: Tutorial on how to automate a floor-fan with a DHT11 sensor
tags: [Examination, IoT]

---

# Tutorial on how to automate a floor-fan with a DHT11 sensor

###### tags: `IoT` `Examination`
> Name: **Adam Wengrud**
> Student credentials: **aw223na**
> Time estimation following this tutorial: **8h**
> Operating system: **macOS Catalina Version 10.15.5**

## Project overview 
:::info
This project is about how to automate a specific object tied to a cord. By, controlling the electrical circuit on the cord with sensor values and a relay. In this case, the object is a floor-fan, controlled by temperature and humidity. Data from the sensor is being handled by a microcontroller that are sending signals to control the electrical circuit for the physical object. Data will be transmitted through an MQTT server and a local TIG-stack. Which uses Grafana to present data on the internet. This project also contain a trigger functions in Grafana that sends me a notification on discord when the fan is on. 
:::

## Objective
### Why this project and what purpose does it serve
The reason why I chose this type of project is because of my interest in optimization and efficiency. I wanted to understand how to use IoT to transmit data from a sensor on the internet and actually automate and optimize a physical object by the data. The purpose of the project itself does not make a huge difference in my daily life. For me, the project was more about understanding the powerful technology of IoT. 

### What insights you think it will give
I think this is a good starting project for someone who wants a straight forward project for an introduction to IoT. This project is easy to understand and will give insights on how IoT technology can be used for optimization. It also gives a good overview of how all elements from the sensor, protocols, databases, and internet are connected. This project will give you the base of knowledge to develop more complex projects later on and most important the knowledge to communicate and discuss this growing technology with others.

## Material
### List of material
|Component | Item| Purchased| Price|
|-|-|-|-|
|1| LoPy4 - With Headers| [:link:][Lopy4 with header]|366 SEK|
|2| Expansion Board 3.0 | [:link:][Expansion Board 3.0] |167 SEK|
|3| LoRa (868MHz/915MHz) & Sigfox Antenna Kit (Optional)| [:link:][Antenna Kit]|95 SEK|
|4| DHT11 Sensor | [:link:][DHT11-sensor] |100 SEK|
|5| Relay Maxload of 250V AC/10A, 30V DC/10A.| [:link:][Relay]|100 SEK|
|6| Jumper Cables M/M 10pack| [:link:][Jumper-hane/hane]|29 SEK| 
|7| Jumper Cables M/F 10pack| [:link:][Jumper-hane/hona]|29 SEK|
|8| Breadboard | [:link:][Breadboard]|59 SEK|
|9| Micro-USB| [:link:][Micro-USB]|100 SEK|
|10| Floor-fan | [:link:][Floor-fan]|349 SEK|
|11| Non-conductive enclosure | [:link:][Box]|47 SEK|
|| ==**TOTAL**==|| ==**1441SEK**==|

[DHT11-sensor]:          https://www.kjell.com/se/produkter/el-verktyg/arduino/moduler/temperatur-och-luftfuktighetssensor-for-arduino-p87086
[Relay]:              https://www.kjell.com/se/produkter/el-verktyg/arduino/moduler/relamodul-for-arduino-1x-p87032
[Floor-fan]:          https://www.clasohlson.com/se/Golvfläkt/p/Pr366576000
[Jumper-hane/hane]:   https://www.electrokit.com/produkt/labsladd-1-pin-hane-hane-150mm-10-pack/
[Jumper-hane/hona]:   https://www.electrokit.com/produkt/labsladd-1-pin-hane-hona-150mm-10-pack/
[Breadboard]:         https://www.electrokit.com/produkt/kopplingsdack-400-anslutningar/
[Lopy4 with header]:  https://pycom.io/product/lopy4/
[Expansion Board 3.0]:https://pycom.io/product/expansion-board-3-0/
[Antenna Kit]:        https://pycom.io/product/lora-868mhz-915mhz-sigfox-antenna-kit/
[Micro-USB]: https://www.kjell.com/se/produkter/mobilt/kablar-adaptrar/micro-usb-kablar/linocell-micro-usb-kabel-svart-025-m-p93423?gclid=CjwKCAjw88v3BRBFEiwApwLevZzQZzopLKChwViVHMMx4CzDfxVnFD7eDxAQWviZOUHTEKF0QF2tjxoC5rMQAvD_BwE&gclsrc=aw.ds
[Box]:                https://www.biltema.se/en-se/construction/electrical-installations/electrical-connection-boxes/junction-box-2000034324

### Short specifications

**1. LoPy4 with headers**
LoPy4 is a combination of wireless radios (WiFi, Bluetooth, LoRa, SigFox) and a MicroPython development platform that helps to get started with making Internet of Things (IoT) endpoints. The device has different inputs and outputs which is necessary to understand before setting up a project. The LoPy4 documentation is shown on [pycom.io].

[pycom.io]:      https://docs.pycom.io/gitbook/assets/lopy4-pinout.pdf

**2. Expansion board 3.0**
The board is where code is being handled. Here is also where you power your device through USB or batteries.

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

**3. Antenna Kit**
A universal LoRa & Sigfox Antenna that can be used with the LoPy, SiPy, LoPy4 and FiPy IoT Development boards. This project uses WiFi and micro USB to the computer, so this antenna is optional. But, using a LoRa or Sigfox radio without the external antenna can lead to damage to the device.

**4. DHT11 sensor**
A module that measures and provides data. The component contains three pinouts: 3-5V, GND, Data. Product specification for this sensor is a temperature range of 0-50 °C , error of +/- 2 °C, and humidity range of 20-90 %, error +/- 5 %.

**5. Relay**
Controls the electrical circuit. It´s like a switch, when the module gets a signal from the pycom device it closes the circuit and the power is on. Else the power can´t go through. The terminals can handle, normally closed 120-240 V (NC), normally open (NO) 120-240 V and common, from the AC side. From the DC there are three pinouts, Voltage +5V, GND, and Signal.

**6-7. Jumper Cables**
Propper cables that will be used as a connection between pycom device and module/breadboard.

**8. Breadboard**
A neat tool to let you create simple and organized circuits. 

**11. Non-conductive enclosure**
Very important for safety reasons. For this project, you need to cut and handle cords on 230 V. Therefore the relay has to be put inside a non-conductive enclosure for safety reasons. Also, make sure something is keeping the cords in place so there's no risk of drag it out by accident.

## Computer setup

### Update your Expansion Board

It might be the case that you first need to update the firmware on the expansion board, I didn´t. But, if you do, you can check that by follow the linked  documentation under [Expansion board 3.0.] When you have downloaded the recommended files. You need to follow the guide and execute all the steps in the computer terminal.

|Useful commands|| 
| -|-|
|$ cd|change direction in the terminal|
|$ ls|shows what is in the current file 


[Expansion board 3.0.]: https://docs.pycom.io/gettingstarted/installation/firmwaretool/

### Atom and PyMakr plugin

As IDE I use Atom, which can be downloaded at https://atom.io.

1. Download Atom, and install the package pymakr.
 
![](https://i.imgur.com/aDiCHoF.png)


Atom basics, how to upload code and structure your files.

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

2. Connect the pycom device to the computer via micro USB and press the reset button on the lopy. You should now be able to execute code directly on the device!
![](https://i.imgur.com/HTZqWho.png)

### Update Firmware

1. Download [Pycom Firmware Update], the link under updating firmware.

[Pycom Firmware Update]:    https://docs.pycom.io/gettingstarted/installation/firmwaretool/

2. Connect your Pycom device to the computor and open Pycom Firmware Update Tool. Remember to first close Atom before update, it will not work otherwise.

Depending on which platform you want to use for transmitting data you should choose the appropriate "type". Pybytes is the easiest choice when getting started. They already have their libraries installed in "type" pybytes. 

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

If you want to run with "type" pybytes their will be a conflict between multiple MQTT arguments later on. You need therfore disable the Pybytes lib by using the code line below in the REPL-interface, when you want to connect with your MQTT lib.
``` python
pybytes_on_boot(False)
```

## Putting everything together

*Note: Power source for the Pycom device is through micro USB connected to computer. Which is not shown in the picuture below.*
![](https://i.imgur.com/POIod5l.png)

### Electrical calculation
*The calculation is about how long time the sensor and fan can run before they consuming 1kWh.*

P = Watt (W), V = Voltage (V), I = Amp (A)

$$
P = V*I
$$


Power source:
3.3V from microcontroller (DC).
230V from house electricity to fan (AC).

#### Sensor
Prerequisites for the DHT11 sensor to work is DC power supply with 3-5V. The DC power supply comes from the pycom device, through 3.3V connected to the sensor. The sensor have a min and max milliAmp(mA) supply during measuring. Powered by a range of [3:5] V the sensor consumes [0.5:2.5] mA (while requesting data). The sensor also consuming [100:150] uA on standby, which neglects in this case. To calculate total time for consume 1 kWh, we need to calculate absorbing Wh on both sensor and fan.


$$
P_{dht11} = {3.3*0.5*10^{-3}} = 0.00165W
$$

Time to consume 1kWh if measuring every tenth minute.

$$
0.00165*{60\over10} = 0.0198Wh
$$

$$
{1000\over0.0198} = 50505h = 2104.4 days
$$

#### Fan
Further, the fan is powered by 230V AC(house electricity) and is absorbing 40Wh. That means that 1kWh can power the fan in 25hours (same calculations as above). The total time for the energy consumption of 1kWh is therefor:

$$
{1000\over0.0198+40} = 24.98h
$$

Which means that the project can run for 24.98h to consume 1kWh. This calculation gives a good perspective on how powerful the sensor technology is according to low power consumption.

## Platform
I started by presenting data on the Pybytes platform. Where data is automatically stored in the cloud and it uses an MQTT protocol. Pybytes is a user-friendly platform that is automatically connected to the device through the Pycom library, that you get if you update your device with “type” Pybytes. It´s good and it works but, you don’t really have the authority to see what happens in the database. Therefore I created a local TIG-stack with containers of Telegraf, Influxdb, and Grafana on a MQTT server instead. Telgraf is used to collect the data from the MQTT server and send it to the Influxdb. Influxdb stockage the data and send it to Grafana where the data can be presented on the internet. The reason why to set up a TIG-stack was basically that I wanted the authority to control and see everything that happens, which I also think is good for an understanding of the process. I´ve tried both of these platforms, and both are free. For me, it was good to start in Pybytes and with time go more to a local installation as the complexity raises as more authority you get. If I would to scale this idea I would absolutely run a local installation with TTN and maybe using Node-red as well.


## Code

**main**
``` python=1
import json
import time
import read_dht
import pycom
import _thread
from mqtt import MQTTClient
import ubinascii
import hashlib
import machine

#open config. In this case connection to WiFi and mqtt
with open('config.json') as f:
    config = json.load(f)

def sub_cb(topic, msg):
    print((topic, msg))

#method that controls the sending interval
def interval_send(t_):
    while True:
        send_value()
        time.sleep(t_)

#Visual signal when sending data to mqtt server
def blink_led():
    for n in range(1): # one lap
        # print(n)
        # 0
        # green ligth on the device
        pycom.rgbled(0x007f00)
        time.sleep(0.5)
        pycom.rgbled(0x000000)
        time.sleep(0.2)

def send_value():
    try:
        # define variables
        dht_Temperature, dht_Humidity, counter= read_dht.value()
        #Sensor range
        #Temperature measuring range: 0 ~ +50 --> one byte
        #Humidity measuring range: 20% ~ 90%  --> one byte
        #Counter is a binary value that shows on/off
        print('DHT11 Temperature: ', dht_Temperature,)
        print('DHT11 Humidity: ', dht_Humidity)
        print("Counter:", counter)
        #Publish data on the defined MQTT server. Config format-->
        #Collect in telegraf stockage in Influxdb
        c.publish(topic_pub,'{"Adam_sensor":{"DHT11 Temperature":'
                              + str(dht_Temperature) + ',"DHT11 Humidity":'
                              + str(dht_Humidity) + ',"Counter":'
                              + str(counter) +
                              '}}')
        #start visual sendingsignal on the device
        blink_led()

    except (NameError, ValueError, TypeError):
        pass

#define variables for lib:mqtt
topic_pub = 'devices/DHT11 Project-Adam/'
topic_sub = 'devices/DHT11 Project-Adam/control'
broker_url = 'sjolab.lnu.se'
# create a md5 hash of the pycom WLAN mac
client_name = ubinascii.hexlify(hashlib.md5(machine.unique_id()).digest())

#connect and subscribe to mqtt server
c = MQTTClient(client_name,broker_url,user=config['user_mqtt'],password=config['pass_mqtt'])
c.set_callback(sub_cb)
c.connect()
c.subscribe(topic_sub)

#start
_thread.start_new_thread(interval_send,[600])
```

**read_dht**
``` python=1
import pycom
from dht import DHT
from machine import Pin
import time

#stop blue blinking led on the device
pycom.heartbeat(False)
#define pinout on the device
#Type 0 = dht11, Type 1 = dht22
th = DHT(Pin('P23', mode=Pin.OPEN_DRAIN), 0)
relay = Pin('P5', Pin.OUT)
counter = 0
time.sleep(1)

#metod that read sensor values
def value():
    result = th.read()
    if result.is_valid():
        #starts the fan
        if result.temperature > 24:
            counter = 1
            #controls the relay. Value(1)=On
            relay.value(1)
            return(result.temperature,result.humidity, counter)
        else:
            counter = 0
            #controls the relay. Value(0)=Off
            relay.value(0)
            return(result.temperature,result.humidity, counter)

``` 



## Transmitting the data/connectivity
For this project, data is sent every tenth minute (600 sec), when the device is plugged in with micro USB. The choice of sending interval is based on how fast temperature and humidity change. Normally that doesn´t happen very quickly. Therefore I send data every 600second. 

``` python
_thread.start_new_thread(interval_send,[600])
```



The data is further transmitted to the internet through WiFi as a wireless protocol and MQTT and webhooks as transport protocols. WiFi means that the wireless protocol can handle high data rates and also is able to consume a lot of battery power. But, that comes to a cost of low range. Therefore this project actually is more suitable for the usage of LoRa as a wireless protocol. My DHT11 sensor sends temperature and humidity values of low data rate (one byte per value) which means that I don´t need the big data rate advantage the WiFi gives. Therefore it´s better to use the range and mobility advantage through the LoRa protocol which also is less battery consuming, as shown in the picture below. The reason why I didn´t use LoRa was because I was out of range for a station and didn´t have the equipment to solve it.


![](https://i.imgur.com/up5A3KF.png)
```
Table that descirbes the characteristics of wireless protocols
```

As a transport protocol, I use MQTT which is a custom protocol for IoT. MQTT is useful because it´s lightweight and takes minimum bandwidth that does ensure high latency. Data send through webhooks in json objects (JavaScript Object Notation), which is a specific format, that is shown in step 4 below. At first, I wanted to use my TIG-stack with the gateway protocol TTN (The Things Network) but I didn´t get any connection with LoRa therefor I use MQTT instead.

### How to transmitting data on MQTT in Atom

1. Upload a library called mqtt in a lib folder: [mqtt.py]

[mqtt.py]:  https://github.com/iot-lnu/applied-iot-20/blob/master/network-examples/ccs811-bmp180-dht22-MQTT/lib/mqtt.py

2. Set up a json object for webhooks called config.json. 

``` python=1
{
  "ssid": "YOUR_WIFI",
  "ssid_pass": "YOUR_PASSW",
  "user_mqtt": "MQTT_SERVER",
  "pass_mqtt": "MQTT_PASSW"
}
``` 

3. Then you need to connect WiFi to the device: [boot.py]

[boot.py]:  https://github.com/iot-lnu/applied-iot-20/blob/master/network-examples/ccs811-bmp180-dht22-MQTT/boot.py

4. You already have the main code where you publish data on MQTT. That´s shown code line 48-52.

5. Check data from the MQTT server. Download [MQTT explorer] and log in on your MQTT server.

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

[MQTT explorer]:    http://mqtt-explorer.com

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

### How to set up a TIG-stack with Docker
For setting up the TIG-stack I highly recommend the [TIG-stack guide]. I used that and it does describe every element you need to know about create your own TIG. Note that you need to find the TIG-stack map from the terminal when you run it. **Depending on where you place your TIG map.**

```
$ cd Desktop
$ cd TIG-stack
$ docker-compose up
```

[TIG-stack guide]:     https://hackmd.io/@lnu-iot/tig-stack



## Presenting the data

My dashboard in Grafana contains the process of inside temperature and humidity in a room. The graph shows the values over the last six-hour. I also use “Stat” visualization to present current values and max/min over the last six hours. In the middle of the board, I have an on/off chart which is illustrated in binary code that represents the status of the fan. This is coded in main and read as “counter”, sets to 1 when temperature is over 24 Celsius. I thought it would be a neat feature to have, to clearly see when the fan is on and off.

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

On the Object graph, I also created an alert function that automatically sends a status notification to my discord server when the counter is 1 for a timeintervall of 2min.

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



### How is the dashboard built
For setting up Grafana i refer to [TIG-stack guide] agian. To the topic "Visualizing data with Grafana", it doesn´t get anymore clear than that. 

My dashboard is built upon two graphs, one text, and six “Stat” visualizations. The principle is the same for all except text visualization. You need to get data from somewhere and filter what you want to present, as shown in the pictures below.

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

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


For the alert function you need to first create a notification channel.

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

After that you choose that channel into where you want to apply the alert and decide settings.

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



### Choice of database

The database I use in this project is a time series database called Influxdb. The data in this database is being aggregated over time which means that every data point has a timestamp associated with it, compared to rational databases that are based on tables. The biggest difference is that rational databases are more scalable but a time series database often has a faster ingestion rate. Which makes it perfect for me in this project as a combination with IoT where I monitoring devices. As shown in the picture below rational databases also have a fast ingestion rate at first but decrease by size of data.

![](https://i.imgur.com/0cMVmFi.png)
https://devconnected.com/the-definitive-guide-to-influxdb-in-2019/


Data is saved as often as you send it. For this project as I mentioned earlier that data is sent every tenth minute (600 sec). In my time series databases, Influxdb can take care of dropping data after a certain time, with a concept called retention policy. That defines how long you are going to keep your data. My Influxdb is set to default which automatically sets the retention policy to “autogen” and will keep my data forever, if I don´t want to erase it.

## Finalizing the design

### Final results of project

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


The floor-fan works! My intention with this project was to get a great understanding of IoT technology and how it works, which I did. I also gained knowledge to control electrical objects tied to a cord which I think is a neat thing to know. My pre-knowledge before this project was programming, basic python. Besides that everything was new to me, which means that I developed a lot of valuable knowledge from this course and by doing this project.


### What could I have done in another way?
This course gave me a new perspective on the importance of low power consumption and how powerful the IoT technology is. Therefor I really wanted to connect my project to LoRa and work with TTN, which didn´t work because of long-distance. Also, it would have been a good idea to add batteries connected to the device instead of always power with micro USB. This would effect the mobility on the device which I think that is an important aspect to take along to future projects. 



