---
# System prepended metadata

title: Daily temperature data (with web interface)

---

# Daily temperature data (with web interface)

> Name: Anton Fridlund
> Student credendtials: af222xh
> Estimated time: 4h

[ToC]

## Overview

:::info
This tutorial will cover how to connect an NTC temperature sensor to your LoPy4, send sensor data via Wi-Fi to any website of your choice and walk you through the installation of all the necessary tools needed for this project. I will also showcase how my sensor data is visualized.
:::

## Objective

My idea for the sensor is to have it measure the daily temperature in our greenhouse. This is so that I can get a better idea of how the plants health correlates to temperature changes. But right now it is placed in the window of my living room until I know it's working correctly (might be moved by the time you're reading this).

The sensor data could be used to further develop an automatic watering system that regulates the amount of water the plants need depending on the greenhouse's temperature. But something that I'm even more exited to develop is a system that opens the ventilation hatch when the temperature reaches a certain threshold since I often have to manually open and close the ventilation and it would save a lot of time and effort. But this will have to wait until another time.

## Material

This is all the material needed to complete this tutorial.

| :gear: Parts | :memo: Description | :shopping_trolley: Shop | :moneybag:  Price |
| -------- | -------- | -------- | -------- |
| `1x` KY-013 <br/> Temperature  sensor| NTC temperatuer sensor. | [Electrokit](https://www.electrokit.com/en/product/temperature-sensor-ntc/) | 29 SEK |
| `1x` 30-pack of <br/> Jumper cables | Used to connect sensors. 3-6 cables needed. <br/> Depending on the length you want. | [Electrokit](https://www.electrokit.com/produkt/labbsladdar-100mm-hane-hane-30-pack/) | 33 SEK |
| `1x` LoPy4 | Main development board. | [Pycom](https://pycom.io/product/lopy4/) | €38.45 <br/> (~390 SEK) |
| `1x` Expansion <br/> Board 3.0 | Provides easy battery, pin and USB access. | [Pycom](https://pycom.io/product/expansion-board-3-0/) | €17.60 <br/> (~180 SEK) |
| `1x` USB cable<br/> A to micro B M/M | Used to upload code to LoPy4 and power it. | [Electrokit](https://www.electrokit.com/produkt/usb-kabel-a-hane-micro-b-5p-hane-1-8m/) | 39 SEK |
| `1x` Breadboard | Makes it easy to connect/test components. | [Electrokit](https://www.electrokit.com/produkt/kopplingsdack-400-anslutningar/) | 59 SEK |
| `1x` Battery pack | To power the device anywhere. | [Electrokit](https://www.electrokit.com/produkt/batterihallare-3xaaa-med-strombrytare-och-jst-kontakt/) | 29 SEK |
| Total | | | ~759 SEK |

You might want three male/female jumper cables in order to connect the sensor without the breadboard. You can also use the cables as an extension to give the temperature sensor better reach.

## Computer setup

The operating system used in this project is Windows 10.

* First things first, LoPy4 runs Python (MicroPython) so we need to install the latest version of Python using the official webpage [here](https://www.python.org/downloads/).
* Install [node.js](https://nodejs.org/en/)!
* To easily write, edit and upload Python projects to LoPy4 we need to install the [Atom IDE](https://atom.io/) and add the [Pymakr](https://atom.io/packages/pymakr) package to Atom. If you encounter any issues when installing the Pymakr package you might need to install [vs-build-tools](https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019) first.
* Now for the last setup step we will add the device to Pybytes and update the firmware with the help of the firmware updater tool in order to easily connect with Pybytes in the future.

Tutorial for [getting started](https://docs.pycom.io/gettingstarted/), [adding the device to Pybytes as well as updating the firmware](https://docs.pycom.io/pybytes/gettingstarted)!
That's all for the initial setup.

## Putting everything together

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


As you can see in this setup we make use of a breadboard to easier connect the components but you are free to connect the components in any way you like. The color coding of the wires in this image goes as such: Red=3.3V, Black=Ground, Blue=In signal.

## Platform

The project is not relied upon any cloud solutions and I also opted to skip PyBytes in order to send data directly to my server in order to minimize the number of Single point of failure (SPOF). As to my knowledge I do not use any platforms and instead handle the data myself.

It is possible that the project could benefit from cloud solutions such as [DataCake](https://datacake.co/) in order to easily store and visualize sensor data but since the task was to *create* a user interface they were not used.

## The code

The project files will look something like this:
```
project
|-lib
| |-keys.py
| |-urequests.py
|-boot.py
|-main.py
|-pybytes_config.json
``` 

`keys.py` Is used to store any sensitive data such as passwords, device identification and more.

`urequests.py` Is a library that I use in order to send sensor data via Wi-Fi and can be found [here](https://github.com/jotathebest/micropython-lib/blob/master/urequests/urequests.py).

`boot.py` In this case is empty and *could* be removed. I've kept it in case I wanted to add anything later on in the project.

`pybytes_config.json` Should have been automatically added when we updated the firmware of our device and it contains WiFi credentials, device id, registered email and more:
```json=1
{"wifi": {"ssid": "xxx", "password": "xxx"}, "wlan_antenna": 0, "dump_ca": false, "server": "mqtt.pybytes.pycom.io", "ssl": false, "lte": {"apn": null, "cid": 1, "reset": false, "carrier": null, "band": null, "type": null}, "device_id": "xxxxxxxx-xxx-xxx-xxx-xxxxxxxxxxxx", "network_preferences": ["wifi"], "ota_server": {"port": 443, "domain": "software.pycom.io"}, "pybytes_autostart": true, "username": "xxx@xxx.xxx"}
```

`main.py` Contains the majority of the code in this project and is used to collect and send data:
```python=1
import keys
from machine import Pin
import machine
import urequests as requests
import math

# Define pins.
adc = machine.ADC(bits=12)
temp_pin = adc.channel(attn=machine.ADC.ATTN_11DB, pin='P16')

# Creates and sends payload.
def send_data(temp):
    data = { "device": keys.device_serial, "data": { "temp": temp } }
    url = 'https://cscloud8-119.lnu.se/1dv027-iot/api/temperature'
    headers = {"Content-Type": "application/json"}
    requests.post(url=url, headers=headers, json=data)

# Calculation from https://bhave.sh/micropython-measure-temperature/.
temp_calc = math.log(1/(4095/temp_pin.value() - 1))
temp_calc = ((1/(temp_calc/3950 + 1/298.15)) - 273.15)

# Send data to server.
send_data(temp_calc)

# Sleep for 24 hours.
machine.deepsleep(86400000)
```

## Transmitting the data

The device uses **Wi-Fi** to transmit the data via a **POST** request once every 24 hours. I am currently using my home router as the gateway and the data is being sent to an Express server which stores that data in **MongoDB** for one week and then automatically deletes the data.

The data that is sent uses the **JSON** format because it is easy to understand and also easy for the server to handle:
```JSON=1
{
    "device": #device identification.
    "data": {
        "temp": #temperature in celsius.
    }
}
```

## Presenting the data

The data that is stored is accessible through an API which is currently being used by a web interface that I developed in order to fetch data and display it in a graph. Since the graph only needs one week worth of data we can without problem remove any data older than one week.

Here is an image of the graph (I've only measured two days):
![](https://i.imgur.com/DayXnCZ.png)

**MongoDB** is the database that I use because it is easy to work with and has options for data retention. It's also worth to mention that I had previous knowledge of this particular database and it therefore sped up the creation of this project.

If you were to do this yourself it would probably be better to send your data to a cloud service that offers several prebuilt dashboards to quickly visualize your data.

## Finalizing the design

The temperature sensor is placed next to a bought thermometer in order for me to confirm that the sensor data measured by my LoPy4 is correct. I found an old box that perfectly fit my LoPy4 and the battery pack. The box also has a lid to protect its content:

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

I turned on the device at 12 PM (12:00) which means that the temperature will always be measured at that time each day since the device sleeps for exactly 24 hours.

To better understand how the device works I made a video explaining the different parts (Swedish):

{%youtube fIIBWJ0ip-U %}

The final product works the way I expected and I would like to further develop my IoT-device to get more readings both at the start of the day and later in the evening. This way I can collect more accurate data throughout the day that explains how my plants are doing. :sunflower: 

Even if the project was quite simple I had some difficulties getting started. Now that everything is set up correctly I feel like it would be much easier to add more sensors and adjust the already existing ones. I think I will continue this project as a hobby during the summer! :sunny: