Visualize IMU data sent over BLE on a computer

Dependencies:   PinDetect mbed

Fork of LSM9DS1_Library by jim hamblen

main.cpp

Committer:
cvmp94
Date:
2016-03-13
Revision:
3:fd549671e512
Parent:
0:e8167f37725c

File content as of revision 3:fd549671e512:

#include "LSM9DS1.h"
#include "MadgwickUpdate.h"

Serial pc(USBTX, USBRX);

Timer t;
int lastPrint = 0;
int printInterval = 500;

RawSerial dev( p13, p14 );

int calibrate = 1;

void dev_recv()
{
    while(dev.readable()) {
        if ( dev.getc() == 'r' ){
                calibrate = 1;
        }
    }
}

int main() {
    
    LSM9DS1 lol(p28, p27, 0xD6, 0x3C);
    
    t.start();

    dev.baud(9600);
    dev.attach(&dev_recv, Serial::RxIrq);

    lol.begin();
    if (!lol.begin()) {
        pc.printf("Failed to communicate with LSM9DS1.\n");
    }

    while(1) {

        if( calibrate ){
            lol.calibrate();
            firstUpdate = t.read_us();
            lastUpdate = firstUpdate;
            q[0] = 1.0f; q[1] = 0.0f; q[2] = 0.0f; q[3] = 0.0f; 
            calibrate = 0;
        }
        
        if ( lol.accelAvailable() || lol.gyroAvailable() ) {
         
            lol.readAccel();
            lol.readGyro();
            
            Now = t.read_us();
            deltat = (float)((Now - lastUpdate)/1000000.0f);
            lastUpdate = Now;
            
            float ax = lol.calcAccel(lol.ax);
            float ay = lol.calcAccel(lol.ay);
            float az = lol.calcAccel(lol.az);
            
            float gx = lol.calcGyro(lol.gx);
            float gy = lol.calcGyro(lol.gy);
            float gz = lol.calcGyro(lol.gz);
            
            
            // switch x and y to convert to right handed coordinate system
            MadgwickQuaternionUpdate( ay, ax, az, gy*PI/180.0f, gx*PI/180.0f, gz*PI/180.0f );
            
            int nowMs = t.read_ms();
            if( nowMs - lastPrint > printInterval ){
                lastPrint = nowMs;
                pc.printf("gyro: %f %f %f\n\r", gx, gy, gz);
                pc.printf("accel: %f %f %f\n\r", ax, ay, az);
                pc.printf("quat: %f %f %f %f\n\r", q[0], q[1], q[2], q[3]);
                char* str = (char*) &q;
                int i = 0;
                while (i < 16){
                    dev.putc( str[i] );
                    i += 1;   
                }
            }
            
        }
    }
}