Skip to content

Extended DifferentialDrive class to use IMU and PID to drive straight when using arcade drive #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion XRPLib/differential_drive.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,16 @@ def __init__(self, left_motor: EncodedMotor, right_motor: EncodedMotor, imu: IMU
self.wheel_diam = wheel_diam
self.track_width = wheel_track

self.heading_pid = None
self.current_heading = None
self.reset_heading = True
self.turning = False

if self.imu:
# if the IMU is initialized, then create a PID controller that can be used
# to maintain a constant heading when driving
self.heading_pid = PID( kp = 0.075, kd=0.001, )

def set_effort(self, left_effort: float, right_effort: float) -> None:
"""
Set the raw effort of both motors individually
Expand Down Expand Up @@ -110,7 +120,33 @@ def arcade(self, straight:float, turn:float):
scale = max(abs(straight), abs(turn))/(abs(straight) + abs(turn))
left_speed = (straight - turn)*scale
right_speed = (straight + turn)*scale
self.set_effort(left_speed, right_speed)

if not self.heading_pid:
# if not using IMU assist to maintain heading, just pass down the left and right motor
# speeds to control movement
self.set_effort(left_speed, right_speed)
else:
# else if IMU assist is enabled, then use the IMU with PID to
# maintain a constant heading while driving.
if turn == 0:
# straight drive requested, then maintain the current heading
if self.turning:
# if previously turning, then clear the turn indicator and reset the course heading
self.reset_heading = True
self.turning = False

if self.reset_heading:
self.reset_heading = False
self.current_heading = self.imu.get_yaw()

# use the PID to set the heading correction based on the current heading
heading_correction = self.heading_pid.update(self.current_heading - self.imu.get_yaw())

self.set_effort(left_speed - heading_correction, right_speed + heading_correction)
else:
# set the turning indicator and apply the left and right speeds
self.turning = True
self.set_effort(left_speed, right_speed)

def reset_encoder_position(self) -> None:
"""
Expand Down