Yaw, Pitch and Roll#
These terms can describe the attitude of the module at any given time. We need to convert the acceleration and gyro terms into a more understandable system.
One can calculate the angles roll and pitch or else use what is already available:
pitch = arctan(-Gx/(Gy*Gy+Gz*Gz)**0.5)
roll = arctan2(Gy/Gz)
where Gx, Gy, Gz are the acceleration in each axis
Yaw cannot be computed accurately from acceleration alone, so we require gyroscope data:
angular velocity = dθ/dt
θ(t) ≈ sum(dθ/dt Ts)
Fuse the two sets of data together by complementary filter function (easier), or by Kalman filter:
pitch = 0.96 * (angle + gyroYangle / dT) +0.04 * accelYangle
roll = 0.96 * (angle + gyroXangle / dT) +0.04 * accelXangle
yaw = 0.96 * (angle + gyroZangle / dT) +0.04 * accelZangle
but the yaw measurement drifts, which can only be eliminated by adding a magnetometer, unless the Digital Motion Processor (DMP) is accessed and used, which is where Jeff Rowberg's library shines. Most of the technical stuff is now delegated to the DMP, we can figuratively sit back and enjoy the results.
Using MPU6050_DMP6#
This should have all the functions we require for yaw, pitch and roll, later quaternions. There is a newer sketch MPU6050_DMP6_using_DMP_V6_12 which has problems with the Processing teapot, so stay with MPU6050_DMP6 for the moment.
It has much the same features seen in the other 2 sketches we have used. Note
that he states we should connect the external interrupt pin to 0 on the Uno
and 2 on the Mega. Also he wants 3.3V for his supply. The file we are using
has #define OUTPUT_READABLE_YAWPITCHROLL already uncommented, so we
shall be using this first.
Be careful about #define INTERRUPT_PIN 2, the Uno has 2 x interrupt pins,
he probably means pin D2 which is interrupt 0, this happens to be the same
for the Mega see Table Arduino Interrupt Pins.
When the program asks for any character to be sent when ready, you should have set the baud rate before sending the character. When working with the serial monitor this line is a good idea, when we have a python script the baud rate is already set within the script.
The gyro and acceleration offsets are setup. There is a calibration time, after which the DMP and interrupt detection are enabled.
Running this on the serial monitor you should see something similar to the following:-
Show/Hide Code mpu6050_dmp6.txt
1Initiing I2C devices...
2p⸮⸮& ⸮⸮@HPJ⸮sЀ⸮ҁ⸮雂⸮⸮⸮⸮⸮b4⸮T'⸮⸮PIni⸮Initializing I2C devices...
3Testing device connections...
4MPU6050 connection successful
5
6Send any character to begin DMP programming and demo:
7Initializing DMP...
8Checking hardware revision...
9Revision @ user[16][6] = 4D
10Resetting memory bank selection to 0...
11>......>......
12// X Accel Y Accel Z Accel X Gyro Y Gyro Z Gyro
13//OFFSETS 1328, -2405, 1665, -76, 69, 63
14Enabling DMP...
15Enabling interrupt detection (Arduino external interrupt 0)...
16DMP ready! Waiting for first interrupt...
17ypr 0.01 -0.01 0.44
18ypr 0.01 -0.01 0.43
19ypr 0.01 -0.01 0.43
20ypr 0.01 -0.01 0.43
21ypr 0.01 -0.01 0.43
22ypr 0.01 -0.01 0.43
23ypr 0.01 -0.01 0.42
24ypr 0.01 -0.01 0.42
25ypr 0.01 -0.01 0.41
26ypr 0.01 -0.01 0.41
27ypr 0.01 -0.01 0.41
28ypr 0.01 -0.01 0.41
29ypr 0.01 -0.01 0.40
There will be some indecipherable text on startup (line 2), change the baud rate to 11520, this will then show the next 4 lines and it waits for any character and <Send> Serial Monitor. After making hardware checks and resetting the memory bank it repeats the new offsets (all slightly different - I don't know yet why), it then enables the DMP and interrupt detection then shows the ypr values, the output looked stable with very little drift when the module was at rest.
We should be ready now to add a bit of python spice.
Visual Display for GY-521#
As we have seen the output from the sketch is pretty wordy, copy the
MPU6050_DMP6 sketch and amend it so that we just have the sketch with no
selection between alternatives, then change the output of
OUTPUT_READABLE_YAWPITCHROLL so that ybr call is commented out and the
separators have been changed to commas.
Show/Hide Code MPU6050_DMP6RollPitchYaw.ino
// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
// 2013-05-08 - added seamless Fastwire support
// - added note about gyro calibration
// 2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
// 2012-06-20 - improved FIFO overflow handling and simplified read process
// 2012-06-19 - completely rearranged DMP initialization code and simplification
// 2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
// 2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
// 2012-06-05 - add gravity-compensated initial reference frame acceleration output
// - add 3D math helper file to DMP6 example sketch
// - add Euler output and Yaw/Pitch/Roll output formats
// 2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
// 2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
// 2012-05-30 - basic DMP initialization working
/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg
===============================================
*/
// 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 "NewI2Cdev.h"
#include "NewMPU6050_6Axis_MotionApps20.h"
//#include "NewMPU6050.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
/* =========================================================================
NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
depends on the MPU-6050's INT pin being connected to the Arduino's
external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
digital I/O pin 2.
* ========================================================================= */
// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#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
VectorFloat gravity; // [x, y, z] gravity vector
float ypr[3]; // [yaw, pitch, roll] yaw/pitch/roll container and gravity vector
// ================================================================
// === 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)
Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation
#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 Ardunio
// 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: "));
//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(1334);
mpu.setYGyroOffset(-2407);
mpu.setZGyroOffset(1659);
mpu.setXAccelOffset(-77);
mpu.setYAccelOffset(69);
mpu.setZAccelOffset(62);
// make sure it worked (returns 0 if so)
if (devStatus == 0) {
// Calibration Time: generate offsets and calibrate our MPU6050
mpu.CalibrateAccel(6);
mpu.CalibrateGyro(6);
mpu.PrintActiveOffsets();
// 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)..."));
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);
}
// ================================================================
// === 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();
// 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;
#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(","); // was "\t"
Serial.print(ypr[1] * 180/M_PI);
Serial.print(","); // was "\t"
Serial.println(ypr[2] * 180/M_PI);
#endif
// blink LED to indicate activity
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
}
}
Before running this ensure that it verifies then compile. On the serial plotter you should see the bare values separated by commas.
In this script we will depict the MPU mounted on a small breadboard. To give a relational view use two sets of positional arrows, one set remains static the other set move synchronously with our sensor. Make the sensor from three boxes, make these into a compound object that will move as one. Note that the use of the right hand mouse button is disabled to prevent the view changing.
The packet is parsed then the components are used in vpython to manipulate the module and three of the arrows. Note that the trigonmetric functions have been directly imported from vpython.
Show/Hide Code roll_pitch_yaw.py
from vpython import *
import serial
ad=serial.Serial('com3',115200)
sleep(1)
scene.range=5
toRad=2*pi/360
toDeg=1/toRad
scene.forward=vector(-1,-1,-1)
scene.width=600
scene.height=600
scene.userzoom = False
scene.userspin = False
scene.userpan = False
xarrow=arrow(lenght=2, shaftwidth=.1, color=color.red,axis=vector(1,0,0))
yarrow=arrow(lenght=2, shaftwidth=.1, color=color.green,axis=vector(0,1,0))
zarrow=arrow(lenght=4, shaftwidth=.1, color=color.blue,axis=vector(0,0,1))
frontArrow=arrow(length=4,shaftwidth=.1,color=color.purple,axis=vector(1,0,0))
upArrow=arrow(length=1,shaftwidth=.1,color=color.magenta,axis=vector(0,1,0))
sideArrow=arrow(length=2,shaftwidth=.1,color=color.orange,axis=vector(0,0,1))
bBoard=box(length=6,width=2,height=.2,opacity=.8,pos=vector(0,0,0,))
bn=box(length=1,width=.75,height=.1, pos=vector(-.5,.1+.05,0),color=color.blue)
nano=box(lenght=1.75,width=.6,height=.1,pos=vector(-2,.1+.05,0),color=color.green)
myObj=compound([bBoard,bn,nano])
while 'esc' not in keysdown():
while (ad.inWaiting()>0):
dataPacket=ad.readline()
#print(dataPacket)
dataPacket=str(dataPacket,'utf-8').strip()
splitPacket=dataPacket.split(",")
if len(splitPacket)==3:
try: # used to eliminate xxx.xx.xx
roll=float(splitPacket[0])*toRad
pitch=float(splitPacket[1])*toRad
yaw=float(splitPacket[2])*toRad+pi
#print("Roll=",roll*toDeg," Pitch=",pitch*toDeg,"Yaw=",yaw*toDeg)
rate(50)
k=vector(cos(yaw)*cos(pitch), sin(pitch),sin(yaw)*cos(pitch))
y=vector(0,1,0)
s=cross(k,y)
v=cross(s,k)
vrot=v*cos(roll)+cross(k,v)*sin(roll)
frontArrow.axis=k
sideArrow.axis=cross(k,vrot)
upArrow.axis=vrot
myObj.axis=k
myObj.up=vrot
sideArrow.length=2
frontArrow.length=4
upArrow.length=1
except ValueError:
print('data',dataPacket)
else:
print('split',splitPacket)
Representation of MPU module with arrows#
Make sure that the serial monitor is not running, you can even shut off the Arduino IDE before starting the python script. A new web page is made in your default browser and nothing much happens on the screen until the sketch has finished initialising. Meanwhile python should be printing the startup checks, after a warm up time the module becomes resposive. I found quite a few false pieces of data were being trapped.
Show/Hide Code MPU6050_DMP6RollPitchYaw.txt
split ['']
split ['Initializing I2C devices...']
split ['Testing device connections...']
split ['MPU6050 connection successful']
split ['Initializing DMP...']
split ['Checking hardware revision...']
split ['Revision @ user[16][6] = 4D']
split ['Resetting memory bank selection to 0...']
split ['>**......>......']
split ['// X Accel Y Accel Z Accel X Gyro Y Gyro Z Gyro']
split ['//OFFSETS 1329', ' -2403', ' 1658', ' -48', ' 20', ' 94']
split ['Enabling DMP...']
split ['Enabling interrupt detection (Arduino external interrupt 0)...']
split ['0)...']
split ['DMP ready! Waiting for first interrupt...']
split ['2.78']
split ['45', '0.00']
split ['45', '0.00']
split ['0.08', '-0.00']
data ,-0.08,-0.00
data ,-0.08,-0.00
split ['-6.38', '-0.08', '0.02.19', '1.82', '-12.91']
split ['84.78']
split ['4.80']
split ['0.22']
split ['']
data .,0.03,0.09
split ['']
split ['']