halajamal
Posts: 42
Joined: Wed Sep 26, 2018 11:36 am

encoder with python

Sat Jan 26, 2019 6:16 pm

hello
I have a robot car with 2 dc motor
a dc encoder that connect to RPi3b and dc motor
I want to make a robot move according to number of rotation that measure by encoder . 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 python3 and RPi
please any help or idea
this is my code

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)
#GPIO.setup(32,GPIO.IN)
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:

prv=0

User avatar
OutoftheBOTS
Posts: 711
Joined: Tue Aug 01, 2017 10:06 am

Re: encoder with python

Sat Jan 26, 2019 9:40 pm

OK this is a long story and I will see if I can answer it as short and simple as possible with giving you enough info.

For useful motor control you need to build up layers of behavior with each layer building on the top of the lower layer.

First layer speed control:
You make a function that controls the speed of a single motor. At the moment you have a do() function that turns on both motors full duty. You will more want a function that you pass which motor you want and also what speed you want to the function. The function will be able to take a negative number and put the motor in reverse if it gets a negative number. For the moment you can just use duty as your speed control but you will find input duty doesn't match output speed as duty is a power setting not speed control but it will do for at the moment.

Second layer robot speed and direction control:
With a basic turtle robot design (2 drive wheels and a caster wheel) we talk about linear speed and angler speed. Linear speed is how fast in a forward direction the robot is traveling and angular speed is how fast the robot is turning. You can get the linear speed then add the angular speed to 1 wheel and subtract it from the other wheel to get the speed for each wheel. e.g if I want my robot to go forward at 50 and turn at 20 (positive being turn right) then the speed that I would send to the wheel will be left wheel = 50 + 20 and right wheel = 50 - 20. Another example will be if I want to go forward at 60 and turn at -10 (negative being turn left) then left wheel = 60 + -10 and right wheel = 60 - -20

Return to “Python”