# Temperature & Humidity sensor tutorial
## Intrduction
Hello! my name is Omar Alhamad (oa222ct)
My project is to gather temperature & humidity sensor data for comparing how hot / humid each room will get during the summer period.
the project from A-Z should not take more than 3H to build, upload correct code, install needed software and start seeing results.
## Objective
I choose this project because this will help me make a descicion, and the decisison is to single out the best room in my apartment for sleeping because it can get really hot durin the summer, the insight gathered will show how well the air conditioning is working in the aparment where I do all the measurin
## Material
Now to follow along this tutorial you will need to buy a couple of
things(nothing comes free). prices may vary.
The board we will use is the Pycom lopy4 (The brain) with headers connected to an expansionboard 3.0 (that we use to connect things to) that we will run cables from to the breadboard where we will connect the DHT11 sensor.
The Lopy4 will be running micropython and a simple program to send the data gathered from the sensor.
The Expansionboard 3.0 will house the lopy4 and run driver so you can connect it to your windows pc and upload code to it.
The sensor will be connected to the expansionboard 3.0 with wires and will transmit the data to the lopy4.
The DHT11 is the sensor that will be measuring the temp & relative humidity
The Wires are used to connect everything togheter
The usb cable is used to exchange data between the computer and the lopy4

---
down below is a list of links to each thing that you need to get, some of them are mandatory (bare minimum) and some are optional if you choose to buy them for other usecases.
I choose the cheapest possible parts I could find (prices may vary)
| Link to products | Price in Sek | Mandatory | Optional |
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------|-----------|----------|
| [Pycom Lopy4](https://pycom.io/product/lopy4/) | 364 | x | |
| [Pycom ExpansionBoard 3.0](https://pycom.io/product/expansion-board-3-0/) | 170 | x | |
| [DHT11 Sensor](https://www.electrokit.com/produkt/digital-temperatur-och-fuktsensor-dht11/) | 49 | x | |
| [Wires](https://www.electrokit.com/produkt/labbsladd-20-pin-15cm-hona-hane/) | 29 | x | |
| [Usb Cable](http://www.billigteknik.se/laddare-och-kablar/18084-goobay-microusb-kabel-svart-0783555111819.html?utm_campaign=Laddare+och+kablar&utm_content=18084_11843&utm_source=pricerunner&utm_medium=cpc&utm_term=new#/langd-3_meter) | 29 | x | |
| [Usb Charger](https://www.kjell.com/se/produkter/mobilt/mobilladdare/usb-laddare/linocell-mini-usb-laddare-24-a-vit-p90218) | 99 | | x |
| [Cables for breadboard use](https://www.electrokit.com/produkt/labbsladd-20-pin-15cm-hane-hane/) | 29 | | x |
| [Breadboard](https://www.electrokit.com/produkt/kopplingsdack-400-anslutningar/) | 59 | | x |
The total price for everything that is mandatory expludin shipping will be 641kr.
## Computer setup
There are a couple of things you will need on your computer,
all theese will be running on Windows 10 as an operating system.
An IDE for editing code, the one I use for all my projects is Visual Studio Code (vscode) from microsoft and I will link to all the software in a list below.
Docker to run the database where all the data gathered will be stored, to run grafana that is the graphical interface to preview all the data and also telegraf that is the agent to gather all the iot data.
* [Visual Studio Code](https://code.visualstudio.com/download)
* [NodeJS LTS](https://nodejs.org/en/)
* [Docker](https://www.docker.com/products/docker-desktop)
* [Python](https://www.python.org/ftp/python/3.7.8/python-3.7.8-embed-amd64.zip)
After installing theese 3 you need to setup some more software & drivers.
First you need to follow pycoms guide on how to install the drivers for your expansionboard, follow this [guide](https://docs.pycom.io/gettingstarted/). Setup your hardware and software, After that you will need to setup a plugin for vscode [here](https://docs.pycom.io/pymakr/installation/vscode/). Once you have vscode running with the pymakr plugin and the drivers ready and installed and also after running the pycom firmware updater now we can get started.
## Putting everything together

The image above is the Circuit diagram showing you how to connect everything, you use the female header on the dht11 pins and the male headers on the expansionboard 3.0.
The data pin that is closes to the left goes to p10 on the board, the middle pin goes to vcc (5v) and the last pin to the right goes to ground (gnd).
## Platform
Now that everything is installed and every component is connected we need to connect it to you windows computer with a microusb to usb cable.
The platform will be running on your local computer so no cloud storage, but you have your own data locally, i prefer it that way. Among the db are also grafan that is a powerful tool to visualize data, video showing you how comes later down the tutorial.

You will need to download theese files and have them in the same folder on your computer or prefrably a server of sorts, I run my programes on another computer in my home that I use as a general purpose server but that is not required.
Downlaod the TIG-Stack from the github link i have provided [here](https://github.com/iot-lnu/applied-iot-20/tree/master/tig-stack).
We will be using wifi to send data through mqtt so nothing needs to be changed unless you want to use TTN then you need to setup and account on [The Things Network](https://www.thethingsnetwork.org/) and change a few lines but we wont do that in this tutorial.
Once you have them and have also started Docker, enter the folder and run a terminal / commandline (cmd) and run the command `docker-compose up` or `docker-compose up -d` to run it in the background, the first command will have a terminal up and if you close it down it will shutdown your stack with the database, grafan and telegraf (your data will NOT be lost) but the programs will not be running, you will need to run `docker-compose up` again to run or add the -d in the end to run it in the background.
Now, open up your browser and navigate to [http://localhost:3000/](http://localhost:3000/) and you have entered the grafana interface, the user and password is 'admin' I would recommend changing thseese and you will be promted to do so the first time you sign in.
## The Code
[Code](https://github.com/omar93/TempHumSensor) that you have to download and change a little bit to fit your network and you upload it to your device.
open the config.json and change the "wifi name" to the wifi name you use to connect and the "wifi passoword" to your wifi password, this will be used by the lopy4 to send data.
Below is the `main.py` that is the main program
```
import json
import time
import read_dht
import pycom
import _thread
from mqtt import MQTTClient
import ubinascii
import hashlib
import machine
# Reads from the config file
with open('config.json') as f:
config = json.load(f)
# Interval that calls the data read / send with the interval it gets
def interval_send(t_):
while True:
send_value()
time.sleep(t_)
# Function used to read the data and send it / print it
def send_value():
try:
dht_T, dht_RH = read_dht.value()
print('dht temp: ', dht_T) # one byte
print('dht RH: ', dht_RH) # one byte
c.publish(topic_pub,'{"Topic": {"dht temp":' + str(dht_T) +
',"dht RH":' + str(dht_RH) +
'}}')
print('Sensor data sent ..')
except (NameError, ValueError, TypeError):
print('Failed to send!')
#Topic to publish to
topic_pub = 'devices/office-sens/'
topic_sub = 'devices/office-sens/control'
broker_url = 'sjolab.lnu.se'
client_name = ubinascii.hexlify(hashlib.md5(machine.unique_id()).digest()) # create a md5 hash of the pycom WLAN mac
c = MQTTClient(client_name,broker_url,user='iotlnu',password='micropython')
c.connect()
# Thread running the interval every second
_thread.start_new_thread(interval_send,[1])
```
on row 121 you can change the "topic" to identify your sensor data
"c.publish(topic_pub,'{"changeme"".
## Transmitting the data / connectivity
The data will be sent over wifi for simplicity, the protocol used is MQTT its a public and subscribe and works on the tcp/ip stack, the reason for mqtt is your IOT device wont be sending large ammounts of data compared to HTTP, can be a couple of bytes in size like this case. An MQTT broker will recive the data and send to who ever is subscribed
In this example code above on the last line you have:
```
_thread.start_new_thread(interval_send,[1])
```
and that will run the function for sending data every second, you can change this simply chaning the number 1 to a number 10 and it will send every 10 second etc.
## Presenting the data
Telegraf will store the data in your influxdb and then you will have grafana visualize your data. depending on how often you send the data with the interval that is how often data will be saved in your influxdb.
Grafan should look like this when you connect and i go through how to setup dashboards in the video below, note: i go to http://192.168.10.144:3000 that is because I run grafana on another computer, if you run it on your own computer you go to http://localhost:3000
<iframe width="1280" height="720" src="https://www.youtube.com/embed/C0AUDfx1NP4" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
## Finalizing the design
Now you should have everything up and running, my own project may differ a little frm your own since i only had male/male & female/female wires, but i just connected them to each other and it can be used as a female/male wire in the end.
Overall I really enjoyed this project, I hope you did as well, something I could have done in another way is to try the loRa that I did not have acess to, maby try some more sensors? but all in all it was a great learning experience
