# Distance Buzzer Warning

This project centers around creating a distance-based feedback system using the ACROME [Smart Motion Device (SMD)](/electronics/smd-red.md) platform. The system incorporates a [distance sensor](/electronics/add-on-modules/ultrasonic-distance-sensor-module.md), [RGB LED lights](/electronics/add-on-modules/rgb-led-module.md), and a [buzzer ](/electronics/add-on-modules/buzzer-module.md)to provide real-time feedback based on the distance of an object from the sensor. The system also includes a graphical user interface (GUI) for users to monitor the sensor readings and adjust distance settings. The [RGB lights](/electronics/add-on-modules/rgb-led-module.md) and [buzzer](/electronics/add-on-modules/buzzer-module.md) provide visual and auditory signals, respectively, based on the proximity of the object to the sensor.

**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](/electronics/gateway-modules/arduino-gateway-module.md) ([Purchase Here](https://www.robotshop.com/products/acrome-arduino-gateway-shield-module-acrome-smd-products))

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

[RGB LED Module](/electronics/add-on-modules/rgb-led-module.md) ([Purchase Here](https://www.robotshop.com/products/acrome-rgb-led-add-on-module-acrome-smd-products))

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

## **Step 1: Hardware & Software Overview** <a href="#step-1-hardware-and-software-overview" id="step-1-hardware-and-software-overview"></a>

**Key Components:**

1. [SMD (Smart Motion Device) ](/electronics/smd-red.md)\
   The [SMD ](/electronics/smd-red.md)acts as the communication hub, connecting and controlling the[ distance sensor](/electronics/add-on-modules/ultrasonic-distance-sensor-module.md), [RGB lights](/electronics/add-on-modules/rgb-led-module.md), and [buzzer](/electronics/add-on-modules/buzzer-module.md). It processes sensor data and translates it into corresponding [RGB](/electronics/add-on-modules/rgb-led-module.md) and [buzzer](/electronics/add-on-modules/buzzer-module.md) feedback, ensuring that the system functions in real-time.
2. [Ultrasonic Distance Sensor](/electronics/add-on-modules/ultrasonic-distance-sensor-module.md) \
   The [distance sensor](/electronics/add-on-modules/ultrasonic-distance-sensor-module.md) measures the distance between itself and nearby objects. This data is continuously sent to the [SMD](/electronics/smd-red.md), which then determines the appropriate feedback to provide based on predefined distance thresholds.
3. [RGB LED Module ](/electronics/add-on-modules/rgb-led-module.md)\
   The [RGB LED Module](/electronics/add-on-modules/rgb-led-module.md) displays different colors depending on the distance between the sensor and the object. Colors such as green, yellow, and red are used to indicate different proximity ranges, providing users with an intuitive visual cue for the distance.
4. [Buzzer Module](/electronics/add-on-modules/buzzer-module.md)\
   The [buzzer module](/electronics/add-on-modules/buzzer-module.md) emits sound at varying frequencies based on the object's distance from the sensor. Lower frequencies indicate a larger distance, while higher frequencies signal closer proximity, adding an auditory layer to the feedback.

**Project Key Features:**

1. Distance-Based [RGB](/electronics/add-on-modules/rgb-led-module.md) and [Buzzer](/electronics/add-on-modules/buzzer-module.md) Feedback \
   The system defines three key distance ranges: far, medium, and near. These ranges are associated with different [RGB](/electronics/add-on-modules/rgb-led-module.md) colors and [buzzer ](/electronics/add-on-modules/buzzer-module.md)frequencies.
   1. Far Distance: When an object is far (above a certain threshold), the system shows a green LED and the buzzer is silent.&#x20;
   2. Medium Distance: As the object gets closer, the LED changes to yellow, and the buzzer emits a low-frequency sound.&#x20;
   3. Near Distance: For very close objects, the LED turns red, and the buzzer produces a higher-pitched sound.
2. Real-Time Distance Monitoring \
   The [distance sensor](/electronics/add-on-modules/ultrasonic-distance-sensor-module.md) continuously measures the object’s proximity, sending this data to the [SMD](/electronics/smd-red.md). The system processes this information and updates the [RGB ](/electronics/add-on-modules/rgb-led-module.md)lights and [buzzer ](/electronics/add-on-modules/buzzer-module.md)in real time, ensuring immediate feedback for the user.
3. Customizable Distance Thresholds \
   Users can customize the distance thresholds through a user-friendly GUI. The GUI allows them to input values for the far and medium distance thresholds, which directly affect when the [LED](/electronics/add-on-modules/rgb-led-module.md) and [buzzer](/electronics/add-on-modules/buzzer-module.md) change states. These settings can be saved and loaded for future use.
4. User-Friendly Graphical Interface (GUI) \
   The GUI is created using Tkinter, providing real-time updates on [distance](/electronics/add-on-modules/ultrasonic-distance-sensor-module.md), [RGB ](/electronics/add-on-modules/rgb-led-module.md)color, and [buzzer ](/electronics/add-on-modules/buzzer-module.md)frequency. It also offers fields where users can enter new distance thresholds, ensuring that the system is flexible and adaptable to different environments or applications.
5. Threaded Operation for Continuous Monitoring \
   The system runs the distance monitoring process in a separate thread, allowing the GUI to remain responsive while the sensor continuously collects data. This ensures smooth operation even as the user interacts with the interface.

## **Step 2: Assemble** <a href="#step-2-assemble" id="step-2-assemble"></a>

**Getting Started**

1. **Hardware Setup**
   * Connect the SMD to the PC or Arduino board using [USB Gateway Module](https://docs.acrome.net/electronics/gateway-modules/usb-gateway-module) or [Arduino Gateway Module](https://docs.acrome.net/electronics/gateway-modules/arduino-gateway-module).
   * Connect [RGB LED Module](https://docs.acrome.net/electronics/add-on-modules/rgb-led-module), [Ultrasonic Distance Sensor](/electronics/add-on-modules/ultrasonic-distance-sensor-module.md) and [Buzzer Module](/electronics/add-on-modules/buzzer-module.md) 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="/files/2MTTu5gMPpOfIqMUdgUc" alt=""><figcaption></figcaption></figure>

## Step 3: Run & Test

* Distance Monitoring: The system continuously monitors the distance of an object using the [distance sensor,](/electronics/add-on-modules/ultrasonic-distance-sensor-module.md) and the data is processed in real time.&#x20;
* Feedback Response: Based on the object's distance, the [RGB LED](/electronics/add-on-modules/rgb-led-module.md) and [buzzer](/electronics/add-on-modules/buzzer-module.md) are activated with corresponding colors and frequencies.&#x20;
* GUI Interaction: The user can view the real-time data in the GUI and adjust the distance thresholds for the far and medium ranges.&#x20;
* Threshold Customization: Users can input new values for the distance thresholds, apply them, and save these settings for future use.

## Codes

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

```python
import keyboard
from smd.red import *
import time
import tkinter as tk
from threading import Thread
import json
import os
from serial.tools.list_ports import comports
from platform import system
import logging


# Serial Communication Settings
baudrate = 115200            # Baud rate of communication
module_id = 0                # ID of the SMD module
distance_sensor_id = 1       # ID of the distance sensor module
rgb_led_id = 5               # ID of the RGB LED module
buzzer_module_id = 5         # ID of the buzzer module


# Constants for Distance and Colors
FAR_DISTANCE = 50           # Threshold for far distance
MEDIUM_DISTANCE = 20        # Threshold for medium distance
GREEN = (0, 255, 0)         # RGB color for far distance
YELLOW = (255, 255, 0)      # RGB color for medium distance
RED = (255, 0, 0)           # RGB color for near distance


# Logging Configuration
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


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.
    """
    ports = list(comports())

    usb_names = {
        "Windows": ["USB Serial Port"],
        "Linux": ["/dev/ttyUSB"],
        "Darwin": [
            "/dev/tty.usbserial", "/dev/tty.usbmodem",
            "/dev/tty.SLAB_USBtoUART", "/dev/tty.wchusbserial",
            "/dev/cu.usbserial", "/dev/cu.usbmodem",
            "/dev/cu.SLAB_USBtoUART", "/dev/cu.wchusbserial",
        ]
    }

    os_name = system()
    print(f"Operating System: {os_name}")

    if ports:
        for port in ports:
            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
        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


# Initialize the USB port and SMD module
SerialPort = USB_Port()
if not SerialPort:
    raise Exception("No compatible USB port found. Please check your connection.")

master = Master(SerialPort, baudrate)
master.attach(Red(module_id))
print("Connected Modules:", master.scan_modules(module_id))


# Functions for Distance Settings
def load_settings():
    """
    Loads distance settings from 'settings.json'. If the file doesn't exist, default values are used.
    """
    global FAR_DISTANCE, MEDIUM_DISTANCE
    if os.path.exists("settings.json"):
        with open("settings.json", "r") as f:
            settings = json.load(f)
            FAR_DISTANCE = settings.get("FAR_DISTANCE", FAR_DISTANCE)
            MEDIUM_DISTANCE = settings.get("MEDIUM_DISTANCE", MEDIUM_DISTANCE)
    else:
        logger.info("Settings file not found. Using default values.")


def save_settings():
    """
    Saves the current distance settings to 'settings.json'.
    """
    settings = {
        "FAR_DISTANCE": FAR_DISTANCE,
        "MEDIUM_DISTANCE": MEDIUM_DISTANCE
    }
    with open("settings.json", "w") as f:
        json.dump(settings, f, indent=4)
    logger.info("Settings saved to settings.json")


# Load distance settings at startup
load_settings()


# GUI Setup
window = tk.Tk()
window.title("Distance Sensor Feedback")
window.geometry("400x300")


# GUI Labels
distance_label = tk.Label(window, text="Distance: ", font=("Helvetica", 14))
distance_label.pack(pady=10)

rgb_label = tk.Label(window, text="RGB Color: ", font=("Helvetica", 14))
rgb_label.pack(pady=10)

buzzer_label = tk.Label(window, text="Buzzer Frequency: ", font=("Helvetica", 14))
buzzer_label.pack(pady=10)


def update_gui(distance, rgb, buzzer_freq):
    """
    Updates the GUI labels and background color based on the sensor readings.

    Args:
        distance (float): The current distance measured by the sensor, in cm.
        rgb (tuple): RGB color tuple (R, G, B).
        buzzer_freq (int): Buzzer frequency in Hz.
    """
    distance_label.config(text=f"Distance: {distance:.2f} cm")
    rgb_label.config(text=f"RGB Color: R={rgb[0]}, G={rgb[1]}, B={rgb[2]}")
    buzzer_label.config(text=f"Buzzer Frequency: {buzzer_freq} Hz")
    window.configure(bg=f'#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}')


# Distance Monitoring and Control
def monitor_distance():
    """
    Continuously monitors the distance sensor and updates RGB color and buzzer based on distance thresholds.
    """
    global FAR_DISTANCE, MEDIUM_DISTANCE
    try:
        while True:
            distance = master.get_distance(module_id, distance_sensor_id)
            logger.info(f"Distance: {distance} cm")

            if distance > FAR_DISTANCE:
                rgb, buzzer_freq = GREEN, 0
            elif MEDIUM_DISTANCE < distance <= FAR_DISTANCE:
                rgb, buzzer_freq = YELLOW, 500
            else:
                rgb, buzzer_freq = RED, 1000

            master.set_rgb(module_id, 1, *rgb)
            master.set_buzzer(module_id, 1, buzzer_freq)
            update_gui(distance, rgb, buzzer_freq)

            if keyboard.is_pressed('q'):
                logger.info("Exiting...")
                master.set_rgb(module_id, 1, 0, 0, 0)
                master.set_buzzer(module_id, 1, 0)
                window.destroy()
                break

            time.sleep(0.1)
    except Exception as e:
        logger.error(f"Error in monitor_distance: {e}")


# Start Distance Monitoring in a Thread
monitor_thread = Thread(target=monitor_distance, daemon=True)
monitor_thread.start()

# Run the GUI Main Loop
window.mainloop()
```

{% endcode %}
{% endtab %}

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

```cpp
#include <Acrome-SMD.h>  // Include the ACROME SMD library

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

Red master(ID, Serial, BAUDRATE);    // Define the main module

int distance_module_id = 1;          // ID of the distance sensor module
int rgb_module_id = 5;               // ID of the RGB LED module
int buzzer_module_id = 5;            // ID of the buzzer module

// Distance thresholds
int FAR_DISTANCE = 50;               // Far distance threshold
int MEDIUM_DISTANCE = 20;            // Medium distance threshold

void setup() {
    Serial.begin(115200);            // Initialize serial communication
    master.begin();                  // Start the ACROME-SMD main module
    master.scanModules();            // Scan and detect connected modules
}

void loop() {
    int distance = master.getDistance(distance_module_id);  // Get the distance value

    // Control RGB LED and buzzer based on the detected distance
    if (distance > FAR_DISTANCE) {
        // If the object is far, turn on green LED and keep the buzzer off
        master.setRGB(rgb_module_id, 0, 255, 0);           // Set LED to green
        master.setBuzzer(buzzer_module_id, 0);             // Turn off the buzzer
    } 
    else if (distance > MEDIUM_DISTANCE) {
        // If the object is at a medium distance, turn on yellow LED and set a low-frequency buzzer sound
        master.setRGB(rgb_module_id, 255, 255, 0);         // Set LED to yellow
        master.setBuzzer(buzzer_module_id, 500);           // Set buzzer frequency to 500 Hz (low frequency)
    } 
    else {
        // If the object is near, turn on red LED and set a high-frequency buzzer sound
        master.setRGB(rgb_module_id, 255, 0, 0);           // Set LED to red
        master.setBuzzer(buzzer_module_id, 1000);          // Set buzzer frequency to 1000 Hz (high frequency)
    }

    delay(500);  // Wait for 0.5 seconds before the next loop iteration
}
```

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

**Conclusion:** \
This project showcases the versatility of the [ACROME SMD](/electronics/smd-red.md) platform in integrating a [distance sensor](/electronics/add-on-modules/ultrasonic-distance-sensor-module.md) with [RGB lights](/electronics/add-on-modules/rgb-led-module.md) and a [buzzer](/electronics/add-on-modules/buzzer-module.md) to provide real-time feedback. The combination of distance-based RGB feedback, customizable thresholds, and a user-friendly GUI makes the system both practical and adaptable. Whether used for safety, automation, or interactive installations, this project highlights the potential of the [SMD](/electronics/smd-red.md) platform in creating dynamic, sensor-driven environments.


---

# 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/distance-buzzer-warning.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.
