---
# System prepended metadata

title: IoT Project - Temperature and Humidity for Chinchillas

---

# IoT Project - Temperature and Humidity for Chinchillas

 By: Mikael Eriksson (Student-id: me223fn)
 
 ## Introduction
 
The project is using a "Pycom Lofy4" as microcontroller and IoT Device, which is connected to a Pycom Expansion board 3 for easier programming. The sensor is a "DTH11" which senses temperature and humidity. The mission is to get data of these two elements in the hallway, where two pet chinchillas are located. With the information we will be able to know when they need cooling pads and if it's smarter to open a window to create cool air draft. Data should be sent to PyByte dashboard each half an hour.

Estimated Time: 2 hours

1 hour: Download Atom / Install the IDE necessary software/ Install MAKR for IDE/ Flash both Pycom devices
30 minutes: Connecting components together
30 minutes: Downloading code for sensor and making account and connecting to PyBytes.

## Objective

If you haven't seen a chinchilla before, they are rodant with really thick fur and they kind of look like a mix of a really furry squirrle with a bats head. Because of their thick fur they are suspectible to heat and humidity. If both are too high, the animal is in danger of dying by overheating. The fur is both a blessing and a curse; If the fur gets wet they have a really high chance of catching fungus which will damage their skin. Also can't really trim their fur because it makes them stressed,also if they don't have the fur they handle the cold even worse than than the heat.


Chinchillas will cool down by contact with cool air, they have big ears so the warm blood will go up to their ears and get cooled and pumped back to the body. That is why their ears become red when it's to warm for a chinchilla. Another way for them to coolthemselves down is by cold rocks or cooling pads , their paws then delivers the cool blood to their body. 

The purpose of the IoT device is to sense temperature and humidity in hallway. Chinchilla's ideal temperature is between 60°F and 75°F, and humidity kept less than 60%. There is a general rule that: Temperature + Humidity  shouldn't get higher than 150. [Reference to https://www.avianexoticvetcare.com/handouts/small-mammals/chinchillas.pdf]

The data on Pybytes will then be a reference that can be easy access to knowing the temperature.


## Material

The microcontroller used is Pycom device Lofy4, with a Expansion board 3 for easy programming and a micro-USB cable to connect it to the PC. I have a DTH11 sensor that check temperature and humidity. Also needed are cables to connect all pins together on a breadboard and optional part but makes live easier is a powerbank.



| Product            | Use for                                                                                 |
|:------------------ |:--------------------------------------------------------------------------------------- |
| Pycom LoFy4        | Analog and digital microcontroller,used for handling pretty much everything.            |
| Pycom expansion3   | A development board for Pycom devices to make it easy to program and connect cables to LoFy4 |
| DTH11              | Sensor for checking temperature and humidity.                                        |
| Breadboard         | To put the pins of the sensor in and to make a connect between components.                        |
| USB to micro-USB   | Used between Expansion 3 and PC to program the LoFy4                                       |
| Cables(breadboard) | Cables to go between the components pins.                                               |
| Powerbank          | For mobility with the device after development                                          |

The Lofy4 + Expansion board 3 + Breadboared were bought second hand, unused for 600 SEK.

The DTH11 was recieved in a pack of sensors from a product called "Playknowlogy Lilla modul-paketet för Arduino" from Kjell & Company that costs 299 SEK. However, it can be bought cheaply from Sizable for only 28 SEK. Had cables and powerbank at home so didn't need to buy any, but writing down recommendations below. 

Buying them new is:
* LoPy4 while writing new €38.45 -> [Link to store](https://pycom.io/product/lopy4/)
* Expansion Board 3.0 while writing €17.60 -> [Link to Store](https://pycom.io/product/expansion-board-3-0/)
* DTH11 28 SEK -> [Link to store](https://sizable.se/P.WGXR4/DHT11-Temperatur-och-luftfuktighetssensor)
* Breadboard 34 SEK -> [Link to store](https://sizable.se/P.SFGYT/Kopplingsdack-med-400-punkter) 
* Cables 31 SEK for 20cm -> [Link to store](https://sizable.se/P.K2HUW/Dupont-kopplingskablar-Hane-Hane-40-pin)
* USB to micro 99 SEK -> [Link to store](https://www.kjell.com/se/produkter/mobilt/ladda-koppla/kablar-adaptrar/micro-usb-kablar/micro-usb-kabel-1-m-p68687)
* Powerbank 99.90 SEK -> [Link to store](https://www.kjell.com/se/produkter/el-verktyg/laddare/mobilladdare/powerbank/linocell-powerbank-5000-mah-p89255)

416 + 190 + 28 + 34 + 31 + 99 + 100 =  898 SEK without the postal charges.


## Computer Setup

1. The IDE that will be used in this project is Atom, because it has better support for the plugin Pymakr. I tried Visual Studio Code,because I use it daily, however the plugin was not working as expected so Atom it's.

2. The Code repository will be GitHub. I've used it for other projects and it's used by many. It's easy to use and gets things done. The link is -> [LINK TO GITHUB](https://github.com/Mirke/IoTProject_Pycom_DTH11)

### Tutorial-1

Step-by-step tutorial:

1. First step is to download and install the IDE Atom, which will be used to program and upload code to the PYCOM device: [Atom Website](https://atom.io/)
2. After installing Atom, start it up and press "Install a Package" in the Welcome screen. Search for "pymakr", press install and let it get installed.[Check this link if any problems](https://docs.pycom.io/gettingstarted/software/atom/)
3. Next, go to [Updating Expansion board, Pycom](https://docs.pycom.io/updatefirmware/expansionboard/) and download "Expansion Board DFU v3.1" (v3.0 if it says differently on the backside of the Expansion 3). Then scroll down and download "DFU-util v0.9" for Windows. Now start Powershell and navigate to the folder where you downloaded the two files, and write `dfu-util-static.exe -D expansion31_0.0.11.dfu` (don't push ENTER yet). First remove the LoPy4 from the Expansion3, if it is docked in it. Secondly, connect the micro-USB to the Expansion3 and then hold the "Safe Boot" button on it. While holding the button down, connect the USB to a USB-port on the computer, wait a second then release the "Safe Boot" button and press enter on the computer to run the code -> `dfu-util-static.exe -D expansion31_0.0.11.dfu`. It will run and hopefully it will say that it was successful. IF NOT, follow the guide on [Updating Expansion board, Pycom](https://docs.pycom.io/updatefirmware/expansionboard/). When done disconnect the USB from the computer.
4. Time to update the LoPy4, go to this -> [link](https://docs.pycom.io/updatefirmware/device/), and download for Windows so you get the "pycom_firmware_updater_1.16.6.exe". Now insert the LoPy4 inside the Expansion3 board. Remember the LED-light and button on the LoPy4 should be at the same side as the micro-USB for the Expansio3 board. When LoPy4 is inserted, connect the USB back to the computer. Run the "pycom_firmware_updater_1.16.6.exe" firmware. When greeted with window press continue,then choose PyBytes in the "Type" list. Check "Enable PyBytes/SmartConfig support". If it asks about PyBytes information you can skip it, we will do it later. Lastly, change device type to LoFy3, Type/Version to latest version and check both CONFIG partition and NVS partition boxes,lastly press  Continue and hopefully it should work, if not then follow steps in this [link](https://docs.pycom.io/updatefirmware/device/)
5. Now if all gone well, read the "Building it" part of this report and after that come back here. [Link moves you to "Building it"](#Building-it)
### Tutorial-2
Welcome back from "Building it"!
6. Now run/restart Atom IDE and test writing `print("Hello world")` in the terminal where the Python REPL `>>>` is. This is to see if you are able to communicate with the Pycom. If not, then check the alternative links that I've linked to through out the tutorial and see if you can find the problem. If all well then next step it's. 
7. Now when we have connection to the Pycom we will create an account at Pybytes the link is -> [here](https://pybytes.pycom.io/). Write in your information and when you are logged in on your page, click on Devices->Add via USB. Enter Lopy4 and Expansion 3 board, Wifi SSID and the password to it and let it connect to your device. You will get JSON information which will need later so copy the information and save it somewhere. We going to use it for a `pymakr.conf` file in our project later.
8. Now PyByte should be able to speak with the device so it's time to download the library for the sensor and code that I've modified.Link to project -> [Github](https://github.com/Mirke/IoTProject_Pycom_DTH11) download it by pressing the green button saying "CODE" and download as zip.
9. Unzip it and go to Atom and press `File->Add Project Folder`. Choose "PYCOM_DTH11" folder that got unzipped. Next, `File->New File` give it the name `pymakr.conf` add the information we got from PyBytes, which should look something like this:
 ```json{
  "networks": [
    "wifi"
  ],
  "wifi": {
    "ssid": "YOUR_SSID",
    "password": "PASSWORD",
    "secureType": "PASSWORD"
  }
}
``` 
10. Now go to `main.py` and press the "Upload project to device" button which is at the bottom part of screen, the button with an arrow point away from a disk. It will now send one package every 30minutes to PyBytes, this can be changed at code row 32, change sleepTime `time.sleep(sleepTime)` to how many seconds delay you want to wait until it sends a package.
11. While the code is running you can see the Temp and humidity readings. And now because we uploaded it to the device it will run it even when connecting the device to a power source. You can press `ctrl+c` multiple times to break out of the loop, if it doesn't then disconnect the USB from the computer, hold the "Safe Boot" button on the Expansion3 and reconnect the USB to computer while holding it down. LoFy4 will start with blinking slowly, but when it starts to blink faster, release the button and it will skip the `boot.py` and `main.py` files. You will be able to program and change the code in Atom now.
12. Final part is to go to PyBytes, log in, and go to `Devices->YOUR DEVICE-> Add Widget`. Choose "Temperature" give it a name and set "Pin" to 1, and unit to C. Next press "Add Widget" again but this time add "Humidity", give it a name and set "Pin" to 2. Now when you run the code or start the Pycom, dashboard should get the data from the LoPy4. Congrats! That is the final product, now you can disconnect it and connect the USB to a powerbank to make it mobile.

## Building it

1. Take the LoPy4 and push it into the slots on the Pycom MAKR Expansion 3 board. Remember the LED and button of the LoPy4 should be at the same side as the USB port on the Expansion 3. There are three connection that we will use on the LoPy4: Vin/VCC, GND/Ground and P23 pin for signal. Guide for connecting: Vin/VCC connect to [a,2](on the breadboard check image below) , GND/Ground to [a,1] and P23 to [a,3].
2. There are three pins on the DTH11 that we will connect to the breadboard. Guide: DTH11 pin "S" to [e,3], because middle pin will then fall into [e,2], which is +/5V in, and -/Ground will go into [e,1].

If the above guide was confusing follow the short hand and copare with the image below.

Shorthand:
Pycom:
1. Vin/Vcc red cable -> [a,2] 
2. GND/Ground black cable -> [a,1]
3. P23/Signal green cable -> [a,3] 

DTH11:
1. Pin S into slot -> [e,3]
2. Pin + into slot -> [e,2]
3. Pin - into slot -> [e,1]

![Circuit diagram](https://i.imgur.com/Og996ga.png)

When you done connecting it press this link to go to tutorial point 6. -> [Link to next part of tutorial](#Tutorial-2)

## Platform

As you read in the tutorial I chose PyBytes, this is because it's easy to setup and get running. It's cloud based, and it can update the device through their website(discovered this a little late). Their portal gives many features: adding projects, widgets, PYMAKR, notifications, dashboard and machine learning. 

It's a good start and it's free. However, it has too many bells and whistles that I actually don't need. I'd like to try Node-Red in the future because it's a self-hosting solution and I would be able to create what I need. Also, I would be able to run more temperature and humidity sensors and connect different IoT devices together.

## The Code
Python code of the `main.py` file is modified version of the lnu applied-IoT example file [Link](https://github.com/iot-lnu/applied-iot/blob/master/sensor-examples/DHT11%20%26%20DHT22%20-%20Humidity%20%26%20Temperature%20Sensor/main.py)
```python=
#Helper function - How many minutes it should sleep.
def minutes(howMany):
    return 60 * howMany
sleepTime = minutes(30)

#Turns the led on LoPy4 and Expansion3 off.
led = Pin('P9', mode = Pin.OUT)
led.value(1)
pycom.heartbeat(False)

# Pin for the DTH11 funny they call it DHT here.
th = DHT(Pin('P23', mode=Pin.OPEN_DRAIN))
time.sleep(2)

# Main loop for the program.
while True:
    result = th.read()
    while not result.is_valid():
        time.sleep(.5)
        result = th.read()
    print('Temp:', result.temperature)
    print('RH:', result.humidity)
    pybytes.send_signal(1,result.temperature)
    pybytes.send_signal(2,result.humidity)

    time.sleep(sleepTime)
```


## Transmitting Data and Connectivity

The LoPy4 uses the wireless protocol WiFi to connect to the internet. I chose it because I only need the device at home and I have great coverage. 

The device sends 16 Bytes each half an hour, so each hour it transmitts 32 Bytes of information to PyBytes. 8 Bytes for temperature and 8 Bytes for humidity. 

The transport protocol that speaks to PyBytes is MQTT. It is the code `pybytes.send_signal(1,result.temperature)` that sends the packages.

## Presenting Data
![PyBytes Dashboard](https://i.imgur.com/RfjyfRE.jpg)

Frequency of saves is every half an hour. The free plan for Pycom is 30 days data storage. So I guess, that after 30 days they either wipe the storage, or they roll through each data and delete the ones that have passed that 30 day mark. 

## Finalizing the Design
![](https://i.imgur.com/GEUkBRE.jpg)


I'm happy with the result. The hardest parts was receiving hardware and flashing the firmware. I think that using a Pycom device relieved many of the pain in terms of platform setup. If I would have known about being able to flash the LoPy4 through their webportal I would have done that route. In  a future iteration I will probably get a more accurate sensor, than the DHT11. Also I would connect another  sensor outside and make the device even more automated by comparing outside and inside values. However, I'm glad I learned about IoT, didn't know it could be so much fun! 

Bonus picture: 

![](https://i.imgur.com/ybO4CmS.jpg)
