简体   繁体   English

如何使用编码器测量直流电机来控制Python的机器人运动?

[英]how to use encoder measurement for dc motor to control robot movement with python?

I have a robot car with 2 dc motor a dc encoder that connect to RPi 3 b and dc motor I want to make a robot move according to number of rotation that measure by encoder . 我有一个带2 dc电机的机器人车和连接到RPi 3 b的dc编码器和dc电机。我想根据编码器测量的转数使机器人移动。 so that robot move and encoder start to measure when it reach 5 rotation, robot will stop, Now my problem is I can't turn right or left, how to do that I used python and RPi 这样机器人的移动和编码器达到5旋转时就开始测量,机器人将停止,现在我的问题是我无法向右或向左转,我该如何使用python和RPi

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setwarnings(False)

GPIO.setup(31,GPIO.IN)


GPIO.setup(29,GPIO.IN)

GPIO.setup(12,GPIO.OUT)

GPIO.setup(16,GPIO.OUT)

GPIO.setup(35,GPIO.OUT)

GPIO.setup(33,GPIO.OUT)


pwm=20

frequency=70000

right=GPIO.PWM(12,frequency)

left=GPIO.PWM(33,frequency)

left.start(0)

right.start(0)

def on():

    right.ChangeDutyCycle(pwm)

    left.ChangeDutyCycle(pwm)

def off():

    right.ChangeDutyCycle(0)

    left.ChangeDutyCycle(0)

prv=0

i=0

while True:

          on()  

          if(GPIO.input(31)==(1) and GPIO.input(29)==(1)):

             print"something"

             if prv==0:

                  prv=1

                  i=i+1

                  print"hole"+ str(i)+"times"

                  if i==50

                     off()

                     break     


          else:

                   print"button not pushed"

                   prv=0

Turning left or right is a matter of turning one of the motors on instead of both (or running one side faster than the other). 向左或向右转动是打开一个电动机而不是两个电动机的问题(或者一侧比另一侧运行得更快)。 You could try writing the functions turnleft() and turnright() and running them in the loop (hook them to a button or something). 您可以尝试编写函数turnleft()turnright()并在循环中运行它们(将它们连接到按钮或其他东西上)。

The function for turning left would look something like this: 左转功能如下所示:

def turnleft():
    right.ChangeDutyCycle(pwm)
    left.ChangeDutyCycle(0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM