Basic library for interfacing the AK8975 using I2C. It does not include more advanced functions. The datasheet does not include what the self-test should return for example, so this library does not include the self-test function.

AK8975.cpp

Committer:
Sissors
Date:
2012-05-07
Revision:
1:76f65416ae1b
Parent:
0:bceb91239894

File content as of revision 1:76f65416ae1b:

/**
 * Includes
 */
#include "AK8975.h"

AK8975::AK8975(PinName sda, PinName scl, char address) : connection(sda, scl) {
    deviceAddress=address;   
}

bool AK8975::testConnection( void ) {
    char temp;
    temp = this->read(AK8975_ID_REG);
    return (temp==0x48);
}

bool AK8975::isReady( void ) {
    char temp;
    temp = this->read(AK8975_ST1_REG);
    temp &= 1<<AK8975_DRDY_BIT;
    return (temp==1<<AK8975_DRDY_BIT);
}

int AK8975::getX( void ) {
    short retval;
    char data[2];
    this->read(AK8975_X_REG, data, 2);
    retval = (data[1]<<8) + data[0];
    return (int)retval;
}

int AK8975::getY( void ) {
    short retval;
    char data[2];
    this->read(AK8975_Y_REG, data, 2);
    retval = (data[1]<<8) + data[0];
    return (int)retval;
}

int AK8975::getZ( void ) {
    short retval;
    char data[2];
    this->read(AK8975_Z_REG, data, 2);
    retval = (data[1]<<8) + data[0];
    return (int)retval;
}


void AK8975::getAll( int *data ) {
    char temp[6];
    this->read(AK8975_X_REG, temp, 6);
    data[0] = (int)(short)(temp[1]<<8) + temp[0];
    data[1] = (int)(short)(temp[3]<<8) + temp[2];
    data[2] = (int)(short)(temp[5]<<8) + temp[4];        
}    

bool AK8975::getDataError( void ) {
    char temp;
    temp = this->read(AK8975_ST2_REG);
    temp &= 1<<AK8975_DERROR_BIT;
    return (temp==1<<AK8975_DERROR_BIT);
}

bool AK8975::getOverflow( void ) {
    char temp;
    temp = this->read(AK8975_ST2_REG);
    temp &= 1<<AK8975_OFLOW_BIT;
    return (temp==1<<AK8975_OFLOW_BIT);
}

void AK8975::startMeasurement( void ) {
    this->write(AK8975_CONTROL_REG, AK8975_SINGLE_MEASUREMENT);
}

//--------------------------------------------------
//-------------------PRIVATE------------------------
//--------------------------------------------------

void AK8975::write(char address, char data) {
    char temp[2];
    temp[0]=address;
    temp[1]=data;
    
    connection.write(deviceAddress * 2,temp,2);
}

char AK8975::read(char address) {
    char retval;
    connection.write(deviceAddress * 2, &address, 1, true);
    connection.read(deviceAddress * 2, &retval, 1);
    return retval;
}

void AK8975::read(char address, char *data, int length) {
    connection.write(deviceAddress * 2, &address, 1, true);
    connection.read(deviceAddress * 2, data, length);
}