# Smart Doorbell

The Smart Doorbell project allows the user to interact with environment with both input and output modules. The Ultrasonic Distance Sensor Module is used to detect if there is a person or a hand in front of the doorbell. If anything is near it, it detects and sends a feedback to script, allowing the user to play a sound with a buzzer.

**About Tools and Materials:**

[SMD Red](https://docs.acrome.net/electronics/smd-red) ([Purchase Here](https://www.robotshop.com/products/acrome-smd-red-smart-brushed-motor-driver-with-speed-position-and-current-control-modes))

[SMD USB Gateway](https://docs.acrome.net/electronics/gateway-modules/usb-gateway-module) ([Purchase Here](https://www.robotshop.com/products/acrome-usb-gateway-module-acrome-smd-products))

[Arduino Gateway Module](https://docs.acrome.net/electronics/gateway-modules/arduino-gateway-module) ([Purchase Here](https://www.robotshop.com/products/acrome-arduino-gateway-shield-module-acrome-smd-products))

[Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module) ([Purchase Here](https://www.robotshop.com/products/acrome-buzzer-sound-add-on-module-acrome-smd-products))

[Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module) ([Purchase Here](https://www.robotshop.com/products/acrome-ultrasonic-distance-sensor-add-on-module-acrome-smd-products))

## **Step 1: Hardware & Software Overview**

**Project Key Components**

1. [**SMD**](https://docs.acrome.net/electronics/smd-red)

   The SMD acts as a bridge between the script and the modules. It is responsible for interpreting the commands sent by the script and translating them into actions that read input from the [Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module) and play an alert sound with the [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module).
2. [**Buzzer Module**](https://docs.acrome.net/electronics/add-on-modules/buzzer-module)

   The [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module) is connected to the system for the most crucial role for the application, that is alerting the user when something is nearby.
3. [**Ultrasonic Distance Sensor Module**](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module)

   The [Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module) is used to detect if anything is nearby and if there is, how many centimeters away.
4. [**SMD Libraries**](https://docs.acrome.net/software/libraries)

   The SMD library is at the heart of the application. It communicates with the SMD using a specific communication protocol, sending commands to read the [Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module) and play an alert sound with the [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module).

**Project Key Features**

* **Proximity-Based Activation**

  The project uses the module with the HC-SR04 to detect the surroundings via ultrasonic sound waves. It makes a great way to understand how physics of sound works and also see that it is a way of interacting with environment with such an input sensor.
* **Adjustable Sensitivity**

  The user can change the sensivity of the distance check, customizing it to be more sensitive or unresponsive to near surroundings.
* **Real-time Monitoring**

  The script can easily provide the real-time distance monitoring if the user add a simple line. It enhances the code and gives more opportunity to monitor the surroundings.

## **Step 2: Assemble**

**Getting Started**

1. **Hardware Setup**
   * Connect the SMD to the PC or Arduino board using [USB Gateway Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/gateway-modules/usb-gateway-module) or [Arduino Gateway Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/gateway-modules/arduino-gateway-module).
   * Connect the [Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module) and the [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module) to the SMD using an RJ-45 cable.
   * Make sure that the SMD is powered and all connections are correct.

#### Project Wiring Diagram

<figure><img src="https://1077748559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LuxEcL3mxZNc5Aa92N6%2Fuploads%2FvUUb9z6VJSADMvsFw6ks%2Fsmart%20doorbell1.png?alt=media&#x26;token=9e9b6eb8-5229-4d52-9106-bc0acae3fa08" alt=""><figcaption></figcaption></figure>

## Step 3: Run & Test

1. **Run the Script**
   * Run the script on your computer. This will establish communication with the SMD and initiate control of the [Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module) and the [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module).
2. **Observe Buzzer Activation**
   * Use an object or a hand to trigger the [Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module), if it will detect an obstacle in the specified range, the script will send a signal to the [Buzzer Module](https://docs.acrome.net/electronics/add-on-modules/buzzer-module) to alert the user.

## Codes

{% tabs %}
{% tab title="Python Code" %}
{% code lineNumbers="true" %}

```python
from serial.tools.list_ports import comports
from platform import system
from smd.red import *

baudrate = 115200          # Baud rate of communication
ID = 0                     # ID of the SMD
buzzer_module_id = 5       # ID of the buzzer module
distance_module_id = 1     # ID of the ultrasonic distance sensor module


def USB_Port():
    """
    Scans and identifies a compatible USB port for the current operating system.

    Returns:
        str: The detected USB port or None if no suitable port is found.
    """
    # Get a list of available ports
    ports = list(comports())
    
    # Known USB port names for different operating systems
    usb_names = {
        "Windows": ["USB Serial Port"],  # Names specific to Windows
        "Linux": ["/dev/ttyUSB"],        # Names specific to Linux
        "Darwin": [                      # Names specific to macOS
            "/dev/tty.usbserial",
            "/dev/tty.usbmodem",
            "/dev/tty.SLAB_USBtoUART",
            "/dev/tty.wchusbserial",
            "/dev/cu.usbserial",
        ]
    }

    # Detect the operating system
    os_name = system()
    print(f"Operating System: {os_name}")

    if ports:
        for port in ports:
            # Check if the port matches any known USB names
            if any(name in port.device or name in port.description for name in usb_names.get(os_name, [])):
                print(f"USB device detected on port: {port.device}")
                return port.device  # Return the first matching port
        # If no suitable port is found, print the list of available ports
        print("No suitable USB device found. Available ports:")
        for port in ports:
            print(f"Port: {port.device}, Description: {port.description}, HWID: {port.hwid}")
    else:
        print("No ports detected!")
    return None


try:
    # Find a valid serial port
    SerialPort = USB_Port()
    if not SerialPort:
        raise Exception("No compatible USB port found. Please check your connection.")

    print(f"Using serial port: {SerialPort}")

    # Initialize the SMD module
    master = Master(SerialPort, baudrate)       # Defines the USB gateway module
    master.attach(Red(ID))                      # Gives access to the SMD of specified ID
    master.scan_modules(ID)                     # Scans and identifies the modules connected to the SMD

    # Main loop
    while True:
        # Get distance data from the ultrasonic sensor
        distance = master.get_distance(ID, distance_module_id)  # Variable to store the distance data
        print(f"Distance: {distance} cm")                      # Print the value to observe

        if distance < 15:
            # Set the buzzer frequency to 600 Hz
            master.set_buzzer(ID, buzzer_module_id, 600)        # Number corresponds to the frequency of the buzzer
        else:
            # Turn off the buzzer
            master.set_buzzer(ID, buzzer_module_id, 0)          # Sets the buzzer frequency to 0

except Exception as e:
    print(f"Error: {e}")
```

{% endcode %}
{% endtab %}

{% tab title="Arduino Code" %}
{% code lineNumbers="true" %}

```cpp
#include <Acrome-SMD.h>

#define ID        0           // ID of the SMD
#define BAUDRATE  115200      // Baud rate of the communication

Red master(ID, Serial, BAUDRATE);       // Defines the Arduino gateway module

int buzzer_module_id = 1;               // ID of the buzzer module
int distance_module_id = 1;             // ID of the ultrasonic distance sensor module

int distance = 0;                       // Variable to store the distance data

void setup() {
    master.begin();                     // Starts the communication
    master.scanModules();               // Scans for the connected modules
}

void loop() {
    distance = master.getDistance(distance_module_id);      // Getting the distance data and storing it
    
    if (distance < 15) {
        master.setBuzzer(buzzer_module_id, 600);            // Number is correspond to the frequency of the buzzer
    }

    else {
        master.setBuzzer(buzzer_module_id, 0);              // Sets the buzzer frequency to 0, meaning turning the buzzer off
    }
}

```

{% endcode %}
{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.acrome.net/smd-applications/basics/smart-doorbell.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
