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
  • Example Usage:
  • Codes
  1. SMD Applications
  2. Interactive

Motor Rotation Based on Turn Input Value

PreviousRev Up the EngineNextBasic Motor Speed Control Application

Last updated 1 month ago

This program demonstrates a simple motor control application using Python. The main objective of the script is to rotate a motor by a specific number of turns, which is determined by the user input. The motor's position is tracked, and it continues to rotate until the desired number of turns is achieved.

About Tools and Materials:

()

()

()

()

Step 1: Hardware & Software Overview

Project Key Components

  1. 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 and actuate the BDC motor, the and the .

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

Project Key Features

  • Establishes a connection with the SMD Red motor using the Master and Red classes from the smd.red library.

  • Allows users to specify the number of turns for the motor, using an encoder with a predefined steps-per-turn value.

  • Continuously monitors the motor’s position and stops it once the desired rotation is achieved.

  • Sets the motor velocity dynamically, starting with maximum speed and stopping precisely at the target position.

  • Designed to work efficiently within multi-threaded applications for real-time motor control.

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

Run the Script

  1. Execute the script to initiate the Motor Rotation Based on Turn Input Value project.

  2. Enter different turn values in the control interface to observe the motor behavior.

  3. Input a positive value to rotate the motor clockwise (CW).

  4. Input a negative value to rotate the motor counterclockwise (CCW).

  5. Input zero (0) to stop the motor.

  6. Observe how the motor speed dynamically adjusts based on the magnitude of the input value.

Customize and Experiment

• Modify input values in the script to control the speed and rotation direction.

• Experiment with different PWM signal ranges to fine-tune motor performance.

• Implement acceleration profiles to create smoother speed transitions.

• If using an encoder, integrate it for closed-loop control and precise motor positioning.

Example Usage:

When the program is executed, it will ask the user to input the number of turns:

Enter the number of turns: 5

After the user inputs the value (e.g., 5), the motor will rotate the equivalent number of turns. The program will print a message once the motor has completed the rotation:

It has been rotated as many times as the number of turns entered. Number of turns: 5

Codes

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

# Serial Communication Settings
baudrate = 115200  # Baud rate for communication
motor_id = 0       # Motor module ID
steps_per_turn = 6533  # Encoder counts per revolution

def detect_usb_port():
    """
    Detects and returns the correct USB port for communication.
    
    Returns:
        str: The detected USB port or None if no suitable port is found.
    """
    ports = list(comports())
    usb_names = {
        "Windows": ["USB Serial Port"],  # Windows-specific port names
        "Linux": ["/dev/ttyUSB"],        # Linux-specific port names
        "Darwin": [                      # macOS-specific port names
            "/dev/tty.usbserial",
            "/dev/tty.usbmodem",
            "/dev/tty.SLAB_USBtoUART",
            "/dev/tty.wchusbserial",
            "/dev/cu.usbserial",
        ]
    }
    
    os_name = system()  # Detect the operating system
    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  # Return the first matching port
    
    print("No suitable USB device found.")
    return None

# Initialize USB port and SMD module
serial_port = detect_usb_port()
if not serial_port:
    print("No compatible USB port found. Check your connection.")
    exit(1)

print(f"Using serial port: {serial_port}")

# Initialize SMD Master module and attach the motor
master = Master(serial_port, baudrate)
master.attach(Red(motor_id))

# Configure motor settings
master.set_operation_mode(motor_id, 2)  # Set motor to Velocity Control Mode
master.enable_torque(motor_id, True)  # Enable motor torque
master.set_shaft_rpm(motor_id, 100)  # Set motor RPM
master.set_shaft_cpr(motor_id, steps_per_turn)  # Set encoder CPR value

def rotate_motor(turns):
    """
    Rotates the motor by the specified number of turns.

    Args:
        turns (int): Number of turns the motor should rotate.
    """
    target_position = turns * steps_per_turn  # Calculate target encoder position
    current_position = master.get_position(motor_id)  # Get current motor position

    if current_position is None:
        print("Failed to get motor position. Check motor connection.")
        return

    print("Motor is rotating...")
    master.set_velocity(motor_id, 10000)  # Set motor to maximum speed

    # Wait until the motor reaches the target position
    while abs(master.get_position(motor_id) - current_position) < target_position:
        time.sleep(0.01)  # Short delay for position update

    master.set_velocity(motor_id, 0)  # Stop the motor
    print("Motor rotation completed.")

# Get user input for the number of turns and rotate the motor
turns = int(input("Enter the number of turns: "))
rotate_motor(turns)
#include <Acrome-SMD.h>

// Define motor parameters
#define MOTOR_ID 0  // Motor module ID
#define BAUDRATE 115200  // Serial communication baud rate
#define STEPS_PER_TURN 6533  // Encoder counts per revolution

// Initialize SMD Master and Motor
Master master(&Serial, BAUDRATE);
Red motor(MOTOR_ID);

void setup() {
    Serial.begin(BAUDRATE);
    Serial.println("SMD Red Motor Control Initialized.");
    
    // Attach motor to master
    master.attach(motor);

    // Configure motor settings
    motor.setOperationMode(2);  // Set to Velocity Control Mode
    motor.enableTorque(true);   // Enable motor torque
    motor.setShaftRpm(100);     // Set motor RPM
    motor.setShaftCpr(STEPS_PER_TURN);  // Set encoder counts per revolution
}

void rotateMotor(int turns) {
    long targetPosition = turns * STEPS_PER_TURN;  // Calculate target position
    long currentPosition = motor.getPosition();    // Get current position

    if (currentPosition == -1) {
        Serial.println("Error: Unable to get motor position.");
        return;
    }

    Serial.print("Rotating motor for ");
    Serial.print(turns);
    Serial.println(" turns.");

    motor.setVelocity(10000);  // Set motor velocity

    // Wait until the motor reaches the target position
    while (abs(motor.getPosition() - currentPosition) < abs(targetPosition)) {
        delay(10);  // Small delay for position update
    }

    motor.setVelocity(0);  // Stop the motor
    Serial.println("Motor rotation completed.");
}

void loop() {
    if (Serial.available() > 0) {
        String input = Serial.readStringUntil('\n');  // Read input from Serial
        int turns = input.toInt();  // Convert input to integer

        if (turns != 0) {
            rotateMotor(turns);
        } else {
            Serial.println("Invalid input. Enter a nonzero integer.");
        }
    }
}

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

Connect the 100 RPM with Encoder to the motor ports of the SMD using an RJ-45 cable.

SMD Red
Purchase Here
SMD USB Gateway
Purchase Here
Arduino Gateway Module
Purchase Here
BDC Motor
Purchase Here
SMD
Button Module
RGB LED Module
Buzzer Module
BDC Motor
USB Gateway Module
Arduino Gateway Module
BDC Motor