---
# System prepended metadata

title: TEMPERATURE SENSOR

---

# TEMPERATURE SENSOR

:::info This tutorial is made by: 
**Made by:** Alexander Stenberg (as226fg)
:::

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


The purpose of this tutorial is for anyone interested in IoT (Internet of Things). And how they can create a temperatur-application at home using some basic hardware and code and send the temperature-value using Wifi to a cloud-plattform on the internet. If everything works smooth, and you have all the matieral required for this project you should be able to complete this tutorial and see your data presented in a cloud under 30 minutes. 

**This tutorial will cover the following:**

- Objective 
- Material
- Computer setup
- Putting everything together
- Platform
- The code 
- Transmitting the data / connectivity
- Presenting the data
- Finalizing the design


## **Objective**

The reason behind the project was to analyse the temperature in my apartment. I chose to build this project because of my interest in getting to know more about IoT (Internet of Things), sensor and sending data over the internet from a device. The purpose of this project is to make it simple and easy accessable to show the temperature home even if I'm not around. But also get statistic about the variation in temperature during the days and hours. Hopefully I get insights if the current temperature in my apartment relates to the information I can recieve from my phone using a weather-application, or maybe it differs? 


## **Material**

To be able to create a project that measures the temperature you need the following material:

1. **Computer**
2. **Pycom Expansionboard 3.0**
3. **Pycom Lopy4** 
4. **USB-cable**
5. **DHT11-sensor**
6. **3 Jumping wires**

I purchased all the material from [Electrokit](https://duckduckgo.com/?q=electrokit&atb=v206-1&ia=web&iai=r1-0&page=1&sexp=%7B%22v7exp%22%3A%22a%22%2C%22rgiexp%22%3A%22b%22%2C%22bfexp%22%3A%22b%22%7D), where they created a packaged with all the nessecary artifacts for starting an IoT-project. Unfortunatly the packages is not avaliable anymore. I have linked the same setup and where you can find them in this section to get started. 

I want to point out that if you are using Mac or Linux, you might have to take different routes in order to get it to work. But don't worry. ***Keep Calm And [Google](https://google.se) It.***

Below you will a short presentation of the material.

**Computer** - This project was created on a laptop with Windows 10 Home Edition as operating system. The computer is used to write the code and upload it to the device, but also in this case power the expansionboard, lopy4 and sensor via USB.  

**Pycom Expansionboard 3.0**

Your Pycom device will need som way to be programmed and that's exactly where this board comes in. It allows the means to create and connect new IoT-project with your Lopy. It has a dozen of ready to use templates and libariers. You use this board to connect the sensor with the jumping wires. It powers the devices and sensor via micro-usb. 

![](https://i.imgur.com/qlEW0cY.jpg)
(Source: Pycom)

It can be purchased [here](https://pycom.io/product/expansion-board-3-0/) for £16.00


**Pycom Lopy4**

Lopy4 is a quadruple network MicroPython enabled development board. Quadruple refeers to the different way you can connect the board to. You can use WiFi, Lora, Sigfox and Bluetooth. In this tutorial we are using WiFi as the network protocol. It's the perfect device for anyone who want different alternatives when it comes to sending data. 


![](https://i.imgur.com/tW6rRMf.png)
(Source: Pycom)

It can be purchased [here](https://pycom.io/product/lopy4/) for £34.95. 


**USB-Cable**

The USB-cable is used to power the expansionboard and Lopy4 device. It's also used to transfer the code from the IDE to the device. Make sure that the cable is able to send and receive data, otherwise it will not work. 
![](https://i.imgur.com/u3Pajww.jpg)
(Source: Amazon)



It can be purchased [here](https://www.amazon.com/AmazonBasics-Male-Micro-Cable-Black/dp/B07232M876/ref=sr_1_4?dchild=1&keywords=usb+cable&qid=1593542716&sr=8-4) for $6.34. 


**DHT11-sensor**

The DHT11-sensor is a low-cost digital temperature and humidity sensor. Humidity and temperature sensors detect the relative humidity of immediate environments in which they are placed. They measure both moisture and temperature in the air and express relative humidity as a percentage of the ratio of moisture in the air to the maximum amount that can be held in the air at the current temperature. As the air becomes hotter, it holds more moisture, so the relative humidity changes with the temperature.

![](https://i.imgur.com/v0SqbCB.jpg)
(Source: Components101)


It can be purchased [here](https://www.electrokit.com/en/product/digital-temperature-and-humidity-sensor-dht11/) for 49kr. 

**Jumping wires**
Jumping wires are wires that have connector pins on each end, which allows them to be used to connect two points to each other without souldering. They are typically used with breadboards and other prototyping tools in order to make it easy to change circuits as needed. This wires transfers the data from the sensor to the device and gives the sensor power. 
![](https://i.imgur.com/wL5vM0A.jpg)
(Source: Electrokit)

It can be purchased [here](https://www.electrokit.com/en/product/jumper-wires-20-pin-30cm-male-male/) for 29kr. 
## **Computer setup** 

Now when you know what material that is required to proceed. Let's dig into the computer setup. To be able to measure the temperature you have to do the following steps on your computer to be able to access the device and upload your script.

**Step 1:** The first thing you have to do is to connect the Lopy4 device on top of the expansionboard. It should look like the this: 

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

Make sure that the Lopy4 is connected correct on top of the expansionboard, if the Lopy4 device is attached the wrong way, it will not work.

**Step 2:**
The second step is to connect the USB-cable to the computer and expansionboard. When connected succesfully to the computer the Lopy4 device should start blinking in blue. 

It's recommended to update the FirmWare on the Expansionboard if needed, the 3.0 version has the newest update, so If you have an older version like the Expansionboard 2.0 you can follow the following steps to [Update the device](https://docs.pycom.io/gettingstarted/installation/firmwaretool/). 

**Step 3:**
When the previous steps are done, you are now ready to continue. Now it's time to download the IDE. IDE stands for integrated development enviroment and is a software application that provides comprehensive facilities to computer programmers for software development. 

This is the program you write your code and upload it to the device. I've been using Atom, which is a free IDE and suits very well to this project. It's easy to use and get started. 

You can download Atom [here](https://atom.io/).

Follow the instructions and start the program, when it's done deconnect the USB from the computer and follow the next step.  

**Step 4:** 
To be able to access your device thru Atom you have to install the Pymakr plugin. This can be done easily via Atom. Follow the instructions from Pycoms documentation.

[Download pymakr to Atom](https://docs.pycom.io/pymakr/installation/atom/)

When the installation process is done, connect your device and restart Atom. Now when you start Atom, the Pymakr plugin will auto-connect your device to the IDE. If this is done sucessfully the following indication should be seen >>>. The three arrows shows that you are connected.

![](https://i.imgur.com/7So6a5P.png)
(Source: Pycom)

Now you can write your python code in the REPL after the >>>, and also write in a file and upload the code to the device using the button on the left side of the REPL. 


## **Putting everything together**

Now when you have downloaded Atom, pymakr and successfully connected the device to the IDE the next step is to connect the sensor to the expansionboard. 

Start to unplug the device from the computer. 
Take the three jumping wires and connect the following. 

**Cable 1** - Connect one end to the P23 on the expansionboard. Connect the other end to the pin on the to the data-pin like the illustration shown below. This wiring helps you to transfer data from the DHT11-sensor. 

**Cable 2** - Connect on end to GND on the expansionboard and the second end to the middle pin on the sensor. Ground, in the context of electronics, is the reference point for all signals or a common path in an electrical circuit where all of the voltages can be measured from. This is also called the common drain since the voltage measurement along it is zero. Ground could also refer to the earth ground, literally connecting electrical equipment to the ground to prevent user contact with high voltages.

**Cable 3** - Connect one end to the 3v3 pin on the expansionboard and the second end to the third pin on the sensor. This is a simple 3V3 volt power supply powered from a micro USB connection and sized to fit on a breadboard.

The illustration below shows how the jumping wires should be connected between the expansionboard and the DHT11-sensor. The colors shows which pin, and where it should be connected. 
![](https://i.imgur.com/JtsiL1u.png)



## **Platform** 

Now when you have downloaded the IDE and connected the DHT11-sensor to the expansionboard it time to create an account on the platform that will receive the data from the device and present it in a nice way. 

![](https://i.imgur.com/x7ARjjm.png)
(Source: Ubidots)


I've used [Ubidots](https://ubidots.com/), it's a global cloud platform where you can connect your pycom-device and send data over e.g. WIFI using HTTP and display the results. It's free service which is perfect for education purpose. Ubidots is a great service if you want to scale your project, you can connect a big number of devices and present them nice way using their dashboard-functionally. If you want to set up a big number of sensors and present the results, Ubidots is your tool. Ubidots uses JSON, which stands for JavaScript Object Notation and is a lightweight format for storing and transporting data. It's easy for humans to read and write. The result we get from the device, in this case the ssensordata will be converted to an JSON-object in the code. More about this in the following session. 

1. Start with creating an account. You can do that [here](https://industrial.ubidots.com/accounts/signup_industrial/). 
2. Save the TOKEN that is created, you need that to access your account from the code. 

## **The Code**

Now the fun part starts. The code. 
This section will explain how to set up your project and the code that is helping you transport the data from the DHT11-sensor to the cloud, Ubidots. 

1. First you have to create an empty folder on your computer, name the folder DHT11_Sensor_Project. 

2. Open Atom and click on on File in the top off the window and select "Add new Project Folder...". And select the folder DHT11_Sensor_Project. 

3. The folder will now be displayed on the left part of Atom. Rightclick in the section under Project and press "New folder", name the folder lib. Create one new file in the folder, right-click and press "New file", name the file **urequests.** Create a second file called **dth** in the same folder. Don't forget to end the filenames with .py to create a python-file. Like "urequests.py". 



4. In the DHT11_Sensor_Project-folder create the following files boot and main. 


I've used the following libaries for this project. 

- [**urequests**](https://github.com/jotathebest/micropython-lib/blob/master/urequests/urequests.py)
- [**DHT11**](https://github.com/JurassicPork/DHT_PyCom/blob/master/dht11_example.py)

Copy and paste the code from the libaries above to the files urequests and dth in your project-folder. 

Copy the following code to your boot-file: 

```python= 
from machine import UART
import machine
import os

uart = UART(0, baudrate=115200)
os.dupterm(uart)

machine.main('main.py')

```
Copy the following code to your main-file.

```python=
#import nessecary libaries
from network import WLAN
import urequests as requests
import machine
import time
import pycom
from machine import Pin
from dth import DTH

#Saves TOKEN to a string-variable. 
TOKEN = "COPY YOUR TOKEN HERE" #Paste your TOKEN from Ubidots here.
DELAY = 1 

wlan = WLAN(mode=WLAN.STA)
wlan.antenna(WLAN.INT_ANT)

#Connects the device to WIFI. Assign your network SSID and password to the code. 
wlan.connect("SSID", auth=(WLAN.WPA2, "NETWORK PASSWORD"), timeout=5000)

#Checks if the wifi-connection works. 
while not wlan.isconnected ():
    machine.idle()
print("Successfully connected to WIFI\n")

# Creates a JSON-object with one value, and returns an JSON-object.
def convToJson(variable1, value1):
    try:
        data = {variable1: {"value": value1}}
        return data
    except:
        return None

#Sends the JSON-object to Ubidots.  
def send_data(device, value1):
    try:
        url = "https://industrial.api.ubidots.com/"
        url = url + "api/v1.6/devices/" + device
        headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
        data = convToJson("Temperature", value1)
        if data is not None:
            print(data)
            req = requests.post(url=url, headers=headers, json=data)
            return req.json()
        else:
            pass
    except:
        pass


pycom.heartbeat(False)
pycom.rgbled(0x000008) # shows blue light when it controlls the DTH-sensor. 
th = DTH(Pin('P23', mode=Pin.OPEN_DRAIN),0) #connects the pin on the exp-bord. 
time.sleep(2)
result = th.read()
if result.is_valid():
    pycom.rgbled(0x001000) # If the result = valid, green light appear.
    time.sleep(3)
pycom.heartbeat(True)


#Sends the data-object to the pycom device 
#in Ubidots every 5 minutes and prints a message in the REPL. 
while True:
    currTemp = result.temperature # Data values
    print("\nThe current Temperature is %d C" % result.temperature, 
            ", the next check will be in 5 minutes.")
    send_data("pycom", result.temperature)
    time.sleep(300)


```

Make sure you stand in the right folder (DHT11_Sensor_Project) and click "Upload to Device" in the REPL. You should now see in the REPL if you successfully connected to the WIFI and if any data is sent. 

**NOTE:** Important that you paste your Ubidots TOKEN, and assign your network information in the code.



## **Transmitting the data/connectivity**

Now you have hopefully succeeded to get the code to work and send your data to your Ubidots account. I thought it would be nice to explain how the data is sent to your Ubidots-account. The data is sent to the cloud (Ubidots) every fifth minut. In this tutorial we are using WiFi as the wireless protocol, the data is transported via HTTP, Ubidots REST API. Basically the code builds a JSON-object that is ready to be sent via the API.



```python
def convToJson(variable1, value1):
    try:
        data = {variable1: {"value": value1}}
        return data
    except:
        return None
```
Every request requires a token, which is a unique key that authorizes your device to ingest data inside your Ubidots account. This part in the code creates a function that takes 2 variables as input, one which is the device you send the data to, and the second the result from the DHT11-sensor. 
```python
def send_data(device, value1):
    try:
        url = "https://industrial.api.ubidots.com/"
        url = url + "api/v1.6/devices/" + device
        headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
        data = convToJson("Temperature", value1)
        if data is not None:
            print(data)
            req = requests.post(url=url, headers=headers, json=data)
            return req.json()
        else:
            pass
    except:
        pass
```

Here the function is called, and the result from the DHT11-sensor is sent to the device "pycom" as an JSON-object. 
```python
send_data("pycom", result.temperature)
```
If you want to know more about how this works, you can find good documentation [here](https://www.ubidots.com/docs/hw/?language=Python#send-data-to-a-device).



## **Presenting the data**

As mention in the previous section, the data is sent every fifth minutes. 
The data is presented in Ubidots dashboard-interface. Ubidots interface for dashboard is a powerful tool that gives you good flexibilty on how you want to display/present your data. Because we sending one value to Ubidots a simple linechart is a good presentation of the value received. The data is saved every fifth minute to the database, you can see in the table beneath the chart when the data was received and stores, and also the value. You can configure the dashboard easily for your preferences. You can find more information on how to create nice dashboards on their website. 

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


## **Finalizing the design**

Here is a picture of the final results of the device, what it looks like when it's connected to the DHT11-sensor. Overall I'm proud of the project, it has been an educational journey. This has triggered me to continue explore the world of IoT & building project. 

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



**Note:** The antenna connected to the device is not used, or required to proceed with this project. It's used to access other wireless protocols like Lora & SigFox, but in this tutorial we are only using WiFi. 

**What could I've done differently?**
Because the DHT11-sensor is able to track humidity, now when I have the basic knowledge on how to get, convert and send data to the cloud I would add that values to my project - and maybe get weatherdata from another cloud-service to analyze my results according to another source, e.g. TheWeatherChannel. 


I hope you have enjoyed this tutorial and was able to create a simple temperature-application using basic hardware and code.
This has been so much fun, thanks for visiting my tutorial. 

All the best, 
Alex 






















