INFO: Dieses Forum nutzt Cookies...
Cookies sind für den Betrieb des Forums unverzichtbar. Mit der Nutzung des Forums erklärst Du dich damit einverstanden, dass wir Cookies verwenden.

Es wird in jedem Fall ein Cookie gesetzt um diesen Hinweis nicht mehr zu erhalten. Desweiteren setzen wir Google Adsense und Google Analytics ein.

Antwort schreiben 
 
Themabewertung:
  • 1 Bewertungen - 5 im Durchschnitt
  • 1
  • 2
  • 3
  • 4
  • 5
MPU-6050 und Servo
27.03.2019, 20:48
Beitrag #1
MPU-6050 und Servo
Hallo liebe Comunity

Ich habe mir vor kurzem ein MPU-6050 gekauft. Das auslesen der raw Daten sowie auch das "zusammenfügen" der beiden Werte via den beiden libraries I2Cdev und MPU6050 library habe ich hin bekommen. Anschliesen wollte ich den Code so erweitern dass je nach Lage des Sensors der Servo sich bewegt.
Code:
#include "I2Cdev.h"



#include <Servo.h>
Servo myservo;

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

#define OUTPUT_READABLE_YAWPITCHROLL

#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// 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] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };



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

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



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


void setup() {
  
  myservo.attach(9);
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(115200);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3V or Arduino
    // Pro Mini running at 3.3V, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);

    // 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: "));
    /*3while (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.print(F("Enabling interrupt detection (Arduino external interrupt "));
        Serial.print(digitalPinToInterrupt(INTERRUPT_PIN));
        Serial.println(F(")..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), 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(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
   // setServos();
}



// ================================================================
// ===                    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) {
        if (mpuInterrupt && fifoCount < packetSize) {
          // try to get out of the infinite loop
          fifoCount = mpu.getFIFOCount();
        }  
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        
         myservo.write((ypr[1] * 180/M_PI) + 90);
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }

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

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

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

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & _BV(MPU6050_INTERRUPT_DMP_INT_BIT)) {
        // 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;

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
    //delay(3);
}

Dies funktioniert mehr oder weniger. Wenn ich den Sensor schnell hin und her bewege fangen die Werte an wild zu spinnen.

Ein Auszug aus dem Seriellen Monitor bei einer solchen Störung.
Zitat:ypr -130.35 23.13 -88.38
ypr -6.58 177.48 -92.36
ypr 14.70 -15.18 68.00
ypr 21.36 -37.05 78.36
ypr -66.74 -42.43 54.18
ypr -34.14 119.81 95.10
ypr 41.28 -129.66 164.69
ypr 78.00 138.66 141.71
ypr -14.79 69.97 0.27
ypr -128.61 -154.93 96.46
ypr 79.60 -179.05 -126.33
ypr -109.62 156.02 -136.40
ypr -81.31 163.12 174.13
ypr -47.56 -17.32 -21.14
ypr -179.52 -6.70 7.67
ypr 179.23 -23.91 -12.11
ypr 179.17 -24.43 -12.26
ypr -2.95 1.54 51.90
ypr 3.63 4.21 -51.92
ypr -3.35 171.82 111.00
ypr 7.39 167.96 -118.11
ypr -2.89 1.88 63.65
ypr -2.49 173.56 107.48
ypr -2.45 0.84 57.10
ypr 8.17 166.75 -148.54

Kann ich den obigen Code oben so optimieren dass solche Fehler nicht wieder auftauchen?
Weiter frage ich mich ob ich den Code vereinfachen bzw. schmälern kann?

Vielen Dank bereits im Vorraus.

Wer Rechtschreibfehler findet, darf sie behalten.
Alle Beiträge dieses Benutzers finden
Diese Nachricht in einer Antwort zitieren
Antwort schreiben 


Möglicherweise verwandte Themen...
Thema: Verfasser Antworten: Ansichten: Letzter Beitrag
Wink Solar Roboter- Servo dreht nach Stopp nicht weiter Stagneth.Alexander 28 583 15.07.2019 19:26
Letzter Beitrag: hotsystems
  Stepper und Servo ? Lanzet3 31 1.787 28.12.2018 15:09
Letzter Beitrag: MicroBahner
  PHP WINDOWS XAMPP ARDUINO UNO SERVO steuern über Serielle Verbindung tr3 1 604 21.08.2018 21:59
Letzter Beitrag: georg01
  Schräglagen- u. Kipppunktanzeige Motorrad mit Mpu 6050 mirco432 1 701 13.08.2018 15:59
Letzter Beitrag: mirco432
Big Grin Brauche dringend Hilfe mit dem Programmieren von Servo und Taster holzchistli 4 1.439 19.06.2018 16:45
Letzter Beitrag: hotsystems
Question Servo.h Hilgi 10 2.548 07.05.2018 18:57
Letzter Beitrag: BanditBandeh
  Einmalige Servo Motor Ausführung BanditBandeh 29 5.627 12.04.2018 12:04
Letzter Beitrag: MicroBahner
  Servo langsamer drehen und auf position lassen Thor Wallhall 13 5.795 12.04.2018 11:42
Letzter Beitrag: BanditBandeh
  Arduino DUE mit Adafruit 16 Kanal Servo-Driver juergen001 3 1.124 09.04.2018 10:51
Letzter Beitrag: juergen001
  Servo Steuerung mit PCA 9685 (Adressiernung) bernhard66 3 1.395 10.03.2018 11:06
Letzter Beitrag: juergen001

Gehe zu:


Benutzer, die gerade dieses Thema anschauen: 1 Gast/Gäste