Created
July 29, 2023 22:28
-
-
Save lamont-granquist/dd4808b11d9f0ed110bdbfa57a597b50 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
public class QuaternionPIDController | |
{ | |
// PID gains for each component of the quaternion | |
private double Kp; | |
private double Ki; | |
private double Kd; | |
// Integral and derivative terms for each component of the quaternion | |
private Quaternion integralError; | |
private Quaternion previousError; | |
// Desired quaternion setpoint | |
private Quaternion setpoint; | |
public QuaternionPIDController(double kp, double ki, double kd) | |
{ | |
Kp = kp; | |
Ki = ki; | |
Kd = kd; | |
integralError = new Quaternion(0, 0, 0, 0); | |
previousError = new Quaternion(0, 0, 0, 0); | |
setpoint = new Quaternion(0, 0, 0, 1); | |
} | |
public void SetSetpoint(Quaternion desiredSetpoint) | |
{ | |
setpoint = desiredSetpoint; | |
} | |
public Quaternion Update(Quaternion currentOrientation, double deltaTime) | |
{ | |
// Calculate the error between the current orientation and the setpoint | |
Quaternion error = setpoint * Quaternion.Conjugate(currentOrientation); | |
// Ensure the error lies within the shortest arc | |
if (error.W < 0) | |
{ | |
error = new Quaternion(-error.X, -error.Y, -error.Z, -error.W); | |
} | |
// Update integral term | |
integralError += error * deltaTime; | |
// Update derivative term | |
Quaternion derivativeError = (error - previousError) / deltaTime; | |
previousError = error; | |
// Calculate the control output | |
Quaternion controlOutput = Kp * error + Ki * integralError + Kd * derivativeError; | |
// Return the control output (ensure it's a valid quaternion) | |
return Quaternion.Normalize(controlOutput); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment