---
# System prepended metadata

title: '**Lopy4 Room Sensor Station + Alarm IoT Project**'

---

# **Lopy4 Room Sensor Station + Alarm IoT Project**

Jonatan Högild (jh224va)

Using a pycom LoPy4 device to measure temperature, humidity, luminosity and motion and upload these measurements to the cloud.
Gross estimate of the amount of time to complete project: 2-6 hours. 

---

# **Objective**
In this project I log temperature, humidity, luminosity and movement over time in my bedroom. If the temperature gets too high the device goes into 'alarm mode' and emits a beep. This could be used to warn you about very hot days or a fire (but I wouldn't replace my smoke alarm with this). Motion sensor is used to track movement in and out of the room. With little extra effort it can work as a burglar alarm as well and I will show how. I choose this project because I honestly couldn't come up with anything better. I was thinking about doing something to monitor beer/wine brewery/fermentation process but since I don't have any active batches it will have to wait.

---
# **Material**
* **LoPy4 + Expansion board 3** ~ 600SEK
Alternatively use another pycom device that supports wifi.
* **Piezo element** ~ 10-20SEK
Used as speaker/alarm. 
* **DHT11** - 31SEK
Sensor used to measure temperature and humidity. 
* **PIR mini SR602** - 47SEK
Passive infrared sensor that detects nearby movement.
I'd say this has an effective range of about a meter. There's better PIR sensors to buy and either one works with this project. I bought this because it was the cheapest one. 
* **Photo Resistor** ~ 5-10SEK
Photoconductive component that can be used as a light sensor.
* **Breadboard + Wires + Resistors + LEDs** ~ 50-100SEK
Assorted electrical stuff used for wiring everything together. No soldering required. 
For this project I have used 4 resistors with the following values:
    * 10k Ω
    * 1k Ω
    * 550 Ω
    * 330 Ω

---
# **Computer/Hardware Setup**

* Connect the lopy4 to the expansion board with the LED facing the USB port and connect to your computer via the usb cable. 
* Install Node.js: https://nodejs.org/en/
* Install an IDE that supports pymakr, either Atom or VSCode.
I'm using VSCode though both options work just as well, choose whichever one you prefer.
* Install pymakr in your IDE of choice: https://docs.pycom.io/gettingstarted/software/
* (optional) If you're using windows 7 install the correct drivers from pycom. 
* (optional) Update board firmware if necessary: https://docs.pycom.io/updatefirmware/device/
Newly bought boards should be flashed and working properly out of the box.


---
# **Putting everything together**
Before wiring together the components it's a good idea to read the docs of the components as well as the device. Link for the Lopy4: https://docs.pycom.io/datasheets/development/lopy4/#app


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

**Photo Resistor**
Let the wire going into pin 16 sit on the same row as the ground wire.

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

**PIR**

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


**DHT**
The resistor jumps from the data pin (p2) row into the vcc pin (p1) row. On row p2, add a wire after the resistor that goes into p23 on the pycom board.

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

**Piezo**
connect one pin to the ground via a 550ohm resistor and the other to either P21 or P22 (those are the two digital to analog converter (DAC) pins).

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

**LED (optional)**
The cathode (shorter leg) goes into the GND. There is no real benefit to adding this since you might as well use the onboard rgbled instead. I just felt like attaching a bunch of stuff to my pycom. 

---
**Platform**
I tried pybytes and ubidots and I liked both. Both platforms provide good options for data visualisation, both are free and both are simple to use.

Pybytes is pycom's inhouse device management platform. From pybytes you can update the firmware of your devices. You can also use their pymakr IDE available in the browser which can open up and change the code uploaded to any pycom device.
https://pybytes.pycom.io/

Ubidots is also a great option. It's available for free (stem account) and for this project it's not necessary to pay for a subscription. Ubidots has good support for pycom devices.
https://ubidots.com/stem/


---
# **The Code**

`main.py`

```
import pycom
import machine
from machine import Pin 
import time
import ubi
from lib.dht import DHT
from machine import ADC

ledPin = Pin('P12', Pin.OUT, pull = Pin.PULL_DOWN)

pirPin = Pin('P13',mode=Pin.IN)

piezoPin =  machine.DAC('P21')

thPin = DHT(Pin('P23', mode=Pin.OPEN_DRAIN), 0)

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

timer = 0
delay = 0.2 # delay between each cycle adjusted to check the motion sensor reading

def alarmOn(freq):
    ledPin.value(1)
    piezoPin.tone(freq, 0) 

def alarmOff():
    ledPin.value(0)
    piezoPin.write(0)

pycom.heartbeat(False)

while True:
    dht = thPin.read()
    motion = pirPin()

    if dht.temperature>42:
        ubi.post_var("pycom", dht.temperature, dht.humidity, 0, motion)
        alarmOn(5000)
        for i in range(5):
            alarmOn(5000) # keep the alarm ringing

    elif timer > 60*20:
        light = apin()
        ubi.post_var("pycom", dht.temperature, dht.humidity, light, motion)
        timer = 0

    else:
        alarmOff()
        timer += delay

    time.sleep(delay)


```
For use of the DHT11 (or DHT22), get `dht.py` from here: https://github.com/JurassicPork/DHT_PyCom
Place/create `dht.py` in your lib folder.

To make the device work as a burglar alarm, change line 39 to this:
```
if dht.temperature>42 or motion: 
```

There's also some 'boilerplate' code I'm omitting. There's`boot.py` which scans for available networks to connect to, `urequests.py` and `ubi.py` used to integrate ubidots and `keys.py` used to store network ssid and password. 

---
# **Transmitting the data**

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

Data is sent every 20 minutes ordinarily and every 5 seconds when the alarm is triggered. The time interval is not that important to me, it could be set to 10 minutes or an hour. It depends on what you're going to use the data for. I don't do anything with my data aside from looking at it. 

The wireless protocol I'm using is wifi and the transport protocol is https using the ubidots REST API. The data is packaged as JSON-objects. I followed this tutorial to connect my pycom device to the ubidots platform: https://help.ubidots.com/en/articles/961994-connect-any-pycom-board-to-ubidots-using-wi-fi-over-http

My device stays at home, currently plugged into my pc. wifi and https is good choice since I don't have to worry about range or power consumption. Also the data gets encrypted when sent so that's nice. Im out of range for TTN, Helium and Sigfox which is unfurtunate but not important for this particular project. A quick estimate puts the power consumption close to 100mAh (quite a lot). 

---
# **Presenting the data**

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

Here's my Ubidots dashboard with various widgets attached. There's customization options like expanding/shrinking a widget or changing style/appearance. I've left my widgets as default. 

Using ubidots stem, the data is stored for a month. Using one of their paid subscirptions the data is stored for 24 months. If you rather use pybytes, they offer 5MB free storage.

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

**Events**
Using ubidots we can also make an event that notify us in case something happens. https://stem.ubidots.com/app/events/
When creating a burglar alarm it's a good idea to create an event that responds to a change in the motion variable. So in case burglars steal all your valuables you can at least get an email notification about it. There's all sorts of things you can do with events. If you measure several hot days in a row, why not add an event that reminds you to water your plants. Or create an event should there be something wrong with your device or a sensor. 

---
# **Finalizing the design**

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

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

I keep my device in my bedroom since it's connected to the usb port of the pc but when using it as a burglar alarm it is a much better idea to put it in the hallway near the front door. Before I go on a trip in September I plan on doing just that, enclosing the device in a box and looking into other ways of connecting it. 

Right now, neither the connected led or photoresistor is particurarly useful. I was thinking of maybe doing something cool with the light value like adding a 'night-mode' though I couldn't come up with any use-case for this. 