2017-04-03 120 views
0

我创建了一个robot,它将根据python运行。对于它的自主程序,我需要它运行一定的距离(比如10英尺)。目前我正在使用时间让它走向距离,但是有没有什么办法可以在代码中实现距离,以使其更精确。谢谢。机器人距离

这是旧机器人竞赛的代码,我做过了,我想通过改进来学习。我使用这些库:

import sys 
import wpilib 
import logging 
from time import time 

这是代码:

def autonomous_straight(self): 
    '''Called when autonomous mode is enabled''' 

    t0 = time() 

    slow_forward = 0.25 

    t_forward_time = 6.5 
    t_spin_time = 11 
    t_shoot_time = 11.5 


    while self.isAutonomous() and self.isEnabled(): 
     t = time() - t0 

     if t < t_forward_time: 

      self.motor_left.set(slow_forward) 
      self.motor_right.set(-slow_forward) 
      self.motor_gobbler.set(1.0) 

     elif t < t_spin_time: 
      self.motor_left.set(2 * slow_forward) 
      self.motor_right.set(2 * slow_forward) 
      self.motor_shooter.set(-1.0) 

     elif t < t_shoot_time: 
      self.motor_mooover.set(.5) 

     else: 
      self.full_stop() 
      self.motor_gear.set(-1.0) 

     wpilib.Timer.delay(0.01) 

    self.full_stop() 
+0

你能告诉我们你正在使用的代码吗? –

+0

这是一个真实的物理机器人还是只是一个模拟? –

+0

欢迎来到Stack Overflow!你能分享你正在使用的库和你用来与硬件接口的东西吗?另外考虑列出可用于控制程序的传感器。真的没有足够的细节在这里提供很多帮助。 –

回答

0

它看起来像你想开车基于时间的距离。虽然这可能以已知的速度在短距离内工作,但基于传感器反馈进行驱动通常要好得多。你要看看的是encoders,更具体的是旋转编码器。编码器只是跟踪“滴答”的计数器。每个“嘀嗒”代表传动轴的旋转百分比。

formula

其中d是行驶距离,cir是车轮周长res是编码器“分辨率”(每转蜱的数目),并且num是当前刻度计数(读出的编码器)

# Example Implementation 
import wpilib 
import math 

# Some dummy speed controllers 
leftSpeed = wpilib.Spark(0) 
rightSpeed = wpilib.Spark(1) 

# Create a new encoder linked to DIO pins 0 & 1 
encoder = wpilib.Encoder(0, 1) 

# Transform ticks into distance traveled 
# Assuming 6" wheels, 512 resolution 
def travelDist (ticks): 
    return ((math.pi * 6)/512) * ticks 

# Define auto, takes travel distance in inches 
def drive_for(dist = 10): 
    while travelDist(encoder.get()) < dist: 
    rightSpeed.set(1) 
    leftSpeed.set(-1) # negative because one controller must be inverted 

这个简单的实现将允许您呼叫drive_for(dist)以相当准确的程度行驶所需距离。但是,它有很多问题。这里我们试图设置一个线性速度,注意没有加速控制。这会导致长距离建立错误,解决方案是PID控制。 wpilib有构造来简化数学。只需将设定值和当前行驶距离区分开来,并将其作为错误插入PID控制器。 PID控制器将吐出一个新的值来设置你的马达控制器。 PID控制器(有一些调整)可以考虑加速度,惯性和过冲。

关于PID的文档: http://robotpy.readthedocs.io/projects/wpilib/en/latest/_modules/wpilib/pidcontroller.html