### CMake Build Configuration Source: https://github.com/xiotechnologies/fusion/blob/main/CMakeLists.txt This CMake script defines the build for the Fusion project. It includes the main Fusion library and example subdirectories. The Python imufusion library is conditionally included for debug builds. ```cmake cmake_minimum_required(VERSION 3.15) project(Fusion) add_subdirectory("Fusion") add_subdirectory("Examples/C/Advanced") add_subdirectory("Examples/C/Simple") if(CMAKE_BUILD_TYPE STREQUAL "Debug") add_subdirectory("Python/imufusion") # do not include when run by CI endif() ``` -------------------------------- ### AHRS Outputs - Gravity and Acceleration in Python Source: https://context7.com/xiotechnologies/fusion/llms.txt Retrieves gravity vector and acceleration data from the AHRS algorithm for motion analysis. This example uses the `update_no_magnetometer` method. ```python import imufusion import numpy as np ahrs = imufusion.Ahrs() # Update AHRS with sensor data ahrs.update_no_magnetometer( np.array([0.0, 0.0, 0.0]), # gyroscope np.array([0.1, 0.0, 0.98]), # accelerometer with slight motion 0.01 ) ``` -------------------------------- ### Get AHRS Acceleration Outputs (C) Source: https://context7.com/xiotechnologies/fusion/llms.txt Retrieve gravity vector, linear acceleration, and Earth-frame acceleration from the AHRS algorithm. Useful for motion analysis applications. ```c #include "Fusion.h" #include void get_acceleration_data(FusionAhrs *ahrs) { // Get gravity direction in sensor frame FusionVector gravity = FusionAhrsGetGravity(ahrs); // Get linear acceleration (accelerometer minus gravity, sensor frame) FusionVector linearAccel = FusionAhrsGetLinearAcceleration(ahrs); // Get Earth-frame acceleration (gravity removed, in Earth coordinates) FusionVector earthAccel = FusionAhrsGetEarthAcceleration(ahrs); printf("Gravity: X=%0.2f, Y=%0.2f, Z=%0.2f\n", gravity.axis.x, gravity.axis.y, gravity.axis.z); printf("Linear Accel: X=%0.2f, Y=%0.2f, Z=%0.2f g\n", linearAccel.axis.x, linearAccel.axis.y, linearAccel.axis.z); printf("Earth Accel: X=%0.2f, Y=%0.2f, Z=%0.2f g\n", earthAccel.axis.x, earthAccel.axis.y, earthAccel.axis.z); } ``` -------------------------------- ### Set and Get AHRS Quaternion State Source: https://context7.com/xiotechnologies/fusion/llms.txt Allows manual setting or retrieval of the AHRS quaternion state. Useful for initializing the orientation or transferring state between AHRS instances. ```python import imufusion import numpy as np ahrs = imufusion.Ahrs() # Set initial orientation (quaternion: [w, x, y, z]) initial_quaternion = np.array([1.0, 0.0, 0.0, 0.0]) # Identity ahrs.quaternion = initial_quaternion # Process data... ahrs.update_no_magnetometer(np.array([0, 0, 0]), np.array([0, 0, 1]), 0.01) # Get current quaternion current_quaternion = ahrs.quaternion print(f"Quaternion: w={current_quaternion[0]:.4f}, " f"x={current_quaternion[1]:.4f}, " f"y={current_quaternion[2]:.4f}, " f"z={current_quaternion[3]:.4f}") ``` -------------------------------- ### Get Gravity Direction in Sensor Frame Source: https://context7.com/xiotechnologies/fusion/llms.txt Retrieves the gravity vector in the sensor's coordinate frame using the AHRS object. This is useful for understanding the orientation relative to gravity. ```python import imufusion import numpy as np # Assume ahrs is an initialized imufusion.Ahrs object ahrs = imufusion.Ahrs() # Get gravity direction in sensor frame gravity = ahrs.gravity print(f"Gravity: X={gravity[0]:.3f}, Y={gravity[1]:.3f}, Z={gravity[2]:.3f}") # Get linear acceleration (accelerometer minus gravity, sensor frame) linear_accel = ahrs.linear_acceleration print(f"Linear Accel: X={linear_accel[0]:.3f}, Y={linear_accel[1]:.3f}, Z={linear_accel[2]:.3f} g") # Get Earth-frame acceleration (gravity removed, rotated to Earth frame) earth_accel = ahrs.earth_acceleration print(f"Earth Accel: X={earth_accel[0]:.3f}, Y={earth_accel[1]:.3f}, Z={earth_accel[2]:.3f} g") ``` -------------------------------- ### Initialize and Configure AHRS (C) Source: https://context7.com/xiotechnologies/fusion/llms.txt Sets up the AHRS structure and applies configuration settings including axes convention, algorithm gain, and rejection thresholds. ```c #include "Fusion.h" #define SAMPLE_RATE 100 // 100 Hz int main() { // Initialize AHRS structure FusionAhrs ahrs; FusionAhrsInitialise(&ahrs); // Configure AHRS settings const FusionAhrsSettings settings = { .convention = FusionConventionNwu, // North-West-Up convention .gain = 0.5f, // Algorithm gain (0.5 typical) .gyroscopeRange = 2000.0f, // Gyroscope range in deg/s .accelerationRejection = 10.0f, // Rejection threshold in degrees .magneticRejection = 10.0f, // Rejection threshold in degrees .recoveryTriggerPeriod = 5 * SAMPLE_RATE, // 5 seconds }; FusionAhrsSetSettings(&ahrs, &settings); return 0; } ``` -------------------------------- ### Vector Operations in C Source: https://context7.com/xiotechnologies/fusion/llms.txt Demonstrates common vector operations like addition, subtraction, scaling, dot product, cross product, magnitude calculation, normalization, and checking for zero vectors using the Fusion C library. ```c #include "Fusion.h" #include void vector_operations_example(void) { FusionVector a = {1.0f, 2.0f, 3.0f}; FusionVector b = {4.0f, 5.0f, 6.0f}; // Vector addition FusionVector sum = FusionVectorAdd(a, b); // {5, 7, 9} // Vector subtraction FusionVector diff = FusionVectorSubtract(a, b); // {-3, -3, -3} // Scalar multiplication FusionVector scaled = FusionVectorScale(a, 2.0f); // {2, 4, 6} // Dot product float dot = FusionVectorDot(a, b); // 32.0 // Cross product FusionVector cross = FusionVectorCross(a, b); // {-3, 6, -3} // Magnitude float magnitude = FusionVectorNorm(a); // 3.74... // Normalize FusionVector normalized = FusionVectorNormalise(a); // Check if zero bool isZero = FusionVectorIsZero(FUSION_VECTOR_ZERO); // true } ``` -------------------------------- ### Link Math Library on Unix/Linux Source: https://github.com/xiotechnologies/fusion/blob/main/Fusion/CMakeLists.txt Conditionally links the math library ('m') to the Fusion library when the build system is Unix and not Apple. This is necessary for certain math functions on Linux. ```cmake if(UNIX AND NOT APPLE) target_link_libraries(Fusion m) # link math library for Linux endif() ``` -------------------------------- ### Define Fusion Library with Source Files Source: https://github.com/xiotechnologies/fusion/blob/main/Fusion/CMakeLists.txt This snippet defines a static library named 'Fusion' and includes all C source files found recursively in the current directory. Ensure all source files are correctly placed. ```cmake file(GLOB_RECURSE files "*.c") add_library(Fusion ${files}) ``` -------------------------------- ### Configure imufusion CMake build Source: https://github.com/xiotechnologies/fusion/blob/main/Python/imufusion/CMakeLists.txt Defines the library target and links necessary Python and NumPy dependencies. ```cmake file(GLOB_RECURSE files "*.c") add_library(imufusion-Python-Package ${files}) find_package(Python COMPONENTS Development NumPy) target_link_libraries(imufusion-Python-Package PRIVATE Python::Python Python::NumPy) ``` -------------------------------- ### Apply Magnetic Sensor Calibration Source: https://context7.com/xiotechnologies/fusion/llms.txt Applies calibration parameters to raw magnetometer data using the `model_magnetic` function. Requires soft-iron and hard-iron calibration values. ```python import imufusion import numpy as np # Magnetometer calibration uncalibrated_mag = np.array([45.0, 10.0, -30.0]) soft_iron_matrix = np.eye(3) hard_iron_offset = np.array([25.0, -15.0, 5.0]) calibrated_mag = imufusion.model_magnetic( uncalibrated_mag, soft_iron_matrix, hard_iron_offset ) print(f"Calibrated Magnetometer: {calibrated_mag}") ``` -------------------------------- ### Full AHRS with Magnetometer and Bias Correction in Python Source: https://context7.com/xiotechnologies/fusion/llms.txt Configures and uses the full AHRS algorithm with magnetometer data, custom settings, and gyroscope bias estimation. Requires sensor data including magnetometer readings. ```python import imufusion import numpy as np # Load sensor data data = np.genfromtxt("sensor_data.csv", delimiter=",", skip_header=1) sample_rate = 100 timestamp = data[:, 0] gyroscope = data[:, 1:4] accelerometer = data[:, 4:7] magnetometer = data[:, 7:10] # Initialize bias correction bias = imufusion.Bias() bias.settings = imufusion.BiasSettings(sample_rate) # Initialize AHRS with custom settings ahrs = imufusion.Ahrs() ahrs.settings = imufusion.AhrsSettings( convention=imufusion.CONVENTION_NWU, gain=0.5, gyroscope_range=2000, # deg/s acceleration_rejection=10, # degrees magnetic_rejection=10, # degrees recovery_trigger_period=5 * sample_rate, # 5 seconds ) # Calculate variable delta time delta_time = np.diff(timestamp, prepend=timestamp[0]) # Process data euler = np.empty((len(timestamp), 3)) for i in range(len(timestamp)): # Apply bias correction to gyroscope corrected_gyro = bias.update(gyroscope[i]) # Update AHRS with all sensors ahrs.update(corrected_gyro, accelerometer[i], magnetometer[i], delta_time[i]) # Get Euler angles euler[i] = imufusion.quaternion_to_euler(ahrs.quaternion) print(f"Roll: {euler[-1, 0]:.2f}, Pitch: {euler[-1, 1]:.2f}, Yaw: {euler[-1, 2]:.2f}") ``` -------------------------------- ### Calibrate Inertial Sensors in C Source: https://context7.com/xiotechnologies/fusion/llms.txt Applies misalignment, sensitivity, and offset parameters to raw gyroscope or accelerometer data. ```c #include "Fusion.h" void calibrate_inertial_sensors(void) { // Calibration parameters (obtained from calibration procedure) const FusionMatrix misalignment = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; const FusionVector sensitivity = {1.0f, 1.0f, 1.0f}; const FusionVector offset = {0.0f, 0.0f, 0.0f}; // Raw sensor reading FusionVector uncalibrated = {100.5f, -50.2f, 980.1f}; // Apply calibration: calibrated = M * s * (uncalibrated - b) FusionVector calibrated = FusionModelInertial(uncalibrated, misalignment, sensitivity, offset); } ``` -------------------------------- ### Set Public Include Directories for Fusion Source: https://github.com/xiotechnologies/fusion/blob/main/Fusion/CMakeLists.txt Configures the public include directories for the Fusion library. This allows other targets to include headers from the Fusion library's root directory. ```cmake target_include_directories(Fusion PUBLIC .) ``` -------------------------------- ### Enable Normal Square Root for Normalization Source: https://github.com/xiotechnologies/fusion/blob/main/README.md Define FUSION_USE_NORMAL_SQRT or add it as a preprocessor definition to use normal square root operations for all normalization calculations instead of Pizer's fast inverse square root. This may slightly increase accuracy at the cost of execution speed. ```c #define FUSION_USE_NORMAL_SQRT ``` -------------------------------- ### Simple AHRS (No Magnetometer) in Python Source: https://context7.com/xiotechnologies/fusion/llms.txt Processes IMU data using the imufusion Python package to compute orientation with only gyroscope and accelerometer data. Ensure sensor data is loaded from a CSV file. ```python import imufusion import numpy as np # Load sensor data from CSV data = np.genfromtxt("sensor_data.csv", delimiter=",", skip_header=1) timestamp = data[:, 0] gyroscope = data[:, 1:4] # deg/s accelerometer = data[:, 4:7] # g # Initialize AHRS ahrs = imufusion.Ahrs() # Process each sample sample_rate = 100 # Hz euler_angles = np.empty((len(timestamp), 3)) for i in range(len(timestamp)): ahrs.update_no_magnetometer(gyroscope[i], accelerometer[i], 1 / sample_rate) euler_angles[i] = imufusion.quaternion_to_euler(ahrs.quaternion) # euler_angles contains [roll, pitch, yaw] in degrees for each sample print(f"Final orientation: Roll={euler_angles[-1, 0]:.1f}, " f"Pitch={euler_angles[-1, 1]:.1f}, Yaw={euler_angles[-1, 2]:.1f}") ``` -------------------------------- ### FusionBiasSetSettings Source: https://github.com/xiotechnologies/fusion/blob/main/README.md Configures the settings for the gyroscope bias estimation algorithm. ```APIDOC ## POST FusionBiasSetSettings ### Description Configures the `FusionBiasSettings` structure to define how the algorithm estimates gyroscope offsets. ### Request Body - **sampleRate** (float) - Sample rate in Hz (Default: 100). - **stationaryThreshold** (float) - Stationary detection threshold in degrees per second (Default: 3). - **stationaryPeriod** (float) - Stationary detection period in seconds (Default: 3). ``` -------------------------------- ### Calibrate Magnetometer in C Source: https://context7.com/xiotechnologies/fusion/llms.txt Corrects magnetometer readings for soft-iron distortion and hard-iron offsets. ```c #include "Fusion.h" void calibrate_magnetometer(void) { // Soft-iron matrix (corrects for ellipsoid distortion) const FusionMatrix softIronMatrix = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f }; // Hard-iron offset (corrects for permanent magnetic fields) const FusionVector hardIronOffset = {25.0f, -15.0f, 5.0f}; // Raw magnetometer reading FusionVector uncalibrated = {45.0f, 10.0f, -30.0f}; // Apply calibration: calibrated = S * (uncalibrated - h) FusionVector calibrated = FusionModelMagnetic(uncalibrated, softIronMatrix, hardIronOffset); } ``` -------------------------------- ### Bias Algorithm for Gyroscope Offset Compensation (C) Source: https://context7.com/xiotechnologies/fusion/llms.txt Initialize and use the bias algorithm for runtime estimation of gyroscope offset. Configures sample rate, stationary threshold, and stationary period. ```c #include "Fusion.h" #include #define SAMPLE_RATE 100 // 100 Hz void bias_compensation_example(void) { // Initialize bias algorithm FusionBias bias; FusionBiasInitialise(&bias); // Configure bias settings FusionBiasSettings biasSettings = fusionBiasDefaultSettings; biasSettings.sampleRate = SAMPLE_RATE; biasSettings.stationaryThreshold = 3.0f; // deg/s biasSettings.stationaryPeriod = 3.0f; // seconds FusionBiasSetSettings(&bias, &biasSettings); // Initialize AHRS FusionAhrs ahrs; FusionAhrsInitialise(&ahrs); while (1) { // Read raw gyroscope (replace with actual data) FusionVector gyroscope = {0.1f, -0.05f, 0.02f}; // Apply bias correction gyroscope = FusionBiasUpdate(&bias, gyroscope); // Use corrected gyroscope with AHRS FusionVector accelerometer = {0.0f, 0.0f, 1.0f}; FusionAhrsUpdateNoMagnetometer(&ahrs, gyroscope, accelerometer, 1.0f / SAMPLE_RATE); } } ``` -------------------------------- ### Calculate Tilt-Compensated Compass Heading in C Source: https://context7.com/xiotechnologies/fusion/llms.txt Computes magnetic heading using accelerometer and magnetometer data without requiring full AHRS orientation. ```c #include "Fusion.h" #include void calculate_compass_heading(void) { // Sensor readings FusionVector accelerometer = {0.0f, 0.0f, 1.0f}; // g FusionVector magnetometer = {0.5f, 0.3f, -0.2f}; // arbitrary units // Calculate tilt-compensated heading float heading = FusionCompass(accelerometer, magnetometer, FusionConventionNwu); printf("Compass Heading: %0.1f degrees\n", heading); } ``` -------------------------------- ### Save and Restore Bias Offset (C) Source: https://context7.com/xiotechnologies/fusion/llms.txt Save gyroscope offset estimates to non-volatile memory and restore them to avoid re-estimation after power cycles. ```c #include "Fusion.h" void save_bias_offset(FusionBias *bias) { // Get current offset estimate FusionVector offset = FusionBiasGetOffset(bias); // Save to non-volatile memory (implementation depends on platform) // nvm_write(&offset, sizeof(offset)); } ``` ```c #include "Fusion.h" void restore_bias_offset(FusionBias *bias) { // Load from non-volatile memory FusionVector offset; // nvm_read(&offset, sizeof(offset)); // Restore offset FusionBiasSetOffset(bias, offset); } ``` -------------------------------- ### Apply Inertial Sensor Calibration Source: https://context7.com/xiotechnologies/fusion/llms.txt Applies calibration parameters to raw accelerometer or gyroscope data using the `model_inertial` function. Requires misalignment, sensitivity, and offset matrices/vectors. ```python import imufusion import numpy as np # Inertial calibration (gyroscope or accelerometer) uncalibrated_accel = np.array([0.01, -0.02, 1.01]) misalignment = np.eye(3) # Identity matrix sensitivity = np.array([1.0, 1.0, 1.0]) offset = np.array([0.01, -0.02, 0.01]) calibrated_accel = imufusion.model_inertial( uncalibrated_accel, misalignment, sensitivity, offset ) print(f"Calibrated Accelerometer: {calibrated_accel}") ``` -------------------------------- ### Save and Restore Gyroscope Offset Source: https://github.com/xiotechnologies/fusion/blob/main/README.md Use FusionBiasGetOffset to restore a previously saved gyroscope offset and FusionBiasSetOffset to save the current offset to non-volatile memory. This avoids re-estimation after power cycles. ```c FusionBiasGetOffset(fusionOffset); FusionBiasSetOffset(fusionOffset); ``` -------------------------------- ### Apply Inertial Sensor Calibration Source: https://github.com/xiotechnologies/fusion/blob/main/README.md The FusionModelInertial function applies gyroscope or accelerometer calibration parameters, including misalignment, sensitivity, and offset. It takes uncalibrated sensor data and returns calibrated data. ```c FusionModelInertial(uncalibrated, misalignment, sensitivity, offset, &calibrated); ``` -------------------------------- ### Convert Quaternion to Euler Angles in C Source: https://context7.com/xiotechnologies/fusion/llms.txt Converts a quaternion to roll, pitch, and yaw angles using ZYX rotation order. ```c #include "Fusion.h" #include void convert_orientation(FusionQuaternion quaternion) { // Convert quaternion to Euler angles FusionEuler euler = FusionQuaternionToEuler(quaternion); printf("Roll: %0.1f deg\n", euler.angle.roll); // Rotation around X printf("Pitch: %0.1f deg\n", euler.angle.pitch); // Rotation around Y printf("Yaw: %0.1f deg\n", euler.angle.yaw); // Rotation around Z } ``` -------------------------------- ### Convert Quaternion to Rotation Matrix in C Source: https://context7.com/xiotechnologies/fusion/llms.txt Transforms a quaternion into a 3x3 rotation matrix for coordinate system transformations. ```c #include "Fusion.h" #include void quaternion_to_matrix_example(FusionQuaternion quaternion) { // Convert quaternion to rotation matrix FusionMatrix matrix = FusionQuaternionToMatrix(quaternion); printf("Rotation Matrix:\n"); printf("[%0.3f, %0.3f, %0.3f]\n", matrix.element.xx, matrix.element.xy, matrix.element.xz); printf("[%0.3f, %0.3f, %0.3f]\n", matrix.element.yx, matrix.element.yy, matrix.element.yz); printf("[%0.3f, %0.3f, %0.3f]\n", matrix.element.zx, matrix.element.zy, matrix.element.zz); } ``` -------------------------------- ### Restart AHRS Algorithm Source: https://context7.com/xiotechnologies/fusion/llms.txt Restarts the AHRS algorithm to trigger its startup procedure, allowing for rapid convergence to a new orientation. Call `ahrs.restart()` when a significant change in device orientation is detected. ```python import imufusion import numpy as np ahrs = imufusion.Ahrs() # Normal operation for _ in range(1000): ahrs.update_no_magnetometer(np.array([0, 0, 0]), np.array([0, 0, 1]), 0.01) # Device orientation changed significantly - restart algorithm ahrs.restart() # The algorithm will now rapidly converge to the new orientation ahrs.update_no_magnetometer(np.array([0, 0, 0]), np.array([0, 1, 0]), 0.01) ``` -------------------------------- ### Calculate Tilt-Compensated Compass Heading Source: https://context7.com/xiotechnologies/fusion/llms.txt Calculates magnetic heading using accelerometer and magnetometer data without requiring full AHRS orientation estimation. Uses the `compass` function with specified convention. ```python import imufusion import numpy as np accelerometer = np.array([0.0, 0.0, 1.0]) # Level orientation magnetometer = np.array([0.5, 0.3, -0.2]) # Magnetic field vector # Calculate heading with NWU convention heading = imufusion.compass(accelerometer, magnetometer, imufusion.CONVENTION_NWU) print(f"Compass Heading: {heading:.1f} degrees") ``` -------------------------------- ### Remap Sensor Axes in C Source: https://context7.com/xiotechnologies/fusion/llms.txt Adjusts sensor data to match the body frame orientation using one of 24 orthogonal alignments. ```c #include "Fusion.h" void remap_sensor_axes(void) { // Raw sensor reading in sensor frame FusionVector sensorData = {1.0f, 2.0f, 3.0f}; // Remap if sensor Y-axis aligns with body X-axis (and so on) // Example: +Y+Z+X alignment FusionVector bodyData = FusionRemap(sensorData, FusionRemapAlignmentPYPZPX); // Result: bodyData.x = sensor.y, bodyData.y = sensor.z, bodyData.z = sensor.x } ``` -------------------------------- ### Remap Sensor Axes to Body Frame Source: https://context7.com/xiotechnologies/fusion/llms.txt Remaps sensor axes to align with the body frame when the IMU is mounted in a non-standard orientation. Use `imufusion.ALIGNMENT_...` constants for common remappings. ```python import imufusion import numpy as np # Sensor data in sensor coordinate frame sensor_data = np.array([1.0, 2.0, 3.0]) # Remap axes: if sensor is mounted such that # body X = sensor Y, body Y = sensor Z, body Z = sensor X body_data = imufusion.remap(sensor_data, imufusion.ALIGNMENT_PYPZPX) print(f"Sensor frame: {sensor_data}") print(f"Body frame: {body_data}") # [2.0, 3.0, 1.0] ``` -------------------------------- ### Algorithm Settings Source: https://github.com/xiotechnologies/fusion/blob/main/README.md The AHRS algorithm's behavior can be customized through various settings, affecting its sensor fusion, rejection features, and coordinate system conventions. ```APIDOC ## Algorithm Settings ### Description The AHRS algorithm settings are defined by the `FusionAhrsSettings` structure and set using the `FusionAhrsSetSettings` function. ### Parameters #### Request Body - **convention** (enum) - Required - Earth axes convention (NWU, ENU, or NED). - **gain** (float) - Required - Determines the influence of the gyroscope relative to other sensors. A value of zero will disable startup and the acceleration and magnetic rejection features. A value of 0.5 is appropriate for most applications. - **gyroscopeRange** (float) - Required - Gyroscope range (in degrees per second). Angular rate recovery will activate if the gyroscope measurement exceeds 98% of this value. A value of zero will disable this feature. The value should be set to the range specified in the gyroscope datasheet. - **accelerationRejection** (float) - Required - Threshold (in degrees) used by the acceleration rejection feature. A value of zero will disable this feature. A value of 10 degrees is appropriate for most applications. - **magneticRejection** (float) - Required - Threshold (in degrees) used by the magnetic rejection feature. A value of zero will disable the feature. A value of 10 degrees is appropriate for most applications. - **recoveryTriggerPeriod** (int) - Required - Acceleration and magnetic recovery trigger period (in samples). A value of zero will disable the acceleration and magnetic rejection features. A period of 5 seconds is appropriate for most applications. ### Request Example ```json { "convention": "ENU", "gain": 0.5, "gyroscopeRange": 2000.0, "accelerationRejection": 10.0, "magneticRejection": 10.0, "recoveryTriggerPeriod": 250 } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "Settings applied successfully." } ``` ``` -------------------------------- ### Update AHRS with Magnetometer (C) Source: https://context7.com/xiotechnologies/fusion/llms.txt Processes gyroscope, accelerometer, and magnetometer data to compute orientation as a quaternion, which can then be converted to Euler angles. ```c #include "Fusion.h" #include void process_imu_sample(FusionAhrs *ahrs, float deltaTime) { // Sensor measurements (replace with actual sensor data) const FusionVector gyroscope = {0.0f, 0.0f, 0.0f}; // deg/s const FusionVector accelerometer = {0.0f, 0.0f, 1.0f}; // g const FusionVector magnetometer = {1.0f, 0.0f, 0.0f}; // arbitrary units // Update AHRS with all sensors FusionAhrsUpdate(ahrs, gyroscope, accelerometer, magnetometer, deltaTime); // Get orientation as quaternion and convert to Euler angles FusionQuaternion quaternion = FusionAhrsGetQuaternion(ahrs); FusionEuler euler = FusionQuaternionToEuler(quaternion); // Output: Roll, Pitch, Yaw in degrees printf("Roll: %0.1f, Pitch: %0.1f, Yaw: %0.1f\n", euler.angle.roll, euler.angle.pitch, euler.angle.yaw); } ``` -------------------------------- ### Apply Magnetic Sensor Calibration Source: https://github.com/xiotechnologies/fusion/blob/main/README.md The FusionModelMagnetic function applies magnetometer calibration parameters, including soft-iron matrix and hard-iron offset. It takes uncalibrated magnetometer data and returns calibrated data. ```c FusionModelMagnetic(uncalibrated, softIronMatrix, hardIronOffset, &calibrated); ``` -------------------------------- ### Algorithm Outputs Source: https://github.com/xiotechnologies/fusion/blob/main/README.md The Fusion AHRS algorithm provides several key outputs related to sensor orientation and motion. These outputs can be further processed or converted into different formats as needed. ```APIDOC ## Algorithm Outputs ### Description The algorithm provides four outputs: quaternion, gravity, linear acceleration, and Earth acceleration. The quaternion describes the orientation of the sensor relative to the Earth. This can be converted to a rotation matrix using the `FusionQuaternionToMatrix` function or to Euler angles using the `FusionQuaternionToEuler` function. Gravity is a direction of gravity in the sensor coordinate frame. Linear acceleration is the accelerometer measurement with gravity removed. Earth acceleration is the accelerometer measurement in the Earth coordinate frame with gravity removed. The algorithm supports North-West-Up (NWU), East-North-Up (ENU), and North-East-Down (NED) axes conventions. ``` -------------------------------- ### Monitor AHRS Internal States and Flags in Python Source: https://context7.com/xiotechnologies/fusion/llms.txt Accesses AHRS internal states and flags to monitor algorithm behavior and sensor rejection status. This snippet should be run after updating the AHRS with sensor data. ```python import imufusion import numpy as np ahrs = imufusion.Ahrs() # After updating AHRS... gyro = np.array([0.0, 0.0, 0.0]) accel = np.array([0.0, 0.0, 1.0]) mag = np.array([1.0, 0.0, 0.0]) ahrs.update(gyro, accel, mag, 0.01) # Access internal states states = ahrs.internal_states print(f"Acceleration Error: {states.acceleration_error:.2f} deg") print(f"Accelerometer Ignored: {states.accelerometer_ignored}") print(f"Acceleration Recovery Trigger: {states.acceleration_recovery_trigger:.2f}") print(f"Magnetic Error: {states.magnetic_error:.2f} deg") print(f"Magnetometer Ignored: {states.magnetometer_ignored}") print(f"Magnetic Recovery Trigger: {states.magnetic_recovery_trigger:.2f}") # Access flags flags = ahrs.flags print(f"Startup: {flags.startup}") print(f"Angular Rate Recovery: {flags.angular_rate_recovery}") print(f"Acceleration Recovery: {flags.acceleration_recovery}") print(f"Magnetic Recovery: {flags.magnetic_recovery}") ``` -------------------------------- ### Convert Quaternion to Euler Angles and Rotation Matrix Source: https://context7.com/xiotechnologies/fusion/llms.txt Converts a quaternion representing orientation into Euler angles (roll, pitch, yaw) and a 3x3 rotation matrix. Requires an initialized AHRS object to obtain the quaternion. ```python import imufusion import numpy as np # Get quaternion from AHRS ahrs = imufusion.Ahrs() ahrs.update_no_magnetometer(np.array([0, 0, 0]), np.array([0, 0, 1]), 0.01) quaternion = ahrs.quaternion # [w, x, y, z] # Convert to Euler angles (roll, pitch, yaw in degrees) euler = imufusion.quaternion_to_euler(quaternion) print(f"Euler: Roll={euler[0]:.2f}, Pitch={euler[1]:.2f}, Yaw={euler[2]:.2f}") # Convert to 3x3 rotation matrix rotation_matrix = imufusion.quaternion_to_matrix(quaternion) print(f"Rotation Matrix: {rotation_matrix}") ``` -------------------------------- ### FusionAhrsGetInternalStates Source: https://github.com/xiotechnologies/fusion/blob/main/README.md Retrieves the internal states of the AHRS algorithm, including error metrics and recovery triggers. ```APIDOC ## GET FusionAhrsGetInternalStates ### Description Retrieves the `FusionAhrsInternalStates` structure containing current algorithm states. ### Response - **accelerationError** (float) - Angular error in degrees relative to accelerometer inclination. - **accelerometerIgnored** (boolean) - True if accelerometer was ignored. - **accelerationRecoveryTrigger** (float) - Trigger value between 0.0 and 1.0. - **magneticError** (float) - Angular error in degrees relative to magnetometer heading. - **magnetometerIgnored** (boolean) - True if magnetometer was ignored. - **magneticRecoveryTrigger** (float) - Trigger value between 0.0 and 1.0. ``` -------------------------------- ### Monitor AHRS Internal States and Flags (C) Source: https://context7.com/xiotechnologies/fusion/llms.txt Monitor internal algorithm states like acceleration and magnetic errors, and flags indicating recovery status. Useful for debugging and system monitoring. ```c #include "Fusion.h" #include void monitor_ahrs_status(FusionAhrs *ahrs) { // Get internal states FusionAhrsInternalStates states = FusionAhrsGetInternalStates(ahrs); printf("Acceleration Error: %0.1f deg\n", states.accelerationError); printf("Accelerometer Ignored: %s\n", states.accelerometerIgnored ? "true" : "false"); printf("Acceleration Recovery Trigger: %0.2f\n", states.accelerationRecoveryTrigger); printf("Magnetic Error: %0.1f deg\n", states.magneticError); printf("Magnetometer Ignored: %s\n", states.magnetometerIgnored ? "true" : "false"); printf("Magnetic Recovery Trigger: %0.2f\n", states.magneticRecoveryTrigger); // Get flags FusionAhrsFlags flags = FusionAhrsGetFlags(ahrs); printf("Startup: %s\n", flags.startup ? "true" : "false"); printf("Angular Rate Recovery: %s\n", flags.angularRateRecovery ? "true" : "false"); printf("Acceleration Recovery: %s\n", flags.accelerationRecovery ? "true" : "false"); printf("Magnetic Recovery: %s\n", flags.magneticRecovery ? "true" : "false"); } ``` -------------------------------- ### Update AHRS without Magnetometer (C) Source: https://context7.com/xiotechnologies/fusion/llms.txt Computes orientation using only gyroscope and accelerometer data, suitable for systems lacking a magnetometer. ```c #include "Fusion.h" #include #define SAMPLE_PERIOD 0.01f // 100 Hz = 10ms period void simple_ahrs_loop(void) { FusionAhrs ahrs; FusionAhrsInitialise(&ahrs); while (1) { // Read sensors (replace with actual data) const FusionVector gyroscope = {0.0f, 0.0f, 0.0f}; const FusionVector accelerometer = {0.0f, 0.0f, 1.0f}; // Update without magnetometer FusionAhrsUpdateNoMagnetometer(&ahrs, gyroscope, accelerometer, SAMPLE_PERIOD); // Get Euler angles const FusionEuler euler = FusionQuaternionToEuler(FusionAhrsGetQuaternion(&ahrs)); printf("Roll %0.1f, Pitch %0.1f, Yaw %0.1f\n", euler.angle.roll, euler.angle.pitch, euler.angle.yaw); } } ``` -------------------------------- ### Update AHRS with External Heading (C) Source: https://context7.com/xiotechnologies/fusion/llms.txt Integrates external heading sources like GPS or visual odometry into the AHRS update process. ```c #include "Fusion.h" #include void process_with_gps_heading(FusionAhrs *ahrs, float gpsHeading, float deltaTime) { // Sensor measurements const FusionVector gyroscope = {0.0f, 0.0f, 0.0f}; const FusionVector accelerometer = {0.0f, 0.0f, 1.0f}; // Update with external heading (e.g., from GPS) FusionAhrsUpdateExternalHeading(ahrs, gyroscope, accelerometer, gpsHeading, deltaTime); // Get orientation FusionEuler euler = FusionQuaternionToEuler(FusionAhrsGetQuaternion(ahrs)); printf("Heading from GPS: %0.1f\n", euler.angle.yaw); } ``` -------------------------------- ### Remap Sensor Axes Source: https://github.com/xiotechnologies/fusion/blob/main/README.md The FusionRemap function remaps sensor axes to the body frame using one of the 24 possible orthogonal axis permutations defined by FusionRemapAlignment. This is useful when sensors are not mounted aligned with the body axes. ```c FusionRemap(input, FusionRemapAlignmentNorth); FusionRemap(input, FusionRemapAlignmentSouth); FusionRemap(input, FusionRemapAlignmentEast); FusionRemap(input, FusionRemapAlignmentWest); FusionRemap(input, FusionRemapAlignmentUp); FusionRemap(input, FusionRemapAlignmentDown); ``` -------------------------------- ### FusionAhrsGetFlags Source: https://github.com/xiotechnologies/fusion/blob/main/README.md Retrieves the current status flags of the AHRS algorithm. ```APIDOC ## GET FusionAhrsGetFlags ### Description Retrieves the `FusionAhrsFlags` structure indicating the current operational state of the algorithm. ### Response - **startup** (boolean) - True during algorithm startup. - **angularRateRecovery** (boolean) - True during angular rate recovery. - **accelerationRecovery** (boolean) - True during acceleration recovery. - **magneticRecovery** (boolean) - True during magnetic recovery. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.