---
# System prepended metadata

title: Climate Reader

---

# Climate Reader

Author - Lucas Jutvik || lj223ei

**Summary**
This project was done for the course "Applied Internet Of Things" at Linné university. It reads temperature data and sends it to a mqtt server where it may be fetched for other uses. By following this guide it may take you between 4-6 hours to recreate if you are new to this process. If you are experienced at working with the pycom devices it may be faster.

**Objective**
This project was choosen for the purpose of reading temperature data in a green house and send this data to another media for easier access and therefor helping out with the greenkeeping.

It will during this track temperatures to let the user know when to open or close the windows in the greenhouse.

This project could work to give you insishts in regards to how a simple IoT device works and how easy it could be to start simplifying tasks in your everyday life.

**Material**

The materials needed for this project are the following:


| Product | Usage | 
| -------- | -------- | 
| Lopy4     | Code execution and data transmission    |
|Expansionboard 3.1|Connecting material|
|Breadboard|Easier sensor connection|
|  5x Connection wire   | Connect electrical       |
| Micro usb - Usb cable| Upload code and charge the Lopy4|
|Temperature sensor MPC9700TO-92|Sense the temperature|

These products were mostly choosen because they came in a package deal from www.electrokit.se with some other parts that were not needed for this project at the price of 995 sek.

**Setup**
The first recommendation would be to setup your IDE. During this project Visual Studio Code with the plugin pymkr was used. it may be downloaded from https://code.visualstudio.com/ and then the plug itself is downloaded and installed within the IDE. Then install Node.js from www.nodejs.org.

The next step for you would be to flash the lopy, firstly you should create an acount on https://pybytes.pycom.io/ and register an device by following their instructions. Then you should download the "Pycom Firmware Update" software, connect your lopy4 (added onto the expansion board) to your computer with the usb cable and follow the instructions of the software.

You may now start coding your device by accessing it in the visual studio code IDE and creating a new project within that IDE. When code has been written there you may press the upload button to upload it onto your device (you could also upload code via the pybytes website however at this time it is not recommended). 

**Circut diagram**
In the figure below it shows how the temperature sensor is connected to the breadboard and how that is then connected to the expansionboard (It should be noted in this case the temperature sernsor is located in the picture so that the far most right of its pins is the ground).

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

**Platform**

The platform works as to intercept the data sent by the IoT device and could then be used to transmit this to somewhere else or plot this data in some way. In this case the platform used is a MQTT explorer client which can be found at http://mqtt-explorer.com/

**The code**
```
import json
import time
import pycom
import _thread
from mqtt import MQTTClient
import ubinascii
import hashlib
import machine

pycom.heartbeat(False)

def fetch_temp():
    adc = machine.ADC() # Create a machine object
    apin_temp = adc.channel(pin='P17') #Get the pin info of pin 17
    temp = (apin_temp()*1.1/4096-0.5)*100 # Make the info into actual temperature (In celcius)
    return temp 

def sub_cb(topic, msg):
    print((topic, msg))

def interval_send(t_):
    while True: # Keeps running so the process is repeated
        temperature = fetch_temp() # Fetches the temperature
        send_value(temperature) # Acesses the send value function
        time.sleep(t_)

def send_value(temp):
    try:
        tempstr = "%5.2f" % temp # Creates a string with the temperature and restricts the ammount of decimals
        c.publish(topic_pub,'{"home_climate_sensor": {"temp":' + tempstr
                          '}}') # Publishes the sensor data to the mqtt server as a json object
        print('Data sent correctly') # Shows that the code worked as intended

    except:
        print('Could not send data') # Shows as a print if the data could not be sent

username = 'username' # Insert your username to the mqtt server here
password = 'password' # Insert your password to the mqtt server here
interval = 300 # Defines how often the data should be sent (in seconds)
topic_pub = 'devices/home_climate_sensor/' # The topic where you publish the data
topic_sub = 'devices/home_climate_sensor/control' # The sub where the data is published
broker_url = 'sjolab.lnu.se' # The host name of the mqtt server
client_name = ubinascii.hexlify(hashlib.md5(machine.unique_id()).digest()) # create a md5 hash of the pycom WLAN mac

c = MQTTClient(client_name,broker_url,user=username,password=password)  # Creates a mqtt client with the correct authorisation details
c.set_callback(sub_cb)
c.connect()
c.subscribe(topic_sub)

_thread.start_new_thread(interval_send,[interval]) # Starts an execution of the project with the interval
```

The first part where the import statements are located only exists to import the libraries needed for the code to work. After this the heartbeat of the pycom device (the blinking light) is turned of. This step is optional and if you'd like to have a light blinking to show that the device is on that step could be skipped.

The upcoming function "fetch_temp" is the part that actually checks the temperature sensors data, processes this into the actual temperature and then returns this value as an integer.

The function "sub_cb" works as to print the topic and message when a callback is recieved. After this function the "interval_send" function works to call on the fetch_temp and then "send_value" function where the temperature is sent to the MQTT server once every interval. Even though it is simplified so that the runtime is not included in the interval calculation it seems to work quite well since the runtime in this case is quite low. It is worth noting that the string sent to the MQTT server is formated in a json format, quite identical to how a dictionary is presented in the python language.

In the end we can se the program initiated where the username and password for the MQTT server is defined, the interval of which the data is sent is specified. This is then followed by the information that characterizes the MQTT client that is created. 

And lastly in the code the program is ofcourse initiated.



**Connectivity**
The data is sent every five minutes. The intervall could easily be changed however to fit specific needs by changing the interval variable.

The device uses its WiFi to transmitt data to the transport protocol MQTT. This means that the device must be close to a wifi source to operate correctly and if there is LoRa where you are located it could be a good idea to use this wireless protocol instead.

**Data**
![](https://i.imgur.com/5Jak34I.png)
The figure above shows how the data is represented on the MQTT explorer client. In this case it shows a visual representation of how the temperature has changed during the latest datapoints and one could also get the latest datapoint to see what the temperature is currently.

The data is saved every time a new datapoint is sent so in the current version of the code it would be every 300 seconds.

**Conclusion**
In the end I would have liked to progressed a bit further with the project. It would have been nice to have added a humidity sensor, battery pack and also gotten a shell for the device 3d printed so it could actually be placed in the greenhouse. I would also have liked to have had the time to implement triggers to send an alert to my phone when temperature passes certain limits. 

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