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
  • Key Features
  • Step 2: Assemble
  • Step 3: Run & Test
  • Codes
  • Conclusion
  1. SMD Applications
  2. Basics

Distance Auto Stop

PreviousDistance Buzzer WarningNextSmart Light Control

Last updated 1 month ago

This project showcases a dynamic motor control system utilizing the platform. The project integrates hardware, real-time processing, and dynamic scaling to achieve precision control. The goal is to create a motorized system where the speed decreases as the motor approaches an object and stops completely when it gets very close. This is achieved using distance measurements and velocity interpolation.

About Tools and Materials:

()

()

()

()

()

Step 1: Hardware & Software Overview

Project Key Components

  1. The platform serves as the control hub, interfacing with the motor and reading sensor data.

  2. A distance sensor is used to measure the object's position in real-time.

  3. The motor is controlled using velocity commands, allowing for smooth acceleration and deceleration.

Key Features

  1. Distance-Based Motor Control The motor dynamically adjusts its speed based on proximity.

  2. Smooth Interpolation The velocity decreases gradually instead of abrupt stops, ensuring smoother operation.

  3. Real-Time Feedback The system logs current distance and velocity values for monitoring.

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

  1. Run the Script

Codes

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


# Serial Communication Settings
baudrate = 115200           # Baud rate for communication
module_id = 0               # ID of the SMD module
distance_sensor_id = 1      # ID of the distance sensor module
motor_id = 0                # ID of the motor module


# Distance Thresholds and Motor Speed Settings
middle_distance = 20        # Medium distance threshold (cm)
near_distance = 5           # Close distance threshold (cm)
max_speed = 100             # Maximum motor speed


def detect_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 = detect_usb_port()
if SerialPort is None:
    print("No suitable USB port found.")
    exit(1)

master = Master(SerialPort, baudrate)
master.attach(Red(module_id))


# Motor Configuration
master.set_shaft_cpr(motor_id, 6533)  # Set encoder counts per revolution
master.set_shaft_rpm(motor_id, 100)   # Set maximum RPM
master.enable_torque(motor_id, 1)     # Enable motor torque


# Function for Speed Interpolation
def interpolate_speed(distance):
    """
    Calculates the motor speed based on distance using linear interpolation.

    Args:
        distance (float): The measured distance from the sensor.

    Returns:
        float: The calculated speed.
    """
    if distance < near_distance:
        return 0  # Stop the motor
    elif near_distance <= distance < middle_distance:
        return max(10, max_speed * (distance - near_distance) / (middle_distance - near_distance))  # Smooth acceleration
    else:
        return max_speed  # Full speed


# Main Control Loop
while True:
    distance = master.get_distance(module_id, distance_sensor_id)

    if distance is not None:
        speed = interpolate_speed(distance)
        master.set_duty_cycle(motor_id, speed)

        if speed == 0:
            print("Motor Stopped")
        elif speed == max_speed:
            print("Motor Running at Max Speed")
        else:
            print(f"Motor Running at Speed: {speed}")
#include <Acrome-SMD.h>
#define ID         0 
#define CPR        6533   
#define BAUDRATE   115200 

Red master(ID, Serial, BAUDRATE); 

void setup() {
  master.begin();
  master.torqueEnable(1);       
  Serial.begin(115200); 
}

void loop() {
  int distance = master.getDistance(1);
  Serial.print("Distance: ");
  Serial.println(distance);

  // Define velocity scaling parameters
  int maxVelocity = 1000;  // Maximum velocity 
  int minVelocity = 0;     // Minimum velocity
  int stopDistance = 20;   // Distance at which motor should start slowing down
  int fullStopDistance = 5; // Distance at which motor completely stops

  // Check if motor needs to slow down or stop
  int velocity;
  if (distance > stopDistance) {
    // Full speed if distance is greater than stop threshold
    velocity = maxVelocity;
  } else if (distance > fullStopDistance) {
    // Gradually reduce velocity as distance decreases
    velocity = map(distance, fullStopDistance, stopDistance, 0, maxVelocity);
  } else {
    // Completely stop the motor when very close
    velocity = 0;
  }

  // Set motor to velocity mode and set velocity
  master.setOperationMode(2);
  master.setpoint(2, velocity);

  // Small delay to prevent overwhelming the system
  delay(50);
}

Conclusion

Connect the to the PC or Arduino board using or .

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

Run the script on your computer. This will establish communication with the SMD and initiate control of the .

This project highlights the platform's versatility in creating advanced motor control systems. By combining real-time distance sensing with velocity interpolation, it provides a robust solution for a range of applications.

ACROME SMD
SMD Red
Purchase Here
SMD USB Gateway
Purchase Here
Arduino Gateway Module
Purchase Here
BDC Motor
Purchase Here
Ultrasonic Distance Sensor Module
Purchase Here
ACROME SMD Red Platform
ACROME SMD
Ultrasonic Distance Sensor
BDC Motor
SMD Red
USB Gateway Module
Arduino Gateway Module
Ultrasonic Distance Sensor
Ultrasonic Distance Sensor
ACROME SMD Red