IMU Data to Motion: Tutorial for Translating Sensor Data into Real-World Movement

Pages
Contributors: ROB-24601
Favorited Favorite 0

Arduino Sketch

/*
  Movement to Motion: Using the SparkFun Micro Magnetometer (MMC5983MA) to control servo motors
  By: Rob Reynolds
  SparkFun Electronics
  Date: September 19th, 2024
  Based on original code by Nathan Seidle and Ricardo Ramos
  License: SparkFun code, firmware, and software is released under the MIT License(http://opensource.org/licenses/MIT).

  Feel like supporting our work? Buy a board from SparkFun!
  https://www.sparkfun.com/products/19921

  This example demonstrates how to take raw X/Y/Z readings from the sensor over Qwiic
  and translate them to movement through servo motors on the X and Y axes

  Hardware Connections:
  Plug a Qwiic cable into the sensor and a RedBoard
  If you don't have a platform with a Qwiic connection use the SparkFun Qwiic Breadboard Jumper
  (https://www.sparkfun.com/products/17912) Open the serial monitor at 115200 baud to see the output
*/


#include <Wire.h>

#include <SparkFun_MMC5983MA_Arduino_Library.h> //Click here to get the library: http://librarymanager/All#SparkFun_MMC5983MA

SFE_MMC5983MA myMag;

// Here's where we set up the servos

#include <Servo.h>
Servo servoPitchX; //Create object on X access
Servo servoRollY; //Create object on Y access

// initiate variables for servo positions
int rollYVal;
int pitchXVal;


void setup()
{
    Serial.begin(115200);
    Serial.println("Movement to Motion Example with the MMC5983MA");

    Wire.begin();

    if (myMag.begin() == false)
    {
        Serial.println("MMC5983MA did not respond - check your wiring. Freezing.");
        while (true)
            ;
    }

    myMag.softReset();

    Serial.println("MMC5983MA connected");

    servoPitchX.attach(8);
    servoRollY.attach(9);
}


void loop()
{
    uint32_t currentX = 0;
    uint32_t currentY = 0;
    uint32_t currentZ = 0;

    // This reads the X, Y and Z channels consecutively
    // (Useful if you have one or more channels disabled)
    currentX = myMag.getMeasurementX();
    currentY = myMag.getMeasurementY();
    currentZ = myMag.getMeasurementZ();  // Z axis/Yaw not needed for this example

    // Or, we could read all three simultaneously
    //myMag.getMeasurementXYZ(&currentX, &currentY, &currentZ);

    Serial.print("X axis raw value: ");
    Serial.print(currentX/1000);
    rollYVal = map(currentX/1000, 123, 133, 15, 165);
    servoRollY.write(rollYVal);
    Serial.print("\tY axis raw value: ");
    Serial.print(currentY/1000);
    pitchXVal = map(currentY/1000, 131, 119, 35, 135);
    servoPitchX.write(pitchXVal);
    Serial.print("\tZ axis raw value: ");
    Serial.println(currentZ);  //Z values are not necessary here, unless you want to add yaw on the Z axis

    Serial.println();
    delay(50); // Don't overtax the I2C
}