balance and counterweight

hello,

I would like to create an object that can correct its balance.
The idea is to move a counterweight using a servomotor when the object starts to lose its balance. The servo corrects in real time the balance. For this, I am using an accelero/gyro to calculate the object orientation (using Jeff Rowberg library to have some good values). The accelero/gyro works very well.

That’s what it looks like for now (it’s just the first prototype…) :

Look at this vidéo. It is the same idea :

The counterweight moves as I was hoping but it doesn’t work. The object oscillates and doesn’t find its balance point. The servo/counterweight is too nervous and disturbs the object. It will never find the balance with a simple idea like i had.
The problem seems to be more complex.

Do you know if it’s possible to correct the issue using some appropriate algorithms that can calculate how the servo should react ?
Do you know how it’s possible to find the balance point in real time (like we can see in the video above) ?

Or do you know the principle of reaction wheel which seems to be a proper way to correct balance ?
Reaction wheels use gyroscopic effects to control orientation :

I didn’t find some arduino detailed project using reaction wheel. And it seems really complicated to start to nothing…

I send you my little code. It’s just a question of reading some good pitch values from accelero/gyro and sending the opposite value to the servo to correct the balance. The code does what it have to do but as i told you, it’s not working. Too simple.

// try to move a counterweight using a servo to stabilize an object
// using Jeff Rowberg MPU6050 library, filter and quaternion algorithm

// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"
#include "Servo.h" 
#include "MPU6050_6Axis_MotionApps20.h"

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

MPU6050 mpu;
Servo myservo;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '

All ideas are welcom

thanks

, 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, ‘\r’, ‘\n’ };

const int buttonPin = 7; // button attach to pin 7
int etatbutton = 0; // trigger the button to have a reference value of balance, when the accelerometer/gyro is stabilized
int buttonState; // if the button is HIGH or LOW

int refvalue = 0; // the reference value of balance

int posservo = 0; // to stock pitch value each frame
int servominus = 0; // minimal value
int servoplus = 0; // maximal value
int valueOK = 0; // to stock the proper value i send in to the servo

// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================

volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}

// ================================================================
// === INITIAL SETUP ===
// ================================================================

void setup() {
// join I2C bus (I2Cdev library doesn’t do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif

Serial.begin(115200);
while (!Serial); // wait for Leonardo enumeration, others continue immediately

// initialize device
Serial.println(F("Initializing I2C devices..."));
mpu.initialize();

// initialize button and servo
myservo.attach(11);
pinMode(buttonPin, INPUT);
myservo.write(90);

// verify connection
Serial.println(F("Testing device connections..."));
Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

// wait for ready
Serial.println(F("\nSend any character to begin DMP programming and demo: "));
while (Serial.available() && Serial.read()); // empty buffer
while (!Serial.available());                 // wait for data
while (Serial.available() && Serial.read()); // empty buffer again

// load and configure the DMP
Serial.println(F("Initializing DMP..."));
devStatus = mpu.dmpInitialize();

// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(220);
mpu.setYGyroOffset(76);
mpu.setZGyroOffset(-85);
mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

// make sure it worked (returns 0 if so)
if (devStatus == 0) {
    // turn on the DMP, now that it's ready
    Serial.println(F("Enabling DMP..."));
    mpu.setDMPEnabled(true);

    // enable Arduino interrupt detection
    Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
    attachInterrupt(0, dmpDataReady, RISING);
    mpuIntStatus = mpu.getIntStatus();

    // set our DMP Ready flag so the main loop() function knows it's okay to use it
    Serial.println(F("DMP ready! Waiting for first interrupt..."));
    dmpReady = true;

    // get expected DMP packet size for later comparison
    packetSize = mpu.dmpGetFIFOPacketSize();
} else {
    // ERROR!
    // 1 = initial memory load failed
    // 2 = DMP configuration updates failed
    // (if it's going to break, usually the code will be 1)
    Serial.print(F("DMP Initialization failed (code "));
    Serial.print(devStatus);
    Serial.println(F(")"));
}

}

// ================================================================
// === MAIN PROGRAM LOOP ===
// ================================================================

void loop() {
// if programming failed, don’t try to do anything
if (!dmpReady) return;

// wait for MPU interrupt or extra packet(s) available
while (!mpuInterrupt && fifoCount < packetSize) {
    // other program behavior stuff here
    // .
    // .
    // .
    // if you are really paranoid you can frequently test in between other
    // stuff to see if mpuInterrupt is true, and if so, "break;" from the
    // while() loop to immediately process the MPU data
    // .
    // .
    // .
}

// reset interrupt flag and get INT_STATUS byte
mpuInterrupt = false;
mpuIntStatus = mpu.getIntStatus();

buttonState = digitalRead(buttonPin);

// get current FIFO count
fifoCount = mpu.getFIFOCount();

// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));

// otherwise, check for DMP data ready interrupt (this should happen frequently)
} else if (mpuIntStatus & 0x02) {
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

    // read a packet from FIFO
    mpu.getFIFOBytes(fifoBuffer, packetSize);
    
    // track FIFO count here in case there is > 1 packet available
    // (this lets us immediately read more without waiting for an interrupt)
    fifoCount -= packetSize;

        // display Euler angles in degrees
        if (buttonState == LOW && etatbutton == 0) { // waiting the accelero/gyro to be stabilize

          mpu.dmpGetQuaternion(&q, fifoBuffer);      // jeff rowberg job to have a good quat
          mpu.dmpGetGravity(&gravity, &q);
          mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
          
          Serial.println(ypr[2] * 180/M_PI);         //print the pitch and waiting the accelero/gyro to be stabilize. Once it's ok, I trigger the button to have a reference value.

        }
        
        else if (buttonState == HIGH && etatbutton == 0) {       // trigger the button
          
          mpu.dmpGetQuaternion(&q, fifoBuffer);    // jeff rowberg job to have a good quat
          mpu.dmpGetGravity(&gravity, &q);
          mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            
          refvalue = ypr[1] * 180/M_PI;       // stock a reference value of balance
          servominus = (refvalue - 90);       // determine minimal value
          servoplus = (refvalue + 90);        // determine maximal value
          etatbutton = 1;                     // change state button to avoid to enter in this else if loop a second time
        }
        else {
          
          mpu.dmpGetQuaternion(&q, fifoBuffer);    // jeff rowberg job to have a good quat
          mpu.dmpGetGravity(&gravity, &q);
          mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
          
          posservo = ypr[1] * 180/M_PI;       // stock pitch value
          valueOK = map(posservo, servominus, servoplus, 0, 180);  //map the pitch between servominus (reference value-90) and servoplus (reference value+90) to 0 and 180
          if(valueOK>180) valueOK=180;      // check if the value is not too high
          if(valueOK<0) valueOK=0;          // check if the value is not tt low
          Serial.println(valueOK);           // print the value
          myservo.write(valueOK);            // send to the servo
        }

}

}


All ideas are welcom

thanks

Look up PID in the learning sections.

Mark