Distance Buzzer Warning

This project centers around creating a distance-based feedback system using the ACROME Smart Motion Device (SMD) platform. The system incorporates a distance sensor, RGB LED lights, and a buzzer 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 and buzzer provide visual and auditory signals, respectively, based on the proximity of the object to the sensor.

About Tools and Materials:

SMD Red (Purchase Here)

SMD USB Gateway (Purchase Here)

Arduino Gateway Module (Purchase Here)

Ultrasonic Distance Sensor (Purchase Here)

RGB LED Module (Purchase Here)

Buzzer Module (Purchase Here)

Step 1: Hardware & Software Overview

Key Components:

  1. SMD (Smart Motion Device) The SMD acts as the communication hub, connecting and controlling the distance sensor, RGB lights, and buzzer. It processes sensor data and translates it into corresponding RGB and buzzer feedback, ensuring that the system functions in real-time.

  2. Ultrasonic Distance Sensor The distance sensor measures the distance between itself and nearby objects. This data is continuously sent to the SMD, which then determines the appropriate feedback to provide based on predefined distance thresholds.

  3. RGB LED Module The RGB LED Module 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 The buzzer module 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 and Buzzer Feedback The system defines three key distance ranges: far, medium, and near. These ranges are associated with different RGB colors and buzzer frequencies.

    1. Far Distance: When an object is far (above a certain threshold), the system shows a green LED and the buzzer is silent.

    2. Medium Distance: As the object gets closer, the LED changes to yellow, and the buzzer emits a low-frequency sound.

    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 continuously measures the object’s proximity, sending this data to the SMD. The system processes this information and updates the RGB lights and buzzer 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 and buzzer 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, RGB color, and buzzer 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

Getting Started

  1. Hardware Setup

Project Wiring Diagram

Step 3: Run & Test

  • Distance Monitoring: The system continuously monitors the distance of an object using the distance sensor, and the data is processed in real time.

  • Feedback Response: Based on the object's distance, the RGB LED and buzzer are activated with corresponding colors and frequencies.

  • GUI Interaction: The user can view the real-time data in the GUI and adjust the distance thresholds for the far and medium ranges.

  • Threshold Customization: Users can input new values for the distance thresholds, apply them, and save these settings for future use.

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()

Conclusion: This project showcases the versatility of the ACROME SMD platform in integrating a distance sensor with RGB lights and a buzzer 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 platform in creating dynamic, sensor-driven environments.

Last updated