# Automatic Trash Bin

The Automatic Trash Bin project demonstrates how robotics can simplify everyday tasks, integrating innovative technology into real-life applications. This system utilizes a 100 RPM BDC Motor with Encoder alongside an [**Ultrasonic Distance Sensor Module**](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module) to automate the opening and closing of a trash bin lid. By detecting the presence of a hand or a nearby object, the ultrasonic sensor sends a signal to the motor, which precisely controls the lid’s movement.

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

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

[BDC Motor](https://docs.acrome.net/electronics/electrical-motors/brushed-dc-motors-bdc) ([Purchase Here](https://www.robotshop.com/products/acrome-12v-brushed-dc-motor-with-built-in-encoder-100-rpm-speed))

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

**Project Key Components**

* [**SMD**](https://acrome.gitbook.io/acrome-smd-docs/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 actuate the DC motor precisely.
* [BDC Motor](https://docs.acrome.net/electronics/electrical-motors/brushed-dc-motors-bdc)&#x20;

  The 100 RPM BDC Motor with Encoder is the actuator of the system. It moves the trash bin lid up.
* [**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 the approaching person or the hand.
* [**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 actuate the BDC motor.

**Project Key Features**

* **Hands-free Operation**

  The [Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module) makes it easy in terms of hygiene and automation, automatic trash bin lid project makes life easier.&#x20;
* **Adjustable Sensitivity**

  The script include parameters that can be edited by the user to change the sensivity of the system, it helps to avoid unwanted activations of the BDC motor.

## **Step 2: Assemble**

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 100 RPM BDC Motor with Encoder to the motor ports of the SMD and the [Ultrasonic Distance Sensor Module](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-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%2Fqn3ChiONSb0to2wBZEMX%2FAutomatic%20Trash%20Bin1.png?alt=media&#x26;token=3adfc4ef-332b-4c8b-92ba-4de9baa591b2" alt=""><figcaption></figcaption></figure>

## **Step 3: Run & Test**

1. **Run the Script**
   * Execute the script, initiating the Automatic Trash Bin application.
   * Approach the trash bin, and observe how the lid opens automatically when the user is in close proximity.
2. **Enhance and Customize**
   * Fine-tune the sensitivity parameters in the script based on the user feedback and the specific requirements of the environment.
   * Explore additional features, such as automatic lid closing after a specified period or incorporating status indicators.

## Codes

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

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

baudrate = 115200           # Baud rate of communication
ID = 0                      # ID of the SMD
distance_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

    # Motor and control configuration
    master.set_shaft_rpm(ID, 100)                               # Sets the RPM value of the motor
    master.set_shaft_cpr(ID, 6533)                              # Sets the CPR value of the motor
    master.set_operation_mode(ID, 1)                            # Sets the operation mode to 'Position Control'
    master.set_control_parameters_position(ID, 10, 0, 50)       # Sets the PID parameters, can be auto-tuned instead
    master.enable_torque(ID, 1)                                 # Enables the motor to spin if any command says so

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

        if distance < 10:                                       # If it sees a person nearby 10 cm
            master.set_position(ID, 1000)                       # Motor lifts the trash bin lid
            time.sleep(2)                                       # Delay before putting the lid down
        else:
            master.set_position(ID, 0)                          # Motor puts the lid down

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 distance_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

    master.setMotorRPM(100);        // Sets the RPM value of the motor
    master.setMotorCPR(6533);       // Sets the CPR value of the motor

    master.setOperationMode(PositionControl);                           // Sets the operation mode to 'Position Control'
    master.setControlParameters(PositionControl, 10, 0, 50, 0, 0);       // Sets the PID parameters, can be auto-tuned instead
    master.torqueEnable(1);                                             // Enables the motor to spin if any command say so
}

void loop() {
    distance = master.getLight(distance_id);        // Getting the distance data and storing it
    
    if (distance < 10) {                            // If it sees a person nearby 10 cm
        master.setpoint(PositionControl, 1000);     // Motor lifts the trash bin lid, change position value if it doesn't lift
        delay(2000);
    }

    else {
        master.setpoint(PositionControl, 0);        // Motor puts the lid down
    }
}

```

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