Adventures in Head Tracking for Less Than 10 Quid

 

Arduino Micro Sketch

 

#include “I2Cdev.h”

#include “MPU6050_6Axis_MotionApps20.h”
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include “Wire.h”
#endif

MPU6050 mpu;

#define LED_PIN 17 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
#define buttonPin 10

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
unsigned long last_tick;
unsigned long last_update;
unsigned long last_report;
float last_x;
float last_y;
int acc_x;
int acc_y;

unsigned long set_delay = 200;
float cx = 0;
float cy = 0;
float cz = 0;
float scount = 0;
boolean calibrated = false;
unsigned long calibrate_time = 10000;
#define JSTICKss 1

TrackState_t joySt;
// ================================================================
// === INTERRUPT DETECTION ROUTINE ===
// ================================================================

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

ISR(INT6_vect) {
dmpDataReady();
}

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

void setup()
{
#ifndef JSTICK
Serial.begin(9600);
// while (!Serial); // wait for Leonardo enumeration, others continue immediately
Serial.println(“Hello world”);

#endif

pinMode(buttonPin, INPUT);

last_tick = millis();
}
void delayed_setup() {
last_tick = millis();

// 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 device
#ifndef JSTICK
Serial.println(F(“Initializing I2C devices…”));
#endif

mpu.initialize();

// verify connection
#ifndef JSTICK
Serial.println(F(“Testing device connections…”));
Serial.println(mpu.testConnection() ? F(“MPU6050 connection successful”) : F(“MPU6050 connection failed”));

// load and configure the DMP
Serial.println(F(“Initializing DMP…”));
#endif

devStatus = mpu.dmpInitialize();

// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(27);
mpu.setYGyroOffset(47);
mpu.setZGyroOffset(67);
mpu.setZAccelOffset(1901); // 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
mpu.setDMPEnabled(true);

// enable Arduino interrupt detection
// Pro Micro supports Interrupt on pin 6 in a roundabou way
// attachInterrupt(4, dmpDataReady, RISING);
EICRB |= (1 << ISC60) | (1 << ISC61); // sets the interrupt type for EICRB (INT6).
// EICRA sets interrupt type for INT0…3
/*
ISCn0 ISCn1 Where n is the interrupt. 0 for 0, etc
0 0 Triggers on low level
1 0 Triggers on edge
0 1 Triggers on falling edge
1 1 Triggers on rising edge
*/

EIMSK |= (1 << INT6); // activates the interrupt. 6 for 6, etc
mpuIntStatus = mpu.getIntStatus();

// set our DMP Ready flag so the main loop() function knows it’s okay to use it

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)
#ifndef JSTICK
Serial.print(F(“DMP Initialization failed (code “));
Serial.print(devStatus);
Serial.println(F(“)”));
#endif
}

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

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

void loop() {

//blink LED to indicate activity
unsigned long m = millis();

if (set_delay > 0)
{
if (m > set_delay)
{
delayed_setup();
set_delay = 0;
}
else
{
return;
}
}

unsigned long delta = 100;
if (calibrated)
delta = 300;

if (m > last_tick + delta)
{
blinkState = !blinkState;
digitalWrite(LED_PIN, blinkState);
last_tick = m;
}
// 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) {
delay(0);
}

// 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();

#ifndef JSTICK
Serial.println(F(“FIFO overflow!”));
#endif
// 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
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

float new_x = (ypr[0]) * 0.32; //* 10000.0;
float new_y = (ypr[1]) * 0.32; // 10000.0;
float new_z = (ypr[2]) * 0.32; // 10000.0;

m = millis();
if (m > calibrate_time)

if (!calibrated)
{
//Serial.println(“Cal “);
if (scount < 500)
{ // accumulate calibration
cx += new_x;
cy += new_y;
cz += new_z;
scount ++;
}
else
{
//scount–;
calibrated = true;
cx = cx / scount;
cy = cy / scount;
cz = cz / scount;
}
}
else
{
// curve and scale
new_x = new_x – cx;
new_y = new_y – cy;
new_z = new_z – cz;

//new_x = (120000.0 * new_x) * new_x * new_x;
//new_y = (120000.0 * new_y) * new_y * new_y;
//new_z = (120000.0 * new_z) * new_z * new_z;

int iX = (int)(new_x * 255.0 * 1.0 + 25.0);
int iY = (int)(new_y * 255.0 * 3.0 + 0.0);
int iZ = (int)(new_z * 255.0 * 3.0 + 12.0);

if (digitalRead(buttonPin) == HIGH)
{
#ifndef JSTICK
Serial.print(“Recalibrate”);
#endif
scount = 0;
cx = 0;
cy = 0;
cz = 0;
calibrated = false;
return;
}

joySt.xAxis = iX;
joySt.yAxis = iY;
joySt.zAxis = iZ;

if (m > last_report)
{
Tracker.setState(&joySt);
last_report = m + 10; // limite updates

#ifndef JSTICK
Serial.print(iX );
Serial.print(“\t\t”);
Serial.print(iY);
Serial.print(“\t\t”);
Serial.print(iZ);
Serial.println(” “);
#endif
}
}
}
//delay(200);
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s