Acrome-SMD Docs
All Acrome ProductsReferencesBlogCase StudiesContact Us
  • ACROME SMD
  • Electronics
    • 🔴SMD Red
      • Troubleshooting Guide
    • 🔵SMD Blue
    • 🟢SMD Green
    • Gateway Modules
      • Arduino Gateway Module
      • USB Gateway Module
    • Electrical Motors
      • Brushed DC Motors (BDC)
      • Stepper DC Motors (SDC)
      • Brushless DC Motor (BLDC)
      • Linear Actuator with Feedback – 75 lbs
    • Add-on Modules
      • Ambient Light Sensor Module
      • Button Module
      • Buzzer Module
      • IMU Module
      • Joystick Module
      • Potentiometer Module
      • Reflectance Sensor Module
      • RGB LED Module
      • Servo Module
      • Ultrasonic Distance Sensor Module
  • SMD Kits
    • Starter Kit
      • What You Can Build
    • Education Kit
      • What You Can Build
    • Motion Kit
      • What You Can Build
  • Software
    • Libraries
      • Python Library
      • Arduino Library
      • Java Library
      • Matlab Library
    • SMD UI
    • SMD Blockly
      • Introducing Customized Blockly Blocks
  • SMD Applications
    • Basics
      • Blink
      • Action - Reaction
      • Autonomous Lighting
      • Smart Doorbell
      • Security System
      • Distance Buzzer Warning
      • Distance Auto Stop
      • Smart Light Control
    • Interactive
      • Automatic Trash Bin
      • Radar
      • Chrome Dino Game Player
      • Play Chrome Dino Game With Joystick
      • Snake Game With Joystick
      • Pan-Tilt with Joystick Module
      • Joystick Mouse Control
      • Rev Up the Engine
      • Motor Rotation Based on Turn Input Value
      • Basic Motor Speed Control Application
      • Basic Motor Control Application Using PWM Input
      • Basic Motor Position Control Application
      • Basic Motor Torque Control Application
      • Motor Rotation Based on Joystick Counting
    • Robotics
      • Differential Robot Projects
      • Mouse Cursor Tracker Motion Robot
      • Waypoint tracker robot
      • Braitenberg Robot
      • Line-Follower Robot
      • Teleoperation Robot
      • Obstacle Avoidance Robot
      • ESP32 Wireless Controlled Mobile Robot
  • AI
    • Object Tracking Robot
    • Groq Chatbot-Controlled Robot
  • ROS
    • Teleoperation Robot with ROS
  • Mechanics
    • Building Set
      • Plates
        • 2x2 Plate Package
        • 2x3 120° Plate Package
        • 3x3 Plate Package
        • 3x5 Plate Package
        • 3x9 Plate Package
        • 11x19 Plate
        • 9x19 Plate
        • 5x19 Plate
        • 3x19 Plate
        • 9x11 Plate
        • 5x13 Plate
      • Joints
        • 60° Joint Package
        • 90° Joint Package
        • 120° Joint Package
        • Slot Joint M2 Package
        • Slot Joint M3 Package
        • U Joint Package
      • Mounts
        • Add-on Mount Package
        • Motor L Mount Package
        • Pan-Tilt Package
      • Wheels
        • Ball Wheel Package
        • Caster Wheel Package
        • Wheel Package
      • Cables
        • Power Cable 10 cm Package
        • Power Cable 20 cm Package
        • Power Cable 35 cm Package
        • RJ-11 Cable 7.5 cm Package
        • RJ-11 Cable 20 cm Package
        • RJ-11 Cable 35 cm Package
        • RJ-45 Cable 7.5 cm Package
        • RJ-45 Cable 20 cm Package
        • RJ-45 Cable 35 cm Package
      • Fasteners
        • M2x5 Allen Hex Screw Package
        • M3x6 Allen Hex Screw Package
        • M3x8 Allen Hex Screw Package
        • M3 Hex Nut Package
  • Help
    • Manual
    • Shops
    • Reach Us
Powered by GitBook
On this page
  • Step 1: Hardware & Software Overview
  • Step 2: Assemble
  • Step 3: Run & Test
  • Codes
  1. SMD Applications
  2. Basics

Distance Buzzer Warning

PreviousSecurity SystemNextDistance Auto Stop

Last updated 2 months ago

This project centers around creating a distance-based feedback system using the ACROME platform. The system incorporates a , , and a 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 and provide visual and auditory signals, respectively, based on the proximity of the object to the sensor.

About Tools and Materials:

()

()

()

()

()

()

Step 1: Hardware & Software Overview

Key Components:

  1. The acts as the communication hub, connecting and controlling the, , and . It processes sensor data and translates it into corresponding and feedback, ensuring that the system functions in real-time.

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

  3. The 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. The 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 and Feedback The system defines three key distance ranges: far, medium, and near. These ranges are associated with different colors and 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 continuously measures the object’s proximity, sending this data to the . The system processes this information and updates the lights and 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 and 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 , color, and 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

    • Make sure that the SMD is powered and all connections are correct

Project Wiring Diagram

Step 3: Run & Test

  • 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.

Codes

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

Connect the SMD to the PC or Arduino board using or .

Connect , and to the SMD using an RJ-45 cable.

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

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

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

Smart Motion Device (SMD)
distance sensor
RGB LED lights
buzzer
RGB lights
buzzer
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
SMD (Smart Motion Device)
SMD
distance sensor
RGB lights
buzzer
RGB
buzzer
Ultrasonic Distance Sensor
distance sensor
SMD
RGB LED Module
RGB LED Module
Buzzer Module
buzzer module
RGB
Buzzer
RGB
buzzer
distance sensor
SMD
RGB
buzzer
LED
buzzer
distance
RGB
buzzer
USB Gateway Module
Arduino Gateway Module
RGB LED Module
Ultrasonic Distance Sensor
Buzzer Module
distance sensor,
RGB LED
buzzer
ACROME SMD
distance sensor
RGB lights
buzzer
SMD