can you apply it to my code?
- User
can you apply it to my code?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
can you apply it to my code?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, I've integrated the servoAngleForThrusterAngle function into your code.
Here's the complete modified code. I've added the new function and updated the TVC PID control section to use it.
Key Changes:
servoAngleForThrusterAngle function: Added near the top of the file. This function takes the desired thruster deflection (how much you want the thruster to move from its neutral position, e.g., +10 degrees or -5 degrees) and calculates the required servo deflection to achieve that.pid_correction calculated by your PID is the desired thruster deflection.pid_correction is passed to servoAngleForThrusterAngle.servoAngleForThrusterAngle is the servo deflection needed.constrain after the calculation to ensure the final servo command stays within 0-180, though your max_deflection in the PID already helps.// === SPI VERSION with TVC + Reaction‐Wheel Control === // Make sure to uncomment "#define ICM_20948_USE_DMP" in ICM_20948_C.h
#include <SPI.h>
#include <ESP32Servo.h>
#include "ICM_20948.h" // Your ICM_20948 library header
#include <cmath> // For fabs, sqrt, atan2, asin, round
// --- SPI pins for VSPI (default) ---
#define SPI_SCLK 18
#define SPI_MISO 19
#define SPI_MOSI 23
#define CS_PIN 5 // Chip‐select for ICM-20948
// --- Reaction‐wheel ESC on GPIO27 ---
const int escPin = 27;
const int escFreq = 50; // 50 Hz for typical ESC PWM
const int escRes = 16; // 16-bit PWM resolution
// --- TVC servos on two GPIOs ---
Servo servoX, servoY;
int xPin = 13;
int yPin = 12;
// --- PID constants for reaction wheel (yaw rate) ---
const float Kp_rw = 3.3125f, Ki_rw = 0.2f, Kd_rw = 1.3f;
float prevError_rw = 0.0f, integral_rw = 0.0f;
unsigned long prevTime_rw_micros = 0;
// --- PID constants for TVC (roll/pitch) ---
const float Kp_tvc = 1.5f;
const float Ki_tvc = 0.1f;
const float Kd_tvc = 0.05f; // START VERY LOW (e.g., 0.0) AND TUNE UP
const float TVC_TIME_STEP_TARGET = 0.01f;
const float tvc_deadzone = 2.0f;
const float LPF_BETA = 0.2f;
// Variables for the LPF-based TVC PID
float current_roll_lpf = 0.0f;
float current_pitch_lpf = 0.0f;
float tvc_error_integral[2] = {0.0f, 0.0f};
float tvc_prev_error[2] = {0.0f, 0.0f};
unsigned long tvc_prev_time_micros = 0;
// TVC Limp Mode (Shutdown)
const float TVC_MAX_ANGLE_LIMIT = 30.0f; // Max filtered angle before TVC enters limp mode
const float TVC_RESET_ANGLE_LIMIT = 25.0f; // Angle below which TVC can exit limp mode
bool tvc_in_limp_mode = false;
// --- IMU object ---
ICM_20948_SPI imu;
// --- Helpers ---
uint32_t usToDuty(int us) {
return (uint32_t)us * ((1UL << escRes) - 1) / 20000;
}
static float lpf(float prev_lpf_val, float current_measurement, float beta) {
return beta * current_measurement + (1.0f - beta) * prev_lpf_val;
}
// --- TVC Servo-to-Thruster Angle Correction ---
// Input: desired_thruster_deflection_deg (theta_4 in your formula, interpreted as deflection from neutral)
// Output: required_servo_deflection_deg (theta_2 in your formula, interpreted as deflection from neutral)
// Formula: cos(theta_4 - theta_2) = 2.215 - 1.219*cos(theta_2) + 3.495*cos(theta_4)
// Rearranged for Newton-Raphson (f(theta_2) = 0):
// f(theta_2) = cos(theta_4 - theta_2) + 1.219*cos(theta_2) - 3.495*cos(theta_4) - 2.215
// f'(theta_2) = sin(theta_4 - theta_2) - 1.219*sin(theta_2)
float servoAngleForThrusterAngle(float desired_thruster_deflection_deg) {
float theta_4_rad = desired_thruster_deflection_deg * (PI / 180.0f);
// Initial guess for servo deflection (theta_2) in radians
// A good starting point is often the desired thruster deflection itself
float theta_2_rad = theta_4_rad;
const int MAX_ITERATIONS = 10; // Usually converges quickly
const float TOLERANCE = 0.0001f; // Tolerance in radians for convergence
for (int i = 0; i < MAX_ITERATIONS; ++i) {
float cos_theta_2 = cos(theta_2_rad);
float sin_theta_2 = sin(theta_2_rad);
float cos_theta_4_minus_theta_2 = cos(theta_4_rad - theta_2_rad);
float sin_theta_4_minus_theta_2 = sin(theta_4_rad - theta_2_rad);
// Calculate function value: f(theta_2)
float f_val = cos_theta_4_minus_theta_2 + 1.219f * cos_theta_2 - 3.495f * cos(theta_4_rad) - 2.215f;
// Check for convergence based on function value (close to zero)
if (fabs(f_val) < TOLERANCE) { // Check if f_val is already small enough
break;
}
// Calculate derivative: f'(theta_2)
float df_val = sin_theta_4_minus_theta_2 - 1.219f * sin_theta_2;
if (fabs(df_val) < 1e-6) { // Avoid division by zero or very small number
// Serial.println("Warning: Derivative close to zero in Newton-Raphson for TVC correction.");
// This might mean no solution or multiple solutions, or flat region.
// Returning current guess or uncorrected might be an option.
// For now, we just break and use the current theta_2_rad.
break;
}
// Newton-Raphson update: theta_2_new = theta_2_old - f(theta_2_old) / f'(theta_2_old)
float delta = f_val / df_val;
theta_2_rad -= delta;
// Check for convergence based on the change (delta)
if (fabs(delta) < TOLERANCE) {
break;
}
}
// Convert back to degrees
return theta_2_rad * (180.0f / PI);
}
// --- Setup ---
void setup() {
Serial.begin(115200);
while (!Serial);
Serial.println("Setup starting...");
SPI.begin(SPI_SCLK, SPI_MISO, SPI_MOSI);
Serial.println("Initializing IMU DMP...");
while (imu.begin(CS_PIN, SPI) != ICM_20948_Stat_Ok) {
Serial.println("IMU.begin failed; retrying...");
delay(500);
}
if (imu.initializeDMP() != ICM_20948_Stat_Ok) {
Serial.println("FATAL: initializeDMP failed!");
while (1);
}
if (imu.enableDMPSensor(INV_ICM20948_SENSOR_GAME_ROTATION_VECTOR) != ICM_20948_Stat_Ok) {
Serial.println("FATAL: enableDMPSensor failed!");
while (1);
}
if (imu.setDMPODRrate(DMP_ODR_Reg_Quat6, 1) != ICM_20948_Stat_Ok) { // 0=225Hz, 1=112.5Hz, 2=75Hz ... 9=22.5Hz
Serial.println("FATAL: setDMPODRrate failed!");
while (1);
}
if (imu.enableFIFO() != ICM_20948_Stat_Ok) {
Serial.println("FATAL: enableFIFO failed!");
while (1);
}
if (imu.enableDMP() != ICM_20948_Stat_Ok) {
Serial.println("FATAL: enableDMP failed!");
while (1);
}
if (imu.resetDMP() != ICM_20948_Stat_Ok) {
Serial.println("FATAL: resetDMP failed!");
while (1);
}
if (imu.resetFIFO() != ICM_20948_Stat_Ok) {
Serial.println("FATAL: resetFIFO failed!");
while (1);
}
Serial.println("ICM-20948 DMP ready.");
servoX.setPeriodHertz(50);
servoY.setPeriodHertz(50);
servoX.attach(xPin, 500, 2400);
servoY.attach(yPin, 500, 2400);
servoX.write(90);
servoY.write(90);
ledcAttach(escPin, escFreq, escRes);
Serial.println("Arming Reaction Wheel ESC: Sending 1500us. Please wait ~5 seconds...");
ledcWrite(escPin, usToDuty(1500));
delay(5000);
Serial.println("ESC presumed armed.");
tvc_prev_time_micros = micros();
prevTime_rw_micros = micros();
Serial.println("Setup complete.");
}
// --- Main loop ---
void loop() {
unsigned long loop_start_micros = micros();
// 1) TVC control using DMP Game Rotation Vector
icm_20948_DMP_data_t dmp_data;
if (imu.readDMPdataFromFIFO(&dmp_data) == ICM_20948_Stat_Ok && (dmp_data.header & DMP_header_bitmap_Quat6)) {
double q1 = static_cast<double>(dmp_data.Quat6.Data.Q1) / 1073741824.0; // X-axis rotation component
double q2 = static_cast<double>(dmp_data.Quat6.Data.Q2) / 1073741824.0; // Y-axis rotation component
double q3 = static_cast<double>(dmp_data.Quat6.Data.Q3) / 1073741824.0; // Z-axis rotation component
double q_sum_sq = q1 * q1 + q2 * q2 + q3 * q3;
double q0 = (q_sum_sq < 1.0) ? sqrt(1.0 - q_sum_sq) : 0.0;
// Standard Euler Angle Convention (Confirm your IMU axis mapping to Roll/Pitch vehicle axes)
// Roll (around IMU X-axis / vehicle's longitudinal axis)
double t0_roll = 2.0 * (q0 * q1 + q2 * q3);
double t1_roll = 1.0 - 2.0 * (q1 * q1 + q2 * q2);
float current_roll_raw = atan2(t0_roll, t1_roll) * (180.0 / PI);
// Pitch (around IMU Y-axis / vehicle's transverse axis)
double t2_pitch = 2.0 * (q0 * q2 - q3 * q1);
if (t2_pitch > 1.0) t2_pitch = 1.0;
if (t2_pitch < -1.0) t2_pitch = -1.0;
float current_pitch_raw = asin(t2_pitch) * (180.0 / PI);
current_roll_lpf = lpf(current_roll_lpf, current_roll_raw, LPF_BETA);
current_pitch_lpf = lpf(current_pitch_lpf, current_pitch_raw, LPF_BETA);
// ---------- TVC Limp Mode Logic ------------------------------
if (!tvc_in_limp_mode &&
(fabs(current_roll_lpf) > TVC_MAX_ANGLE_LIMIT ||
fabs(current_pitch_lpf) > TVC_MAX_ANGLE_LIMIT)) {
Serial.println("!!! TVC Entering LIMP MODE: Angle limit exceeded !!!");
tvc_in_limp_mode = true;
servoX.write(90); // Go to neutral
servoY.write(90);
tvc_error_integral[0] = 0.0f; // Reset PID state
tvc_error_integral[1] = 0.0f;
tvc_prev_error[0] = 0.0f; // Reset previous error for D term
tvc_prev_error[1] = 0.0f;
}
if (tvc_in_limp_mode &&
fabs(current_roll_lpf) < TVC_RESET_ANGLE_LIMIT &&
fabs(current_pitch_lpf) < TVC_RESET_ANGLE_LIMIT) {
Serial.println("TVC Exiting LIMP MODE: Angles back in range.");
tvc_in_limp_mode = false;
}
// --- TVC PID Control ---
if (!tvc_in_limp_mode) {
unsigned long current_tvc_micros = micros();
float dt_tvc = (tvc_prev_time_micros == 0) ? TVC_TIME_STEP_TARGET : static_cast<float>(current_tvc_micros - tvc_prev_time_micros) * 1e-6f;
if (dt_tvc <= 0.00001f) { dt_tvc = TVC_TIME_STEP_TARGET; }
tvc_prev_time_micros = current_tvc_micros;
float tvc_error[2];
tvc_error[0] = 0.0f - current_roll_lpf; // Error for X-axis servo (controls roll)
tvc_error[1] = 0.0f - current_pitch_lpf; // Error for Y-axis servo (controls pitch)
// This will store the final servo angles (e.g., 0-180)
float final_servo_angle_command[2] = {90.0f, 90.0f};
for (int axis = 0; axis < 2; ++axis) {
if (fabs(tvc_error[axis]) < tvc_deadzone) {
// Within deadzone, desired thruster deflection is 0, so servo stays at neutral
final_servo_angle_command[axis] = 90.0f;
tvc_error_integral[axis] = 0.0f; // Reset integral if in deadzone
// tvc_prev_error[axis] = 0.0f; // Optionally reset derivative component too
} else {
tvc_error_integral[axis] += tvc_error[axis] * dt_tvc;
// Optional: Clamp tvc_error_integral[axis] here if needed
float derivative = (dt_tvc > 0.00001f) ? (tvc_error[axis] - tvc_prev_error[axis]) / dt_tvc : 0.0f;
// pid_correction is the DESIRED THRUSTER DEFLECTION from neutral
float pid_thruster_deflection = Kp_tvc * tvc_error[axis] +
Ki_tvc * tvc_error_integral[axis] +
Kd_tvc * derivative;
float max_thruster_deflection = 30.0f; // Max desired thruster deflection
pid_thruster_deflection = constrain(pid_thruster_deflection, -max_thruster_deflection, max_thruster_deflection);
// Now, convert desired thruster deflection to required servo deflection
float required_servo_deflection = servoAngleForThrusterAngle(pid_thruster_deflection);
// The final servo command is neutral (90) + calculated servo deflection
final_servo_angle_command[axis] = 90.0f + round(required_servo_deflection);
}
tvc_prev_error[axis] = tvc_error[axis];
}
// Constrain final servo commands to valid servo range (0-180)
// This is important as the servoAngleForThrusterAngle might return values
// that, when added to 90, go out of bounds, or if the Newton-Raphson
// doesn't converge well for extreme inputs.
int servo_x_cmd = constrain(static_cast<int>(final_servo_angle_command[0]), 0, 180);
int servo_y_cmd = constrain(static_cast<int>(final_servo_angle_command[1]), 0, 180);
servoX.write(servo_x_cmd);
servoY.write(servo_y_cmd);
Serial.print("ACTIVE Roll: "); Serial.print(current_roll_lpf, 1);
Serial.print(", Pitch: "); Serial.print(current_pitch_lpf, 1);
Serial.print(" | ServoX: "); Serial.print(servo_x_cmd); // Print actual command
Serial.print(", ServoY: "); Serial.println(servo_y_cmd); // Print actual command
} else { // TVC is in LIMP MODE
servoX.write(90);
servoY.write(90);
Serial.print("LIMP MODE Roll: "); Serial.print(current_roll_lpf, 1);
Serial.print(", Pitch: "); Serial.print(current_pitch_lpf, 1);
Serial.println(" | Servos at Neutral.");
}
} // End of DMP data processing
// 2) Reaction-wheel yaw‐rate PID
if (!tvc_in_limp_mode && imu.dataReady()) { // Only run RW PID if TVC is not in limp mode
imu.getAGMT(); // Make sure to call this to get latest gyro data
float yawRate = imu.gyrZ(); // Make sure this is degrees/sec or rad/sec consistently with PID
float targetYawRate = 0.0f;
unsigned long current_rw_micros = micros();
float dt_rw = (prevTime_rw_micros == 0) ? TVC_TIME_STEP_TARGET : static_cast<float>(current_rw_micros - prevTime_rw_micros) * 1e-6f;
if (dt_rw <= 0.00001f) { dt_rw = TVC_TIME_STEP_TARGET; } // Prevent division by zero or too small dt
prevTime_rw_micros = current_rw_micros;
float error_rw = targetYawRate - yawRate;
integral_rw += error_rw * dt_rw;
// Optional: Clamp integral_rw here
float derivative_rw = (dt_rw > 0.00001f) ? (error_rw - prevError_rw) / dt_rw : 0.0f;
prevError_rw = error_rw;
float pid_output_rw = Kp_rw * error_rw + Ki_rw * integral_rw + Kd_rw * derivative_rw;
// pid_output_rw is a correction value. 1500us is neutral.
// Positive pid_output_rw should decrease pulse (e.g. to speed up CCW / slow down CW)
// Negative pid_output_rw should increase pulse (e.g. to speed up CW / slow down CCW)
// This depends on your motor direction and how PID output maps to thrust change.
// Assuming positive PID output means "need more speed in one direction"
// and the ESC maps 1000us to max reverse/stop, 1500us to stop, 2000us to max forward.
// If pid_output_rw is positive (e.g. need to counteract positive yawRate):
// - If motor spins CCW for pulse > 1500, then we need pulse < 1500.
// - So, 1500 - pid_output_rw.
// Check this logic carefully for your setup.
int pulse_rw = static_cast<int>(round(1500.0f - pid_output_rw)); // Sign might need to be +
pulse_rw = constrain(pulse_rw, 1000, 2000);
ledcWrite(escPin, usToDuty(pulse_rw));
} else if (tvc_in_limp_mode) { // If TVC is in limp mode, set reaction wheel to neutral for safety
ledcWrite(escPin, usToDuty(1500));
// Serial.println("Reaction Wheel Neutral due to TVC Limp Mode.");
}
// --- Maintain loop rate ---
long loop_duration_micros = micros() - loop_start_micros;
long delay_needed_micros = static_cast<long>(TVC_TIME_STEP_TARGET * 1e6f) - loop_duration_micros;
if (delay_needed_micros > 0) {
delayMicroseconds(delay_needed_micros);
}
}
Important Considerations for servoAngleForThrusterAngle:
theta_4 and theta_2 in your formula are deflections from a neutral/zero point. If they are absolute mechanical angles, you might need to adjust how desired_thruster_deflection_deg is used and how the result is interpreted. My current implementation treats the input and output of servoAngleForThrusterAngle as deflections.theta_2_rad = theta_4_rad) is crucial. If it's too far from the actual solution, the method might not converge or might converge to an incorrect root.df_val can become zero or very small, leading to division by zero or instability. I've added a small check for this.MAX_ITERATIONS and TOLERANCE might need tuning.theta_4 and theta_2. Test it with extreme values that your PID might output.cmath trigonometric functions (cos, sin) expect radians.pid_thruster_deflection and output required_servo_deflection from the servoAngleForThrusterAngle function to see if the mapping makes sense.// Inside the TVC PID loop, after calling servoAngleForThrusterAngle
// Serial.print(" Axis: "); Serial.print(axis);
// Serial.print(" ThrusterDeflect: "); Serial.print(pid_thruster_deflection);
// Serial.print(" ServoDeflect: "); Serial.println(required_servo_deflection);
Test this thoroughly. The kinematic correction can significantly improve accuracy but also introduce complexity if the formula is sensitive or has tricky numerical properties.