# Tutorial on how to build a sleep temperature sensor
## Project overview
This project is about how to build a simple temperature sensor using a LoPy4 and a Pycom expansion board. The sensor alerts the user when the optimal sleeping temperature in the bedroom has been reached by making the rgb led on the LoPy4 device turn green. If it´s too cold the rgb led turns blue and if it´s too hot it turns red.
A time estimation for rebuilding this project is approximately 2-3 hours.
**By Jacki Beri, student credentials: jb22mf.**
## Objective
If you suffer from insomnia and other types of sleep disorders, one of the things you could do to improve your sleep is to keep the bedroom at a certain temperature. The optimal sleeping temperature is between 14 and 18 degrees Celsius, according to [Karolinska Institutet](https://utbildning.ki.se/somn).
To do this you would have to put up a room thermometer, check the temperature value and keep track of what temperature is good enough for sleeping. To simplify these steps and hopefully help those who suffer from sleep disorders, this project was developed. It´s aim is to alert the user, in a simple way, when the temperature is too cold, too hot or optimal for sleeping so that they can take measure for example open a window if it´s too hot.
The user will also get insight of the temperatur in the room, so if the user notices that it´s often too hot perhaps they can turn down the heat radiator and both save money and have a good night sleep.
## Material
All the material was bought from electrokit as a Lopy 4 basic bundle kit for 995 SEK. The material that was used in this project:
• **Pycom LoPy4 with headers.**
The LoPy4 is a MicroPython enabled compact development board with LoRa, Sigfox, Wifi and Bluetooth. It´s RAM memory is 4 MB and it has input power of both 3,3 V and 5,5 V.

Fig. 1. LoPy4 with headers, [](https://pycom.io/product/lopy4/)pycom.io.
• **Pycom Expansionboard 3.1**
This is used to connect the LoPy4 via USB to the computer.

Fig. 2. Pycom breadboard.
**• Micro USB cabel**
To connect the Pycom parts to the computer.

Fig. 3. Micro USB cable.
• **Temperature Senor, MCP9700 TO-92.**
This sensor has a wide measurement range and can measure temperature between -40 to 125 degrees Celsius. It has a low power consumtion of 6 µA, and a voltage supply of 2,3-5,5 VDC.

Fig. 4. Temperature sensor MCP9700, [electrokit.com](https://www.electrokit.com/produkt/mcp9700a-to-92-temperaturgivare/).
• **A Breadboard and 3 wires.**
To connect the temperature sensor to the Pycom parts.

Fig. 5. Breadboard with wires.
## Computer setup
In this project, a computer with Windows 10 has been used. There´s a getting started guide at the [Pycom](https://docs.pycom.io/pymakr/installation/) website. Install [Atom](https://atom.io/) as editor (or another optional editor). When the chosen editor has been installed you need to install the Pymakr Plugin. In Atom this is done by clicking on ”File” in the editor menu and then choose ”settings”. In ”settings” you will find the ”Install” page. Type in ”Pymakr” in the search field and the plugin you need to install will appear. Click install. This plugin adds a REPL console to Atom that connects to your Pycom board, so you can easily run code on the board or synchonize files to it. Create a folder and in Atom press ctrl+N to create a new file. Name the file main.py. In this file copy in the program code. To upload the file in Atom to the LoPy4 press the upload button, see figure 6.

Fig.6. Atom terminal with buttons to connect, run and upload project to your Pycom device.
If you want, you can update the Pycom expansionboard firmware but in this project it wasn´t updated and worked anyway. Pycom recommend that you update it, and the steps on how to do it are listed in their [website](https://docs.pycom.io/pytrackpysense/installation/firmware/). Assemble the expansionboard with the Lopy4 as seen in figure 7.

Fig. 7. Breadboard Lopy4 attached to it.
The LoPy4 was flashed with the latest firmware by using Pycom [firmware update utility tool](https://docs.pycom.io/gettingstarted/installation/) that is found on the Pycom website in the Software section. Download the software and create an account at pybytes.pycom.io, it´s free. Pybytes is a device management platform that can be used to register your Pycom device, see figure 8. When you are logged in to Pybytes, choose the ”Add device” box and then the ”Add device via USB”. A list of Pycom devices will appear, choose the LoPy4. Under ”Enable networks” choose ”WiFi” and press next. Then choose a name or keep the proposed one and click on the ”manage WiFi” to configure your network. Manage the wifi, choose it and then press the button ”Save”. Now an activation token will appear. Conncet the Pycom device to the computer using a micro USB cable, copy the token and start the Pycom firmware update utility tool. Press ”continue” until the communication page appears. Make sure that the Pycom device is found and is appeared in the port section (this was done automatically) and in the Type section choose pybytes and check the ”Force update Pybytes registration” box and press continue. Now paste the activation token in the Pybytes registration page that has been appeared and press continue. Advanced settings will appear, make sure they are correct then press continue and the device will be flashed. When it has finished a page with the header result will appear. Save the information about your device.

Fig. 8. Pybytes.
## Putting everything together
According to the [datasheet](https://www.electrokit.com/uploads/productfile/41016/2243473.pdf) of the temperature sensor it should be connected as shown in figure X. It has three leads. One is power, one is ground and one is the analog signal. It has a voltage supply of 3,3-5,5 V so we will use the 3V3 on the Pycom device and no resistors are needed. Pycom provides a nice [wiring diagram](https://docs.pycom.io/datasheets/development/lopy4/) for the LoPy4, which can be used to identify which pins provide analog inputs etc. For this tutorial P16 is used as input on the expansionboard. Connect P16 to the middle lead on the temperature sensor. Connect the 3V3 on expansionboard to the lead marked VDD and connect the GND on the expansionboard to the lead labeled GND, see figure 9. In figure 10 you can see the circuit, which is a development setup.

Fig. 9. Temperature sensor leads.

Fig. 10. The circuit.
## Platform
The platform that has been used is [Pybytes](https://pybytes.pycom.io/), which is a free cloud based device management platform. It´s simple to use, free and suits this low scale project. If the project were to grow and I would want to scale this idea I would have to use another platform as this is more suited for low scalable projects.
With Pybytes you can have control over your Pycom device and it´s data stream. The data can be visualised accoding to your interest and saved in the cloud. Other advantages are that you can distribute firmware updates over the air and track your devices with a geolocation feature.
## The code
The librarys that have been used are: machine, time and pycom. The first two lines in the code configure the analog input on P16. The third line turns off the pulsating heartbeat light of the Pycom device so we can set it to blue, green and red. The optimal sleeping temperature is in a range of 14 to 18 degrees Celsius, in the code below represented by the lower and upper limit. We then have a loop that repeatedly reads the analog input and converts it to degrees and checks if the temperature is within the lower limit and the upper limit and prints out, in the terminal, the status. If the temperature is over the upper limit, the rgb led light turns red, if it´s lower than the lower limit it turns blue. If the temperature is within the limits, the light turns green. The data is sent every 15 minutes using the pybytes.send_signal on channel 1 and the data that has been sent is the degrees.
The degrees are calculated by a formula which was included in the [datasheet](https://www.electrokit.com/uploads/productfile/41016/2243473.pdf) of the temperature sensor. In this formula the millivolts are used to calculate the degrees in Celsius.
```
adc = machine.ADC()
apin = adc.channel(pin='P16')
pycom.heartbeat(False)
LowerLIMIT = 14
UpperLIMIT = 18
while True:
millivolts = apin.voltage()
degC = (millivolts - 500.0) / 10.0
if (degC > UpperLIMIT):
pycom.rgbled(0xFF0000) # Red
print("It´s too hot")
time.sleep(1)
if (degC < LowerLIMIT):
pycom.rgbled(0x0000FF) # Blue
print("It´s too cold")
time.sleep(1)
if (degC == LowerLIMIT) or (degC == UpperLIMIT) or (degC > LowerLIMIT) and (degC < UpperLIMIT):
pycom.rgbled(0x00FF00) # Green
print("It´s perfect for a good night sleep")
time.sleep(1)
pybytes.send_signal(1, degC)
print(millivolts)
print(degC)
time.sleep(900)
```
## Transmitting the data / connectivity
In Pybytes create a project, set the network configuration, using WiFi and press ”Save”. Add the LoPy4 that was registrated in the computer setup step to the project.
The data is sent every 15 minutes with a size of 8 MBit over the WiFi to Pybytes. The transport protocol that has been used is MQTT and is already builtin. To send the data use the pybytes.send_signal (), see code block above.
## Presenting the data
The data is saved in Pybytes for one month and is presented in a line chart. To visualize the data, go to the project in Pybytes, see figure 11. In the ”dashboard” you can organize your data by pressing the ”organize” button to get a better overview of your streaming data.

Fig. 11. Pybytes current project menu, the dashboard view.
Choose ”signals” and define a new signal. Enter channel, name and unit and press ”save”. Choose the newly defined signal and press ”create new display” and select the display you want to visualize your data in. In figure 12 a line chart was created.

Fig. 12. Linechart of the room temperature depending on the time.
## Finalizing the design
The project is pretty basic and well suited for beginners. It went well. It´s open for furthermore improvements, for example a battery can be used to make it wireless. A lamp instead of the rgb led of the Pycom device could be used or instead of light use sound to alert the user of the temperature status. Maybe a power button to turn it on and off or make the Pycom device turn on by itself at a certain time instead of having it run all day, since it´s for checking if the roomtemperature is suited for sleeping and most people don´t sleep all day. Another thing that can be improved has something to do with the temperature unit. Since not all use the Celsius scale, find a good solution like a converter so that other temperature units can included. 8 Mbit are sent to Pybytes over the WiFi and the temperature values consits of several decimals. Another thing that can be improved is to lower the amount of data sent and round off the degree value to only send one decimal.
Although basic, the project is overall very instructive since it consist of several different parts (coding, hardware, electronics etc.) to put together the final product.

Fig. 13. The sleep temperature sensor, indicating that it´s too hot to sleep.