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

Basic Motor Control Application Using PWM Input

PreviousBasic Motor Speed Control ApplicationNextBasic Motor Position Control Application

Last updated 18 days ago

This program demonstrates a fundamental motor control application, where the motor’s behavior is controlled through Pulse Width Modulation (PWM) input specified by the user. The script sets up the motor, establishes communication, and allows the user to input a PWM value to control the motor's rotation speed and direction. PWM is a common method to adjust motor speed in motor control applications.

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

  1. USB Port Detection:

    1. The script first identifies and connects to the appropriate USB serial port based on the operating system. It uses the serial module to scan for connected serial devices.

    2. The program is compatible with Windows, Linux, and macOS, using different naming conventions for the USB port depending on the OS.

  2. Motor Initialization and Configuration:

    1. The Master and Red objects from the smd.red library are used to set up the motor and establish communication.

    2. The motor's essential parameters are initialized, such as counts per revolution (set_shaft_cpr) and shaft RPM (set_shaft_rpm).

  3. PWM Input for Motor Control:

    1. After configuring the motor, the program prompts the user to input a PWM value, which will control the motor’s rotation speed and direction.

    2. PWM values can vary, with positive values for one direction and negative values for the opposite. This input is passed to the motor using m.set_duty_cycle(0, -int(pwm)).

    3. By inputting a PWM value, the user directly controls the motor’s duty cycle, affecting both the speed and direction.

  4. User Feedback:

    1. After setting the PWM, the program prints a confirmation message indicating that the motor is running at the specified PWM level.

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

• Execute the script to initiate the Basic Motor Control Application Using PWM Input.

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

• Enter a PWM value (0 to 255) when prompted to adjust the motor speed.

Experience PWM-Based Motor Control

• Observe how the motor speed increases as the PWM value increases.

• Enter zero (0) to stop the motor completely.

• Notice how the PWM signal directly influences the motor speed, providing smooth and efficient control.

Codes

from smd.red import *  # Import the SMD Red motor control library
import math
import os

from serial.tools.list_ports import comports  # Import serial communication tools
from platform import system  # Import system detection module

# Function to detect and return the correct USB port for communication
def USB_Port():
    ports = list(comports())  # Get a list of available serial ports
    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",
            "/dev/cu.usbmodem",
            "/dev/cu.SLAB_USBtoUART",
            "/dev/cu.wchusbserial",
        ]
    }
    
    os_name = system()  # Detect the operating system
    if ports:  # If ports are available
        for port, desc, hwid in sorted(ports):  # Iterate through detected ports
            # Check if the port name or description matches the expected USB names
            if any(name in port or name in desc for name in usb_names.get(os_name, [])):
                return port  # Return the detected port
        
        # If no matching port was found, print the available ports
        print("Current ports:")
        for port, desc, hwid in ports:
            print(f"Port: {port}, Description: {desc}, Hardware ID: {hwid}")
    else:
        print("No port found")  # Print message if no ports are detected
    return None  # Return None if no suitable port is found

# Get the detected USB port
port = USB_Port()

# Initialize the motor controller using the detected port
m = Master(port)

# Attach the motor with ID 0
m.attach(Red(0))

# Set motor parameters
m.set_shaft_cpr(0, 6533)  # Set encoder counts per revolution (CPR)
m.set_shaft_rpm(0, 100)  # Set shaft speed in RPM

# Initialize control variables
motor_speed = 0
angle_degrees = 0
current_limit = 100  # Maximum allowable current
current_value = 0
previous_current = 0  # Store the previous current value for monitoring

# Configure motor operation modes and control parameters
m.set_operation_mode(0, OperationMode.Velocity)  # Set velocity control mode
m.set_control_parameters_velocity(0, 30.0, 5.0, 0.0)  # Set PID parameters for velocity control
m.set_control_parameters_position(0, 0.5, 0.0, 20.0)  # Set PID parameters for position control
m.set_control_parameters_torque(0, 3.0, 0.1, 0.0)  # Set PID parameters for torque control

# Enable motor torque to allow movement
m.enable_torque(0, True)

# Switch the motor to PWM control mode
m.set_operation_mode(0, OperationMode.PWM)

# Ask user to enter PWM value
pwm = input("PWM: ")

# Set motor PWM duty cycle (negative value for reverse direction)
m.set_duty_cycle(0, -int(pwm))

# Print confirmation message
print(f"The motor is running with a PWM value of {pwm}.")
#include <Acrome-SMD.h>

// Define motor parameters
#define MOTOR_ID 0       // SMD Red Motor ID
#define BAUDRATE 115200  // Serial Communication Baud Rate
#define CPR 6533         // Encoder Counts Per Revolution (CPR)
#define DEFAULT_RPM 100  // Default motor speed in RPM

// 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.setShaftCpr(CPR);    // Set Encoder Counts Per Revolution (CPR)
    motor.setShaftRpm(DEFAULT_RPM);  // Set default motor speed in RPM

    // Configure control parameters
    motor.setOperationMode(OperationMode::Velocity);  // Set to Velocity Control Mode
    motor.setControlParametersVelocity(30.0, 5.0, 0.0);  // PID for Velocity Control
    motor.setControlParametersPosition(0.5, 0.0, 20.0);  // PID for Position Control
    motor.setControlParametersTorque(3.0, 0.1, 0.0);  // PID for Torque Control

    // Enable motor torque
    motor.enableTorque(true);

    // Switch motor to PWM control mode
    motor.setOperationMode(OperationMode::PWM);
}

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

        if (pwmValue >= -255 && pwmValue <= 255) {  // Limit PWM range
            motor.setDutyCycle(pwmValue);  // Apply PWM value
            Serial.print("The motor is running with a PWM value of ");
            Serial.println(pwmValue);
        } else {
            Serial.println("Invalid PWM value! Enter a number between -255 and 255.");
        }
    }
}

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

Connect the 100 RPM with Encoder to the motor ports of the SMD Red.

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