Library for driving the MMA8452 accelerometer over I2C

Dependents:   MMA8452_Test MMA8452_Demo Dualing_Tanks IMU-Controlled_MP3_Player ... more

Here is a simple example:

#include "mbed.h"
#include "MMA8452.h"

int main() {
   Serial pc(USBTX,USBRX);
   pc.baud(115200);
   double x = 0, y = 0, z = 0;

   MMA8452 acc(p28, p27, 40000);
   acc.setBitDepth(MMA8452::BIT_DEPTH_12);
   acc.setDynamicRange(MMA8452::DYNAMIC_RANGE_4G);
   acc.setDataRate(MMA8452::RATE_100);
   
   while(1) {
      if(!acc.isXYZReady()) {
         wait(0.01);
         continue;
      }
      acc.readXYZGravity(&x,&y,&z);
      pc.printf("Gravities: %lf %lf %lf\r\n",x,y,z);
   }
}

An easy way to test that this actually works is to run the loop above and hold the MMA8452 parallel to the ground along the respective axis (and upsidedown in each axis). You will see 1G on the respective axis and 0G on the others.

MMA8452.cpp

Committer:
ashleymills
Date:
2013-10-17
Revision:
9:dfb0f6a7a455
Parent:
8:89272163f395
Child:
10:ca9ba7ad4e94

File content as of revision 9:dfb0f6a7a455:

// Author: Nicholas Herriot
/* Copyright (c) 2013 Vodafone, MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

# include "MMA8452.h"

// Connect module at I2C address using I2C port pins sda and scl
Accelerometer_MMA8452::Accelerometer_MMA8452(PinName sda, PinName scl,int frequency) : m_i2c(sda, scl) , m_frequency(frequency)
{
    //m_i2c.frequency(m_frequency);
    
    // setup read and write addresses to avoid duplication
   _readAddress   = (MMA8452_ADDRESS<<1) | 0x01;
   _writeAddress  = (MMA8452_ADDRESS<<1) & 0xFE;
}


// Destroys instance
Accelerometer_MMA8452::~Accelerometer_MMA8452() 
{

}

// Setting the control register bit 1 to true to activate the MMA8452
int Accelerometer_MMA8452::activate()
{
    // set control register 1 to active
    char init[2] = {CTRL_REG_1,ACTIVE};
    
    // perform write and return error code
    return m_i2c.write(_writeAddress,init,2);
}


// Get 'Fast Read Mode' called F_READ. If bit 1 is set '1' then F_READ is active. Fast read will skip LSB when reading xyz
// resisters from 0x01 to 0x06. When F_READ is '0' then all 6 registers will be read.

int Accelerometer_MMA8452::get_CTRL_Reg1(int* dst)
{   
   return read_reg(CTRL_REG_1,dst); 
}

// Setting the control register bit 1 to true to activate the MMA8452
int Accelerometer_MMA8452::standby()
{
    // set control register 1 to standby
    char init[2] = {CTRL_REG_1,STANDBY};
    
    // write to the register and return the error code
    return m_i2c.write(_writeAddress,init,2);
}



// Device initialization
void Accelerometer_MMA8452::init()
{
    
    write_reg(INTSU_STATUS, 0x10);      // automatic interrupt after every measurement
    write_reg(SR_STATUS, 0x00);         // 120 Samples/Second
    write_reg(MODE_STATUS, 0x01);       // Active Mode
    
}

// Get real time status of device - it can be STANDBY, WAKE or SLEEP
int Accelerometer_MMA8452::get_SystemMode(int *dst)
{
    return read_reg(SYSMOD,dst);
}



// Get real time status of device - it can be STANDBY, WAKE or SLEEP
int Accelerometer_MMA8452::get_Status(int* dst)
{
    return read_reg(STATUS,dst);
}


// Get device ID 
int Accelerometer_MMA8452::get_DeviceID(int *dst)
{
    return read_reg(WHO_AM_I,dst);
}


/*
// Reads x data
int Accelerometer_MMA8452::read_x(int& xaxisLSB)
{
    char mcu_address = (MMA8452_ADDRESS<<1);
    m_i2c.start();
    if( m_i2c.write( mcu_address & 0xFE) == 0)          // just good practice to force bit 1 to a '0' by ANDing with 0xFE
    {
        return 1;                                       // we failed to write the mcu address on the bus to initiate dialogue 
    }
    if( m_i2c.write( OUT_X_MSB) == 0) 
    {
        return 1;                                       // we failed to write 'X axis LSB' to the chip
    }
    m_i2c.start();
    if( m_i2c.write( mcu_address | 0x01) == 0)          // this is asking to read the slave mcu address - even though it's a 'write' method!!! Crap API...
    {
        return 1;                                       // we failed to request a read from that mcu - this really is just writing the mcu vaule on the bus
    }
    xaxisLSB  = m_i2c.read(0);
    m_i2c.stop();
    return 0;
}
*/

int Accelerometer_MMA8452::read_raw(char src, char *dst, int len) {
    // this is the register we want to get data from               
    char register_address[1];
    register_address[0] = src;
    
    if(m_i2c.write(_writeAddress,register_address,1,true) == 0)
    {
        if(m_i2c.read(_readAddress,dst,len)==0)
        {
           return 0;
        }
    }
    
    // failure case, zero array and return error
    for(int i=0; i<len; i++) {
       dst[i] = 0x00;
    }
    return 1;   
}

// Reads x data. This method reads two registers containing the x-axis values from the accelerometer. 
// It takes a 2 byte char array and copies the register values into the buffer. If it fails the char array
// is set to '0'. It returns '0' success '1' fail. This method does nothing to the registers - just returns
// the raw data.
//int Accelerometer_MMA8452::read_x(int& xaxisLSB)
int Accelerometer_MMA8452::read_x_raw(char *xaxis)
{   
    return read_raw(OUT_X_MSB,xaxis,2);  
}


// Reads y data. This method reads two registers containing the x-axis values from the accelerometer. 
// It takes a 2 byte char array and copies the register values into the buffer. If it fails the char array
// is set to '0'. It returns '0' success '1' fail. This method does nothing to the registers - just returns
// the raw data.

int Accelerometer_MMA8452::read_y_raw(char *yaxis) {
   return read_raw(OUT_Y_MSB,yaxis,2);
}



// Reads z data. This method reads two registers containing the x-axis values from the accelerometer. 
// It takes a 2 byte char array and copies the register values into the buffer. If it fails the char array
// is set to '0'. It returns '0' success '1' fail. This method does nothing to the registers - just returns
// the raw data.

int Accelerometer_MMA8452::read_z_raw(char *zaxis)
{
   return read_raw(OUT_Z_MSB,zaxis,2);
}



// Reads y data
int Accelerometer_MMA8452::read_y()
{
    char mcu_address = (MMA8452_ADDRESS <<1);

    m_i2c.start();                  // Start
    m_i2c.write(mcu_address);              // A write to device 0x98
    m_i2c.write(OUT_Y_MSB);             // Register to read
    m_i2c.start();                  
    m_i2c.write(mcu_address);              // Read from device 0x99
    int y = m_i2c.read(0);         // Read the data
    m_i2c.stop();
    
    return y; 

}


// Reads z data
int Accelerometer_MMA8452::read_z()
{
    char mcu_address = (MMA8452_ADDRESS <<1);
    
    m_i2c.start();                  // Start
    m_i2c.write(mcu_address);              // A write to device 0x98
    m_i2c.write(OUT_Z_MSB);             // Register to read
    m_i2c.start();                  
    m_i2c.write(mcu_address);              // Read from device 0x99
    int z = m_i2c.read(0);         // Read the data
    m_i2c.stop();
    
    return z;

}


// Reads xyz
int Accelerometer_MMA8452::read_xyz(char *x, char *y, char *z) 
{
    
    
    char mcu_address = (MMA8452_ADDRESS <<1);
    char register_buffer[6] ={0,0,0,0,0,0};
    const char Addr_X = OUT_X_MSB;
    m_i2c.write(mcu_address);              // A write to device 0x98
    m_i2c.write(MMA8452_ADDRESS, &Addr_X, 1);         // Pointer to the OUT_X_MSB register
    
    if(m_i2c.write(mcu_address,&Addr_X,1) == 0)
    {
        if(m_i2c.read(mcu_address,register_buffer,6) == 0)
        {
            *x = register_buffer[1];
            *y = register_buffer[3];
            *z = register_buffer[5];
            return 0;           // yahoooooo
        }
        else
        {
            return 1;           // failed oh nooo!
        }    
    }
    else
    {
        return 1;               // failed oh nooo!
    }

}

        // Write register (The device must be placed in Standby Mode to change the value of the registers) 
void Accelerometer_MMA8452::write_reg(char addr, char data)
{

    char cmd[2] = {0, 0};
    
    cmd[0] = MODE_STATUS;
    cmd[1] = 0x00;                      // Standby Mode on
    m_i2c.write(MMA8452_ADDRESS, cmd, 2);
  
    cmd[0] = addr;
    cmd[1] = data;                      // New value of the register
    m_i2c.write(MMA8452_ADDRESS, cmd, 2); 
      
    cmd[0] = MODE_STATUS;
    cmd[1] = 0x01;                      // Active Mode on
    m_i2c.write(MMA8452_ADDRESS, cmd, 2);
                  
}



        // Read from specified MMA7660FC register
int Accelerometer_MMA8452::read_reg(char addr, int *dst)
{
    
    m_i2c.start();
    if( m_i2c.write(_writeAddress) == 0)
    {
        return 1;                                   // we failed to write the mcu address on the bus to initiate dialogue 
    }
    if( m_i2c.write(addr) == 0) 
    {
        return 1;                                       // we failed to write 'status' to the chip
    }
    m_i2c.start();
    if( m_i2c.write(_readAddress) == 0)          // this is asking to read the slave mcu address - even though it's a 'write' method!!! Crap API...
    {
        return 1;                                       // we failed to request a read from that mcu - this really is just writing the mcu vaule on the bus
    }
    *dst = m_i2c.read(0);
    m_i2c.stop();      
 
    return 0;
    
}