Getting servo to turn the opposite direction of IMU orientation

As the title implies, I'm trying to get a servo to turn in the opposite direction that the IMU detects. Here is my code, it currentally turns in the same direction as the IMU

#include "Wire.h"       // allows communication to i2c devices connected to arduino
#include "I2Cdev.h"     // I2Connection library (communication to serial port)
#include "MPU6050.h"    // IMU library
#include "Servo.h"      // servo control library
 
MPU6050 mpu; //defines the chip as a MPU so it can be called in the future
 
int16_t ax, ay, az;  // x y z orientation values from accelerometer
int16_t gx, gy, gz;  // x y z orientation values from gyrscope
/////////////////////////////////////////////////////////////////////////////////////// 
Servo outer; 
Servo inner;
///////////////////////////////////////////////////////////////////////////////////////
int valo;     // outer val
int prevValo; // outer prev val
///////////////////////////////////////////////////////////////////////////////////////
int vali;  //inner val
int prevVali; //outer prev val
/////////////////////////////////////////////////////////////////////////////////////// 
//initializes the IMU
void setup() 
{
    Wire.begin(); 
    Serial.begin(38400); 
 
    Serial.println("Initialize MPU");
    mpu.initialize();
    Serial.println(mpu.testConnection() ? "Connected" : "Connection failed"); 
    outer.attach(9); //servo on pin 9 for large ring y
    inner.attach(10);//servo on pin 10 for small ring x
}
/////////////////////////////////////////////////////////////////////////////////////// 
void loop() 
{
    mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); 
 
    valo = map(ax, -17000, 17000, 0, 179);
    if (valo != prevValo)
    {
        outer.write(valo); 
        prevValo = valo; 
    }
    
     vali = map(ay, -17000, 17000, 0, 179);
    if (vali != prevVali)
    {
        inner.write(vali); 
        prevVali = vali; 
    }
}
///////////////////////////////////////////////////////////////////////////////////////

I think you can do that with the map function.
Try to change these: map(ax, -17000, 17000, 0, 179);
into these: map(ax, -17000, 17000, 179, 0);

map() has 2 typical behaviours to keep in mind

  • it can overflow internally resulting in unexpected values
  • the behaviour at the extremes is not always what you want due to truncation
    (try ax = 16999)

Doing the mapping yourself prevents both to certain extend.

assuming that ax can be in the range -17000 ..17000

long temp = ax + 17000;  // temp = 0 .. 34000   
temp = temp / 189;  // temp = 0 .. 179

or

long temp = ax - 17000;  // temp = -34000  .. 0 
temp = temp / -189;  // temp = 179 .. 0