Use a touchscreen display to select which sensor measurement to display

Dependencies:   mbed DisplayModule24_demo_day10

acc.cpp

Committer:
ldelaney17
Date:
2017-01-17
Revision:
8:a7b7edb66de5
Parent:
5:8a2afc6fdeb0

File content as of revision 8:a7b7edb66de5:

/* 
* see acc.h for description of this file
*/
#include "acc.h"
void acc_init(){
    char acc_config_dataFormat[2] = {0x31,0x0b}; //measurement range
    char acc_config_powerControl[2] = {0x2d,0x08};
    connection.write(addr_acc, acc_config_dataFormat, 2); // full measurement range
    wait(.05); // busy wait tolerable during initialization
    connection.write(addr_acc, acc_config_powerControl, 2); // measure mode
    wait(.05);
}
    
float get_acc_magnitude(){
    char data_arr[2] = {0x80|0x40|0x32};
    connection.write(addr_acc, data_arr, 1); //set up the connection for reading from data  
    char acc_data[6];
    connection.read(addr_acc, acc_data, 6); //read the 6 bytes of data
    int16_t data[3];
    float x, y, z;
    data[0] = acc_data[1] << 8 | acc_data[0]; //shift the bytes into 16bit integers
    data[1] = acc_data[3] << 8 | acc_data[2];
    data[2] = acc_data[5] << 8 | acc_data[4];
        x = 0.004 * data[0]; //convert the raw data to a value in terms of g
        y = 0.004 * data[1];
        z = 0.004 * data[2];
        float mag = sqrt(x*x + y*y + z*z); //calculate the magnitude
        #ifdef DEBUG_MODE
        pc.printf("x = %+1.2fg\t y = %1.2fg\t z = %1.2fg\t mag = %+1.2fg\n\r", x, y, z, mag);  
        #endif
    return mag;
}

//gets the average of n (default 5) readings
float get_avg_mag(int n){
    if ( n <= 0)
        return 0;
    float counter = 0;
    for (int i = 0; i < n; i++){
        counter += get_acc_magnitude();
    }
    return counter / n;
}