---
# System prepended metadata

title: Tutorial on how to build a temperature sensor to notify differences in temperature.

---

*By Elias Soprani, es225bd*
## Introduction
This is an IOT project hoping to introduce a general overview about how an IOT project can bring real life value with only a basic understanding of the fundamentals in IOT. This project will create a device with a temperature sensor to notify when the temperature in a room drops below a certain threshold. The tutorial will cover everything needed to finish this project from scratch.

Estimated time to complete this tutorials project is about half a work day (4 hours), provided that all the components required are available.
## Objective

This project could be applied in several different use-cases such as keeping track of temperature to maintain a sustainable work place environment, help optimize plant growth, or even remotely tracking the temperature within a rental property, eliminating the need for physical presence to check the temperature. This specific device was chosen as a project to gain a fundamental and general understanding of how IOT works and how analog data can be gathered in one place and read and visualized in another. I believe this tutorial will give an insight to how IOT is fun and can be a relatively easy environment to get started in with a basic understanding of how it works. Many interesting projects can be created which can bring a real life value.
## Material


| Component | Used for | 
| -------- | -------- | 
|1x Raspberry Pi Pico WH     | Microcontroller with WiFi access to enable wireless communication    | 
|1x DHT11 |Sensor to gather data about the temperature
|1x Breadboard |Allows components to easily be removed and replaced
|5x M2M jumper wires | To connect the componenents with eachother 
|1x USB Cable | To connect the microcontroller with the host computer
![](https://hackmd.io/_uploads/BJgSTp2u3.jpg)*DHT11 sensor*
![](https://hackmd.io/_uploads/rk4uap3u2.jpg)*Raspberry Pi Pico WH*

The material was bought at Electrokit.com and costed 399kr.
## Computer setup
The chosen IDE for this project was visual studio code. First you need to install Node.js then to upload the code to the microcontroller the visual studio code extension "Pymakr" was used. The next step is to download the micropython firmware from https://micropython.org/download/rp2-pico-w/. After this uf2 file has been downloaded it can be uploaded to the microcontroller by connecting a usb from the host computer to the microcontroller. Before connecting the computer and microcontroller you should hold down the BOOTSEL key on the microcontroller and THEN insert the usb cable to your computer. After this a new drive should open on your computer containing the microcontrollers files where the uf2 file can be uploaded to. To visualize the data collected I used ubidots.
## Putting everything together
![](https://hackmd.io/_uploads/B1SiUA2un.png)
*Circuit Diagram taken from https://hackmd.io/@lnu-iot/r1U1bPgw2*
This setup allows analog data to be sent from the DHT-11 to the microcontroller as well as send electricity to the DHT-11 sensor through the microcontroller.
## Platform
The platform to use is Ubidots. This tool allows data transmission from any device with Internet access to the cloud, initiates actions and notifications in response to the data, and facilitates its visualization. This platform is free.
## The Code
The DHT11 sensor is initialized with tempSensor = dht.DHT11(Pin(27)). This line sets up the sensor on pin 27 of our device.

We then define our WiFi credentials (WIFI_SSID, WIFI_PASS) and Ubidots token (TOKEN). These are used in the function connect() which sets up a WiFi connection. The function checks if the device is already connected to a network. If not, it activates the network interface and attempts to connect using provided credentials. It waits until a successful connection is established or an error occurs.
```python=
def connect():
    wlan = network.WLAN(network.STA_IF)         # Put modem on Station mode
    if not wlan.isconnected():                  # Check if already connected
        print('connecting to network...')
        wlan.active(True)                       # Activate network interface
        # set power mode to get WiFi power-saving off (if needed)
        wlan.config(pm = 0xa11140)
        wlan.connect(WIFI_SSID, WIFI_PASS)  # Your WiFi Credential
        print('Waiting for connection...', end='')
        # Check if it is connected otherwise wait
        while not wlan.isconnected() and wlan.status() >= 0:
            print('.', end='')
            time.sleep(1)
    # Print the IP assigned by router
    ip = wlan.ifconfig()[0]
    print('\nConnected on {}'.format(ip))
    return ip


```
Once connected, we enter an infinite loop where we continuously read temperature and humidity values from the DHT11 sensor using tempSensor.measure(), tempSensor.temperature(), and tempSensor.humidity().
```python=
while True:
    try:
        tempSensor.measure()
        temperature = tempSensor.temperature()
        humidity = tempSensor.humidity()
        value = temperature
        returnValue = sendData(DEVICE_LABEL, VARIABLE_LABEL, value) 
        print("Temperature is {} degrees Celsius and Humidity is {}%".format(temperature, humidity))
    except:
        print("Error in reading sensor values")
    time.sleep(5)


```
The function sendData(device, variable, value) is used to send these readings to Ubidots. It builds a JSON object containing our data (build_json(variable, value)) and sends it as a POST request to Ubidots API endpoint
```python=
def sendData(device, variable, value):
    try:
        url = "https://industrial.api.ubidots.com/"
        url = url + "api/v1.6/devices/" + device
        headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
        data = build_json(variable, value)

        if data is not None:
            print(data)
            req = requests.post(url=url, headers=headers, json=data)
            return req.json()
        else:
            pass
    except:
        pass

```
## Connectivity
The data is sent every 5 seconds, but can be adjusted in the code to fit different use-cases where on might want to gather the data more often or less often. The wireless protocol used is WiFi by connecting the microcontroller to a WiFi so it is able via HTTPS to send requests to Ubidots for data storage. The transport protocol chosen was HTTPS to enable safe transfer of data to the backend.
## Presenting the data
![](https://hackmd.io/_uploads/S1SbFA2un.png)
Data is saved in the database every 5 seconds.
## Finalizing the design
![](https://hackmd.io/_uploads/SyctKA2d2.jpg)
Using this device, data about the temperature in the room the device is in can be sent to Ubidots to enable data visualization. 
![](https://hackmd.io/_uploads/H18U5ChO3.jpg)
![](https://hackmd.io/_uploads/SyUU5C2u2.jpg)
As shown in the pictures above the data visualization can show when the temperature has dropped below a certain degree (in this case 25*C) an "alarm" will turn green to notify about the drop in temperature.


