# Connect Temperature Sensor to LoPy Tutorial
>Name: Richard Palm
>
>Student ID: rp222je
>
>Time estimate: 2h
>
>Operating System: Windows 10
## Project overveiw
This is a basic project made for the tillämpad IoT course at LNU. It is a basic thermometer that uses a LoPy4 and a temperature sensor to meassure the temperature of the
surrounding air and then sends the data to Ubidots where it is displayed. [github link](https://github.com/richard-proj/tillampad-iot)
### Objective
I chose this project partly because it was the sensor I had at my disposal. As a student I couldn't think of anything that I could build with a LoPy4 right now that could justify spending more money on the project. The purpose of this project was learning the basic premise of IoT, which could be done with the temperature sensor, and from there it would be easy to add additional sensors in the future if I had need of them.
Hopefully this project will expand my IoT knowledge and show me its many possible uses so that it can be used in the future as another tool to solve problems.
## Materials
| Item | Price | Link |
| ---------------------------------|---------------|-----------------------------------------------------------------------------------------------|
| LoPy4 | 364 kr | [Link](https://pycom.io/product/lopy4/) |
| Pycom expansion board | 166 kr | [Link](https://pycom.io/product/expansion-board-3-0/) |
| MCP9700 TO-92 temperature sensor | 8 kr | [Link](https://www.electrokit.com/en/product/mcp9700-e-to-to-92-temperature-sensor/) |
| Breadboard | 59 kr | [Link](https://www.electrokit.com/en/product/solderless-breadboard-400-tie-points/) |
| Wires | 36 kr | [Link](https://www.electrokit.com/produkt/kopplingstrad-byglar-for-kopplingsdack-mjuka-65st/) |
| **Total:** | 633 kr | |
The LoPy4 was used as the base for the project and is a small computer programmable with micropython. However the LoPy4 does not have an usb connection by default and therefore the expansionboard is needed. It adds a micro-USB connection and makes it easier to connect the wires to the correct pins.
<img src="https://cdn.antratek.nl/media/product/5c9/lopy4-lora-sigfox-wifi-ble-module-pycom-lopy4-aef.jpg" width="25%">
<span style ="color:grey">The Pycom LoPy4 board</span>
<img src="https://docs.pycom.io/gitbook/assets/expansion3.png" width="25%">
<span style ="color:grey">Pycom expansion board</span>
<img src="https://media.rs-online.com/t_large/R9122847-01.jpg" width="25%">
<span style ="color:grey">The MCP9700 temperature sensor</span>
## Computer setup
To start off the project we will need to set up our computer and the pycom device. I am using Wndows 10 and this tutorial will be focused on that operating system.
First you will need to chose an IDE. I personally preffer Visual Studio Code and will be using it in this tutorial.
It can be downloaded [here](https://code.visualstudio.com/download). Follow the instructions of the installer and then download the Pymakr extension using the extension tab in
Visual Studios. This extension will be used to send code to your Pycom device. The most important commands are Ctr+Shift+C to connect to your device, Ctrl+Shift+R to run your current code and Ctrl+Shift+S to sync your files to the LoPy4.
But lets not get ahead of ourselves. Before we can start coding we the to setup the LoPy itself. Start by downloading the [Pycom Firmware Updater](https://pycom.io/downloads/). This will be used to update the firmware of the board after you have connected it to your computer via USB. With LoPy4 attached to the expansion board and connected to your computer you can start the firmware updater. We will be running a standard setup so most things we need are already checked, simply follow the instructions.
Now the Pymakr extension should work with your LoPy4 and we can begin the next stage of the project!
## Assembling the Circuit
Now for the setup. The setup is very basic and only used for testing purposes as a breadboard is used to simplify the connections. There are three pins of the sensor that need to be hooked up. with the round part of the MCP9700 facing you the lefmost pin is the ground pin. It should be connected onto the expansionboard where it is labeled GND. The middle pin of the sensor outputs voltage depending on the temperature around the senor. 500mV is 0 °C, from there it is 10 mV/°C so a formula for converting the V-output to degrees is *(mV-500)/10*. The right pin of the sensor is for V input. The LoPy4 outputs 3.3 V and the sensor can handle 2.3-5.5 V so no resistors are needed. The image bellow show the connections, except I placed the sensor directly in the breadboard but for clarity's sake it is not in the diagram.
<img src="https://i.imgur.com/RBrviac.png" width="40%">
## Platform
When choosing a platform it was important for me that it was free and easy to use. I am sure there are many platforms that would fit those critera but I chose to use Ubidots because of it's detailed documentation about using the service with a Pycom device. The guide I followed can be found [here](https://help.ubidots.com/en/articles/961994-connect-any-pycom-board-to-ubidots-using-wi-fi-over-http). Using the guide it was easy to setup and Ubidots also functions as a dashboard. You can setup your own variables through the Ubidots website or do like I did and let it do so automatically by sending it data. Ubidots has a restriction on how much data you can send each day which might make it a worse choice for some projects but for the purpose of this one it is more than enough. Using Ubidots of course requires an Ubidots account which can be made for free [here](https://ubidots.com/stem/). It is important to note that the free version can only be used for education and private projects.
## Code
>boot
>
>This was taken from the Ubidots documentation and makes the pycom device able to communicate over USB.
```python
from machine import UART
import machine
import os
uart = UART(0, baudrate=115200)
os.dupterm(uart)
machine.main('main.py')
```
>main
>
>replace UBIDOTS TOKEN, SSID and PASSWORD with relevant information
>
>The last loop runs once every five minutes and converts the voltage output by the sensor into degrees.
>
>The communication part is a modified version of the code from the Ubidots documentation.
>
>Basically a json object with the information is created and sent via HTTP POST to the Ubidots servers.
```python
#main.py -- put your code here!
import pycom
import time
import machine
from network import WLAN
import urequests as requests
pycom.heartbeat(False)
TOKEN = "UBIDOTS TOKEN" #Put here your TOKEN
DELAY = 360 # Delay in seconds
wlan = WLAN(mode=WLAN.STA)
wlan.antenna(WLAN.INT_ANT)
# Assign your Wi-Fi credentials
wlan.connect("SSID", auth=(WLAN.WPA2, "PASSWORD"), timeout=5000)
while not wlan.isconnected ():
machine.idle()
print("Connected to Wifi\n")
# Builds the json to send the request
def build_json(variable1, value1):
try:
data = {variable1: {"value": value1}}
return data
except:
return None
# Sends the request. Please reference the REST API reference https://ubidots.com/docs/api/
def post_var(device, value1):
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("Temperature", value1)
if data is not None:
print(data)
req = requests.post(url=url, headers=headers, json=data)
return req.json()
else:
pass
except:
pass
# setup sensor
adc = machine.ADC()
apin = adc.channel(pin='P16')
while True:
millivolts = apin.voltage()
degC = (millivolts - 500.0) / 10.0
print(degC)
post_var("pycom", degC)
time.sleep(DELAY)
```
## Transmitting Data to Ubidots
The data is transferred to the Ubidots servers using HTTP and WiFi. I first tried to use LoRa but there where no gateways within range and I had no intent to set up my own for only this project. So even though WiFi is inefficient when sending small amounts of data it was most practical in my situation. Ubidots has good HTTP integrations so that ended up being the protocol I used. The data is sent once every five minutes and saved at the Ubidots and stored on thier servers.
## Displaying the Data at Ubidots
The data can be Displayed at the Ubidots website by using the dashboard feature. Press the data tab at the top of the Ubisoft website och select dashboard. Create a new dashboard using the plus sign in the top right and add your device to it. You can add a widget clicking on your newly created dashboard and then pressing the plus in the corner again. I added two widgets, a graph showing the raw data for the last day and a thermometer showing the average temperature in the last hour. These numbers can be adjusted for a more long term project but for this one they provide nice looking graphs.
<img src="https://i.imgur.com/cOln8AK.png" width="40%">
## Final thoughts
I did this project to get a basic understanding of IoT and I think the project was a success in that regard. If I were to do this again I would make a more complicated project using more sensors which in turn would give me more data to play around with but I couldn't come up with a problem that I could solve with a more advanced IoT solution so I was not motivated to spend too much time on the project. Here are som pictures of the finished project:
<img src="https://i.imgur.com/9tHW1WZ.jpg" width="40%">
<img src="https://i.imgur.com/4gJHFBT.jpg" width="40%">
<img src="https://i.imgur.com/pDbdo94.jpg" width="40%">