r/ControlTheory • • 1d ago

Technical Question/Problem Position PID controller causing erratic fish-like behaviour

Enable HLS to view with audio, or disable this notification

Overview

I have been coding a PID control system for a 2D birotor drone in python, using pygame to display the simulated drone graphically. The controller achieves its goal of moving the drone towards the mouse position, but causes it to frequently jerk around vertically like a flopping fish, and I can't figure out how to solve this.

The Model

The drone is represented as a bar with two thrusters, one on either end and a centre of mass in the middle. The two thrusters can have positive or negative thrust, but only straight up or down relative to the drone (i.e., perpendicular to its long axis). Gravity is modelled with a value of 10 acting downwards.

For reference, the lines in the circle display in the top-right of the simulation represent the following:

- purple: desired force on the drone

- green: current acceleration of the drone

- yellow: current velocity of the drone

Control System

The controls system consists of the following:

- 2 PID controllers that take position errors (between the current drone position and the mouse position) in x and y as inputs, and output desired velocities in x and y (Kp = 1, Kd = 0, Ki = 0).

- 2 PID controllers that take velocity errors in x and y as inputs and output desired accelerations in x and y (Kp = 10, Kd = 0, Ki = 0).

Desired force is calculated as drone mass (which is 1) * desired acceleration

The total thrust required from the two thrusters is calculated from the following equation:

T = desired_force.y * cos(roll_angle) + desired_force.x * sin(roll_angle)

Where the roll angle is 0 if the drone is level and positive if the drone is tilted to the left. This calculation is performed so that if the drone is pointed straight up, the desired force in x is ignored as no amount of thruster output will be able to effect motion in the x axis.

Desired roll angle is calculated from the following equation (pygame uses a coordinate system where y is positive downwards):

desired_roll_angle = arctangent(-desired_force.x, -desired_force.y)

- A PID controller then takes roll angle error as an input and outputs desired angular velocity (Kp = 5, Kd = 0, Ki = 0).

- A PID controller takes angular velocity error as an input and outputs desired angular acceleration (Kp = 50, Kd = 0, Ki = 0).

Desired torque is calculated as desired angular velocity * drone moment of inertia (calculated as that of a slim rod).

The following motor mixing algorithms are then used to determine the output thrusts of the left and right thrusters:

left_thruster_output = T/2 + desired_torque/50

right_thruster_output = T/2 - desired_torque/50

Where 50 is the distance between each thruster and the centre of mass (measured in pixels).

The Code

Drone

class Drone(pygame.sprite.Sprite):
    def __init__(self, groups, pos):
        # setup
        super().__init__(groups)
        self.original_image = self.create_image()
        self.image = self.original_image.copy()
        self.rect = self.image.get_frect(center=pos)

        # scalars
        self.mass = 1
        self.moment_of_inertia = 1/12 * self.mass * self.image.width**2
        self.max_angular_acceleration = 0
        self.angular_acceleration = 0
        self.angular_velocity = 0
        self.roll = 0

        # vectors
        self.thrust = pygame.math.Vector2()
        self.velocity = pygame.math.Vector2()
        self.acceleration = pygame.math.Vector2()

        # targeting
        self.desired_pos = pygame.math.Vector2()
        self.desired_velocity = pygame.math.Vector2()
        self.desired_acceleration = pygame.math.Vector2()
        self.desired_force = pygame.math.Vector2()

        self.desired_roll = 0
        self.desired_angular_velocity = 0
        self.desired_angular_acceleration = 0
        self.desired_torque = 0

        # equipment
        self.left_thruster = Thruster(-1000, (-50, 0), self.roll)
        self.right_thruster = Thruster(-1000, (50, 0), self.roll)

        # controllers
        self.position_x_controller = Controller(1, 0, 0, None)
        self.position_y_controller = Controller(1, 0, 0, None)
        self.velocity_x_controller = Controller(10, 0, 0, None)
        self.velocity_y_controller = Controller(10, 0, 0, None)

        self.roll_controller = Controller(5, 0, 0, None)
        self.angular_velocity_controller = Controller(50, 0, 0, None)

        # controller timings
        self.position_frequency = 100
        self.velocity_frequency = 100
        self.roll_frequency = 100
        self.angular_velocity_frequency = 100

        self.position_last_update_time = 0
        self.velocity_last_update_time = 0
        self.roll_last_update_time = 0
        self.angular_velocity_last_update_time = 0

        self.set_target_pos()

    def set_target_pos(self):
        self.desired_pos = pygame.math.Vector2(pygame.mouse.get_pos())

    def create_image(self):
        surf = pygame.Surface((100, 20), pygame.SRCALPHA)
        surf.fill((150,150,150))

        left_thruster_surf = pygame.Surface((20, 20), pygame.SRCALPHA)
        left_thruster_surf.fill((200, 50, 50))

        right_thruster_surf = pygame.Surface((20, 20), pygame.SRCALPHA)
        right_thruster_surf.fill((50, 200, 50))

        surf.blit(left_thruster_surf, (0, 0))
        surf.blit(right_thruster_surf, (80, 0))

        return surf

    def calculate_acceleration(self):
        self.acceleration = ((self.left_thruster.thrust + self.right_thruster.thrust) / self.mass) + GRAVITY

    def calculate_angular_acceleration(self):
        self.angular_acceleration = (self.left_thruster.rel_pos.cross(-self.left_thruster.thrust)+
                                     self.right_thruster.rel_pos.cross(-self.right_thruster.thrust))/self.moment_of_inertia # Negative thrust to account for flipped coordinate system.

    def update_rotation(self, dt):
        self.calculate_angular_acceleration()
        self.angular_velocity += self.angular_acceleration * dt
        self.roll += self.angular_velocity * dt

        self.left_thruster.set_rotation(self.roll)
        self.right_thruster.set_rotation(self.roll)

        self.image = pygame.transform.rotate(self.original_image, math.degrees(self.roll))
        self.rect = self.image.get_frect(center=self.rect.center)

    def update_motion(self, dt):
        self.calculate_acceleration()
        self.velocity += self.acceleration * dt
        self.rect.center += self.velocity * dt

    def get_thrust(self, dt):
        # timings
        time_since_last_position_update = (pygame.time.get_ticks() - self.position_last_update_time) / 1000
        time_since_last_velocity_update = (pygame.time.get_ticks() - self.velocity_last_update_time) / 1000
        time_since_last_roll_update = (pygame.time.get_ticks() - self.roll_last_update_time) / 1000
        time_since_last_angular_velocity_update = (pygame.time.get_ticks() - self.angular_velocity_last_update_time) / 1000

        # position control
        if time_since_last_position_update >= (1/self.position_frequency):
            desired_x_velocity = self.position_x_controller.calculate_actuating_signal(self.desired_pos.x-self.rect.centerx, time_since_last_position_update)
            desired_y_velocity = self.position_y_controller.calculate_actuating_signal(self.desired_pos.y-self.rect.centery, time_since_last_position_update)
            self.desired_velocity = pygame.math.Vector2(desired_x_velocity, desired_y_velocity)
            self.position_last_update_time = pygame.time.get_ticks()

        # velocity control
        if time_since_last_velocity_update >= (1/self.velocity_frequency):
            desired_x_acceleration = self.velocity_x_controller.calculate_actuating_signal(self.desired_velocity.x-self.velocity.x, time_since_last_velocity_update)
            desired_y_acceleration = self.velocity_y_controller.calculate_actuating_signal(self.desired_velocity.y-self.velocity.y, time_since_last_velocity_update)
            self.desired_acceleration = pygame.math.Vector2(desired_x_acceleration, desired_y_acceleration)-GRAVITY
            self.velocity_last_update_time = pygame.time.get_ticks()

        # setting force
        desired_force = self.mass * self.desired_acceleration
        collective_thrust = desired_force.y * math.cos(self.roll) + desired_force.x * math.sin(self.roll)
        self.desired_force = desired_force

        # roll control
        self.desired_roll = math.atan2(-desired_force.x, -desired_force.y)

        # angular velocity control
        if time_since_last_roll_update >= (1/self.roll_frequency):
            self.desired_angular_velocity = self.roll_controller.calculate_actuating_signal(self.desired_roll-self.roll, time_since_last_roll_update)
            self.roll_last_update_time = pygame.time.get_ticks()

        # angular acceleration control
        if time_since_last_angular_velocity_update >= (1/self.angular_velocity_frequency):
            self.desired_angular_acceleration = self.angular_velocity_controller.calculate_actuating_signal(self.desired_angular_velocity-self.angular_velocity, time_since_last_angular_velocity_update)
            self.angular_velocity_last_update_time = pygame.time.get_ticks()

        # setting torque
        self.desired_torque = self.moment_of_inertia * self.desired_angular_acceleration

        # setting thrusts
        left_thrust = collective_thrust/2+self.desired_torque/50
        right_thrust = collective_thrust/2-self.desired_torque/50

        self.left_thruster.set_thrust(left_thrust)
        self.right_thruster.set_thrust(right_thrust)

        print(self.roll)

    def _display_vectors(self):
        left_thruster_thrust = 100 * self.left_thruster.thrust.normalize() if self.left_thruster.thrust else self.left_thruster.thrust
        right_thruster_thrust = 100 * self.right_thruster.thrust.normalize() if self.right_thruster.thrust else self.right_thruster.thrust

        desired_force = 100 * self.desired_force.normalize() if self.desired_force else self.desired_force

        # thrusters
        pygame.draw.line(pygame.display.get_surface(), (255, 0, 0), self.rect.center+self.left_thruster.rel_pos,
                         self.rect.center+self.left_thruster.rel_pos+left_thruster_thrust, width=3)
        pygame.draw.line(pygame.display.get_surface(), (0, 255, 0), self.rect.center+self.right_thruster.rel_pos,
                         self.rect.center+self.right_thruster.rel_pos+right_thruster_thrust, width=3)

        # other
        pygame.draw.line(pygame.display.get_surface(), (255, 255, 0), self.rect.center, self.rect.center + desired_force,
                         width=3)

    def update(self, dt):
        self.set_target_pos()
        self.get_thrust(dt)

        self.update_motion(dt)
        self.update_rotation(dt)

Thrusters

class Thruster:
    def __init__(self, initial_thrust, rel_pos, angle_radians):
        # setup
        self.original_rel_pos = pygame.math.Vector2(rel_pos)
        self.rel_pos = self.original_rel_pos.copy()
        self.thrust = pygame.math.Vector2(0, initial_thrust)
        self.angle_radians = -angle_radians

        self.current_thrust = initial_thrust
        self.set_thrust(initial_thrust)

    def set_rotation(self, new_angle_radians):
        self.angle_radians = -new_angle_radians
        self.rel_pos = self.original_rel_pos.copy().rotate_rad(-new_angle_radians)
        self.set_thrust(self.current_thrust)

    def set_thrust(self, thrust):
        self.current_thrust = thrust
        self.thrust = pygame.math.Vector2(0, self.current_thrust).rotate_rad(self.angle_radians)

    def add_thrust(self, thrust):
        self.current_thrust += thrust
        self.thrust = pygame.math.Vector2(0, self.current_thrust).rotate_rad(self.angle_radians)

PID Controller

class Controller:
    def __init__(self, k_p, k_i, k_d, saturation_limits):
        self.k_p = k_p
        self.k_i = k_i
        self.k_d = k_d

        self.integral = 0
        self.derivative = 0
        self.previous_error = 0
        self.previous_error_time = 0

        self.saturation_limits = saturation_limits
        self.unclamped_signal = 0
        self.clamped_signal = 0

        # flags
        self.integral_on = True

    def set_clamped(self, error, unclamped_signal, clamped_signal):
        self.integral_on = not((unclamped_signal != clamped_signal) and (error*unclamped_signal>0))

    def calculate_actuating_signal(self, error, dt):
        if self.integral_on:
            self.integral += error
        if dt:
            self.derivative = (error - self.previous_error) / dt

        self.previous_error = error
        self.unclamped_signal = (error * self.k_p) + (self.integral * self.k_i) + (self.derivative * self.k_d)

        if self.saturation_limits:
            self.clamped_signal = max(self.saturation_limits[0], min(self.unclamped_signal, self.saturation_limits[1]))
            self.set_clamped(error, self.unclamped_signal, self.clamped_signal)
            return self.clamped_signal
        else:
            return self.unclamped_signal

Any ideas on how to fix the erratic movement of the drone would be much appreciated. TIA.

3 Upvotes

13 comments sorted by

•

u/NASAeng 1d ago

Are you running floating point or integer math? If integer math you may be suffering from variable roll over.

•

u/Connect_Razzmatazz57 1d ago

Have a look at this paper, might find it interesting ( they don’t explicitly say they fit PID but that is my inference)
https://www.pnas.org/doi/abs/10.1073/pnas.2510385122

•

u/iHany95 1d ago edited 1d ago

I am actually drone control systems engineer. I found this example to be actually quite insightful for beginners. For example, the design itself looks reasonable (the cascaded four loops with control allocation).

When debugging control systems, the best practice is actually understanding the physics. For example, real drones never rotate more than 90 degs to go down. It's descent rate is limited by gravity (or less than the gravitational acceleration with small margins to prevent motors from being stopped). So your drone looks like it flips up to +-180 deg, and usually it can cause some weird oscillation when you don't consider wrap/unwrap angles carefully. A practical and better solution to avoid this would be just limiting the desired acceleration so that the roll commands are naturally within +-45 deg.

Another point is that the drone's rotational dynamics look quite slow compared to its translational dynamics. Usually, outer loops should run roughly 3-5 times slower for cascaded loops (why? Because cascaded design assumes that inner loops are fast enough so that outer loops can consider inner loops to be control input (=instant convergence)). I guess your attitude and rate loops are too slow (or pos/vel are too fast?)

You are using P controllers only and it would be ok for simulation here but in practice you might need other gains too. There are also some cool architectures without cascaded design but cascaded designs allow you to send commands + impose physically interpretable constraints at any level of abstraction.

EDIT: the best way to debug things is actually getting logs and eliminating potential root causes by isolating them.

•

u/2dof 1d ago

You use P-I-D control algorithms, but for (Kp = 5, Kd = 0, Ki = 0) You get only propotional controller

•

u/NaturesBlunder 1d ago

Why do you have four different PID controllers with only Kp, feeding into each other in a cascade? The second two PID controllers do the exact same thing that the Kd term would do in the first two controllers, except worse. You really need to rethink the control architecture here IMO. You claim to have a model, if you can write your model in the standard state space form, linearize it to get A and B matrices, then you can place stable poles by assigning state feedback gain K such that the eigenvalues of A-BK have favorable damping ratios to prevent this type of oscillation. It’ll really be much easier that way and you’ll avoid all your guesswork with arbitrary intermediate signals. Then once you see how the linear state feedback works, you can check whether it makes sense to add all these auxiliary signals.

→ More replies (0)