Код: Выделить всё
import serial
import time
class VelmexMotorController:
def __init__(self, com_port, axis=1, home_position=0, target_start_position=-9000, baudrate=9600, timeout=5, max_step=2000):
self.com_port = com_port
self.axis = axis # Specify the axis (1 by default)
self.baudrate = baudrate
self.timeout = timeout
self.home_position = home_position # Define the home position (e.g., 0 steps)
self.target_start_position = target_start_position # Define the desired starting position
self.current_position = 0 # Track the current position of the motor
self.ser = None # Serial object, initialized later
self.max_step = max_step # Max steps per command to prevent overload
def connect(self):
"""Initialize and open the serial port."""
self.ser = serial.Serial()
self.ser.port = self.com_port
self.ser.baudrate = self.baudrate
self.ser.bytesize = serial.EIGHTBITS
self.ser.parity = serial.PARITY_NONE
self.ser.stopbits = serial.STOPBITS_ONE
self.ser.timeout = self.timeout
self.ser.xonxoff = False
self.ser.rtscts = False
self.ser.dsrdtr = False
self.ser.writeTimeout = 2
try:
self.ser.open() # Attempt to open the serial port
print(f"Serial port {self.ser.port} opened successfully.")
except Exception as e:
print(f"Error opening serial port: {e}")
return False
return True
def disconnect(self):
"""Close the serial port."""
if self.ser and self.ser.isOpen():
self.ser.close()
print(f"Serial port {self.ser.port} closed.")
def move(self, steps, delay=1):
"""Move the motor a specified number of steps on the specified axis, with delay."""
if not self.ser or not self.ser.isOpen():
print("Serial port not open.")
return
remaining_steps = abs(steps)
direction = 1 if steps > 0 else -1 # Determine direction of movement
while remaining_steps > 0:
move_steps = min(remaining_steps, self.max_step) # Limit each move to max_step steps
move_steps *= direction # Apply direction
try:
# Flush input and output buffers
self.ser.flushInput()
self.ser.flushOutput()
# Send command to move the motor on the specified axis
command = f"F,C,I{self.axis}M{move_steps},R\r\n".encode('utf-8')
self.ser.write(command)
time.sleep(delay) # Wait for the motor to complete the movement
self.current_position += move_steps # Update the current position
print(f"Moved {move_steps} steps on axis {self.axis}. Current position: {self.current_position}")
except Exception as e1:
print(f"Error communicating: {e1}")
break
remaining_steps -= abs(move_steps) # Reduce the remaining steps to move
def go_home(self, delay=5):
"""Move the motor back to the home position on the specified axis."""
steps_to_home = -self.current_position # Steps to return to home (reverse of current position)
self.move(steps_to_home, delay)
print(f"Motor on axis {self.axis} returned to home position.")
self.current_position = self.home_position # Reset the current position to home
def read_current_position(self):
"""Read the current position of the motor from the hardware."""
# Replace with the actual command to read the position
try:
command = f"F,C,I{self.axis}PR\r\n".encode('utf-8') # Replace with correct read command
self.ser.write(command)
time.sleep(0.1) # Wait for response
response = self.ser.readline().decode('utf-8').strip() # Read response
self.current_position = int(response) # Assuming response is the current position
print(f"Current position read: {self.current_position}")
except Exception as e:
print(f"Error reading current position: {e}")
def initialize(self):
"""Move to home position initially and then to the target start position."""
print(f"Homing the motor on axis {self.axis}...")
self.go_home() # Start by going to the home position
# Read the current position after homing
self.read_current_position()
# Calculate the steps needed to reach the target start position
steps_to_start = self.target_start_position - self.current_position
print(f"Moving to target start position: {self.target_start_position} from current position: {self.current_position}...")
self.move(steps_to_start) # Move to the target start position
print(f"Motor on axis {self.axis} is now at the starting position: {self.current_position}")
if __name__ == "__main__":
# Initialize motor controller for axis 2
motor = VelmexMotorController(com_port="COM3", axis=2)
# Connect to the motor
if motor.connect():
motor.initialize() # Home the motor initially and move to target start position
# Example movement
# motor.move(-6000, delay=1) # Move motor -60000 steps on axis 2, with 1 second delay between chunks
# Disconnect after operations
motor.disconnect()
Код: Выделить всё
Serial port COM3 opened successfully.
Homing the motor on axis 2...
Motor on axis 2 returned to home position.
Error reading current position: invalid literal for int() with base 10: '?^'
Moving to target start position: -9000 from current position: 0...
Moved -2000 steps on axis 2. Current position: -2000
Moved -2000 steps on axis 2. Current position: -4000
Moved -2000 steps on axis 2. Current position: -6000
Moved -2000 steps on axis 2. Current position: -8000
Moved -1000 steps on axis 2. Current position: -9000
Motor on axis 2 is now at the starting position: -9000
Serial port COM3 closed.
https://velmex.com/wp-content/uploads/2018/07/VXM -Command-Summary-Rev-B-814.pdf
Подробнее здесь: https://stackoverflow.com/questions/791 ... ith-python