---
# System prepended metadata

title: '**Monitoring the light intensity, temperature and noise in trains**'

---

# **Monitoring the light intensity, temperature and noise in trains**
**Batoul Almadani, ba222rj**

In trains, the temperature is set to the same degree both in summer and winter, which is not comfortable to all passengers and may unnecessarily cost more energy. The same thing with train carriages' lights that dosen't need to be on all the time. Public transport need to be quiet as well to allow passengers to enjoy a quieter journey without distractions or noise. This project aim to construct a simple sensor for use in in train carriages to monitor the temperature, light intensity and noise in order to automaticlly control the temperature and lights and keep the train atmosfer as calm and comfortable as possible.

Approxiamtly estimated time needed for the project is 1hour.

# Objective
Monitoring the light intensity and temperature may help in controlling the energy consumption in trains and improve the environment's quality for the passengers. In addition, monitoring the noise levels would provide an indication of the rush hour in the train as well as in case noise level is high the passengers will be notified to stay calm. This project would be helpful in libraries too and can be extended to monitor the air quality as well. Because this was the author's first experience constructing an IOT device, it was vital that the project be simple to accomplish but at the same time includes the application of the basic concepts of IOT, programming, electric circuits and send data with LoraWAN.

# Material


| Component | Description | Cost |  Picture    |
| -------- | -------- | -------- | --- |
|  Pysense 2.0 expansion board  | This expansion board including Accelerometer, Light Sensor, Pressure Sensor, Temperature, and Humidity Sensor.    | 300.00 SEK     | ![](https://i.imgur.com/zCNifAm.png)
|   Pycom FiPy  | It is a small micro controller programmed by MicroPython. FiPy is a multiprotocol development devise that includes WiFi, Bluetooth, LoRa, Sigfox and dual LTE-M.  The input and output pins located on the sides allow to connect analog and digital components.     | 682.93 SEK     |  ![](https://i.imgur.com/MxRcnTj.png)|
|  ICS-40180  | Microphone    | 129.00 SEK     | ![](https://i.imgur.com/E7p3VyY.jpg) |
|  LoRa Antenna  | LoRa is a long range wireless technology for Internet of Things     | 90.00 SEK     |  ![](https://i.imgur.com/t5hUhbP.png)|
|  Bread Board  | A breadboard is used for building circuits. It is useful because it connects components without the use of solder which allow to be removed and replaced easily.     | 52.00 SEK     |   ![](https://i.imgur.com/BAwVQzw.png)|
|  Photoresistor  | Is a light sensitive devices used to measure the light intensity. The resistance decreases as the light increases.     | 8.00 SEK     |   ![](https://i.imgur.com/BuN91Kt.jpg)|
| Batteri    | 3.7V 1500mAh    | 149.00 SEK     | ![](https://i.imgur.com/RwvCmyS.jpg) |
|LED    |  5mm red, diffuse 1500 mcd   | 5.00 SEK    |   ![](https://i.imgur.com/ozd33F6.jpg)|
|  Resistor  | 10kohm     | 3.00 SEK    |  ![](https://i.imgur.com/SadiWEw.png)|
| Jumper Wires   | Female-to-female wires    | 99.00 SEK     |   ![](https://i.imgur.com/dBpLwGr.jpg)|

All prices are approximates and all components were bought from [Electrokit](https://www.electrokit.com/).


# Computer setup
An integrated development environment (IDE) is required to be able to program the device. In this tutorial Atom is used, because I've used VS Code before and Atom will be a new experience. You can simplly download the .exe file  from this link [Atom](https://atom.io/) and then run the file to install Atom. You may also need to download and install [Node js](https://nodejs.org/en/). The next step is to install package needed to communicate to our Pycom board. To do that open Atom and the package manager from: File >> Settings >> Install then look for **Pymakr** and Install it.

The next step is Updating device firmware to the latest version. In order to do that I followed the tutorial in this [link](https://docs.pycom.io/updatefirmware/device/). When the updating is complete then we can use the Pymakr plugins to upload and run programs in our device.

# Putting everything together
First of all we connect the FiPy to the breadboard. Then according to the FiPy pinout diagram in Figure 1 and the Pysense pinout diagram in Figure 2 we connect  the following pins from  FiPy to Pysense expansion board:
* 5V <-----------------> 5V
* GND <---------------> GND
* 3.3 V from expansion board to positive rail on the breadboard.
* P0 (Programming port) <---------------> UART_Rx on expansion board.
* P1 (Programming port) <---------------> UART_Tx on expansion board.
![](https://i.imgur.com/tCGaHlB.png)
*Figure 1. PyCom FiPy.*

   ![](https://i.imgur.com/weN2k7j.png)
*Figure 2. Pysense expansion board.*

There are five different sensors on this expansion board including Accelerometer, Light Sensor, Pressure Sensor, Temperature, and Humidity Sensor. In this project I only need the temperature sensor (SI7006A20). we connect it as following:
* P22 (DAC pin) <---------------> SDA.
* P21 (DAC pin)<---------------> SCL.

All the sensors will be connected to expansion board via the breadbord. Connecting the Photo resistor is as following:
* Red wire  --------------->  positive rail on the breadboard (3.3V)
* Blue wire  ---------------> negative rail on the breadboard
* Yallow wire ---------------> analog pin P16 on FiPy

Connecting the sound sensor (ICS-40180) is as following:
* AUD (green wire) ---------------> analog pin P13 on FiPy
* GND (black wire) ---------------> negative rail on the breadboard
* VCC (red wire)  --------------->  positive rail on the breadboard (3.3V)

Connecting the LED light:
* Positive long leg (green wire) ---------------> digital pin P23 on FiPy.
* negative short lag (black wire) ---------------> negative rail on the breadboard

The final setup of the device, sensors and the wiring are shown in a circuit diagram in Figure 3.

![](https://i.imgur.com/p0fFZSD.jpg)
*Figre 3. Circuit diagram from Fritzing.*

# Platform
In this project I chose to receive, present and analyzing the created data by Datacake platform. Datacake is a cloud based platform that dose not require programming skills and that is why I prefer to use it. And since I'm using LoRaWAN so Datacake is a good chose because it offers Integration for LoRaWAN Network Servers including  Helium. Besides that, it offers connecting the first two devices for free.

# The code
Main.py contains the following code:
* Import libraries that is needed to run the program.
* Definition of the different pins that will be used by the sensors. 
* In the main loop the temperature, light and sound will be Measured every 6 minutes and the values will be inserted into a list.
* Each houre the average value of temperature, light and sound will be calculated by the average function and then the average data will be send with LoRaWAN.
```
from machine import ADC
from machine import Pin
import time
import pycom
from pycoproc_1 import Pycoproc
import machine
from SI7006A20 import SI7006A20
from MPL3115A2 import MPL3115A2,ALTITUDE

LightSensorPin = 'P16'

lightPin = Pin(LightSensorPin, mode=Pin.IN)
#
adc = ADC(bits=10)
apin = adc.channel(attn=ADC.ATTN_11DB, pin=LightSensorPin)


SoundSensorPin = 'P13'

soundPin = Pin(SoundSensorPin, mode=Pin.IN)


adc2 = ADC(bits=10)

apin2 = adc2.channel(attn=ADC.ATTN_11DB, pin=SoundSensorPin)

led = Pin('P23', Pin.OUT, pull = Pin.PULL_DOWN)


pycom.heartbeat(False)
pycom.rgbled(0x0A0A08)

py = Pycoproc(Pycoproc.PYSENSE)


pybytes_enabled = False
if 'pybytes' in globals():
    if(pybytes.isconnected()):
        print('Pybytes is connected, sending signals to Pybytes')
        pybytes_enabled = True


def Average(l):
    avg = sum(l) / len(l)
    return avg


while True:
    light=[]
    sound=[]
    temp=[]
    for x in range(9):
        val1 = apin()
        light.append (val1)
        val2=apin2()
        sound.append (val2)
        val3= MPL3115A2(py,mode=ALTITUDE)
        temp.append(val3.temperature())
        print("Light Value", val1)
        print("Sound Value", val2)
        print("MPL3115A2 temperature: " + str(val3.temperature()))
        if val2 > 500:
            led.value(1)
            time.sleep(1)
            led.value(0)
        time.sleep(360)
    average = Average(light)
    print("avr light", average)
    average2 = Average(sound)
    print("avr sound", average2)
    average3 = Average(temp)
    print("avr temperature", average3)
    Tosend = int(average3*100+average2*100+average*100) # combine both in an int
    bytes_to_send = [average3,average2,average]
    s.send(bytes_to_send) 
```
boot.py contains the following code:
* Import libraries that is needed to connect LoRaWAN on Helium. Initialise LoRa and LORAWAN mode and select the region that matches the device place.
* Add your own AppKey and DevEUI that Helium have been genearted when you created your device.
* Join the network using the previous parameters.
* Wait until the module has joined the network.
* Create a LoRa socket and make the socket non-blocking.
```
from network import LoRa
import time
import binascii
import socket

lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)

dev_eui = binascii.unhexlify('6081F921C4424A8A')
app_eui = binascii.unhexlify('6081F92F63046EA5')
app_key = binascii.unhexlify('0F3F37365D6B31D7FE9DA2DE5C1C78BA')

lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0)

while not lora.has_joined():
    time.sleep(2.5)
    print('Not joined yet...')

print('Network joined!')

s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

s.setblocking(False)
```
# Transmitting the data / connectivity
In this project I will use the LoRaWAN protocol to wirelessly connects the device to the internet and manages communication between the end-node device and network gateways. The data transmission is done through Helium Network and ,as shown in the code section, the data is transmitted each hour. The first thing to do is to add our device to Helium then Helium will genearte the Dev EUI, App EUI and the App Key that will be used in boot.py file to connect to Helium. All this steps are explained in this [tutorial](https://hackmd.io/@lnu-iot/Sk1bej8d9).

# Presenting the data
The last step is to connect Helium Console to Datacake IoT Platform for storage and visualization. After the registration in Datacake Platform we can add our device and at this step we need to provide the DEV_EUI we got from the Helium. Next step is to set up Datacake integration in Helium as in this [link](https://docs.helium.com/use-the-network/console/integrations/datacake/). Now we are ready to adjust some configuration on our device as [following](https://hackmd.io/@lnu-iot/B1GUJqJq9#Part-4-Datacake-Integration). Finally we can add widgets in our dashboard which gives us a graphical way to see the changes in temperature, light and sound.

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


# Finalizing the design
This project can be extended to include to monitor the air quality in trains and we can add more components like a LCD screen to display a message  when the noise level is high. But as an overall result, I'm very satisfied with this project as it is my first IOT project. 

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

