---
# System prepended metadata

title: Rios Doorbell

---

# Rios Doorbell


## Tutorial on how to build a smart doorbell for an outdoor cat

*Castillo - cn223fc*

<u>Short project overview</u>
This tutorial will walk you thru the steps on building a system that will alert you whenever your cat is in their cat house, waiting to be let in. The alerts will come as discord message.

<u>How much time it might take to do (approximation)</u>
Given that you have the proper knowledge, this project shouln't take more than a couple of hours, most of which will be spent on troubleshooting, and calibrating the sensors. Around 6 hours is reasonable.

### Objective

<u>Why I chose this project</u>
My cat Rio, likes to be outside. He also has a cat house in the small patio, right next to the door, where he patiently waits to be let in.
My problem is, that I very often have to check if he's waiting to be let in, which causes a feeling on always being on the watch. Also, in winter, I wouldn't want him to wait outdoor an extensively long time, as it can get pretty cold. One solution would be to install cat door, but that would require changing the door, since it is a glass door. This solution is therefore a quite expensive one, not suitable for a student like myself. Therefore, my approach will be to use a sensor and a microcontroller to tell me when he's waiting in his cat house. 


<u>What purpose does it serve</u>
The main purpose here is to not always be on the lookout, and instead be notified when he's home. That way I wouln't need to stop in the middle of my day just to check if he's in his cat house. And for Rio, he wouln't need to be kept waiting for hours on end.

<u>What insights I think it will give</u>
Since the sensors are gonna log when he's in his cat house, I think some usefal data could be retrieved. Usually, the last thing before I go to bed is to check if Rio is back. The data could now provide a schedule, on the typical times Rio comes back home. It would also let me know how mant times he comes back to his cat house during the day when I'm away. This information could lead to me put a food dispensor outside, which is activated when he's in his cat house. 


### Material

<u>List of material</u>
 1. Raspberry Pi Pico W
 2. Solderless breadboard
 3. Ultrasonic Sensor - HC-SR04
 4. 6 Jumper wires, male-male
 5. Micro USB cable




<u> What the different things do </u>
*Raspberry Pi Pico W*
This is the microcontroller, the “brain” of the project. It collects the data from the sensor and sends it forward through its Wi-Fi connection.

*Solderless breadboard*
A platform that allows to test the circuit without the need to solder. The use of the breadboard facilitates proving our concept, making sure it works as intended.

*Ultrasonic Sensor - HC-SR04*
This sensor sends out a high-frequency sound wave and measures the time it takes for the echo to return. By calculating the time difference, we can determine the distance to Rio, which is used to determine if he’s in his cat house.

*6 Jumper wires, male-male*
Used to connect various components on the breadboard. The different colors of cable also help to clearly visualize the circuit.

*1 Micro USB cable*
To connect the Raspberry Pi Pico W to the computer, so that we can program it.

<u>Where the hardware was bought and how much they cost</u>

>| Hardware            | Price (kr)|   Available     |
>| --------------------| ------- |---------------- |
>| Raspberry Pi Pico W |   89    |https://www.electrokit.com/en/raspberry-pi-pico-w
>| Solderless Breadboard   |49 | https://www.electrokit.com/en/kopplingsdack-400-anslutningar
>| Ultrasonic Sensor - HC-SR04 | 59 | https://www.electrokit.com/en/avstandsmatare-ultraljud-hc-sr04-2-400cm
>| 6 Jumper wires, male-male | 29 | https://www.electrokit.com/en/labsladd-1-pin-hane-hane-150mm-10-pack
>| 1 Micro USB cable | 28| https://www.electrokit.com/en/usb-kabel-a-hane-micro-b-hane-60cm





### Computer setup


I use a Macbook Air in this project, running on Sonoma 14.0. The instruction will be written for this use, although, they should be very similar in other operating systems as well. 

<u>Chosen IDE</u>
#### Installing Visual Studio Code and PyMakr
For this project, VS Code was used as the IDE. With the plugin PyMakr, it works very streamlined on the Raspberry Pi Pico W. Here's the instructions:
- Download & install Visual Studio Code from the official [website](https://code.visualstudio.com/Download).
- After installing, open VS Code, open the Extension view by clicking on its icon on the sidebar, or press `cmd+shift+x` on the keyboard. Search fo PyMakr and install it. **Careful to not install *PyMakr - Preview*, this is not the correct one.**

<u>How the code is uploaded</u>
#### Flashing MycroPython into the Raspberry Pi Pico W
PyMakr allows us to upload code directly to the the Pico W, but first we need to prepare it by flashing MycroPython into it.

- Download the [latest .uf2 version](https://micropython.org/download/RPI_PICO_W/) of MycroPython for the Pico W. You don't need to do anything with this file, so no point in trying to open it.
- While holding the `bootsel` button the the Pico, plug it in into your computer via the USB cable. The `bootsel`button is the white button on top of the Pico. There is only one button so you can't miss it.
- If your computer recognices the Pico as a storage device, then you have succeeded.
- Drag and drop the .uf2 file we downloaded earlier into the storage space of the Pico.
- Want until the Pico automatically disconnects.
- Done! Now you should be able to directly write MycroPython code directly into the Pico using PyMakr.

<u>Extra steps needed for the computer?</u>
Since this project is very light, no extra installation more than the ones mentioned above are needed. 

### Putting everything together

During the development stage, the solderless breadboard is used to prove the concept. Bear in mind that for a final implementation, it would be better to use a perfboard and an appropriate enclosure to protect and shield the components more effectively.

*The circuit*
![Ultrasonic_Sensor_bb](https://hackmd.io/_uploads/SkH_GXeP0.png)

The ultrasonic sensor has 4 pins, which are connected as follows:
1. VCC is connected VSYS
2. TRIG is connected to GPIO26
3. ECHO is connected to GPIO27
4. GND is connected GND

It is important that VCC is connected to VSYS, since the sensor needs 5.0V to operate. With the components all connected together, the circuit is complete.

### Platform

The platform of my choosing was Adafruit IO, using MQTT and Webhooks. It’s a free cloud-based platform that is very beginner-friendly, with a dashboard to visualize data. It’s also very easy to integrate Discord through webhooks, so it was a clear choice. One limitation is that Adafruit only allows 30 data points per minute, but for our purposes, that is more than enough, since we can assume Rio won’t go in and out of his cat house every second.

By creating feeds for our data, we can visualize it on a created dashboard. This way, we are able to keep a log of when Rio is in his house and when he is not. Not only that, but since Discord can receive webhook messages, we can integrate that with Adafruit’s “Actions” and send a message whenever Rio enters or leaves his house. 


### The code


Besides `boot.py`, there's 4 more files that you need when it comes to the code, and making it work with Adafruit IO.
- `main.py`
This is the main file for your project. Here, you place the code that contains the necessary functions to make the sensor work as intended, including measurements, calculations, and other critical logic that is central to the project’s components.
- `keys.py`
Here your store your credentials, both for the Wi-Fi conneciton, and for the Adafruit IO server, which would have the key for your account, and the feed adress, to use with MQTT.
- `mqtt.py`
This file contains the code to handle the MQTT communication. MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol for small sensors and mobile devices.
- `wifiConnection.py`
To handle the Wi-Fi connetion of the Pico.
#### Read [this link](https://hackmd.io/@lnu-iot/r1yEtcs55) on how to setup `keys.py`, `mqtt.py` and `wifiConnection.py`

Now, given we have all the files above, we now can look into the code in `main.py`. There are 2 important parts of the code. Measuring the distance, and sending the status.

#### Measuring distance



```python=
def measure_distance():
    MAX_WAIT_TIME = 30000
    trigger.low()
    time.sleep_us(2)
    trigger.high()
    time.sleep_us(10)
    trigger.low()

    pulse_start = time.ticks_us()
    while echo.value() == 0:
        if time.ticks_diff(time.ticks_us(), pulse_start) > MAX_WAIT_TIME:
            return None
    pulse_start = time.ticks_us()

    while echo.value() == 1:
        if time.ticks_diff(time.ticks_us(), pulse_start) > MAX_WAIT_TIME:
            return None
    pulse_end = time.ticks_us()

    pulse_duration = time.ticks_diff(pulse_end, pulse_start)
    distance = (pulse_duration * 0.0343) / 2

    print(f"Pulse duration: {pulse_duration} us, Distance: {distance} cm")

    return distance
```

#### Sending status to Adafruit IO
```python=
...
    distance = measure_distance()

    if distance is not None:
        status = "0" if distance < 20 else "1"
        try:
            client.publish(topic=keys.AIO_DOORBELL_FEED, msg=status)
            print("DONE")
        ...
```

### Transmitting the data / connectivity

During the development phase, it’s reasonable to send data every 10 or so seconds, to be able to easily spot problems and troubleshoot if needed. But when deployed outside, the idea is to only transmit data when the sensor senses something within 20 cm, meaning that the cat is home.

The transmission is done through Wi-Fi, to Adafruit IO, using the MQTT protocol, as stated in *The Code* section above. Further, messages were forwarded to Discord using webhooks. Bear in mind that Adafruit IO Actions have a minimum limit of sending webhook messages every 15 minutes. This could be an issue during the development phase, where you might have to wait 15 minutes between tests. However, for practical purposes, it’s totally reasonable to send messages every 15 minutes, since we wouldn’t want our Discord to get spammed every minute just because Rio is still inside his house.
##### Wi-Fi Problems
One problem I encountered while setting up the Wi-Fi connection is the bandwidth on which the Pico operates. The Pico uses 2.4GHz, whereas I’ve only used 5GHz before. Even though my router gave the option to connect to the 2.4GHz, the credentials didn’t work. The solution was as follows:

1. Go to your router login page by entering `192.168.0.1` or `192.168.1.1` in the adressbar and press `Enter`.
2. Log in. If this is the first time you are encountering this window, then probably your username is `admin` with password `password`.
3. Go to the Wi-Fi settings
4. Change the credentials for the 2.4GHz bandwith.

This "resets" the 2.4Ghz, and now the Pico should be able to connect with the new credentials.


### Presenting the data


The dashboard is very simple, with 2 blocks. One is the toggle, that toggles from `Home` to `Away` depending on status. And the second one in a stepped line chart graph. This is because the sensor really one cares about 2 states, he´s either `Home` or `Away`, we´re not interested in how far he is from the ultrasonic sensor.

#### Away - Graph is indicating a logical 1
![Screenshot 2024-07-02 at 14.31.43](https://hackmd.io/_uploads/rJkBfwMw0.png)


#### Home - Graph indicating a logical 0
![Screenshot 2024-07-02 at 14.31.52](https://hackmd.io/_uploads/Hy0LMDfDR.png)


For demonstration purposes, the data is sampled here every 2 seconds. This is, of course, unreasonable in our practical scenario. In practice, anything more than 1 hour is not really practical because we’re interested in the moment. With the sensor updating every 15 minutes, that gives us enough data points to be sure of our measurement.

With this said, to gain greater insights into Rio’s behavior, it would be reasonable to sample and save the data for a 24-hour cycle. That way, we can learn more about his schedule and his preferences for coming home. Is it perhaps correlated to the sunrise or sunset?


#### Presenting on Discord

Now that we have a dashboard, we quickly realize that it’s very inconvenient to always be checking the dashboard to see if Rio’s back or not. Instead of us checking every time, we’d like to set up some kind of interrupt. This is where webhooks and Discord come into play.
Follow [these instructions](https://hackmd.io/@lnu-iot/r1yEtcs55) on how to set up webhooks and send messages to a Discord server. Now, every time Rio is in his cat house, we’ll get a notification on our server. This way, we can go about our day without worrying about having to check the dashboard every time.

![Screenshot 2024-07-03 at 07.59.25](https://hackmd.io/_uploads/rJ0auwGvA.png)


### Finalizing the design

Everything put together, this is the result. It should be said that this design is for prototyping only, since it wouldn’t last long outside without proper encasing. I think this project went very well, and I’m quite happy with the results.

The only downside is that right now it would need to be hooked up to a power outlet, since I haven’t made the calculations for battery usage. This could be a future improvement, as we could then hook it up to a rechargeable battery or even a power bank. That would make our project even more compact. Then, when the battery dies, we can create a webhook message to react when the feed is no longer updated, reminding us to check the batteries.


![IMG_1152-min](https://hackmd.io/_uploads/ByNU0wGPR.jpg)


---
