Tutorial on how to build a temperature sensor
===
###### tags: `Pycom` `IoT` `Tutorials`
>Name: Noel Karlsson Johansson
>Student credentials: nk222nr
>Time to build: 4-6h
## Project overview
This project shows how to build a temperature sensor using a pycom device connected over Wifi. That also allows real time monitoring of the temperature, the data is displayed via Ubidots.
## Objective
### Why and for what purpose
The main reason for this project is that I wanted something simple and easily understandable to build. So that I could get a good grasp of how IoT's transmit data from a sensor and how that can later be displayed anywhere via the internet. The whole project was mean to be a learning experiment for myself. The thermometer will be placed in my garage as the temperature tends to vary alot in there.
### What insights I got
I got alot of insigts in to how to go about building an IoT from the ground up. I have myself never done anything like this before, so this was a big learning expreience for myself and I hope this tutorial can be that for others that are just starting out. More specificly I got alot more insights into how all sensor, databases, protocols and internet are connected.
I Hope this porject will give others the base knowlegde to continue to inovate and build more complex projects in the future.
## Material
### List of material
| Component | Item | Link | Price |
| -------- | -------- | -------- |-------- |
| 1 | LoPy4 | [Link](https://pycom.io/product/lopy4/) |€34.95 |
| 2 | Expansion Board 3.0 | [Link](https://pycom.io/product/expansion-board-3-0/)|€16.00 |
| 3 |MCP9700-E/TO TO-92 temperature sensor| [Link](https://www.electrokit.com/en/product/mcp9700-e-to-to-92-temperature-sensor/) |8.00kr |
| 4 |Test wires 100mm m/m 30pcs| [Link](https://www.electrokit.com/en/product/test-wires-100mm-m-m-30pcs/) |33.00kr |
| 5 |Breadboard| [Link](https://www.electrokit.com/produkt/kopplingsdack-400-anslutningar/) |59.00kr |
### LoPy4
LoPy4 can be describe as a small computer which can be programmed with microPython. The LoPy4 chip itself does not have a power source and therefor it needs a expansionboard for power and easier access to the pins.

### Expansion Board 3.0
The board is a way to make it easier to connect various things to the LoPy and is powered by a micro USB cable.

### MCP9700-E/TO TO-92 temperature sensor
The sensor has three pins: 3-5V, GND and V-out.

## Computer/Hardware Setup
### Updating firmware
1. Before you start you should flash the firmware on the expansion board, I [followed this guide](https://docs.pycom.io/pytrackpysense/installation/firmware/)
2. If you are using Windows, which I did(I used windows 10), you may need to update some drivers. This only applies if you are using Windows 7. [Link to guide](https://docs.pycom.io/gettingstarted/installation/drivers)
3. Now you can connect your LoPy4 to the expansion board. Just insert the LoPy4 module on the Expansion Board with the reset button pointing towards the USB connector. The LoPy4 should click into place.
4. Time to flash the firmware of the LoPy4. Connect your Pycom device to the computor and follow [the guide Pycom created](https://docs.pycom.io/gettingstarted/installation/firmwaretool/).
### VSCode and PyMakr plugin
For the IDE I use VSCode, this is just a prefrance but I recommend using either VSCode or Atom.
>VSCode can be downloaded at https://code.visualstudio.com/ or Atom at https://atom.io/
After installing either IDE install the PyMakr plugin. In VSCode just searth for "PyMakr" in the extensions tab and install.
>Here is a guide for both atom and VSCode https://docs.pycom.io/gettingstarted/installation/pymakr/
PyMakr needs Node.js to function correctly, which can be found an installed at https://nodejs.org/en/
When coding in VSCode and using PyMakr you need to make sure your in the correct folder, otherwise pushing code to your LoPy4 device might not work.
Start by pressing ctrl + shift + G to open up the PyMakr config file named "pymakr.json". Here you should se a line which has "sync_folder". Enter the name of the project folder you are working on after ":"

Now in VSCode open the folder that is above this folder in the hierarchy

Now you are ready to begin coding. To sync a projet press ctrl-shift-s and to run the current file ctrl-shift-r.
>For more information about PyMakr keymaps go to https://docs.pycom.io/pymakr/toolsfeatures/ or open the extension in VSCode
## Putting everything together

>The power source for the device is a micro USB connected to your computer.
## Platform
This tempereature will need to be accessable by everyone in the house at any time. It would be easier for everyone if the information was accessable from the internet and from a platform which dosent need an account for people to view.
I found Ubidots which provides a free platform for storing the small amounts of data required. It also is easy to use and has a neet design to it.
>Link to Ubidots webpage https://ubidots.com/
## The code
The libary used for this project can be found from this [link](https://github.com/jotathebest/micropython-lib/blob/master/urequests/urequests.py). The libary should be placed in a seperate folder called "lib" and saved with the name "urequests.py".
#### main
```python=
from network import WLAN
import urequests as requests
import machine
import pycom
import time
TOKEN = "xxxxx" # Put your TOKEN here
DELAY = 300 # 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")
# Gets the temperature from pycom device
def calTemp():
try:
adc = machine.ADC()
pinIn = adc.channel(pin='P13')
mVolts = pinIn.voltage()
degC = (mVolts - 500.0) / 10.0 # Converts millivolts to degrees celsius
return degC
except:
return 0
# Sends the request
def post_var(device, value):
try:
url = "https://industrial.api.ubidots.com/"
url = url + "api/v1.6/devices/" + device # Url for ubidots api
headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"} # Builds the header
data = {"temperature": {"value": value}} # Builds the json
if data is not None:
print(data)
req = requests.post(url=url, headers=headers, json=data)
return req.json()
else:
pass
except:
pass
while True:
post_var("pycom", calTemp())
time.sleep(DELAY)
```
#### boot
```python=
from machine import UART
import machine
import os
uart = UART(0, baudrate=115200)
os.dupterm(uart)
machine.main('main.py')
```
>Link to the github for this [project](https://github.com/noeljn/pycomTempSensor)
## Transmitting the data
With the location of the garage and Wifi accesspoints allready setup, the easiest choice was to connect hte device direcly using Wifi. I tried using LoRa but with no success I switched to going over Wifi. Ubidots has good integration with HTTP, so I used the HTTP protocol.
The data is sent every 5 minutes (mostly because Ubidots has a limit of how much data you can send per day)
## Presenting the data
On Ubidots there is a dashboard with two widgets, one representing the temperature parameter which receives new data every five minutes. The data is stored as soon as it's sent to the Ubidots servers and the data is saved for a month. For the temperature parameter there is also a line graph showing previus reported data. The temperature is displayed using Ubidots analog thermometer widget.

## Finalizing the design
Overall I thing the project went pretty well, hardest part of the project was getting to know this new environmentof IoT development. There are alot of this here that i've never done before. The presentation looks really nice. It looks clean and simple.
Something to add to this project in the future would be more sensors that can measure humidity, atmospheric pressure and light aswell has a battery pack so it could be moved outside. I have a server at home but it has not been used for a while. But using it as a database would have been a nice ide.
