# Radar

The Radar project is a comprehensive project that combines software, hardware and mechanics of the SMD family. There are specially designed 3D parts for the mount system of the Ultrasonic Distance Sensor Module. The mount system and 100 RPM BDC Motor with Encoder work together to turn around the Ultrasonic Distance Sensor Module to have a radar-like working principle.

<figure><img src="https://1077748559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LuxEcL3mxZNc5Aa92N6%2Fuploads%2Fu6JXcaQJ03W0pyVZKr9l%2Fradar.gif?alt=media&#x26;token=22c8b7eb-b4d2-483e-a3c9-306ace5e71c8" alt=""><figcaption></figcaption></figure>

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

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

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

3D Printed Parts

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

**Project Key Components**

1. [**SMD**](https://docs.acrome.net/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://acrome.gitbook.io/acrome-smd-docs/electronics/add-on-modules/ultrasonic-distance-sensor-module) and meanwhile, actuate the motor for the continuous reading of the script.
2. [BDC Motor](https://docs.acrome.net/electronics/electrical-motors/brushed-dc-motors-bdc)

   The 100 RPM BDC Motor with Encoder is used to rotate the radar mechanism in a full circle. The user can precisely control the motor and get the position through the built-in encoder.
3. [**Ultrasonic Distance Sensor Module**](https://docs.acrome.net/electronics/add-on-modules/ultrasonic-distance-sensor-module)

   The Ultrasonic Distance Sensor Module measures the surroundings every cycle through its spin.&#x20;
4. **3D Printed Parts**

   Custom 3D printed parts allow the user to mount the Ultrasonic Distance Sensor Module on top of the BDC motor.
5. [**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://acrome.gitbook.io/acrome-smd-docs/electronics/add-on-modules/ultrasonic-distance-sensor-module) and actuate the BDC motor to spin the module around.

**Project Key Features**

* **Rotating Radar Scan**

  The rotation of the Ultrasonic Distance Sensor Module make the system seem like a geniune radar.
* **Real-time Distance Visualization**

  The script receives distance data continuously, allowing the user to visualize the data around a circle plot, just like a radar.

## **Step 2: Assemble**

**Getting Started**

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).
   * Mount the custom 3D printed mount parts on the BDC motor.
   * Connect the 100 RPM BDC Motor with Encoder to the motor ports of the SMD and the [Ultrasonic Distance Sensor Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/add-on-modules/ultrasonic-distance-sensor-module) to the SMD using an RJ-45 cable.
   * Mount the [Ultrasonic Distance Sensor Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/add-on-modules/ultrasonic-distance-sensor-module) on top of the motor mount parts
   * 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%2FphuXzMPDYCw74iVX8d2j%2FRadar1.png?alt=media&#x26;token=b1c1d52e-e702-449b-9917-7257f2d6ab12" alt=""><figcaption></figcaption></figure>

## Step 3: Run & Test

1. **Run the Application**
   * Execute the Python script, initiating the Radar application.
   * Observe the rotation of the [Ultrasonic Distance Sensor Module](https://acrome.gitbook.io/acrome-smd-docs/electronics/add-on-modules/ultrasonic-distance-sensor-module) in a full circle.
   * See the continuous data from the terminal.
2. **Experiment and Customize**
   * Experiment with different scanning speeds, put different objects near the radar.
   * Implement a plotting library and plot the data on a circle plot.

## Codes

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

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

baudrate = 115200          # Baud rate of communication
ID = 0                     # ID of the SMD
motor_module_id = 0        # ID of the motor module
distance_sensor_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
    master.scan_modules(ID)                     # Scans and identifies the modules connected to the SMD

    # Configure the motor module
    master.set_operation_mode(motor_module_id, 2)  # Set operation mode to 'Velocity Control'
    master.enable_torque(motor_module_id, True)    # Enable motor torque
    master.set_velocity(motor_module_id, 500)      # Set initial velocity
    master.set_shaft_rpm(motor_module_id, 100)     # Set RPM to 100
    master.set_shaft_cpr(motor_module_id, 6533)    # Set CPR (Counts Per Revolution)

    # Main loop
    while True:
        # Get distance data from the ultrasonic sensor
        distance = master.get_distance(ID, distance_sensor_id)  # Variable to store the distance data
        encoder_position = master.get_position(motor_module_id)  # Get motor position

        # Print the distance and position
        print(f"Distance: {distance} cm, Motor Position: {encoder_position}")

        # Control motor direction based on position
        if encoder_position > 9000:
            master.set_velocity(motor_module_id, -500)  # Reverse direction
        elif encoder_position < 0:
            master.set_velocity(motor_module_id, 500)   # Forward direction

        time.sleep(0.1)  # Delay for smooth operation

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
#define BAUDRATE   115200

Red master(ID, Serial, BAUDRATE);

void setup() {
    Serial.begin(BAUDRATE);
    master.begin();
    master.scanModules();

    // Motoru sıfırlayalım
    master.setOperationMode(2);
    master.setpoint(1,0);
    master.torqueEnable(1);
    master.setMotorRPM(100);
    master.setMotorCPR(6533);
    master.setControlParameters(1, 10, 1, 0, 0, 0);
    master.setpoint(2,500);
}

void loop() {
    int distance = master.getDistance(5);
    
    int encoder_counts = master.getPosition();
    
    Serial.print("Pozisyon (derece): ");
    Serial.print(encoder_counts);
    Serial.print(", Mesafe: ");
    Serial.println(distance);

    if (encoder_counts > 9000) {
        master.setpoint(2,-500);
    } else if (encoder_counts < 0) {
        master.setpoint(2,500);
    }
    
    delay(100);
}
```

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

#### Hardware Designs

{% file src="<https://1077748559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LuxEcL3mxZNc5Aa92N6%2Fuploads%2FoFF9rErhsIIwG9l6tAAy%2F3D%20Piece.STEP?alt=media&token=45511edd-b0ed-453b-9a7f-3357b751e6d4>" %}

{% file src="<https://1077748559-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LuxEcL3mxZNc5Aa92N6%2Fuploads%2FiOU4f0TSy507TuOpEyXs%2FAssembly.STEP?alt=media&token=98a9e919-ca74-416f-809c-292ce3f3db8f>" %}
