Output onboard accelerometer data of FRDM-KL25Z board on serial.

Dependencies:   MMA8451Q mbed

main.cpp

Committer:
DWeng
Date:
2017-07-18
Revision:
0:effa4c81f363

File content as of revision 0:effa4c81f363:

/**
 * +----------------------+
 * | Accelerometer Output |
 * +----------------------+
 *
 * Sample accelerometer at x Hz and output data onto serial port. Used for 
 * UC Merced data acquisition and filtering project.
 *
 * Leverages Antonio Quevedo's MMA8451Q library for interfacing with the 
 * accelerometer over I2C, with slight modification to configuration.
 *
 * Acceleration should be sampled no faster than 800Hz, but we will output at
 * 100Hz. -- ADD ODR MODIFIER
 *
 * Output Data Packet:
 * [ start_byte, acc_xH, acc_xL, acc_yH, acc_yL, acc_zH, acc_zL, checksum1, checksum2, end_byte ]
 *
 * Output all axes, but really only interested in y and z axes. 
 *
 * Darrel Weng
 *
 */
 
#include "mbed.h"
#include "MMA8451Q.h"

#include <string.h>

int period     = 8; // data reads before output; set at 50Sps
int acc_flag   = 0; // flag to super loop to read data
int flag_count = 0; // counter for how many times data has been read

void
mma8451q_int()
{
    acc_flag = 1;   
}

int main() 
{
    /* objects */
    DigitalOut  laser(PTE2);
    Serial      pc(USBTX, USBRX);
    //Timer       timer;
    MMA8451Q    acc(PTE25, PTE24);
    InterruptIn accINT1(PTA14);
    
    /* init */
    laser = 0;       // turn laser on; pin is active sinking
    pc.baud(115200); // high baudrate for lower latency comm
    accINT1.fall(&mma8451q_int);
    
    /* local variables */
    int16_t  acc_data[4]; // 4th entry contains checksum
    uint8_t  output[10]; 
    
    /* Start and Stop delimiting Bytes */
    output[0] = 0xBE;
    output[9] = 0xEF;
    
    while(1) 
    {
        // if data ready, read data
        if (acc_flag)
        {
            acc_flag = 0;
            acc.getAccAllAxis(acc_data);
            for (int i=0;i<3;i++)
                acc_data[i] /= 4;
            flag_count++;
        }
        // if time to output
        if (flag_count >= period)
        {
            flag_count = 0;
            //pc.printf("%d %d %d \r\n", acc_data[0], acc_data[1], acc_data[2]);
            // Build packet
            acc_data[3] = acc_data[0] + acc_data[1] - acc_data[2];
            memcpy(output+1, acc_data, 8);
            for (int i=0; i<10; i++)
                pc.putc(output[i]);
        }
    }
}