---
# System prepended metadata

title: Tutorial on how to build a temperature and humidity sensor to check on my dog in the car.

---

# Tutorial on how to build a temperature and humidity sensor to check on my dog in the car.

My name is Camilla Gustafsson and my student credential at Linneaus University is cg222qb. In the course applied IoT we got to do an own IoT project. I chose to measure temperature and humidity in my car so that I could monitor how hot or cold it is for my dog in the car if I had to leave him in there for example to run an errand.

To follow this tutorial I think it might take a day or so if you already have bought and recieved your hardware needed. If you are new to IoT-projects, an other day may be needed to fix bugs that may occur.

## Objective
I've choosen to monitor the temperature and humidity in my car so I can make sure that my dog, which I sometimes need to leave in the car for a short period of time, doesn't get to hot or cold. One purpose for this is obviosly to monitor the dogs wellbeing, but another purpose is to be able to expand the project to display the temperature on a small screen in the car window so that bypassers can se what the temperature and humidity is in the car. Every summer car gets smashed (rightfully) to rescue dogs that have been left in hot cars. But in newer cars you can leave the airconditioning on and the cars stays cool enough for the dog to be comfortable in and therefor I think a IoT device like this fills its purpose. I think I will gain insights in how hot or cold it actually gets in the car when away for a while. 

:::info
:information_source: Disclamer! The expansion of the project wasn't possible during the course since hardware in form of a special simcard for IoT project wasn't ordered and recived in time. The tutorial will show how I set up my project to connect my device in an other way than preferred for a moving obejct such as a car.
:::

## Material
Here's a list of the hardware used for the project: 


| Hardware |Description | Place of purchase | Cost |
| ------------------------------------- | ----------------- | ---- |---- |
| Pycom Fipy microcontroller            | Microcontroller programable with micropython. Supports WiFi, Bluetooth, LoRa, Sigfox and dual LTE-M (CAT-M1 and NB-IoT)  | https://pycom.io/product/fipy/| 59.40€ | 
| Pycom Pyscan expansionboard  | Expansionboard with accelerometer, light sensor and RFID-NFC         | https://pycom.io/product/pyscan/| 35.09€|
| Breadboard and wires     | Connects sensors via wires to the microcontoller or expansionboard             | Local electronics shop   | 200SEK  |
| LoRa antenna        |  Antenna for transmitting data over LoRa                | https://pycom.io/product/lora-868mhz-915mhz-sigfox-antenna-kit/| 9€     |
| 3.7V LiPo battery 500mHa | Powers the IoT device            | Gift from friend|approx. 100-200SEK|
| Usb-cable both power and data  |Uploads code to the microcontroller and can be used for power       | Gift from friend|approx. 50-100SEK|
| DHT22 Temperature and humidity sensor | Measures temperature and humidity |https://sizable.se/P.JN41E/DHT22-AM2302-Temperatur-och-luftfuktighetssensor| 61SEK |

:::warning
+ Specifications can be found at each link.
+ I realised that there's a bundlepack you can order from Pycom instead of loose parts, check this link: https://pycom.io/product/fipy-multipack/
:::

![](https://i.imgur.com/4zW613y.jpg)
Imgage 1: The picture shows the Fipy microcontroller and the Pyscan expansion board from Pycom, then the breadboard and wires. Then 3 antennas, first is an RFID-antenna and then an LTE-antenna not used in the project but were included in my order. The last antenna is a LoRa and Sigfox-antenna which is the one used.

![](https://i.imgur.com/XmueJiF.png =300x)
![](https://i.imgur.com/dIvBrxX.png =300x)
Image 2 and 3: The pictures shows the DHT22 temperature and humidity sensor.


## Computer setup and IDE
I'm working om a mac with the macOS Catalina version 10.15.7. I chose Atom as my IDE since I haven't used VScode as much as I needed to be comfortable and the course were using Atom as preferred IDE in workshops and such. 

I followed the steps in the roadmap of the course and we started of with a tutorial https://hackmd.io/@lnu-iot/SydH7MTcw on installing Node js (https://nodejs.org/en/) and then Atom (https://atom.io/). In Atom we then installed a Pymakr package. 
![](https://i.imgur.com/hIoT992.png =400x)
Image 4. Install packages in Atom.

![](https://i.imgur.com/N71KW0N.png =300x)
Image 5. Search for pymakr and then press install.


After that I followed this tutorial https://hackmd.io/@lnu-iot/SJ91R_jSO#Part-1-Firmware-Update-amp-Running-Code-PyCom-Boards to connect the boards to the computor via data usb and to update the firmware on the microcontroller. You can find the update here: https://software.pycom.io/findupgrade?product=pycom-firmware-updater&type=all&platform=macos&redirect=true Then it was time to start using some code to test it out. The goal was to get the led on the board to flash in tre different colors continously. This is the code I needed to use to get the colors to flash:

```python=
from pyscan import Pyscan
from MFRC630 import MFRC630
import time
import pycom
import _thread

VALID_CARDS = [[0x43, 0x95, 0xDD, 0xF8],
               [0x43, 0x95, 0xDD, 0xF9]]

py = Pyscan()
nfc = MFRC630(py)

RGB_BRIGHTNESS = 0x8

RGB_RED = (RGB_BRIGHTNESS << 16)
RGB_GREEN = (RGB_BRIGHTNESS << 8)
RGB_BLUE = (RGB_BRIGHTNESS)

# Make sure heartbeat is disabled before setting RGB LED
pycom.heartbeat(False)

# Initialise the MFRC630 with some settings
nfc.mfrc630_cmd_init()

def check_uid(uid, len):
    return VALID_CARDS.count(uid[:len])

def discovery_loop(nfc, id):
    while True:
        # Send REQA for ISO14443A card type
        atqa = nfc.mfrc630_iso14443a_WUPA_REQA(nfc.MFRC630_ISO14443_CMD_REQA)
        if (atqa != 0):
            # A card has been detected, read UID
            uid = bytearray(10)
            uid_len = nfc.mfrc630_iso14443a_select(uid)
            if (uid_len > 0):
                if (check_uid(list(uid), uid_len)) > 0:
                    pycom.rgbled(RGB_GREEN)
                else:
                    pycom.rgbled(RGB_RED)
        else:
            # No card detected
            pycom.rgbled(RGB_BLUE)
        nfc.mfrc630_cmd_reset()
        time.sleep(.5)
        nfc.mfrc630_cmd_init()

# This is the start of our main execution... start the thread
_thread.start_new_thread(discovery_loop, (nfc, 0))

# We disable LED heartbeat to control it manually
pycom.heartbeat(False)

# Your board run this section over and over
while True:
    #colors in hexadecimal (0xRRGGBB)
    pycom.rgbled(0xFF0000)  # Red
    time.sleep(1)
    pycom.rgbled(0x00FF00)  # Green
    time.sleep(1)
    pycom.rgbled(0x0000FF)  # Blue
    time.sleep(1)


```
To upload code to your board you need to press the upward pointing arrow (see image 6), if you only choose the play arrow you only run the code locally and the code doesn't get saved on the board. When succeded with the flashing you know your board is connected and receiving code properly. To stop the flashing you should press ctrl + c in the lower part of the IDE/in the terminal.

![](https://i.imgur.com/Qkt7AdO.png =100x) 
Image 6. The image shows the button to upload code in Atom.

To get the DHT22 temperature and humidity sensor to work you need to install a library to Atom which you can find here: https://github.com/JurassicPork/DHT_PyCom

## Putting everything together 
![](https://i.imgur.com/61OMSZJ.png)
Image 7. The circuit diagram shows how I connected everything. The red cable connects the DHT22 sensor with power from the expansionborad through the positive rail on the breadboard. The black cable is connected to ground through the negative rail on the breadboard and the green cable sends data to the exansionboard at pin 19. (You'll have to ignore that the breadboard picture I found for the circuit diagram has + & - opposite to positive and ground rails on my breadboard. The wireing on the diagram is consistent to how I've done it.)
The LiPo battery is connected to the JST connector on the expansionboard and the LoRa antenna is connected to the external LoRa and Sigfox antenna connector on the microcontroller.


![](https://i.imgur.com/whAUtkK.jpg =350x) ![](https://i.imgur.com/CGzJR8J.jpg =350x)
Image 8 & 9. These images shows how it looks like when connected.

This setup I believe can be used in production if you slim it down, solder connections and make it nice and neat in a case. I think if you were to go for the expansion of the project with a lcd or other monitor to display the data in the car window for others to se, it can be a commercial product.




## Platform
To present the data I used Datacake which is a low code IoT cloud based plattform. Datacake has templates for easy access of LoRaWAN devices. 

The first two devices you connect are free and the data is preserved for a week. If you need to connect more devices or need a longer overview of the data check out the pricing at https://datacake.co/pricing But as I understand it is a bit pricy service if you want to scale up and connect many devices. 




## The code

This is the final code of the main file. It shows the library needed for the DHT22, a socket to connect to LoRaWAN, code for the temperature and humidity sensor, which pin to collect data from and how often it should send data, which I set to every 10 minutes.

```python=
# Data is sent to Pybytes. Needs to flashed with Pybyte firmware
import time
from machine import Pin
from dht import DHT # https://github.com/JurassicPork/DHT_PyCom
import socket


# Create a socket to LoRa
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
s.setblocking(False)

# Type 0 = dht11
# Type 1 = dht22

def sendData(temp, humidity):
    tempAndHumidity = int(temp*1000000+humidity*100) # combine both in an int
    bytes_to_send = tempAndHumidity.to_bytes(4, 'big') # convert to bytes in big endian order
    s.send(bytes_to_send) # send
    print("data sent")

th = DHT(Pin('P19', mode=Pin.OPEN_DRAIN), 1)
time.sleep(2)

while True:
    result = th.read()
    while not result.is_valid():
        time.sleep(.5)
        result = th.read()
    print('Temp:', result.temperature)
    print('RH:', result.humidity)
    sendData(result.temperature, result.humidity)


    time.sleep(600) # update every 10 minutes

```
![](https://i.imgur.com/wBq5jkg.png)
Image 10. Make sure to change the pin number to correspond to which pin you choose on your board. Here I've changed it to pin 19.

To connect to Helium over LoRaWAN you need to paste some code into your boot.py file: 

``` python=
from network import LoRa
import time
import binascii

lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)

dev_eui = binascii.unhexlify('0000000000000000')
app_eui = binascii.unhexlify('0000000000000000')
app_key = binascii.unhexlify('00000000000000000000000000000000')

lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0)

# wait until the module has joined the network
while not lora.has_joined():
    time.sleep(2.5)
    print('Not joined yet...')

print('Network joined!')

# Your old code from main.py should be here

```

When adding a new device at your Helium account a Dev EUI, App EUI and App Key will be generated. These values you need to put in at line 7-9 in your boot file. Then run your boot file in the console to connect to Helium.

## Transmitting the data / connectivity
I chose LoRaWAN and Helium for transmitting the data. Since we were encouraged to try out LoRaWAN, I checked both Helium and The Things Network if I had any gateway coverage were I live. It turned out that in Skövde only Helium was avaliabe so thats what I chose to go with. 

:::info
It was in this stage of the course when I realised that sending data over LoRaWAN wasn't optimal for my project since a car is a moving object and I want my IoT device to work where ever I go. So after consulting with the teaching assistants they suggested that sending data over cellular towers with LTE and narrowband IoT would be the preferable choice. I ordered a simcard but I didn't recieve it in time to try it out in the scope of the course.
:::

Helium is a peoples network of decentrilized wireless infrastructure based on local gateways called hotspots that recieve and sends data over the internet forming a global wireless network (https://www.helium.com/). No data is stored in the gateways. It is opens source and data is sent over the LoRaWAN technology.

Helium uses two types of currency, HNT is eraned when hosting a hotspot/gateway and datacredits are used by devices to send data on the network (https://www.helium.com/token). If you don't host a gateway yourself you only pay in datacredit for the data sent, which is much cheaper than sending over cellular.

Data is in the projects current state transmitted over LoRaWAN and the transport protocol used is HTTP. The data is set to be sent every ten minutes. I set it to this pace since temperature in a car can rapidly rise. Maybe one would benefit from having data sent every 3-5 minutes instead, but take into consideration that the more often you sent data both your battery consumtion and your data load will increase.

"The HTTP protocol is a request/response protocol based on the client/server based architecture where web browsers, robots and search engines, etc. act like HTTP clients, and the Web server acts as a server" (https://www.tutorialspoint.com/http/http_overview.htm). The HTTP protocol isn't as safe as the MQTT protocol which has built in cryptation. The MQTT protocol works as a broker that recieves data from sensors (publishers) and lets different subscribers of that data collect it from the broker. 


## Presenting the data
I chose Datacake to present my data since people seemed to have a bit of struggle with Pybytes and the teaching assistans recommended Datacake as an option if you were fairly new to IoT. 

When you add a device in Datacake and chosing Helium as network you need to add the DEV_EUI you got when adding the device to Helium. 
![](https://i.imgur.com/EzfvFRi.png =400x)
Image 11. This is where you need to add the DEV_EUI.

The dashboard has a drag and drop function for widgets, no code experince needed and you can set alerts when values exced or drop below set values. As I understand it when data is recieved in Datacake, it is automatically stored. So when I transmitt data every 10 minutes, it's stored in that pace and then kept for a week if you're on the free plan. 

![](https://i.imgur.com/3yxVXoe.png =150x)
Image 12. This is the mobile version of data visualisation of my IoT device at Datacake.

![](https://i.imgur.com/zYvhQqT.png)
Image 13. This is how the presentation of data from the device looks like in desktop mode at Datacake.

A nice function is that you can create public links for others to see the data without them needing to register for an account.


## Finalizing the design
Since the project is supposed to evolve into an IoT device which can show temperture and humidity data both over the internet and locally in the car to a monitor the design is not yet finalized but is supposed to be placed as in image X. 

![](https://i.imgur.com/huSmtYy.jpg =300x)
Image 14. The placement of the IoT device and the future screen.

For the sake of the project I think it really could serve a purpose both for dogowners (and other petowners) themself, but also for concerned bypassers. The project could evolve even further by setting alerts if temperature values exceeds predefined thresholds, with video and audio monitoring, maybe also to be able to talk to the pet via a speaker if the dog needs to be calmed down etcetra.

I learned a lot on this project since I was a total beginner in the field of IoT. It was really great learning to make an own project from a-z (almost in my case) not just to read about it, as might be the case in other teoretical university courses. Also to wright a tutorial in this format was a new experience for me. Great course over all and the teaching assistants were gold :smiley: 
