【发布时间】:2018-04-23 07:27:15
【问题描述】:
我目前正在使用 AlphaBot 使用树莓派 3 进行一个小项目。我正在尝试使用轮编码器状态转换或滴答声使机器人旋转 90 度。这是我的尝试:
import RPi.GPIO as GPIO # Importing Libraries
import time
import math
GPIO.setmode(GPIO.BCM) # Choosing BCM numbering
GPIO.setwarnings(False) # Disables Warnings when setting the pins
r = 4.85 #width of robot chasis in inches
d = 8.5 #diameter of wheel in inches
C = math.pi*d #circumference of wheel in inches
slits = 20 #number of slits on wheel encoders
state_trans = 2*slits #total # of state transitions of wheel encoders
inpertick = C/state_trans #total inches per tick
def pivot(degrees,turn):
s = 0 #used to count ticks needed to pivot a certain number of degrees
L = 0 #used for number of pulses on left encoder
R = 0 #used for number of pulses on right encoder
ticks = (degrees*math.pi*r)/180
final_ticks = int(round(ticks/inpertick))
while(s != final_ticks):
if (turn == "left"):
L += 1
R -= 1
elif (turn == "right"):
R += 1
L -= 1
s += 1
if (turn == "left"):
GPIO.output(IN1,GPIO.LOW)
GPIO.output(IN2,GPIO.HIGH)
GPIO.output(IN3,GPIO.LOW)
GPIO.output(IN4,GPIO.HIGH)
elif (turn == "right"):
GPIO.output(IN1,GPIO.HIGH)
GPIO.output(IN2,GPIO.LOW)
GPIO.output(IN3,GPIO.HIGH)
GPIO.output(IN4,GPIO.LOW)
PWMA.ChangeDutyCycle(R)
PWMB.ChangeDutyCycle(L)
IN1 = 12
IN2 = 13
IN3 = 20
IN4 = 21
ENA = 6
ENB = 26
GPIO.setup(IN1,GPIO.OUT) # Set GPIO pin 12 as an output
GPIO.setup(IN2,GPIO.OUT) # Set GPIO pin 13 as an output
GPIO.setup(IN3,GPIO.OUT) # Set GPIO pin 20 as an output
GPIO.setup(IN4,GPIO.OUT) # Set GPIO pin 21 as an output
GPIO.setup(ENA,GPIO.OUT) # Set GPIO pin 6 as an output
GPIO.setup(ENB,GPIO.OUT) # Set GPIO pin 26 as an output
PWMA = GPIO.PWM(ENA,50) # Setup ENA as PWM at 50 Hertz
PWMB = GPIO.PWM(ENB,50) # Setup ENB as PWM at 50 Hertz
PWMA.start(45)
PWMB.start(50)
pivot(90,"right")
time.sleep(2)
PWMA.stop()
PWMB.stop()
正如您在 pivot() 函数中看到的那样,我计算了进行 90 度转弯所需的滴答声或状态转换的数量。我尝试获取这些刻度数并将其应用于更改占空比。我确定这是错误的,但我不知道如何获取滴答数并将其转换为编码器应该执行的操作。有什么想法可以解决这个问题吗?
【问题讨论】:
-
您的代码目前是否有效?
-
确实如此,但使用我使用的 PWM 并没有太大的转折。我正在尝试找出编码器如何让机器人在这些滴答声中移动。
-
这似乎是 PID 控制器的一个很好的应用。我会尝试制作一个调整脉冲宽度以响应错误(实际滴答声减去预期滴答声)。
标签: python python-2.7 python-3.x raspberry-pi raspberry-pi3