Skip to main content

Set Motor Speed Example

Full Example

This example shows how to set the speed of a motor using the Kinisi Motor Controller in Python.

Overview

In this example, you will learn how to:

  • Establish a connection with the Kinisi Motor Controller.
  • Initialize a motor with a specified direction.
  • Set the motor speed.
  • Stop the motor after a certain period.

Code Example

Set motor speed
import time
from pykinisi import *

# Define the serial port for the motor controller connection
# Update the port name based on your system configuration
# (e.g., "COM3" for Windows, "/dev/ttyUSB0" for Linux)
port = "COM3"

# Create an instance of the KinisiController class
controller = KinisiController()

# Attempt to connect to the motor controller via the specified serial port
if not controller.connect(port):
print(f"Error: Unable to open serial connection. Port {port}.")
exit() # Exit the program if the connection fails

# Specify which motor to control (Motor0, Motor1, Motor2, or Motor3)
motor_index = MotorIndex.Motor0

# Define the motor speed as a percentage (0% to 100%)
speed = 40 # Set speed to 40% of the motor's maximum speed

# Set whether the motor's direction should be reversed
# False = normal direction, True = reversed direction
is_reversed = False

# Initialize the motor with the specified settings
# This prepares the motor for operation, including setting its direction
controller.initialize_motor(motor_index, is_reversed)

# Set the motor speed to the desired value
# This command will cause the motor to start spinning at the specified speed
controller.set_motor_speed(motor_index, speed)

# Let the motor run for 5 seconds
time.sleep(5)

# Stop the motor after the 5-second run time
# Stopping the motor is important to prevent it from running indefinitely
controller.stop_motor(motor_index)

# Optionally, disconnect from the motor controller
# This is good practice to free up the serial port and clean up resources
controller.disconnect()

print("Motor operation completed successfully.")