How can I reset the value of my encoder to 0 after 0.5 sec and go again through the loop?
The Implementation part of the PID I think I got it, but I need to get the proper readings from my encoder in order to implement it. Here is the code.
Also the calculation for the RPM I need to take them out of the loop, so the RPM will be calculated only for the value of counter at 0.5sec and not for all the readings, that way I will reduce the processing in my code.
Code: Select all
import RPi.GPIO as GPIO
import time
# GPIO Setup
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
# Pin Setup (change only fwd and bwd pins for both the motors)
Afwd_pin = 38
Abwd_pin = 40
Bfwd_pin = 37
Bbwd_pin = 35
enc_Al_pin = 11
enc_Ar_pin = 13
enc_Bl_pin = 29
enc_Br_pin = 31
# GPIO.out settings (Don't change anything)
GPIO.setup(Afwd_pin, GPIO.OUT)
GPIO.setup(Abwd_pin, GPIO.OUT)
GPIO.setup(enc_Al_pin, GPIO.IN)
GPIO.setup(enc_Ar_pin, GPIO.IN)
GPIO.setup(Bfwd_pin, GPIO.OUT)
GPIO.setup(Bbwd_pin, GPIO.OUT)
GPIO.setup(enc_Bl_pin, GPIO.IN)
GPIO.setup(enc_Br_pin, GPIO.IN)
# Set variables for fwd and bwd
Afwd = GPIO.PWM(Afwd_pin,100)
Abwd = GPIO.PWM(Abwd_pin,100)
Bfwd = GPIO.PWM(Bfwd_pin,100)
Bbwd = GPIO.PWM(Bbwd_pin,100)
# Initialize (Don't change anything)
Afwd.start(0)
Abwd.start(0)
Bfwd.start(0)
Bbwd.start(0)
# Loop to make the robot move forward
''' We run the code for 5 seconds. Period is the time that we have to run it for'''
start = time.time()
period = 0.5
last_AA = 0b00
last_BB = 0b00
counter_A = 0
counter_B = 0
outcome = [0,-1,1,0,-1,0,0,1,1,0,0,-1,0,-1,1,0]
# Run motor
Afwd.ChangeDutyCycle(80)
Bfwd.ChangeDutyCycle(80)
''' The ChangeDutyCycle() makes the motors rotate at that speed '''
try:
while True:
# Encoder reading
left_A = GPIO.input(enc_Al_pin)
right_A = GPIO.input(enc_Ar_pin)
left_B = GPIO.input(enc_Bl_pin)
right_B = GPIO.input(enc_Br_pin)
while True:
current_aa = (left_A << 1) | right_A
position = (last_AA << 2) | current_aa
counter_A += outcome[position]
last_AA = current_aa
print('A = ', counter_A)
current_bb = (left_B << 1) | right_B
position = (last_BB << 2) | current_bb
counter_B += outcome[position]
last_BB = current_bb
print('B = ', counter_B)
# stop loop in time = period
if time.time() > start + period : break
#print('final counter of A = ', counter_A)
#print('final counter of B = ', counter_B)
# RPM calculation
RPM_A = ((counter_A*60/682.4)/0.5)
print('RPM_A = ', RPM_A)
RPM_B = ((counter_B*60/682.4)/0.5)
print('RPM_B = ', RPM_B)
except KeyboardInterrupt:
pass
# Error and PID implementation
# Stop commands to run (Don't change anything)
Afwd.stop()
Abwd.stop()
Bfwd.stop()
Bbwd.stop()
GPIO.cleanup()