---
# System prepended metadata

title: cheese storage temperature and humidity measurment

---

# cheese storage temperature and humidity measurment
Created by Wietze Schelhaas (ws222cu)



# Introduction
I have always considered myself to be very fortunate, this is partly due to the fact that at a young age, my parents decided to create a company whose sole purpose was to create and sell, arguably two of the best foods ever, namely cheese and ice cream. From that day we would always have what it felt like an infinite amount of the two at home. For this, I like to give back and created this IoT project. Storing ice cream is fairly simple. Cheese on the other hand is a bit trickier, the reason is that if you don't have the right temperature or humidity, mold very easily appears. This IoT project revolves around creating a device that constantly measures and reports the temperature and humidity of a cheese storage room.This data is sent to a nearby raspberry pi where it is stored and could later be used for analysis. if a received measurement is outside certain predefined boundaries, a notification in the form of a Telegram message will be eminently sent to the user.This project would take anywhere between 2 hours and one entire day depending on familier the reader is with IoT and micropython

# Objective
There are two main objectives to this project:
1. Whenever there the measurements are outside normal boundaries, which should be around 13 degrees Celsius and 75% humidity someone would be immediately notified. If this is the case, it might be for example due to a faulty humidifier. 
2. When livsmedelverket comes knocking, it is nice to show a graph of all historic temperatures, for example, to see how the temperature has risen during a power outage.

# Material 
The main functionality lies in the Lopy4 microcontroller, this device performs the measurements and transmitting of the data. A lopy4 basic bundle is bought which contains the following:
* **Pycom Expansion board 3.1** 
* **antenna** 
* **Breadboard** 
* **Jumper wires**
* **Micro usb cable**


A Raspberry Pi 4 model B as seen in Fig. 1 is used to receive the transmitted data and store it on disk. **The use of Raspberry Pi is optional,** any other microprocessor even a normal desktop could be used but since the Raspberry Pi is small and energy efficient it is recommended. The DHT11 sensor is used for measuring temperature and humidity.

![Raspberry Pi model B](https://i.imgur.com/jV94O1K.jpg) Fig. 1 Raspberry Pi model B




| Device | Price | 
| -------- | -------- |  
| [Raspberry Pi 4 ](https://www.netonnet.se/art/smarta-hem/system-varumarke/raspberry-pi/raspberry-pi-4-model-b-4gb/1009084.14591/?gclid=CjwKCAjwr56IBhAvEiwA1fuqGt8dFwDInstoxUFD1LmoaN9xJ-E7X54Wskof9upjNYn8KhBmXTOQBRoCQXsQAvD_BwE)    | 690 kr     | 
| [Lopy 4 ](https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-basic-bundle/)    | 849 kr     |
| [DHT11 sensor ](https://www.electrokit.com/produkt/digital-temperatur-och-fuktsensor-dht11/)    | 50 kr     |

this all adds up to a total cost of 1589 kr

# Computer setup
The ide used for this project is Visual Studio Code, this can easily be installed [here](https://code.visualstudio.com/). NodeJS is also required, this can easily be downloaded and installed from the NodeJS website here [here](https://nodejs.org/en/).


### telegram-bot
In order to send telegram messages from python we need the python-telegram-bot library, this is easily installed using pip:
```
pip3 install python-telegram-bot
```

### pymaker
In order to run python code on the Lopy4 board, we need to install a plugin called Pymakr. In Visual Studio Code this is done by simply installing through the extensions tab:
![](https://i.imgur.com/Z1MFcga.png)

Search for pymakr and press the install button
![](https://i.imgur.com/oscYnE1.png)

After giving it a minute to initialize everything the following options should appear in the lower part of Visual Studio code 
![](https://i.imgur.com/hb09V6y.png)
 
Plugin your Lopy4 device and windows should automatcialy install all necessary drivers. If everything is installed properly, pymakr should automatcially connect to the plugged in device! We can now upload code using the upload button as seen above.   


## TelegramBot
To use TelegramBot follow this tutorial, make sure to write down the bot token and chat id since they will be used in the code later.
https://medium.com/@mycodingblog/get-telegram-notification-when-python-script-finishes-running-a54f12822cdc

# Putting everything together
The antenna has to be connected to the lopy4 board. Since we use wifi for this project, the antenna has to be connected to the wifi  U.FL connector as illustrated here:
![](https://i.imgur.com/gh9jwah.png)

The lopy4 microcontroller can now be mounted on top of the expension board like so:
![](https://i.imgur.com/IzLF3In.png)

Now its time to connect the sensor to the extension board. On the DHT11 sensor we have three pins. We will use jumper cables and a breadboard to connect the sensor to the extension board. Both the extension board and the sensor will have its pins and connections labled, below follows a list of what sensor pin goes to what connection on the extension board:
* The pin that is labled S on the sensor is the signal pin, this will go to connection p23 on the extension board
* The pin that is labled with a minus sign -, will go to the gnd connection on the extension board
* Both the S and - pin sit on each side, the only one that is left is the middle pin and this one goes to the 3v3 connection on the extension board

The dht11 sensor has a built in resistor so this is not needed! Using a breadboard and jumper cables to make these connections would look something like this:

![](https://i.imgur.com/IXbFYBI.png)


# Platform
The initial idea was to use pybytes but this had some disadvantages. Creating the notification system would have been a bit tedious since there is no way to run code in the pybytes cloud. Also, storing the data on a server that you own yourself makes it more flexible for statistical analysis. Another good reason a second device is used is because the pycom devices have limited storage space and can therefor not store all the measurements. 


# the code
boot.py is the first file that gets executed upon booting. This file connects to the wifi network. Change the SSID and password to the router you want to connect to
```python
from network import WLAN
import machine
wlan = WLAN(mode=WLAN.STA)

nets = wlan.scan()
for net in nets:
    if net.ssid == "SSID":
        print('Network found!')
        wlan.connect(net.ssid, auth=(net.sec, "Password"), timeout=5000)
        while not wlan.isconnected():
            machine.idle() # save power while waiting
        print('WLAN connection succeeded!')
        print(wlan.ifconfig())
        break
```

main.py measures the temperature and humidity and periodically transmits this data to the raspberry pi. Here, change the ip address to the raspberry pi or other computer you want to act as server.
```python
import time
from machine import Pin
from dht import DHT # https://github.com/JurassicPork/DHT_PyCom

import socket

# Type 0 = dht11
# Type 1 = dht22

th = DHT(Pin('P23', mode=Pin.OPEN_DRAIN), 0)
time.sleep(2)



host = ''  #IP address of the raspberry pi 
port = 50007                   # The same port as used by the server


while(True)
    result = th.read()
    while not result.is_valid():
        time.sleep(.5)
        result = th.read()

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('Temp:', result.temperature)
    print('RH:', result.humidity)
    s.connect((host, port))
    s.send(str(result.temperature) + " " + str(result.humidity))
    s.close()
    #pybytes.send_signal(2,"test")
    #pybytes.send_signal(2,result.humidity)

    time.sleep(10)

```


server.py is the server code. The servers job is to store the received measurements and to notify the user if either the temperature or the humidity goes above a certain threshold. Here, change the bottoken to the created telegram bot and the chat id to the id of the group chat created. 
```python=
import socket
from datetime import datetime
import telegram

tempThreshold = 14
humidThreshold = 75

telegramToken = "" #Bottoken here
telegramChatId = "" #groupchat id here

bot = telegram.Bot(token=telegramToken)

HOST = '' #own ip adress                
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
print("listening on ", HOST)
while 1:
  s.listen(5)
  conn, addr = s.accept()
  print('Connected by', addr)
  data = conn.recv(1024)
  #sometimes empty bytes are recevied, this keeps it from crashing
  if not data == b'':
    file_object = open('data.txt', 'a')
    
    now = datetime.now()
    tmp = data.split()
    print(tmp)
    current_time = now.strftime("%H:%M:%S")

    temperature = float(tmp[0])
    humid = float(tmp[1])

    file_object.write(current_time + " " + str(temperature) + " " + str(humid) + "\n")
    file_object.close()

    if temperature > tempThreshold:
      bot.sendMessage(chat_id=telegramChatId,text="temperature of " + str(temperature) + " is too high!")
    if humid > humidThreshold:
      bot.sendMessage(chat_id=telegramChatId,text="humidity of " + str(humid) + " is too high!")

  conn.close()
```


# Transmitting the data / connectivity
Unfortunatly since the farm this project was created at is located in the middle of nowhere amongst the forests of värmland so there was no LoRaWAN gateway close, otherwise it would have been interesting to experiment with LoRa. Instead the data is sent over WIFI using simple TCP sockets. The data is sent using 10 seconds intervals, in hindsight this might be a bit too often, tempatreus in a big cheese storage room does not rise that quickly. 




# Presenting the data
Using the data stored by the raspberry pi, we can plot a simple timeseries. Below is a graph of the measured temperature and humidity over one hour. The measurements are saved along with the current time everytime the raspberry pi receives new data. The reason that the temperature starts high and the humidity starts low is because the DTH11 sensor just came from a warmer less humid room, and it took some minutes to adapt to the new environment. The data is saved everytine
![](https://i.imgur.com/QWxhxFX.png)

Whenever the temperature or humidity goes above the threshold value, a message is sent to the users phone through telegram and this looks like this: 
![](https://i.imgur.com/07tXAdz.jpg)


# Finalizing the design
Im happy with the final design, but there are some things i would have liked to change. A nice 3d printed casing would have been nice, also no battery is used which would have simplyfied things cablewise
![](https://i.imgur.com/m9Wuq6O.jpg)