---
# System prepended metadata

title: The Landlord Buster

---

# The Landlord Buster
By Max Bekkhus | mb224y

Estimated time of completion: 2 hour
## Overview
The Landlord Buster is a tutorial designed to provide basic knowledge about hardware assembly, sensor-data collection, data transmission and data visualization with the help of a [Pycom](https://pycom.io/) Internet-of-things (IoT) prototyping device. This project is created to enlighten people how manageable and straight forward creating an IoT-device can be.

Basic knowledge about electrical circuits, programming and the programming language Micropython is of help but not crucial to complete this tutorial.

## The Device
The Landlord Buster is a device that lets tenants without control of their residence heating/cooling systems ensure that their landlord follows the local indoor climate regulations. The device includes a temperature and humidity sensor for collecting climate data and an RGB-LED for indicating the current temperature range.

## Material
This section displays a list of hardware material needed to complete the tutorial and the assemby of The Landlord Buster.

### Pycom LoPy4 Development Board
The LoPy4 is a powerful and user friendly development board that offers wireless connectivity over 4 different protocols.

In this tutorial the LoPy4 acts as the brain of the device and the onboard LED has a specific use case.
**Price:** €34.95
**Vendor:** [pycom.io](https://pycom.io/product/lopy4/)
![LoPy4]

### Pycom Expansion Board 3.0/3.1
The Pycom Expansion Board 3.0/3.1 is compatible with all Pycom modules and a great feature extender in pair with the LoPy4.

In this tutorial Expansion Board 3.1 is used, mainly with the purpose of pushing code to and powering the LoPy4 via USB.

**Price:** €16.00
**Vendor:** [pycom.io](https://pycom.io/product/expansion-board-3-0/)
![expansionBoard]

### DHT11 Digital Sensor
The DHT11 is a module equipped with a digital sensor for reading temperature and air humidity.

In this tutorial the DHT11 is used in connection with the LoPy4 to read and store temperature and humidity data.

**Price:** ~ €4.70
**Vendor:** [electrokit.com](https://www.electrokit.com/en/product/digital-temperature-and-humidity-sensor-dht11/)
![dht11]

### LED RGB SMD
This module is equipped with an RGB LED which color can be controlled with 3 [PWM-signals](https://en.wikipedia.org/wiki/Pulse-width_modulation).

In this tutorial this module will be used to indicate a specific range which the current temperature resides within. The LED will emit different colors depending on range.

**Price:** ~ €1.80
**Vendor:** [electrokit.com](https://www.electrokit.com/en/product/led-module-rgb-smd/)
![rgbsmd]

### Solderless Breadboard
With no need for soldering this breadboard is great for experimenting, prototyping and testing electrical circuits.

In this tutorial this breadboard will be used to create an electrical circuit to connect the development board with the sensor modules.

**Price:** ~ €5.60
**Vendor:** [electrokit.com](https://www.electrokit.com/en/product/solderless-breadboard-400-tie-points/)
![breadboard]

### Jumper Wires
No wiring equals no connectivity! 

In this tutorial jumper wires are used to connect the electrical circuit of The Landlord Buster.

**Price:** ~ €2.80
**Vendor:** [electrokit.com](https://www.electrokit.com/en/product/jumper-wires-1-pin-male-male-150mm-10-pack/)
![wire]

## 330ohm Resistors
Resistors are electrical components used to control the current flowing through an electrical circuit.

Three 330ohm resistors are in this tutorial used to control the current flowing through the temperature indicating RGB LED. 

**Price:** ~ 3x€0.1
**Vendor:** [electrokit.com](https://www.electrokit.com/produkt/motstand-kolfilm-0-25w-330ohm-330r/)
![resistor]
## Setup & Environment
This tutorial will describe the process of setting up your LoPy4 and a development environment on the operating system [Pop!\_OS](https://pop.system76.com/).

### Firmware & PyBytes
The first step in the LoPy4 setup is to make sure that the boards firmware is up to date. During the firmware update we will in this tutorial complete a [Pybytes](https://pycom.io/products/software/pybytes-3/) registration. PyBytes is a cloud platform which we will later use to store the data read from our sensor modules. Complete the following steps to set up your LoPy4 device:

1. Register a PyCom account [here](https://sso.pycom.io/register/)
2. Log in to your created account [here](https://sso.pycom.io/login).
3. Navigate to the Pybytes service. 

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

4. Choose the *Configure Networks* card and add the WiFi you wish to connect to with your LoPy4. **Make sure to select a WiFi on the 2.4 GHz frequency!**

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

5. Return to the previous card choice and now click the *Add Device* card to create your Pybytes LoPy4 device.
6. To add a device to Pybytes via USB the LoPy4 need to be attached to the Expansion Board. Attach the LoPy4 following the last 3 steps of the *Basic connection* instructions [here](https://docs.pycom.io/gettingstarted/connection/lopy4/). 
7. Run the following commands and reboot your computer to gain user access to the USB-port.

```shell
sudo apt install dialout
sudo apt install python3-serial
sudo usermod -a -G dialout $USER
```

9. Now connect your Expansion Board to your computer and click *Add via USB* on the *All devices* page.
10. Choose your device to be a LoPy4. 

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

8. Enable the WiFi network type.

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

9. Name your device and select your previously created WiFi-network.

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

10. Now select your newly created device in the device list and click the *Provisioning* tab. This is where the device activation and firmware update process begins.

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

11. To activate the device you first need to download the firmware updater for Linux. Choose  and install the *Ubuntu Linux 18.04 LTS (and higher)* version for your system.
12. Run the installed firmware updater and follow the next steps for completing the update. **Make sure that your Expansion Board is connected during the process!**
13. Exclude development releases to ensure stability and help Pycom with reports and stats if you wish. Continue to the next step.

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

14. Select your USB-port (which is usually auto detected), high speed transfer and advanced settings. The type should be set to Pybytes with both related boxes checked. Continue to the next step.

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

15. Visit the *Provisioning* tab on your Pybytes device page as we did in **step 10**. Generate an activation token and paste it into the box displayed in the firmware updater. Continue to the next step.

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

16. Check the *Erase during update* box to clean the device from unwanted code. Make sure the version is set to the lastest and the other fields according to the image below. Continue to begin the update process.

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

17. Your LoPy4 is now successfully updated! Scroll down to the bottom of the scroll view and (if you wish) store the device identification data for possible future use. Finish the process by clicking *Done*.

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


### Visual Studio Code & Uploading code
In this tutorial we will make use of the text editor [Visual Studio Code](https://code.visualstudio.com/) (VSC) to write and upload code to our LoPy4.

Install and run VSC by running the following commands:


```shell
sudo apt install code
code
```

With VSC running its now time to install the [PyMakr extension](https://marketplace.visualstudio.com/items?itemName=pycom.Pymakr). This extension enables you to run and upload code from your editor as well as provides you with a [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop). When the extension is installed VSC will prompt an installation of the dependency NodeJS, go ahead and do so.

With your device connected you can now (via the VSC Status Bar) run or permanently upload code to your device.

## Construction

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

A circuit diagram displaying the wiring and construction details of The Landlord Buster can be seen above. The diagram displays information such as which LoPy4-pins to utilize, the sensor module pins and their functionality as well as resistor attributes.

### Resistors

The 330 ohm resistors for the RGB SMD is high enough to limit the current and avoid burning the LEDs inside the module. The DHT11 module includes a 1000 ohm resistor which results in a more straight forward connection.
## Data Storage Platform
As mentioned earlier the this tutorials storage platform of choice is PyBytes. The platform is free of charge and the procedure of adding additional devices for scale is simple. 

To setup the structure of your data points visit the *Signals* tab on the web page for your created device and follow the instructions below.

1. Click *Define New Signal* to create a signal for the temperature data read from the DHT11. Provide a signal index, name and the unit representing the signal data. In our case the index would be 0 (our first signal), the name Temperature and the unit Celcius. Save the signal.
2. Click the newly created signal and click the green button named *Create New Display*.
3. Select a display type of your liking and click *Create*
4. Repeat the process for the humidity data read from the DHT11, increment the index of this signal, set the name to Humidity and the unit to %.

The indicies of the two signals created will be of use when by code sending data from your LoPy4 device.

## The code
The code of this tutorial is divided into 3 Micropython modules shown in the VSC-explorer below.

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

### dht

The dht module is a third party [resource](https://github.com/JurassicPork/DHT_PyCom/blob/master/dth.py) from the GitHub user [JurrasicPork](https://github.com/JurassicPork). This module lets you construct a DHT11 object from which you can read sensor data.

### rgb_temp

The rgb_temp module was written to partly enforce the [Single Responsiblity Principle](https://en.wikipedia.org/wiki/Single-responsibility_principle) and remove the temperature indicating LED functionality from the main module.

This module provides the class RGB_TEMP holding a PWM-pin object, temperature ranges and colors for each range. Running the new_temp method updates the colors according to the ranges provided during construction.

```python=
from machine import PWM

class RGB_TEMP:

    def __init__(self, pins, temps_in_celcius, colors):
        self.__pwm = PWM(0, frequency=5000)
        self.__pins = pins
        self.__pwm_rgb = {
            'red': self.__pwm.channel(0, pin=self.__pins['red'], duty_cycle=0),
            'green': self.__pwm.channel(1, pin=self.__pins['green'], duty_cycle=0),
            'blue': self.__pwm.channel(2, pin=self.__pins['blue'], duty_cycle=0)
        }
        self.__temps = temps_in_celcius
        self.__colors = colors
        self.__active_color = None

    def new_temp(self, temp_in_celcius):
        if temp_in_celcius < self.__temps['cold']:
            self.__active_color = self.__colors['cold']
        elif temp_in_celcius >= self.__temps['hot']:
            self.__active_color = self.__colors['hot']
        else:
            self.__active_color = self.__colors['neutral']

        self.__update_color()

    def __update_color(self):
        duty_cycle_red = self.__decimal_to_duty_cycle(self.__active_color['red'])
        duty_cycle_green = self.__decimal_to_duty_cycle(self.__active_color['green'])
        duty_cycle_blue = self.__decimal_to_duty_cycle(self.__active_color['blue'])

        self.__pwm_rgb['red'].duty_cycle(duty_cycle_red)
        self.__pwm_rgb['red'].duty_cycle(duty_cycle_red)
        self.__pwm_rgb['red'].duty_cycle(duty_cycle_red)

    def __decimal_to_duty_cycle(self, dec):
        return dec/255
```

### main
The main module is the module that runs when your LoPy4 device is booted. In the implementation below objects for both the DHT11-sensor, the RGB LED and the wireless connection are created. With all nessecary objects a the main run loop is started. The loop consists of 4 distinct phases

1. The wireless connection is checked and the LoPy4 onboard LEDs color is set to indicate the connection status.
2. The sensor data is read from the DHT11 module. Not until a result is recieved the process continues.
3. The temperature recieved (in celcius) is passed to the RGB_TEMP object to update the temperature indicating LED.
4. The temperature and humidity data is sent to the signals previously created for our PyBytes device. The signals are indentified by the selected indicies.

```python=
import pycom
import time
from network import WLAN
from machine import Pin
from dht import DTH
from rgb_temp import RGB_TEMP

pycom.heartbeat(False)

rgb_temp = RGB_TEMP(
    {
        'red':'P21',
        'green':'P22',
        'blue':'P23'
    },
    {
        'cold': 18,
        'hot': 25
    },
    {
        'cold': {'red':0, 'green':0, 'blue':255},
        'neutral': {'red':255, 'green':200, 'blue':0},
        'hot': {'red':255, 'green':0, 'blue':0}
    }
)

dht11_gpio = DTH(Pin('P20', mode=Pin.OPEN_DRAIN), 0)
time.sleep(2)

wlan = WLAN(mode=WLAN.STA)

while True:
    # 1
    if wlan.isconnected():
        pycom.rgbled(0x001100)
    else: 
        pycom.rgbled(0x110000)
    # 2
    result = dht11_gpio.read()
    while not result.is_valid():
        time.sleep(5)
        result = dht11_gpio.read()
    
    #3
    rgb_temp.new_temp(result.temperature)
    
    #4
    pybytes.send_signal(0, result.temperature)
    pybytes.send_signal(1, result.humidity)

    time.sleep(1200)
```

## Data Transmission and Connectivity

* **Data transmission rate:** 3 times per hour
* **Wireless protocal used:** WiFi
* **Transport protocol used:** MQTT

## Presenting the data
Data presentation is included in the PyBytes platform. Visit the devices signal page to view the previously created displays. See images below.

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

![](https://i.imgur.com/PtpHRrc.png)
## Final Result
Here is an image of how a final result of The Landlord Buster could look like.

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

<!-- IMAGE URIs -->
[lopy4]: https://pycom.io/wp-content/uploads/2018/08/lopy4NoHeadersTopN.png
[expansionBoard]: https://pycom.io/wp-content/uploads/2020/03/Website-Product-Shots-ExpB-Front.png
[dht11]: https://www.electrokit.com/uploads/productimage/41015/41015728-1.jpg
[rgbsmd]: https://www.electrokit.com/uploads/productimage/41015/41015716.jpg
[breadboard]: https://www.electrokit.com/uploads/productimage/41012/41012199.jpg
[wire]: https://www.electrokit.com/uploads/productimage/41015/41015693.jpg
[resistor]: https://www.electrokit.com/uploads/productimage/40810/40810233.png