# Motor Rotation Based on Joystick  Counting

This Python code demonstrates a joystick-controlled motor rotation system that enables a user to count joystick inputs and control the motor's rotations accordingly. The application uses a **USB-connected motor controller** to read joystick inputs and perform precise motor movements based on the input count. Below is a step-by-step explanation of the code.

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

[Joystick Module](https://docs.acrome.net/electronics/add-on-modules/joystick-module) ([Purchase Here](https://www.robotshop.com/products/acrome-joystick-2-axis-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** <a href="#step-1-hardware-and-software-overview" id="step-1-hardware-and-software-overview"></a>

**Key Components:**

1. [ACROME SMD](https://docs.acrome.net/electronics/smd-red)\
   The [ACROME SMD](https://docs.acrome.net/electronics/smd-red) acts as the communication hub between the [Joystick Module](https://docs.acrome.net/electronics/add-on-modules/joystick-module) and the computer. It collects [Joystick Module](https://docs.acrome.net/electronics/add-on-modules/joystick-module) data, processes user input, and translates it into mouse movements and clicks.
2. [Joystick Module](https://docs.acrome.net/electronics/add-on-modules/joystick-module)\
   The [Joystick Module](https://docs.acrome.net/electronics/add-on-modules/joystick-module) serves as the main input device. The user can move the [Joystick Module](https://docs.acrome.net/electronics/add-on-modules/joystick-module) to control the mouse pointer’s X and Y coordinates on the screen. Additionally, the [Joystick Module](https://docs.acrome.net/electronics/add-on-modules/joystick-module) button can be used to trigger mouse clicks.
3. [BDC Motor](https://docs.acrome.net/electronics/electrical-motors/brushed-dc-motors-bdc) \
   &#x20;The motor is controlled using velocity commands, allowing for smooth acceleration and deceleration.

#### **Project Features:**

* **Button Press Detection**: Reads the joystick button state from the motor controller.
* **Entering Counting Mode**: Holding the button for 5 seconds activates counting mode.
* **Incrementing the Counter**: In counting mode, pressing and releasing the button increases the counter.
* **Triggering Motor Rotation**: Holding the button for another 5 seconds rotates the motor according to the counter value.

## **Step 2: Assemble** <a href="#step-2-assemble" id="step-2-assemble"></a>

**Getting Started**

1. **Hardware Setup**
   * Connect the SMD to the PC or Arduino board using [USB Gateway Module](https://docs.acrome.net/electronics/gateway-modules/usb-gateway-module) .
   * Connect the [BDC Motor](https://docs.acrome.net/electronics/electrical-motors/brushed-dc-motors-bdc)  and the [Joystick Module](https://docs.acrome.net/electronics/add-on-modules/joystick-module) to the SMD using an RJ-45 cable.
   * Make sure that the SMD is powered and all connections are correct

#### **Project Wiring Diagram**

## Step 3: Run & Test

#### Run the Script

• Execute the script to initiate the Motor Rotation Based on Joystick Counting project.

• The script will automatically detect the USB port and establish communication with the SMD Master Controller.

• Move the joystick to control the motor’s rotation and observe the response.

#### Experience Joystick-Based Motor Control

• Move the joystick forward to rotate the motor clockwise (CW).

• Move the joystick backward to rotate the motor counterclockwise (CCW).

• Return the joystick to the center position to stop the motor.

• Observe how the motor speed and direction change dynamically based on joystick movement.

## Codes

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

```python
from smd.red import Master, Red
import time
from serial.tools.list_ports import comports
from platform import system

# Detect USB Port
def detect_usb_port():
    ports = list(comports())
    usb_names = {
        "Windows": ["USB Serial Port"],
        "Linux": ["/dev/ttyUSB"],
        "Darwin": ["/dev/tty.usbserial", "/dev/tty.usbmodem", "/dev/cu.usbserial"]
    }
    os_name = system()
    for port in ports:
        if any(name in port.device or name in port.description for name in usb_names.get(os_name, [])):
            return port.device
    return None

# Initialize SMD Red Connection
serial_port = detect_usb_port()
if not serial_port:
    print("No compatible USB port found.")
    exit(1)

master = Master(serial_port)
motor_id = 0
joystick_id = 5  # Joystick module ID

master.attach(Red(motor_id))
master.set_operation_mode(motor_id, 0)  # Set motor to PWM mode
master.enable_torque(motor_id, True)

# Control Motor with Joystick
def control_motor():
    while True:
        joystick_data = master.get_joystick(motor_id, joystick_id)
        if joystick_data is None:
            print("Joystick data could not be read.")
            time.sleep(0.1)
            continue

        x_axis, y_axis = joystick_data[0], joystick_data[1]

        # Convert joystick Y-axis input to PWM signal
        speed = int(abs(y_axis) * 100 / 100)  
        if y_axis > 0:
            master.set_duty_cycle(motor_id, speed)   # Move forward
        elif y_axis < 0:
            master.set_duty_cycle(motor_id, -speed)  # Move backward
        else:
            master.set_duty_cycle(motor_id, 0)       # Stop

        print(f"Joystick: X={x_axis}, Y={y_axis} | PWM: {speed}")
        time.sleep(0.05)

# Start Motor Control
control_motor()
```

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