# Distance sensor with a threshold
**Author:** cs223vr
Table of Content
[ToC]
## Introduction
This project is about warning the user if an object is above/below a certain threshold, using a distance sensor (HC-SR04) and a buzzer (PKM22EPP-40). The distance measurements will be sent over WiFi and will be visualised through pybytes platform. By following this tutorial you will learn how to collect data from a sensor and pass it on to the internet. The estimated time for this project is 2 hours.
## Objective
I chose this project because I wanted to work with the distance sensor (HC-SR04). The purpose is to be able to warn the user if the distance to an object increases or decreases. This can be applied in many scenarios, such as monitoring if a door is opened.
---
# :memo: Tutorial
### Material
The material used in this projekt can be seen in Table 1.
<div style="text-align: center"> Table 1 - List of materials </div>
| Component | Description | Bought from |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | ----- |
| Pycom LoPy4 | A device programmed by MicroPython and has several bands of connectivity. The device has many digital and analog input and outputs and is well suited for an IoT project. | Elektrokit | |
| Expansion board 3.0| Pycom Expansion Board is compatible with Pycom's WiPy, LoPy, SiPy, FiPy, and GPy development boards. Use the Pymakr IDE code editor to easily write Python scripts. | Elektrokit | |
| HC-SR04 | A distance sensor that provides measurements from 2cm to 400cm. | Electrokit |
| PKM22EPP-40 | An electrical component that can be used to detect vibrations and create noises. | - | - |
| Breadboard | A board which you can build electronic circuits. | Elektrokit | |
| Jumper wires | Is used to connect components to each other on the breadboard and to the LoPy4. | Elektrokit | |
---
### Computer Setup
The integrated development environment (IDE) that was used was Pymakr Plugin for Atom, which is programmed in MicroPython language. Down below is a guide on how to install Atom and the Pymakr Plugin, along with how to connect the Pycom device to your computer and how the code is uploaded to the device.
>**Step 1:**
>Download and install Atom, [here](https://docs.pycom.io/gettingstarted/installation/pymakr/#app).
>**Step 2:**
>Navigate to the Install page, via *Atom > Preferences > Install* and search for **Pymakr** and install the official Pycom Pymakr Plugin.
>**Step 3:**
>Connect your Pycom device to your computer via USB. Pymakr has auto-connection enabled by default and in case your device hasn’t connected right away, click on Connect device and then on your device.
>**Step 4:**
>To upload the code, click on "*Upload project to device*", as shown by the red rectangle in Figure 1. The code for this project can be found under *The code-section*
>
<div style="text-align: center"> Figure 1 - How to upload the code to the Pycom device.</div>
---
### Putting everything together
This section describes how all the electronics were connected.
The breaboard was connected to the expansion board with two jumper wires, one to 3V3 (power) and one to GND (ground), which is shown by (1) and (2) in Figure 2. The Pycom LoPy4 was also attached to the breadboard.
The *HC-SR04* were attached to the breadboard and jumper wires were connected the following way:
> (3) VCC -> power (+ on the breadboard)
> (4) Trig -> P23 (Pin 23 on the expansion board)
> (5) Echo -> P22 (Pin 22 on the expansion board)
> (6) GND -> GND (- on the breadboard)
>
where the numbers are connected to the numbers in Figure 2.
The *PKM22EPP-40* was also attached to the breadboard with one jumper wire connected to P21 (7) and one to GND (8).

<div style="text-align: center"> Figure 2 -
Assembly of components.</div>
### Platform
In this project, the free cloud-based device management platform *Pybytes* was used, which is available for all Pycom development boards and modules. On Pybytes, you can add your device via USB and keep your devices connected to your favourite network and monitor them in a easy dashboard.
### The code
The code for this project is presented down below and consists of two functions. A *main-function* that is looping forever, and checks if the distance is above the threshold or not. If the distance is above the threshold the buzzer is turned on and the distance is sent to the platform, otherwise the buzzer is turned off. The *distance-function* returns the measured distance from the sensor.
```python=16
# Libraries
import utime
from machine import Pin, PWM
import time
# Setup
echo = Pin('P22', mode=Pin.IN) # HC-SR04 sensor, pin 22
trigger = Pin('P23', mode=Pin.OUT) # HC-SR04 sensor, pin 23
buz = Pin('P21') # PKM22EPP-40, pin 21
tim = PWM(0, frequency=300)
ch = tim.channel(2, duty_cycle=0.5, pin=buz)
threshold = 10;
# Main function
def main():
while True:
distance = distance_measure() #Get measured distance
time.sleep(2)
#Check if the distance is below threshold or not
if(distance > threshold):
ch.duty_cycle(0.50) # Turn the buzzer on
pybytes.send_signal(1, distance) # Send distance to platform
else:
ch.duty_cycle(0) # Turn the buzzer off
# Distance function
def distance_measure():
# Make sure output is low
trigger.value(0)
utime.sleep_us(10)
# Trigger 8 cycle sonic burst by setting trigger to high for 10us
trigger.value(1)
utime.sleep_us(10)
trigger.value(0)
# Wait for pulse to start on input pin.
while echo() == 0:
pass
start = utime.ticks_us()
# Run until input pin changes to low.
while echo() == 1:
pass
finish = utime.ticks_us()
utime.sleep_ms(10) # wait before the next measuring
# Calc the duration of the received pulse, divide the result by
# 2 (round-trip) and divide it by 29 (the speed of sound is
# 340 m/s and that is 29 us/cm).
distance = utime.ticks_diff(finish, start)/29/2
return distance
```
### Transmitting the data / connectivity
To send data to the Pybytes platform, the function *pybytes.send_signal(signalNumber, value)* is called. This function is part of the Pybytes library, and it has two arguments: *signalNumber* and *value*. The *signalNumber* represents which signal is receiving data and the *value* is in this case the distance measurements.
The choice of wireless protocol was WiFi and the data was sent every time the measured distance was above a certain threshold.
### Presenting the data
In Pybytes, you can define the signal and visualize the data in a dashboard, which is shown in Figure 3.

<div style="text-align: center"> Figure 3 - Dashboard in Pybytes.</div>
.
Here you can see when the data was received and how many bytes that was sent. You can also visualize the data with different charts, as can be seen in Figure 4.

<div style="text-align: center"> Figure 4 - Line chart with received distances.</div>
.
The figure represents what time the data was received along with the measured distance.
### Finalizing the design
Figure 5 shows the final result of this project.

<div style="text-align: center"> Figure 5 - Pycom device and sensors </div>
.
There have been no difficulties during the course of the project and by following this tutorial you should have learned how to collect data via a sensor and pass it on to the internet.
An improvement that could have been made is to send fewer bytes as 8 bytes are currently being sent, which is a bit much. LoRa could also have been used instead of WiFi since it enables transmission of data over longer distances and has low energy consumption.