Skip to content

Instantly share code, notes, and snippets.

@jarrodhroberson
Last active August 29, 2015 14:13
Show Gist options
  • Save jarrodhroberson/16f99d207204e397536c to your computer and use it in GitHub Desktop.
Save jarrodhroberson/16f99d207204e397536c to your computer and use it in GitHub Desktop.
arduino telemetry code for science fair 2015 project
#include <I2Cdev.h>
#include <LiquidCrystal.h>
#include "MPU6050_6Axis_MotionApps20.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_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
#define OUTPUT_READABLE_REALACCEL
// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL
#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
volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
mpuInterrupt = true;
}
LiquidCrystal lcd(12,11,5,4,3,7);
void setup() {
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print(F("MPU-6050"));
// 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
// 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);
// 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
lcd.clear();
lcd.print(F("Initializing I2C devices..."));
mpu.initialize();
lcd.clear();
lcd.print(F("MPU initialized"));
// verify connection
lcd.print(F("Testing device connections..."));
lcd.print(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
// load and configure the DMP
lcd.print(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
lcd.print(F("Enabling DMP..."));
mpu.setDMPEnabled(true);
// set our DMP Ready flag so the main loop() function knows it's okay to use it
lcd.print(F("DMP ready! Waiting for first interrupt..."));
// enable Arduino interrupt detection
lcd.print(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
attachInterrupt(0, dmpDataReady, RISING);
mpuIntStatus = mpu.getIntStatus();
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)
lcd.print(F("DMP Initialization failed (code "));
lcd.print(devStatus);
lcd.print(F(")"));
}
// configure LED for output
pinMode(LED_PIN, OUTPUT);
lcd.clear();
int wait = 3;
for (int i = wait; i > 0; --i) {
lcd.clear();
lcd.printf("Waiting for %d", i);
delay(1000);
}
lcd.clear();
lcd.print("Go!");
}
int16_t maxZ = 0;
int16_t prevZ = 0;
int threshold = 500;
long startTime = 0;
long stopTime = 0;
boolean stopped = true;
boolean ended = false;
void loop() {
// if programming failed, don't try to do anything
if (!dmpReady || ended) return;
// 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();
//lcd.print(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();
mpu.getFIFOBytes(fifoBuffer, packetSize);
fifoCount -= packetSize;
// calculate real acceleration, adjusted to remove gravity
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetAccel(&aa, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
maxZ = max(maxZ,abs(aaReal.z));
int16_t deltaZ = abs(aaReal.z) - prevZ;
prevZ = abs(aaReal.z);
if (stopped && !ended) {
// stopped so start recording
if (deltaZ > threshold) {
stopped = false;
startTime = millis();
lcd.setCursor(0,0);
lcd.print("Recording...");
}
} else {
if (deltaZ == 0 && maxZ != 0) {
stopped = true;
stopTime = millis();
ended = true;
}
}
if (ended) {
ended = true;
long elapsedTime = stopTime - startTime;
lcd.clear();
lcd.printf("MaxAccel = %d", abs(maxZ));
//Serial.printf("MaxAccel = %d\n", abs(maxZ));
lcd.setCursor(0,1); // second line
lcd.printf("ET %dms", elapsedTime);
//Serial.printf("ET %dms\n", elapsedTime);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment