Запоминание углового положения в шаговом двигателе - PullRequest
0 голосов
/ 17 июня 2019

Я ищу предложения о том, как определить начальное положение для двигателя, чтобы я мог отслеживать свое текущее угловое положение относительно этой точки. Я использую шаговый двигатель, поэтому для перемещения на заданный угол я считаю шаги. В настоящее время у меня есть функция, которая подделывает своего рода сигнал ШИМ и перемещает двигатель через заданный угол с определенной скоростью и направлением. Это выглядит так:

def RotMotor(SPIN, DPIN, direction, degrees, speed):
    GPIO.output(DPIN, direction)
    #For precise control the number of steps required to move to a given angle 
    #is calculated by the following line of code
    num_steps = (float(degrees) / float(360)) * 800
    #The sleep time is derived from the input RPM by converting RPM to time 
    #between each step
    sleeptime = 1 / ((float(speed) * 800) / 60)
    print('Taking ' + str(num_steps) + ' steps at ' + str(speed) + ' RPM.')
    #This while loop will take the calulated number of steps and count each 
    #step the motor makes in moving to its next point
    while num_steps > 0:
        GPIO.output(SPIN, 1)
        #The sleep function is called twice (High duration + Low Duration)
        time.sleep(sleeptime / 2)
        GPIO.output(SPIN, 0)
        #Second call of sleep function. Sleep function 1 + Sleep function 2 = 
        #Time for One Step
        time.sleep(sleeptime / 2)
        #Count 1 step
        num_steps -= 1

То, что я пытаюсь сделать, - это разработать способ, которым я могу передать этой функции список позиций так, чтобы она:

1.) Знайте, что это начало с нуля 2.) Знайте, что если он находится под углом 90 градусов, и ему говорят, что он должен идти на 180 градусов, то он перемещается на 90 градусов.

Ранее я говорил, что моя функция будет двигаться через угол. Моя цель - двигаться на угол. Затем, когда мой список закончится, он вернется к нулю без необходимости включать эту координату в список.

У меня есть смутное представление о том, что мне нужно делать, но я очень открыт для предложений на данный момент. Спасибо за любой отзыв.

1 Ответ

0 голосов
/ 18 июня 2019

Я придумал простое решение для тех из вас, кто интересовался этим вопросом. Вместо того, чтобы объяснять, я просто опубликую здесь код для всех желающих.

'''
This code is used to drive two NEMA 17 stepper motors both driven by their own A4988 
driver circuit. The step resolution is set to 1/4 steps, which results in 800 steps 
per revolution for this specific motor. If you use this code be sure to change the number 
800 anywhere in this code to your own motors steps per revolution.
'''
#!/usr/bin/env python

#Importing all relevant packages

import os
import RPi.GPIO as GPIO
import numpy
import time

#Defining GPIO setup (STEP PINS (odd) AND DIRECTION PINS (even) FOR EACH MOTOR)

PINS = [11, 12, 15, 16]
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(PINS, GPIO.OUT)

#Initialize a list that stores the amount of steps taken for each coordinate for the duration of the program

mem1 = [0]
mem2 = [0]

#Function to tell a motor how to move based on direction (CW / CCW), how many degrees to move, and what speed to move at (RPM)
#For precise control the number of steps required to move to a given angle is calculated by the following line of code

def RotMotor(SPIN, DPIN, direction, degrees, speed, memory):
    pos = sum(memory)
    num_steps = ((float(degrees) / float(360)) * 800) - pos
    memory.append(num_steps)
    if num_steps < 0:
        x = abs(num_steps)
        dir = GPIO.output(DPIN, 1)
    else:
        x = num_steps
        GPIO.output(DPIN, 0)
    sleeptime = 1 / ((float(speed) * 800) / 60)
    print('Taking ' + str(num_steps) + ' steps at ' + str(speed) + ' RPM.')
    while x > 0:
        GPIO.output(SPIN, 1)
        time.sleep(sleeptime / 2)
        GPIO.output(SPIN, 0)
        time.sleep(sleeptime / 2)
        x -= 1

#THE FOLLOWING LINES ARE QUICK CODE FOR TESTING.

Motor1Ins = []
Motor2Ins = []

angles = [45, 90, 135, 180, 225, 270, 315, 360, 315, 270, 225, 180, 135, 90, 45, 0]

for i in angles:
   Motor1Ins.append([11, 12, i, 20, mem1])
   Motor2Ins.append([15, 16, i, 20, mem2])

try:
   while True:
      for s, d, theta, t, MotMem in Motor1Ins:
         RotMotor(s, d, theta, t, MotMem)
         time.sleep(0.5)
      for s, d, theta, t, MotMem in Motor2Ins:
         RotMotor(s, d, theta, t, MotMem)
         time.sleep(0.5)
except KeyboardInterrupt():
   RotMotor(11, 12, 0, 20, mem1)
   RotMotor(15, 16, 0, 20, mem2)

GPIO.cleanup()

По сути, я создал список, который действует как память, а затем использовал некоторую логику, чтобы решить, как должно работать движение, основываясь на том, что оно запоминает. Я думаю, что я должен записать в файл где-то еще, а затем заменить текущее значение памяти, а не позволить списку постоянно расти по причинам памяти, но это работает на данный момент.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...