---
# System prepended metadata

title: Beginner-friendly home temperature measurement station

---

# Beginner-friendly home temperature measurement station
By Stefan Jägstrand (sj223gg)
___

### Overview
This tutorial goes through the steps how to setup your pycom device to measure the ambient indoor temperature using a temperature sensor hooked up to a LoPy4, and visualize it on the PyBytes platform.

## Objective

As inspiration for this project, i wanted to see how the temperature in my apartment varied during a full 24-hour session in summertime.
This tutorial aims to give the insights necessary to complete this objective, as well as provide knowledge on how to set up an IoT-device for complete beginners.

In this tutorial we will:
* Set up and configure a LoPy4 device
* Program the device using micropython
* Hook it up to a temperature sensor and read the data
* Send the data through WiFi
* Present the data using Pybytes

### Approx. time
As this tutorial is aimed at beginners, replicating this project should not take very long.
Newcomers to this sort of stuff should be able to complete this setup within 4-6 hours, while experienced users would probably take about 1-2 hours.
___
## Material

For this project, i got all the materials i needed from Electrokit in this bundle: https://www.electrokit.com/en/product/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/
This includes all that we need to realize this project, plus a little extra.
If you only want the components required however, the following is what you need:



| Name                   | Price                | Description                      | Link  |
| ---------------------- |:----------------     | :------------------------        | :--   |
| ![](https://i.imgur.com/0luC3oY.png) LoPy4 | ~399.00kr (€38.45)   | Star of the show.                             | https://pycom.io/product/lopy4/ |
| ![](https://i.imgur.com/vmh3vyN.png) Expansion board 3.0 | ~199.00kr (€17.60)   | Accessory to the lopy. Enables us to connect via USB and hook up to the sensor.                             | https://pycom.io/product/expansion-board-3-0/ |
| ![](https://i.imgur.com/ptIoUfS.jpg) Temp sensor MCP9700    | 8.00kr (€0.86)       | Sensor that measures temperature                             | https://www.electrokit.com/produkt/mcp9700-e-to-to-92-temperaturgivare/     |
| ![](https://i.imgur.com/9KhXit9.jpg) Breadboard | 59.00kr (€6.31)      | Makes it a lot easier to connect our pycom device to the sensors.                             | https://www.electrokit.com/produkt/kopplingsdack-400-anslutningar/ |
| ![](https://i.imgur.com/ebdVVWo.jpg) Jumper wires | 29.00kr (€3.10)      | Sends data, provides power to our sensor.                             | https://www.electrokit.com/produkt/labbsladd-20-pin-15cm-hane-hane/ |
| ![](https://i.imgur.com/AkMlOmh.jpg) Micro USB-C cable | 39.00kr (€4.17)      | Enables us to connect the pycom to our computer when developing. If you have an old USB-C cable lying around, you can use that as well.                             | https://www.electrokit.com/produkt/hdmi-kabel-mini-c-hane-till-a-hane-svart-1m/ |

Optional:

| Name                   | Price                | Description                      | Link  |
| ---------------------- |:----------------     | :------------------------        | :--   |
| ![](https://i.imgur.com/hP3y0jx.jpg) Battery holder         | 29.00kr (€3.10)      | If you don't want your pycom to constantly connected to your computer with USB, this enables you to place the device wherever you want.                             | https://www.electrokit.com/produkt/batterihallare-3xaaa-med-strombrytare-och-jst-kontakt/ |
| ![](https://i.imgur.com/cPBLfw0.jpg) Multimeter | 299.00kr (€31.99)        | Really useful if you need to troubleshoot your connections in case something isn't working as intended. Is a good investment, and might just save your life!                             | https://www.electrokit.com/produkt/multimeter-digital-3-1-2-siffra-auto-range/ |

___
## Computer setup

:::info
This section describes how to connect the Lopy using Windows 10.
Other operating systems might require different steps.
You can always check out the <i>official documentation:</i>
https://docs.pycom.io/gettingstarted/
:::

### Setting up the device

Insert the LoPy into the expansion board so that the RGB LED on the LoPy is directly above the USB connector on the expansion board.
![](https://i.imgur.com/EyywwRB.png)

### Update device firmware
Updating the device firmware will enable us to connect to the PyBytes platform later on. This step can be done at any time, but we might aswell do it now so we know that everything works as intended.

:::info
:bulb: Make sure to close down any program (Atom or VSCode) if it is currently connected to the device before running the firmware software.
:::

> 1. Connect your device to the computer via USB.
> 2. Download and install the firmware update tool from https://docs.pycom.io/updatefirmware/device/
> 3. Run the update tool.
> 4. Select the COM port with the highest number, and check the <i>Show advanced settings</i> box.
>  ![](https://i.imgur.com/1yHyqDg.png =350x250)
> 5. Choose pybytes version 1.20.1 in the Type/Version dropdown menu * ![](https://i.imgur.com/eEhYj9Y.jpg =350x250)
> 6. The firmware of your device is now upgraded!

:::info
:bulb: * I personally experienced an issue using the most recent PyBytes version while trying to connect to the device, causing it to take forever. Downgrading to v1.20.1 seemed to solve this issue. For this project, this version is perfectly fine for our needs.
:::


### Setting up the software

#### Node.js
Before installing the IDE, which we will write our code in, make sure that you have Node.js installed. You can download and install the latest version of Node from https://nodejs.org/en/ .

#### Atom
We will be using Atom as our Integrated Development Environment (IDE), which can be downloaded from https://atom.io/ .

For a detailed guide on how to install atom, check out the official documentation https://flight-manual.atom.io/getting-started/sections/installing-atom/ .

#### Pymakr plugin
Next, we need to setup the Pymakr plugin for Atom. This enables us to communicate with our Pycom board using the command line to upload files, and/or directly execute commands.

> 1. Run <b>Atom</b>
> 2. Go to <i>File -> Settings -> Install </i>
> 3. Search for <b>pymakr</b> and select the official Pycom Pymakr Plugin (should be the first result). Click <i>install</i>
> 4. That's it! Pymakr should now be installed as a plugin on Atom.

We can now connect the Pycom via USB. Pymakr should automatically connect to the device when plugged in, but if in case it does not, you can do it manually by clicking on <b>Connect device</b>.
When connected, the terminal should show three arrows ==>>>==.

At this point we can execute commands directly on the device via the terminal, run single files or even upload the project to the device itself. We will later use this method to upload the code to the device in order to read and send sensor data.

:::info 
<b>Upload project to device</b> will save the uploaded code to the device, and run each time the device is started. 
:::

___
## Putting everything together

Connecting the sensor is pretty straight-forward. No resistors or anything is needed, so the wires can be connected directly to the pins in the expansion boards.
Note that this setup is most suitable as a development setup for indoor use only, since the device and sensor is exposed. If you are using batteries for providing power, the placement of the device is much more flexible, as you are not restricted by USB cable.

The MCP9700 sensor has three legs, <i>Positive voltage (**left**), Data output (**middle**) and ground (**right**)</i>. 
It is an analog sensor, which means that we can connect it to <i>any</i> pin with ADC capabilities: **P16**, in our case.
The following diagram shows how you can connect the sensor.
Note that you might have to bend the legs slightly in order to connect it properly to the breadboard.

![](https://i.imgur.com/JPRj8U9.png =1000x400)

> * **RED:** Connect the **left leg** to row 25 on the breadboard, and a jumper wire on the same row to positive voltage (**3v3**) on the expansion board.
> * **GREEN:** Connect the **middle leg** to row 26 on the breadboard, and a jumper wire to **Pin 16**.
> * **BLUE:** Connect the **right leg** to row 27 on the breadboard, and a jumper wire to ground (**GND**)

To make your connections easier on the eyes, it is recommended to use the same colour wire for each connection if you're using multiple wires.

:::info
:bulb: Keep in mind that the MCP9700 sensor has a curved face and a flat face. 
To avoid confusion, consider the flat face as the <i>"Front"</i> of the sensor, so that the left and right legs connects to the right pin.

![](https://i.imgur.com/F2XHfJJ.jpg =150x100)

:::
___
## Platform
### PyBytes

https://pybytes.pycom.io/

For this project we will be using **PyBytes** as a platform to handle our sensor data. PyBytes is a device management platform which provides the means to visualize data from several devices, track the geolocical location of the device, as well as providing a scaleable approach for updating the firmware remotely.

For the purpose of this project, i chose pybytes because of how simple it is to setup a device and visualize the data in real-time.

### Connect your device to Pybytes

To get started with Pybytes and prepare for sending and visualizing data from our device, we need to:

> * Create an account at Pybytes
> * Go to <i>Configure Networks</i> and enter your Wi-Fi credentials (ss-id and password)
> ![](https://i.imgur.com/2NbdsrI.png)

Next, follow the official guide on how to add a device: https://docs.pycom.io/pybytes/gettingstarted/

Add your network to the device.

> * Select your device, and go to **Provisioning**.
> * Select **OFFLINE FIRMARE UPDATER**, and generate a new activation token.
> * Run the firmware updater again. Make sure to check <i>Force update Pybytes registration</i> and <i>Enable Pybytes / SmartConfig support</i> and provide the activation token from pybytes.

![](https://i.imgur.com/8WhXFeH.png)
![](https://i.imgur.com/3szMcM4.png)


Your device is now connected to the Pybytes platform!

___
## The code

The source code is relatively simple and only consists of one file, **main.py**.
The code is a modified version of the code found in this tutorial: https://www.losant.com/blog/how-to-read-the-tmp36-temperature-sensor-with-pycom-and-sigfox

The code reads the temperature value from the sensor each 30 seconds, and adds it to a list of measurements. After ten measurements (which takes 5 minutes), the average value from these measurements is calculated and is sent to the Pybytes platform.

:::info
The reason for calculating the average instead of directly sending each measurement to Pybytes is because i found that the sensor measurements to not be that accurate. During testing the values would often differ +- 1 to 2 degrees, even with short intervals between measurements.
So in my mind, calculating the average value during a set period of time gives a better representation of the average temperature.
:::

In atom, create a new project. Create a file called **main.py** and copy-paste the following code.

#### main.py

```python=
# main.py -- 
import machine
import time

print("-- Starting measurements! --")

# Create reference to pin
adc = machine.ADC()
apin = adc.channel(pin='P16')

# Timer values init
total_cycle_time = 300   # Seconds between each cycle
avg_sleeptime = 30       # Seconds between measurements
avg_count = 10           # no of measurements between sending

while True:
    measured_temps = [] # Create empty list each cycle
    
    # Read measurements periodically
    for i in range(0, avg_count):
        # Read value from sensor
        millivolts = apin.voltage()
        celsius = (millivolts - 500.0) / 10.0
        print(i , ": measuring: " , celsius)
        # Add value to list and sleep
        measured_temps.append(celsius)
        time.sleep(avg_sleeptime) # sleep for 30 sec

    print("Measured values: ", measured_temps)

    # Calculate avg value from list of measurements
    avg_temp = round(sum(measured_temps) / len(measured_temps), 2)
    print("Pybytes: Sending average value: ", avg_temp)

    # Send value to pybytes
    pybytes.send_signal(2, avg_temp)

```

Reading the temperature requires us to convert the voltage from the sensor into celcius using the following formula: ==(millivolts - 500) / 10==

Click the ***Upload project to device*** and it will automatically start the program!

![](https://i.imgur.com/QwvjSwl.jpg)
![](https://i.imgur.com/FE6N2gn.png)

___
## Transmitting the data / connectivity


Since we configured the device using the firmware updater and adding the activation token earlier, the device now automatically connects to WiFi using the credentials we provided. This means that we can send the data directly to Pybytes by using the function ==pybytes.send_signal(2, avg_temp)== every five minutes.

I have set up a signal on my Pybytes device which listens to "signal 2", which is why the first argument is 2 in the code.![](https://i.imgur.com/eS06MKY.png)

Pybytes uses a built-in broker using the MQTT protocol to handle the data. This was automatically made available to us when we registered the device using the firmware updater in the previous step.
___
## Presenting the data

Now all that there is left is to visualize the data from our device. Pybytes provide us to create custom dashboards which listens to a specific signal and presents the data.
Pybytes will save the data for one month for free. 

#### Create a dashboard:

> 1. Select your device and go to <i>SIGNALS</i>
> 2. Select the signal that listens to our temperature measurements.
> ![](https://i.imgur.com/i5HdIwt.png)
> 3. Click <i>Create new display</i> and choose **Line chart**.
> 4. Name the display and customize it to your liking. I chose a pull size of 100 and selected <i>hour</i> as Time scale.
> ![](https://i.imgur.com/dO0E5Kc.png)
> You now have a line chart vizualizing the temperature! You can set it so that the chart displays on dashboard.
> ![](https://i.imgur.com/Uw93Jlx.png)

The chart clearly shows how the temperature fluctuates during the day, peaking during the day and drops at night, cool!
___
## Finalizing the design

#### Summary
In conclusion, i am happy with the results of this project. As a complete beginner of everything IoT-related it was fun to learn the basics of how things work, from connecting the sensors to present and visualize the data on the internet.
I kept the project on a basic level, as i wanted the tutorial to be beginner-friendly and act as a first step into the world of IoT.

Future considerations:
* **The sensor**. As mentioned, the accuracy of the MCP9700 sensor is not that great, causing the measurements to fluctuate somewhat. It is a cheap sensor and suits the scope of this project well, but in the future i would like to try other temperature sensors and compare the results.
* **The code**. There is currently no exception handling in the code. This means that if the device would fail to connect to WiFi, it would still continue on as normal and read values despite not being able to send the data correctly.
* **Mobility**. This setup using a breadboard for connecting to the sensor means that the device is not that mobile, and has to be placed indoors because of its exposure to the elements. It would certainly be interesting to explore the possibilities of creating a case or something to hold everything, perhaps using 3D-printing?

![](https://i.imgur.com/ra2RH2R.jpg =400x400)
![](https://i.imgur.com/mzLUDgQ.jpg =400x400)
