---
# System prepended metadata

title: How to build a room temperature meter that sends Discord notifications

---

# How to build a room temperature meter that sends Discord notifications
Jon Cavallie Mester - jc222rz

Recently, I moved into a new apartment that just so happens to be located in a basement. As you may now, the climate in basements can be quite cold and sometimes damp. For this reason, I decided to create a device that reads the room temperature. If the temperature is below or above the limits specificed by the Public Health Agency of Sweden, it sends an alert to my Discord channel. This tutorial will show you how to build a similar device.

**Estimated tutorial time**: 2 hours

## Objective
Recently, I moved into a new apartment that just so happens to be located in a basement. As you may now, the climate in basements can be quite cold. However, the Public Health Agency of Sweden has recommendations for what the lowest and highest acceptable temperatures in a home should be, and if the measured temperature is outside that range, you can demand your landlord to adjust the temperature. For this reason, I find a device that alerts you when the measured room temperature is unacceptable to be quite handy.

## Material
|   Item	|   Purpose	|   Specification	|   Source
|---	|---	|---	|---	|
|   LoPy4	|   Development board enabling you to use MicroPython and the PyMakr plugin.	|   LoPy4 with headers	|   https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/	|
|   LoPy4 Expansion Board	|   Enables you to connect to the LoPy4 with pins and micro-USB.	|   PyCom Expansion Board 3.0 is compatible with LoPy4	|   https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/	|
|   MCP9700 sensor 	|   To measure temperature.	|   Wide measurement range, -40°-125°C, and a current consumption of 6µA.	|   https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/	|
|   Breadboard	|   Makes it easier to wire connections.	|  - |  https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/ 	|
|   Jumper wire	|   To wire connections between pins.	|   At least 5 wires.	|   https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/	|

## Setup
### Python setup
You need an up-to-date version of Python installed. As the installation progress is largely dependent on the OS you're using, I refer you to the [Python installation page](https://www.python.org/downloads/).

### Firmware
Next up, you want an updated version of the LoPy firmware. I recommend you to make use of [Pycom update tool](https://docs.pycom.io/updatefirmware/device/), which facilitates this process. Although detailed instructions are supplied in the link, the general process looks like this:

    1. Download the tool for your OS
    2. Insert your LoPy into the expansion board.
    3. Connect the board to your PC through USB.
    4. Start the tool.
    5. Select the Pybytes firmware option.
    6. Done!
### Pybytes setup
Pybytes is a platform that enables us to more easily manage our devices and receive signals from them. [Here's how you get started](https://docs.pycom.io/pybytes/gettingstarted/):

1. Create a [Pybytes account](https://pybytes.pycom.io/)
2. Create a device by selecting "Add device" in the menu
3. Select the LoPy4 option
4. Enable WiFi networking
5. Click "Save"
6. Inform the device of the Pybytes connection
    7. Open the previously installed firmware updater tool
    8. Select your device and select the options "Force update Pybyte's registation" and "Enable Pybytes support".
    9. Next, the tool will ask for an activation token which you need to generate in Pybytes.
    10. You should instantly see a success message in Pybytes.
11. Press the reset button on your device to reboot and activate the Pybytes connection.

### Pybytes signals and Discord webhook
What we want to accomplish is essentially to read the room temperature with our device, send it to Pybytes if it's outside our defined range of acceptability, and then send an alert in a Discord channel. Putting the temperature reading aside for a moment, we first have to push the data to a Discord webhook when a signal is received in Pybytes.

To accomplish this, we need to create a [Pybytes webhook integration](https://docs.pycom.io/pybytes/integrations/webhooks/):

1. Create a Discord server or use an existing one you administrate. Go to Server Settings → Integrations → Webhooks → New Webhook → Copy URL (this copies the webhook URL to your clipboard)
2. Select Integrations → New integration → Webhook from the main menu.
3. This opens a form. In the URL field, paste your Discord webhook URL.
4. In the body definition section of the form, delete all pre-set parameters and create one called "content".
5. Set the "content" parameter's value to "MESSAGE_PAYLOAD".
6. At the bottom of the form, add your LoPy4 device, that you previously added to Pybytes, to the integration.

### Atom and PyMakr
I had some issues connecting my LoPy through the VS Code PyMakr plugin which is the reason I finally settled with the Atom IDE, as its PyMakr plugin worked out of the box. After having installed Atom, you install PyMakr by going to Packages → enter "pymakr" in the search field → clicking install.

Now that you have the PyMakr plugin up and running, you can begin to write your code. Create a project folder where you deem suitable, and open Atom inside of it. Next, create a file called `main.py` and write the following:

```python
import machine
import time
import pycom
from network import WLAN
from _pybytes import Pybytes
from _pybytes_config import PybytesConfig

"""
By default, the LoPy4 has a LED
that constantly blinks. This turns it off.
"""
pycom.heartbeat(False)

"""
These are the constant max- and min temperatures
defining the acceptable room temperature range.
"""
MAX_TEMP = 28
MIN_TEMP = 20

"""
Start a Pybytes instance, enabling us to
send signals through WiFi to Pybytes.
"""
conf = PybytesConfig().read_config()
pybytes = Pybytes(conf)
pybytes.start()

"""
Connect to your local WiFi network.
Make sure to enter your own ssid and credentials.
"""
wlan = WLAN(mode=WLAN.STA)
wlan.connect(ssid='your-ssid', auth=(WLAN.WPA2, 'your-password'))

"""
Convert the analog data from our sensor
to digital. Returns a value between 0 and 1023.
"""
adc = machine.ADC(bits=10)
apin = adc.channel(pin='P16')

"""
Our "main loop" where we keep reading
the room temperature and sending it to
Pybytes.
"""
while True:
  millivolts = apin.voltage() # Read voltage from sensor
  celsius = (millivolts - 500) / 10.0 # Convert voltage to celsius
  
  # If temperature is outside acceptable range, send signal
  if celsius > MAX_TEMP or celsius < MIN_TEMP:
      pybytes.send_signal(0, round(celsius, 1))
  time.sleep(60 * 10) # Repeat every ten minutes

```

As you can see inside the main loop, we send asignal to Pybytes with `pybytes.send_signal(0, round(celsius, 1))` containing the measured temperature, which Pybytes in turn pushes to our Discord webhook integration. After you've saved the file, you can try to run a test by clicking on "Run selected file" in the PyMakr console. If everything works as intended, you upload it to the device for persistence by clicking "Upload project to device".


## Putting everything together
I found the simplest way to put the wiring and the sensor together to be by looking at a circuit diagram and following it to a tee. The bottom part is your Lopy development board, and the upper part is your breadboard. As you may have noticed in the materials section, there is no need for resistors. Just wire the three wires in the way described in the diagram. Also note, that the colors of the wires do not imply differing types, it's just a color code. Thus, it's not required for your wires to be of the same color, but they need to be wired in the same way displayed here.

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

I would deem this setup to be most suitable for development.

## Platform
I chose Pybytes as a cloud-based platform mainly because:

1. It is convenient to set up with a Pycom device.
2. It was free.
3. The requirements of my project did not really demand any more advanced or scalable platform.

Going forward, I would probably try out a paid platform such as Google Cloud solely. At this point in time, the functionality of the system is quite simple, but eventually I may want to perform some data analysis and store data more long-term, which I believe Google Cloud may be more suitable for.

## The code
See the comments in the code. I find it quite self explanatory.

````python=
import machine
import time
import pycom
from network import WLAN
from _pybytes import Pybytes
from _pybytes_config import PybytesConfig

"""
By default, the LoPy4 has a LED
that constantly blinks. This turns it off.
"""
pycom.heartbeat(False)

"""
These are the constant max- and min temperatures
defining the acceptable room temperature range.
"""
MAX_TEMP = 28
MIN_TEMP = 20

"""
Connect to your local WiFi network.
Make sure to enter your own ssid and credentials.
"""
wlan = WLAN(mode=WLAN.STA)
wlan.connect(ssid='your-ssid', auth=(WLAN.WPA2, 'your-password'))

"""
Start a Pybytes instance, enabling us to
send signals through WiFi to Pybytes.
"""
conf = PybytesConfig().read_config()
pybytes = Pybytes(conf)
pybytes.start()

"""
Convert the analog data from our sensor
to digital. Returns a value between 0 and 1023.
"""
adc = machine.ADC(bits=10)
apin = adc.channel(pin='P16')

"""
Our "main loop" where we keep reading
the room temperature and sending it to
Pybytes.
"""
while True:
  millivolts = apin.voltage() # Read voltage from sensor
  """
  Convert voltage to celsius
  This calculation is wholly dependent on
  the sensor we're using.
  """
  celsius = (millivolts - 500) / 10.0
  
  """
  If temperature is outside acceptable
  range, send signal
  """
  if celsius > MAX_TEMP or celsius < MIN_TEMP:
      pybytes.send_signal(0, round(celsius, 1))
  time.sleep(60 * 10) # Repeat every ten minutes
````

# Explain your code!

### Transmitting the data / connectivity

As can be seen in the code, only a floating point value is transmitted. As the data is sent only when the measured temperature is outside of a given range, it is hard to say how often the data is sent over the internet. However, the maximum frequency is ten minutes, as that is how often the temperature is measured. I went for this quite infrequent measurement and transmission in order to reduce the battery consumption.

In this project, WiFi is used for wireless communication, and webhooks for the transport protocol. 

### Presenting the data

Describe the presentation part. How is the dashboard built? How long is the data preserved in the database?

I created a simple table in Pybytes to visualize the data, in which the time of the signal was sent and the room temperature in celsius is displayed. However, the data is only saved in Pybytes for one month. On the other hand, the notifications that are in turn sent to my Discord channels persist, in theory, forever. However, there's not, in my case, any need for more than a month's storage, as the utility is very temporal in nature and should only serve as a notification for you to keep closer track of your room temperature. 

As mentioned, the trigger of the data is when the measured room temperature falls outside of a given, acceptable range.
![](https://i.imgur.com/wN292hc.png)

## Finalizing the design
After having finished this project, you should receive Discord notifications whenever the temperature of your room is unacceptable:
![](https://i.imgur.com/m3WCVJS.png)

Show the final results of your project. Give your final thoughts on how you think the project went. What could have been done in an other way, or even better? Pictures are nice!

    Show final results of the project
    Pictures
    *Video presentation

I believe the current system can not be built in a substantially better way given the current requirements - they are quite simple. However, if one were to want to expand the functionality of the system, I probably would have went for a database that stores the data for longer, and a paid platform such as Google Cloud to allow for more detailed analysis of the data. In the future, I would find it interesting to:

- Send alerts whenever there is an abnormal deviation from the room temperature -- even if it is within the acceptable range defined by the Public Health Agency of Sweden.
- Track the room temperature AND energy usage of whatever heating you're using in your home. Are there ways to minimize one's energy usage while maintaining a comfortable room temperature?