# Temperature, Humidity and Illuminance Sensing for a Baby Crib using Pysense & FiPy
Author: Syed Zamir Abid Kazmi (sk224et)
[TOC]
This tutorial deals with designing a temperature, humidity and illuminance monitoring, visualization and alert system for a baby crib using [Pycom's](https://pycom.io/) FiPy and Pysense devices. For the purpose of measurement, the built-in sensors of a Pysense expansion board namely, SI7006A20 and LTR329ALS01 ,have been utilized, whereas, for the purpose of visualization and alerting, the data is transmitted over the Wifi using the MQTT protocol to a low-code IOT platform [datacake](https://datacake.co/).
The project was initially aimed at measuring air quality (TVOCs) and noise levels in the crib as well, nevertheless, due to delays in the delivery of the needed sensors, it, unfortunately,had to be limited to temperature, humidity and illuminance sensing only. Project does not lie on the farthest end of sophistication spectrum, as it uses the built in sensors of Pysense. This has an unwanted side-effect, i.e. susceptibility to rather low accuracy of data readings due to two reasons:
1. Expansion board gets heated up due to continuous use.
2. Development board also contributes to the heat when it runs.
The above issue of heat affects the ability of temperature & humidity sensor to take perfect readings. The drawback could be eradicate by the use of a fan, however.
The estimated time to make this project in my opinion is about 2 to 4 hours depending on your knowledge in IOT.
## Objective
The reason for choosing this project is that I became a father, for the first time, quite recently.Since learning to take care of the baby properly, which ensures their good health, can be a daunting task, especially for the first-time parents. But I took it as a challenge and tried to study it in a bit detail.
One of the factors that may impact their health a big time is how well they sleep. Quality of sleep may be impacted by multitude of factors, both inside the body and outside. Nevertheless, the affect of some fundamental outside factors is so imperative that it cannot be ignored.Some of those factors are the temperature, humidity and illuminance in and around a baby's crib.
In case of temperature, it is a wellknown fact that adults and infants alike need a certain temperature for an optimal sleep. According to the [sleep foundation](https://www.sleepfoundation.org/baby-sleep/best-room-temperature-for-sleeping-baby) an optimal temperature must be between 20 to 22 degree Celsius.
Light on the other hand, is another external factor that affects the sleep quality of a newborn. Illuminance, which can be described as lumens per square meter of area, is a parameter which measures the light intensity. For the sleeping process no or a lower light intensity is needed for the production of sleeping hormone, [melatonin](https://en.wikipedia.org/wiki/Melatonin#:~:text=Melatonin%20is%20a%20natural%20product%20found%20in%20plants,been%20associated%20with%20control%20of%20the%20sleep%E2%80%93wake%20cycle.), but complete darkness is not good for their mood and growth either. Therefore, a light between 50 to 100 lux is something that suits both. If we can manage to measure the intensity of light, corrective actions can easily be taken. For example, adjustments by curtains and/or using different combinations of low intensity lamps.
Lastly, humidity, which in simple terms, can be defined as the percentage of water vapours in the air, may not only affect the sleep cycle but can also cause higher concentartion of alergens according to the [sleep foundation](https://www.sleepfoundation.org/bedroom-environment/humidity-and-sleep). A good humidity for an infants nursery lies between 30 to 50 percent. To lower humidity a [dehumidifier](https://en.wikipedia.org/wiki/Dehumidifier) can be used.
In a nutshell, a measurement & visulaization of the intended parameters and observing the quality of sleep, at the same time, can not only be interesting from a research perspective, but also help educate parents, which can result in an improved health of their child.
#### Development Roadmap
The roadmap followed to realize this tutorial can be broken down in to following steps.
* Hardware Used
* Computer Setup
* Atom IDE
* Node.js
* Pymakr
* Pycom firmware update
* Updating the firmware of the Pysense & FiPy
* Putting Everything Together
* Sensors Outline
* Hardware Assembly
* Choosing Visualization Platform
* Datacake Setup
* Development of Code
* The Complete Code Repository
* Transmitting the Data
* Presenting the Data
* Finalizing the Design
Let us begin!
## Hardware Used
| Article | Price per unit | Purpose | Images |
|:--------------------------------------------:|:---------------:|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|:------------------------------------:|
| [Pysense 2.0x](https://pycom.io/?s=pysense) | €29.65 | A built-in sensor mount from Fipy that also serves as an expansion board to program the microcontroller. |  |
| | | | |
| [Pycom FiPy](https://pycom.io/product/fipy/) | €59.40 – €65.40 | A micropython based microcontroller. It supports 5 different modes of connectivity WiFi, Bluetooth, LoRa, SigFox, and LTE. |  |
| [Breadboard](https://www.electrokit.com/produkt/kopplingsdack-840-anslutningar/) | € 5.50 | For the sake of connecting FiPy to avoid adding to the heating of sensors on Pysense ||
| Micro USB Cable | € 3.00 | A USB cable to powers the expansion board, which in turn powers the board. It also serves the purpose of communication between the IDE and the board during the programming phase. |  |
All the above mentioned hardware has been purchased from [Elektrokit Sweden](https://www.electrokit.com/). The setup can be powered by a battery or any spare phone adapter at home, I used an old Samsung adapter. By using the later, we do not have to worry about any power comsumption issues.
## Computer Setup
The are different softwares that have been used to realize this tutorial.First of all, the computer operating system used is Microsoft Windows 10. Please take note that If your operating system does not have python installed, it can be easily downloaded from [here](https://www.python.org/downloads/).
As far as the integrated development environment is concerened, out of different available options such as, Visual Studio, Thonny, Atom and many others, I have chosen to use Atom. One of the reason for that is it is userfriendly, I used it in workshops, and with just one simple plugin installation, it could communicate with my Pycom device.
To be able to use Atom, the software tools that needed to be installed before any development is possible on the Pycom boards, are node.js and pymakr plugin. The list of important softwares used is as follows:
| Software | Purpose |
|:----------------------:| ------- |
| [Atom IDE](https://atom.io/) | A text editor that was used for programming the device |
| [Node js](https://nodejs.org/en/download/) | A javascript runtime environment used for software development |
| [Pymakr Plugin](https://atom.io/packages/pymakr) | An application to communicate to the Pycom devices in commandline REPL |
| [Pycom Firmware Updater](https://docs.pycom.io/updatefirmware/device/) | Software tool used for updating the firmware of the board |
### Installing the Software
#### Atom IDE
1.Click the [link](https://atom.io) and select the download option.
2.Install the package with few very easy clicks.
#### Node.js
1. Node js is required for pymakr plugin. Open the [link](https://nodejs.org/en/) and download the current type.
2. Install the package with a few clicks.
#### Pymakr Plugin
Pymakr plugin is required for IDE to communicate with the Pycom development boards, which in my case is FiPy. Please follow the following steps to install it.
1. Open Atom.
2. Go the settings in lower right corner.
3. Click install icon in the bottom of the list.
4. In install packages, search for pymakr and click install.
#### Pycom Firmware Update Tool
To download the tool to update the firmware of the development board we need a software that can be [downloaded](https://docs.pycom.io/updatefirmware/device/) from pycom website.
1. Open the link embedded in the line above.
2. Download the software based on your operating system. In my case, it was Windows.
3. It can be installed in one step by pressing install.
#### Updating the Firmware of the Pysense & FiPy
The expansion board ran without a firmware update on Windows 10, however, I later encountered a problem while working with the built-in sensors.Therefore, I recommend doing it anyways. I followed the tutorial from the [core electronics website](https://) to do it. I found the tutorial to be very easy and self-elobrative, therefore I won't go in to details of writing the steps myself.
In order to update the firmware of the development board, I followed the course tutorial. It requires only a few steps. The link of the tutorial can be found [here](https://hackmd.io/@lnu-iot/SJ91R_jSO).
After the flashing of the device, they are ready for writing code and it can simply be verified by mounting the development board on pysense and connect it to computer using microusb cable. In atom REPL write the following command:
```Python=1
print(2+2)
```
The board should perform the arthimetic operation and give 4 as an asnwer. That shows that everything is up and running.
## Putting Everything Together
Before we delve in to the hardware assembly, I deem it necessary to know some basics about the sensors that are embedded on Pycom expansion board that we are utilizing in this tutorial.
#### Sensors Outline
1. SI7006A20
It is an accurate, low power digital temperature and humidity sensor with applications in indoor weather monitoring, thermostats, automatic climatic control and defogging. The temperature readings have a tolerance of ±1 °C. It also measures the relative humidity with a tolerance values of ±5 percent. The [specification sheet](https://www.silabs.com/documents/public/data-sheets/Si7006-A20.pdf) can be found here.The operating voltage of this sensor is 1.9 to 3.6 volts
1. LTR329ALS01
It is a low power digital light sensor with I~2~C interface with application in consumer electronics such as mobile phones and computing devices. The [datasheet](https://optoelectronics.liteon.com/upload/download/DS86-2014-0006/LTR-329ALS-01_DS_V1.pdf) can be found here.The operating voltage for this sensor is 3.8 volts.
#### Hardware Assembly
Please note that the development board can be mounted on top of Pysense, it is very easy, but, to eliminate the heating effect caused by the development board(FiPy) at least, I used a breadboard for mounting the FiPy. Please follow the following steps for the correct hardware assembly.
1. Mount the development board on top of a breadboard in a way that the LED side faces outwards.
 Now we need to power the pysense using the micro USB and then power the FiPy through it.
2. Connect the 5v GND pins from Pysense to those of FiPy.
3. Take the 3V pin on Pysense and plug it to the plus of breadboard power rail and from there apply in to Pysense 3V input pin, this powers the built-in sensors on expansion board.
4. Connect the P0 and P1, **UART_Rx** and **UART_Tx**, these pins enable the communication between the Pysense and Fipy during the code development, in other words, code from IDE, through Pysense, reaches to FiPy through these pins.
5. Connect the pins 8 and 9 of Pysnese to those of FiPy. This establishes a connection between the sensors o0f Pysense to the development board.
At this point the hardware configuration is ready to be connected to the computer port.. It looks like follows.

6. Open Atom IDE(Integrated Development Environment).
7. Plug the micro USB to your computer port, at this point, after the COM port is open, the LED of the development board should start flashing, indicating that the board is up and running and the program development can be started.
The above fabricated circuit can be visualized in a Fritzing circuit diagram as follows. This diagram is taken from one of the course [tutorials](https://hackmd.io/@lnu-iot/By-930cTu).

Sicne I have used the built in sensors, it is not possible for me to do the electrical calculations involved. At this point we can tend to writing the code for sensing, transmitting, and visualizing the data.
## Choosing The Visulaization Platform
I have used one of the low code IOT soultions, i.e. Datacake. The reason that I chose datacake over other solutions are many.
First, during the tutorials I had already used Pybytes for the purpose of visualization. I found it really basic and there was no further scope for me to learn. Second, I did not use the high end solutions like hosting my own server or using Amazon or google cloud due to lack of time and expertise. Thirdly, datacake is very simple yet entails details for learning about network protocols like MQTT.Forth, it is free, and has an alert system in place and some interesting things to be used for visulaization .
The downside of using datacake in free version is limited data points available, that is 500 per 24 hours. However, for the sake of my project I deem it to be enough. If not, I can increase the data collection from every 2 minutes to every 10 to 15 minutes, since my system is not a safety critical system.
#### Setting Up Datacake
1. Go to the datacake [website](https://datacake.co/) and signup.
2. After signing up, go the device, and click add device.

3. Select the API option.

4. Select new product and add a device name for your product.

5. In next step, add name and a custom serial number.
6. Choose a plan as per your needs, I chose a free plan, and hit add device.

7. Open the newly added device and go the configuration portion, scroll down to the add field area and choose add fields. Here I added, temperature, humidity and illuminance. It is important to save the identifiers which are to be used in topics for publishing the data.

8. After adding fields, go to the MQTT section right under the fields section and click configure.Here we have the broker and topic that data is to be published to, take note of them.

9. After that go the profile section and hit edit profile and choose API for the security token that is to be used in the code, take note of it.

10. Go to the dashboard section and to add widget. I have added temperature, humidity and illuminance. My dashboard looks like as follows:

Now our device is configured on Datacake. We will use MQTT protocol to transmit data over Wifi and visualize in Datacake.The details are comming in the following section.
## Development of Code
In the process of code development, we first attend to make our device connect to Datacake over Wifi. The connection to Wifi is eastablished in a file called boot.py, this is the first file that runs when the device is booted. After that the file main.py runs, which includes the MQTT client setup, sesning of the data from sensors, and publishing it to visualization platform.
But before everything, let us add all the configuration details, such as WiFi SSID and Passwords, Datacake Broker Address, Security Token, and its Username & Password in a separate file called config.py. It is done for the sake of clarity and simplicity of changing any configuration if the need be.
The config.py code snippet looks as follows:
```Python=1
# WiFi credentials
WIFI_SSID = 'Your ID'
WIFI_PASS = 'Your Password'
# Datacake credentials
SERIAL_NUMBER = '1214HamzaKazmi'
MQTT_BROKER = 'mqtt.datacake.co'
TOKEN = 'Your own device security token'
PORT = 1883
TOPIC_temp = 'dtck-pub/microcontroller/0366311e-53a2-41a7-b702-4c548ba039f0/TEMPERATURE'
TOPIC_humid = 'dtck-pub/microcontroller/0366311e-53a2-41a7-b702-4c548ba039f0/HUMIDITY'
TOPIC_illum = 'dtck-pub/microcontroller/0366311e-53a2-41a7-b702-4c548ba039f0/ILLUMINANCE'
```
#### The Complete Code Repository
The complete code for my tutorial can be found in my github [repository](https://github.com/zamirkazmi89/Temperature--Humidity-and-Illuminance-Sensing-for-a-Baby-Crib-using-Pysense---FiPy). I have used some code inspiration from different tutorials from the course and written the main.py myself.
## Transmitting the Data
For transmission a connection to Wifi is made possible by the following code in the file boot.py.
To transmit the sensor data I have used Wifi. The code snippet from boot.py is as follows: The code used below is taken from one of the tutorials from connectivity part of workshops.
```Python=1
import network
import time
import config
print("Connecting to Wifi...")
wlan = network.WLAN(mode=network.WLAN.STA)
wlan.connect(config.WIFI_SSID, auth=(network.WLAN.WPA2, config.WIFI_PASS))
while not wlan.isconnected():
time.sleep_ms(50)
print(wlan.ifconfig()
```
Once the device is connected to the Wifi, the next thing that happens is connecting to the MQTT broker. This is done by the file main.py.The MQTT portion of code snippets of client setup looks as follows:
```Python=23
client = MQTTClient(config.SERIAL_NUMBER,
config.MQTT_BROKER,
user=config.TOKEN,
password=config.TOKEN,
port=config.PORT)
client.set_callback(sub_cb)
client.connect()
print('connected to Datacake MQTT broker')
```
Here the sensing of the data takes palce. As mentioned above in this tutorial only two sensors from the Pysense have been used, namely SI7006A20 and LTR329ALS01 for temperature & humidity and light sensing respectively.The code snippet from main.py for sensing is as follows:
```Python=42
while True:
#Continuous sensing of temperature, humidity and illumination
print("Measuring the Crib Temperature, Humidity and Illuminance")
si = SI7006A20(py)
lt = LTR329ALS01(py)
temp = si.temperature()
humid = si.humidity()
print("Temperature: " + str(temp)+ " deg C")
print("Humidity: " + str(humid))
Lux = lt.lux()
print("Illuminance: " + str(Lux))
```
After the sensing has been completed, the stage to transmit the data comes. The device tries to send the data afer every two minutes, which can be adjusted as per the need. Have a look at the code snippet for it:
```Python=54
# Publishing to MQTT broker on given topics
client.publish(topic=topic_temp, msg=str(temp))
client.publish(topic=topic_humid, msg=str(humid))
client.publish(topic=topic_illum, msg=str(Lux))
client.check_msg()
print("Data Sent to Data cake, sleeping for 2 minutes...")
time.sleep(120) # Wait 2 minutes (120 seconds)
```
## Presenting the Data
The dashboard of my actual device(not the one added above) and atom shell after data is sensed, published and visualized look as below:


## Finalizing the Design
Final visualized data can be seen under the section "Presenting the Data" and final design of the project under the section "Hardware Assembly".
As far as the meeting of objectives is concerned, I think it fulfills the goals. One problem however, could be slight inaccuracy of readings from the sensors once the board heats up, this, as I mentioned above, could easily be overcome using a fan that can keep the board temprature regulated. It is also viable since it is plugged in to the wall socket, so we do not need to worry about power optimization concerns.A 3D printed casing could be an icing on top of the cake.
## References
1. https://www.sleepfoundation.org/baby-sleep/best-room-temperature-for-sleeping-baby
2. https://core-electronics.com.au/guides/pycom-pysense-pytrack-firmware-update/
3. https://www.wikipedia.org/
4. https://pycom.io/