# Tutorial on how to show the readings of pysense 2.0 internal sensors. Temperature, Humidity and Pressure.
### **Pysense 2.0 with fipy and pybytes**
> Student name: Mikael Torndal
> Student username: mt222uy
> Summer 2022
This tutorial is for assisting the beginners through their first steps in the world of IoT. We will together learn the basics on how to get up running with a IoT-device to read and display data of its sensors.
The estimated time to finish this really depends on your technical experience aswell as how fast you can absorb information. If you are a total beginner I would say something between 1-2 days.
## **Objective**
This tutorial is for the total beginner and since "1DT305 - Introduction to Applied IoT" is an introduction course to IoT we will simply learn what we need to do to get started with reading data of a simple device with inbuilt sensors, in this case the Pysense 2.0 unit mounted with Fipy for wifi and then display the data with Pybytes. This will hopefully spark an interest and with that you can dig in deeper to the world of IoT.
## **Prerequisites**
Before continuing
Get familiar with pycom
https://docs.pycom.io/ - Here you can find anything you need.
https://docs.pycom.io/gettingstarted/ - To get going.
https://docs.pycom.io/tutorials/basic/ - Get familiar with the code.
## **Material**
The material needed are products from Pycom
https://docs.pycom.io/products/
We will use a Development board together with a expansion board:
* Pysense 2.0 - Expansion board
* FiPy - Development board
Information about the two:
Pysense 2.0 is sensor header that allows you to sense the enviroment using 5 different senors including:
* Accelerometer (LIS2HH12)
* Light Sensor (LTR329ALS01)
* Pressure Sensor (MPL3115A2)
* Temperature / Humidity Sensor (SI7006A20)

The FiPy holds five networks in one small board featuring WiFi, Bluetooth, LoRa, Sigfox and dual LTE-M (CAT-M1 and NB-IoT), the FiPy gives access to global LPWAN networks.

The “1DT305 - Introduction to Applied IoT” course helpfully provides links to bundles with what you might need. They work together with electrokit to offer these. Personally I went for the fipy and sensors bundle, its a bit more expensive but then you also get a breadboard, jumper wires and more to get you further down the road when you decide to. However to get through this tutorial the basic bundle is enough.
FiPy and Sensors bundle: 142€
https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-fipy-and-sensors-bundle/
The basic bundle: 128€
https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-fipy-basic-bundle/
## **Computer setup**
I Was using a mac for this project but any computer with USB connectors and wifi would do.
## **Software / Tools**
Atom - the IDE to write your code (free)
pymakr - pycom plugin (free)
## **Chosen IDE**
For this project we will use Atom IDE but you can choose another IDE if you are more comfortable with that, as long as the pymakr tool is available to install and use.
## **Platform**
For this project we will use Pybytes that is a device management platform that empowers you by giving you full control over your Pycom devices. Its beginner friendly, free, scalable and has integration with external services (cloud services)
## **How the code gets uploaded to the pycom device**
The device is connected to the computer which allows for code to be uploaded via USB-connection to Pymakr in the Atom IDE.
## **The steps needed to take**
The program, plugin, library and visualizer we will install and use are:
* Atom IDE (To write, upload and run your code)
* Pymakr (Let you communicate with your pycom board)
* Pycom library for pysense 2 (ready to run code for using your sensors)
* Pybytes (With Pybytes you have control over your device’s data stream)
**Install Atom**
Download and install at:
https://atom.io/
**Install pymakr**
In atom navigate to Atom > Preferences > Install
Search for Pymakr and select the official Pycom Pymakr Plugin.
You should now see and click the Install button. This will download and install the Pymakr Plugin.
That’s it! You’ve installed the Pymakr Plugin for Atom.
**Download Pycom library**
Choose the pysense 2.zip and download
https://github.com/pycom/pycom-libraries/releases/
**Using Pybytes to Visualize Collected Data**
To be able to send your sensor data to a cloud and visualize the data we will use Pybytes. This is done in 2 steps, first, you’ll get the device connected to Pybytes over Wi-Fi and then you’ll get to send data and organize the Dashboard.
Follow these steps to set up the environment for your Pybytes connection:
Step 1: If you already have a Forum or Webshop account with PyCom, you can use the same credentials to log into Pybytes, Else, go to Pybytes ([here](https://pybytes.pycom.io/)) and create an account and login.
Step 2: After you logged in to the Pybytes follow the numbered steps on the screenshots below to register your device on the Pybytes website. (Before being able to send data we must register our device)
Click on Devices
from the left panel then on Via USB

Choose your development board from the choices (FiPy in our case)

Choose your expansion board from the choices (Pysense 2.0x in our case)

Choose WiFi and then enter your home WiFi credentials.

Click on next.

Write a Device name and description then click on next.

Click on finnish

Now you see your newly created device, click on it and follow the next step.

Now we need to Flash our development board with PyComFirmwareUpdate tool. It is because we have Pybyte dependencies for being able to connect to it. We start by creating a new Token on the Pybytes website and use that token while we flash our device. Follow numbered steps on the screenshots below: Choose Provisioning then DesktopApplication and Finally click on the button to generate a new token and Copy it.

## **Flashing / Updating firmware**
We first must be sure to upgrade any firmware on both the development board (fipy) and the expansion board (Pysense 2)
Use the docs for pycom and go to:
https://docs.pycom.io/updatefirmware/
You have the links there for both the device (fipy) and the expansion board (Pysense 2)
**Update expansionboard firmware**
https://docs.pycom.io/updatefirmware/expansionboard/
To update the firmware of your expansionboard plug the board in to your computer via USB and then pop up your terminal, we will use the terminal tool DFU-util to update.
We need to download the latest DFU firmware file.
Chose the link for pysense 2 DFU in the link provided earlier.
Now there is different choices regarding what OS you use. I used mac and will describe that procedure, there are information about the other options in the docs for updating firmware.
**Install homebrew for your mac terminal**
Copy and paste following to your terminal:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
> Homebrew is a free and open-source software package management system that simplifies the installation of software on Apple's operating system, macOS, as well as Linux.
When the installation of homebrew is done go ahead and paste in: brew install dfu-util
Now we will use the DFU-util to update the firmware:
1. Navigate the terminal to the folder where you downloaded the .dfu file to
1. Unplug the device
1. Remove the development module
1. Press and hold the S1/MCLR button on your device. Highlighted in red: 
2. Plug in the USB cable to the host computer and wait 1 second before releasing the button
3. After this you will have approximately 7 seconds to run the DFU-util tool
4. Make sure to navigate the terminal to where your .dfu file is located and paste in: sudo dfu-util -D pysense2_v16.dfu
If the update was successful, “Done!” should appear in the bottom of the command prompt. The output should look like the following:
> dfu-util 0.9
>
> Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
> Copyright 2010-2016 Tormod Volden and Stefan Schmidt
> This program is Free Software and has ABSOLUTELY NO WARRANTY
> Please report bugs to http://sourceforge.net/p/dfu-util/tickets/
>
> Match vendor ID from file: 04d8
> Match product ID from file: f014
> Opening DFU capable USB device...
> ID 04d8:f014
> Run-time device DFU version 0100
> Claiming USB DFU Runtime Interface...
> Determining device status: state = dfuIDLE, status = 0
> dfu-util: WARNING: Runtime device already in DFU state ?!?
> Claiming USB DFU Interface...
> Setting Alternate Setting #0 ...
> Determining device status: state = dfuIDLE, status = 0
> dfuIDLE, continuing
> DFU mode device DFU version 0100
> Device returned transfer size 64
> Copying data from PC to DFU device
> Download [=========================] 100% 16384 bytes
> Download done.
> state(2) = dfuIDLE, status(0) = No error condition is present
> Done!
**Updating Device Firmware**
https://docs.pycom.io/updatefirmware/device/
1. Disconnect your device from your computer
1. Insert the module (fipy) in to the expansion board with the reset button and RGB LED above the USB connector like shown below.
1. Reconnect the board via USB to your computer.
2. Install and run the Firmware Upgrade tool for mac: https://software.pycom.io/findupgrade?product=pycom-firmware-updater&type=all&platform=macos&redirect=true (for other OS check the docs)

There are several different firmware types and we will use Pybytes.
> Pybytes is the most commonly used latest firmware with built in Pybytes library. You can use this firmware to connect to Pybytes to be able to:
> * Visualise the sensor data according to your interests by using our customisable dashboard.
> * Check the status of your entire fleet.
> * Track of your assets with our geolocation feature.
> * Distribute firmware updates on a scalable approach.
Go on with the Firmware upgrade tool for mac:
1. Press continue
2. Continue again
3. Choose following: 
4. Paste your pybytes activation token (See the pybytes section you read earlier, paste your token from Provisioning in Pybytes under Desktop Application)
5. Choose following: 
After finishing the flash it takes a while and if you provide the correct home WiFi credentials you will see your device connection on PyBytesControlPanel.

After you’re done with upgrading, you can use the Pymakr Plugins to upload and run programs in your device.
## **Circuit diagram**
**Pinout**
The PyPort connector is for a 6 lead mini ribbon cable, part: Amphenol 20021511-00006T4LF. The external IO header power pins are labelled as follows
3V3AUX - The power provided by the development module
3V3AUX_LP - the power provided by the development module for the SD card (This can be switched off)
3V3 - The power provided by the Pysense 2, for the USB-Serial converter.
The Pysense 2 can be powered through the USB port, the battery connector and the VUSB_AUX header just below the PyPort. Connecting a 5V supply to the header will result in exactly the same behaviour as powering it through the USB connector.

**Block Diagram**

**Features**

**Battery Charger**
The board features a single cell Li-Ion/Li-Po charger with a JST PHR‑2 connector. When the board is being powered via the micro USB connector, it will charge the battery (if connected).
Make sure you check the polarity of the battery before plugging it in! Connect the positive side to the side marked with a +.
**Mechanical Dimensions**

## **Putting it all together**
 ("Setup")
**Connecting via Serial USB**
After installing the Pymakr Plugin, you need to take a few seconds to configure it for first time use. Please follow these steps:
1. Connect your Pycom device to your computer via USB. If you are using an Expansion Board 2.0, and have just finished a firmware upgrade, be sure to remove the wire between GND and G23 and reset your device by pressing the button. Note: you don’t need the wire for Expansion Board 3.0
2. Open Atom and ensure that the Pymakr Plugin has correctly installed.

3. Pymakr has auto-connection enabled by default. In case your device hasn’t connected right away, click on Connect device and then on your device.

4. Now it should show three arrows >>>, indicating that you are connected!

**First Test**
Now that you have connected your device and installed Pymakr, it is time to begin programming your device!
Running your first code
If you have any experience with python, you know that the >>> means we can start typing commands! Type the following commands in the REPL terminal:
> import pycom
> pycom.heartbeat(False)
> pycom.rgbled(0x330033)
This will turn the RGB LED on your device purple! Notice that the REPL does not give any feedback. Only when we make a mistake, or ask it to return something will it give us a response.
**Creating a project in Pymakr**
In this first project, we will make the on-board RGB LED flash different colors.
Firstly you will need to create a new, empty, directory on your computer. For this example we will create one called RGB-Blink.
Open the project folder you have created in your IDE.
Now, we will need to add some files. A standard MicroPython project will have a lib folder for additional libraries, and two python files: main.py and boot.py.
main.py: This script runs directly after boot.py and should contain the main code you wish to run on your device.
boot.py: This is the first script that runs on your module when it turns on. This is often used to connect a module to a network without cluttering up the main.py file. As a beginner you generally do not need to use a boot.py.
It is often a good idea to split out re-usable code into libraries. If you want to create or use libraries created by others, you will need to create a lib directory and put the library files in this. It is important that you put .py files directly into lib rather than creating a directory tree. For example, the extra sensor libraries for the Pytrack, Pysense and Pyscan are put in this folder. In this example, we will not use it.
**Controlling the on-board RGB LED**
Now that you have setup and configured your project, we can move on to programming your module. The first thing we will need to do is import some libraries in order to interact with the on-board LED. The Pycom firmware comes with a large amount of built-in modules. You can find out more about these in the API documentation. For this example you will need to open the main.py file and add the following code:
> import pycom
> import time
This will import two libraries, pycom which is responsible for Pycom specific features, such as the on-board LED and time which is a standard library used for timing and delays.
You may have noticed that when you power up your Pycom module, the on-board LED blinks blue on a regular basis. This “heartbeat” is used as a way of know that your module has powered up and started correctly.
Before we can change the colour of this LED we need to disable this heart beat. Below your imports you will need to add the following:
> pycom.heartbeat(False)
Now it’s time to test your code. On the Pymakr pane, you will see a run button, but als an upload (to device) button. For now, we will use run.
After running the example code above, you should see that that on-board LED stops blinking blue. Now, we can complete our script to blink the LED like so:
> import pycom
> import time
> pycom.heartbeat(False)
> 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)
Once you run the above script, it will run forever (due to the infinite While-loop). In order to stop the script, click onto the Pymakr terminal, and press ctrl-c on your keyboard. This stops the script and returns to the interactive REPL.
Great work, the RGB-LED on your device should now blink in red, green and blue
**Uploading to your module**
In the previous section we got code running on on your Pycom module using the run feature of Pymakr. This is useful for quick testing but has a couple of drawbacks.
Firstly the code does not remain on the device permanently. If you reboot the device, it will no longer be running your code.
Secondly, it will only work if you are using libraries built into the firmware. If you need any extra libraries, these need to be copied to the device first. This is where the upload feature comes in.
If instead of run you click upload, Pymakr will upload all the files in the project. These then persist on your device even between reboots, and allows you to use libraries from the lib folder in your project.
## **The Project - Use the inbuilt sensors and visualize its data with an updating interval**
Open Atom.
In atom navigate to File > Add Project Folder
Create a new folder wherever you want on your computer and choose open.
Now right click on the folder in the left pane and create 2 files called boot.py and main.py.
now drag the lib folder to our project in atom from the pysense2 zip file we downloaded earlier. This is so we have code to interact with our inbuilt sensors.
It should look like in the picture below.

## **The code**
Now open the main.py file from the same zip and copy and paste that code to your main.py in atom or just replace the main.py since its nothing in it yet. The code is running your sensors to gather the data.
The code should look like this:
```python=
import time
import pycom
from pycoproc_2 import Pycoproc
import machine
from LIS2HH12 import LIS2HH12
from SI7006A20 import SI7006A20
from LTR329ALS01 import LTR329ALS01
from MPL3115A2 import MPL3115A2,ALTITUDE,PRESSURE
pycom.heartbeat(False)
pycom.rgbled(0x0A0A08) # white
py = Pycoproc()
if py.read_product_id() != Pycoproc.USB_PID_PYSENSE:
raise Exception('Not a Pysense')
pybytes_enabled = False
if 'pybytes' in globals():
if(pybytes.isconnected()):
print('Pybytes is connected, sending signals to Pybytes')
pybytes_enabled = True
mp = MPL3115A2(py,mode=ALTITUDE) # Returns height in meters. Mode may also be set to PRESSURE, returning a value in Pascals
print("MPL3115A2 temperature: " + str(mp.temperature()))
print("Altitude: " + str(mp.altitude()))
mpp = MPL3115A2(py,mode=PRESSURE) # Returns pressure in Pa. Mode may also be set to ALTITUDE, returning a value in meters
print("Pressure: " + str(mpp.pressure()))
si = SI7006A20(py)
print("Temperature: " + str(si.temperature())+ " deg C and Relative Humidity: " + str(si.humidity()) + " %RH")
print("Dew point: "+ str(si.dew_point()) + " deg C")
t_ambient = 24.4
print("Humidity Ambient for " + str(t_ambient) + " deg C is " + str(si.humid_ambient(t_ambient)) + "%RH")
lt = LTR329ALS01(py)
print("Light (channel Blue lux, channel Red lux): " + str(lt.light()))
li = LIS2HH12(py)
print("Acceleration: " + str(li.acceleration()))
print("Roll: " + str(li.roll()))
print("Pitch: " + str(li.pitch()))
print("Battery voltage: " + str(py.read_battery_voltage()))
#set your battery voltage limits here
vmax = 4.2
vmin = 3.3
battery_voltage = py.read_battery_voltage()
battery_percentage = (battery_voltage - vmin / (vmax - vmin))*100
print("Battery voltage: " + str(py.read_battery_voltage()), " percentage: ", battery_percentage)
if(pybytes_enabled):
pybytes.send_signal(1, mpp.pressure())
pybytes.send_signal(2, si.temperature())
pybytes.send_signal(3, lt.light())
pybytes.send_signal(4, li.acceleration())
pybytes.send_battery_level(int(battery_percentage))
print("Sent data to pybytes")
```
Now we will add a loop to run this in 1 hour intervals so the sensor data keeps getting updated.
We begin by creating a variable at the top called:
time_between_collection
put it in after the Pycoproc section like this:
```python=
py = Pycoproc()
if py.read_product_id() != Pycoproc.USB_PID_PYSENSE:
raise Exception('Not a Pysense')
# How often will data be collected
time_between_collection = 3600 #One hour
```
Assign 3600 to it for one hour interval.
in the last part of the code we will wrap the signals that get sent in a while loop. It should look like this:
```python=
while True:
if(pybytes_enabled):
pybytes.send_signal(1, mpp.pressure())
pybytes.send_signal(2, si.temperature())
pybytes.send_signal(3, lt.light())
pybytes.send_signal(4, li.acceleration())
pybytes.send_battery_level(int(battery_percentage))
print("Sent data to pybytes")
#Put device to deepsleep, sleeptime in ms
machine.deepsleep(time_between_collection*1000)
else:
print('Error while reading sensors, wait for next reading')
```
## **Transmitting the data / connectivity**
**The frequency of published data**
The device sends data every hour(because the code) but we can easily change that to our liking.
**The wireless protocols used**
Wifi, inbuilt with the FiPy device.
**The data transport protocols used**
Pybytes.
**Presenting the data**
Pybytes dashboard with widgets.
Data is easily accesible and able to view at a glance with pybytes dashboard.

**How often is data saved in the database.**
While pybytes is enabled and we are plugged in and connected to it we will send new data every hour. We put our device to sleep with the machine.deepsleep function for it only to wake up when need to get the new data, in this case every hour. If something goes wrong we print an error message with the else command.
Now upload project to device and everything works you should see the following (The data will vary of course):
> Connecting to /dev/tty.usbmodemPy42895c1...
> WiFi connection established
> Connected to MQTT mqtt.pybytes.pycom.io
> Pybytes connected successfully (using the built-in pybytes library)
> Pybytes configuration read from /flash/pybytes_config.json
> Pybytes is connected, sending signals to Pybytes
> MPL3115A2 temperature: 26.875
> Altitude: 4.125
> Pressure: 101288.5
> Temperature: 28.21496 deg C and Relative Humidity: 62.57681 %RH
> Dew point: 20.36885 deg C
> Humidity Ambient for 24.4 deg C is 78.24283%RH
> Light (channel Blue lux, channel Red lux): (0, 0)
> Acceleration: (0.02929688, 0.05383301, 1.024048)
> Roll: -1.638722
> Pitch: -2.912335
> Battery voltage: 4.651577
> Battery voltage: 4.651577 percentage: 97.98921
> Sent data to pybytes
>
>
## **Finalizing the design**
Now we want to display and visualize the data with Pybytes.
Open your Pybytes (https://pybytes.pycom.io/) if not open already and go to devices, choose your device that you created earlierand then go to Signals.
You should now see your common signals from your board over the internet.



You also could see the updating charts in the Dashboard:

Now click on add widget


Choose the one you want to add. In this case we want to add pressure, temperature and humidity. So we do the same procedure 3 times.

With Temperature and Humidity you want to choose Pin 2 since the signals are coming that way (It's setup like that) Take a look at the code:

And for Pressure Pin 1 because the setup.

Now you have your widgets showing the sensor data from the pysense 2.0 inbuilt sensors and they are updated with a while loop every hour for fresh data as long as you are plugged in and connected.

## **Final thoughts**
This simple project was thought to spark an interest for the complete beginner, I myself is that beginner and I think I have learned a lot in short amount time, this is not advanced in anyway but since its an introduction course im happy with what I have achived and I know that the journey isnt over, it has just began.
Everything and then I mean everything could have been done in a better way and this tutorial / project rapport could have been written in a better way, but this is me as a beginner explaining in the easiest way possible how to setup the first project in IoT, its straight on with bits and pieces put together from different sources, the goal was to have a full guide for setting this project up without having scroll through differnt pages and click various links, just follow from the beginning to the end and you have something thats IoT.