---
# System prepended metadata

title: Beginner indoor thermometer(IoT)
tags: [pycom, Thermometer, IoT, tutorials]

---

# Beginner indoor thermometer(IoT)
###### tags: `tutorials` `IoT` `Thermometer` `pycom`
## Introduction
By: Patrik Pedersen (pp222kc)

This tutorial describes an easy way to create an indoor thermometer, which measures the indoor temperature in celsius and send its data by wifi, so you can see the temperature changes on a graph. It's also a project that is quite beginner friendly.
Estimated time to create: 15h 


## Objective

This is my first IoT device. So I wanted to make something simple, something that opened the door to the world of IoT for me, without being too intimidated.
The purpose of this project is not to create some advanced Iot-device, rather it is a project that works like an entry door to IoT. And hopefully this project will show it.

## Material
For this project I use devices from pycom. pycom creates devices which are easy to use and very flexible in connectivity. Their devices uses micropython which is an userfriendly programming language for beginners.

Most of the hardware is bought at electrokit.se and the price of the products is pretty similar at other places aswell.

In the table below you can see the things I used for the Iot device:

| Material | Function | Price |
| -------- | -------- | -------- |
|pycom lopy4|MicroPython enabled development board|350kr|
|pycom expansionboard|Connect lopy4 and sensors etc.|199kr|
|Micro USB|Power the pycom devices|40kr|
|Breadboard|Solderless pins and sensors connector|59kr|
|Sensor DS18B20|Sensor for temperature measures|42kr|
|Jumper cables (3pcs) male to male| Connection between expansionboard and breadboard| 36kr (65pcs)

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


For more information about the pycom devices, visit pycom's homepage at pycom.io


## Computer setup
For this project I used visual studio code. And the programming language is micropython. 
Before I start to create something, I make sure visual studio code is prepared for the pycom device. Two things I had to do was install extension in vsc. Click the extension button on the left hand side in vsc and type in Pymakr, download and install this extension. And also make sure you got node.js installed.
When loading your written code into your pycom device. Just press the button upload which you can see in the blue field
![](https://i.imgur.com/jf7UN5S.jpg)
Another thing worth mentioning is to match your ports. Otherwise you will get following message in the vsc console:
![](https://i.imgur.com/Y7fTVV2.jpg)
To change this. Enter your pymakr.json file via vsc (press all commands in the blue field and then global setting). Make sure the adress is the COM-port your device is connected to. (Check which port you have to enter in the device manager).    



## Putting everything together
My setup for my IoT device is purely for prototype since it's still loose cables for example. For a real thermometer I would probably make it more sturdy by soldering etc. But as you can see in the picture below, I have connected the devices as following:
1. Black cable (Ground) -> GND on expansionboard to a12 on breadboard
2. Red cable (3V3) -> 3V3 on expansionboard to b13 on breadboard
3. Blue cable (Data) -> P10 on expansionboard to c15 on breadboard
4. DS18B20 connects(with oval side towards cables) to e12,e13,e14 on breadboard

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


## Platform
My choice of platform for my device is Grafana. Since i'm new to everything that has to do with IoT, I can't really compare to anything else. And for the device I have built, I'm not planning to scale my idea either. So it's purely a choice I made from another persons recommendation and me wanting to have a simple graph to show the differences in temperature.

## The code
Libraries used in the code are following:

* OneWire -> https://github.com/pycom/pycom-libraries/blob/master/lib/onewire/onewire.py
* MQTT ->https://github.com/iot-lnu/applied-iot-20/blob/master/network-examples/ccs811-bmp180-dht22-MQTT/lib/mqtt.py

Borrowed code:

* boot.py -> https://github.com/iot-lnu/applied-iot-20/blob/master/network-examples/ccs811-bmp180-dht22-MQTT/boot.py
* Parts of main.py -> https://github.com/iot-lnu/applied-iot-20/blob/master/network-examples/ccs811-bmp180-dht22-MQTT/main.py



main.py:
```python=
import time
from machine import Pin
from onewire import DS18X20
from onewire import OneWire
import json
import pycom
import _thread
from mqtt import MQTTClient
import ubinascii
import hashlib
import machine

ow = OneWire(Pin('P10'))
temp = DS18X20(ow)

with open('config.json') as f:
    config = json.load(f)

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

def interval_send(t_):
    while True:
        send_value()
        time.sleep(t_)

def send_value():
    try:
        temperature = temp.read_temp_async()
        temp.start_conversion()
        time.sleep(3)
        c.publish(topic_pub,'{"office_sensor": {"Temp":' + str(temperature) + '}}')
        print('Sensor data sent ..')
        print("Temp = ", temperature, "C")

    except (NameError, ValueError, TypeError):
        print('Failed to send!')


# topic = 'testtopic7891/1'
# broker_url = 'broker.hivemq.com' # HiveMQ can be used for testing, open broker
topic_pub = 'patrik/home-temp/'
topic_sub = 'patrik/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=config['user_mqtt'],password=config['pass_mqtt'])
c.set_callback(sub_cb)
c.connect()
c.subscribe(topic_sub)

def listen_command(i_):
    while True:
        c.check_msg()
        time.sleep(i_)

_thread.start_new_thread(interval_send,[10])
_thread.start_new_thread(listen_command,[0.1])
```
Most of the code in main.py is borrowed as mentioned above. The only thing I have changed is that I added line 13&14 + line 29-31 for temperature measuring and removed som unnecessary code for my project.

config.json:
```json=
{
    "ssid": "Your_WiFi",
    "ssid_pass": "your_WiFi_Password",
    "user_mqtt": "username_mqtt",
    "pass_mqtt": "password_mqtt",
    "APP_EUI": "Your_APP_EUI",
    "APP_KEY": "Your_APP_KEY"
  }
```
Above is the short code used in the json file for username and password input.

## Transmitting the data / connectivity
The data is transmitted through WiFi. I did try to send data via LoRa, but I couldn't get a connection in my hometown. So I ended up with using my WiFi. As far as transport protocol, I ended up with MQTT. And all the code I needed for the transport protocol is mentioned in the code section. But with all my code uploaded to my pycom device, I send my data via a broker ("MQTT"). With a simplified explanation, a broker is like a postoffice for data. Then to influxDB(Database). And the end station for my data is Grafana. The data is sent via the broker to the grafana platform every thirteenth second. To run the above application, I needed a docker aswell. To keep it short I will paste a hompage with a good description of what a docker is.
https://opensource.com/resources/what-docker

## Presenting the data
The dashboard contains a simple graph showing the indoor temperature. And it is updating with new data every minute.
![](https://i.imgur.com/O8XI2il.jpg)
The data is saved in the database every 15s.
Database used (InfluxDB).

## Finalizing the design
Probably one of the funniest project and school course so far! It's something special by creating everything by yourself, and of course some help from friends and the online community. Due to lack of time, my project has lacked som finesse. The code could be way more clean. There is still alot to remove from my code until I get a nice clean code. Next step would probably be to add more features to it. And even maybe get a 3D-printer to print my own chassis. I wished I had more time to fix my project a little better. But at the same time, I was aiming for a beginner project to get the feel of it. And I think I did that quite well. And I'm looking forward to my next IoT project.
![](https://i.imgur.com/WFMIa7p.jpg)
