work nice now

Dependents:   Minimu-9v2

Fork of LSM303DLHC by brian claus

LSM303DLHC.cpp

Committer:
patsteph
Date:
2013-11-17
Revision:
7:ddd9717cdb71
Parent:
6:fcf7e9b8ce21

File content as of revision 7:ddd9717cdb71:


#include "mbed.h"
#include "LSM303DLHC.h"


const int addr_acc = 0x32;
const int addr_mag = 0x3c;

bool LSM303DLHC::write_reg(int addr_i2c,int addr_reg, char v)
{
    char data[2] = {addr_reg, v}; 
    return LSM303DLHC::_LSM303.write(addr_i2c, data, 2) == 0;
}

bool LSM303DLHC::read_reg(int addr_i2c,int addr_reg, char *v)
{
    char data = addr_reg; 
    bool result = false;
    
    __disable_irq();
    if ((_LSM303.write(addr_i2c, &data, 1) == 0) && (_LSM303.read(addr_i2c, &data, 1) == 0)){
        *v = data;
        result = true;
    }
    __enable_irq();
    return result;
}


LSM303DLHC::LSM303DLHC(PinName sda, PinName scl):
    _LSM303(sda, scl)
{
    char reg_v;
    _LSM303.frequency(100000);
        
    reg_v = 0;
    
    reg_v |= 0x27;          /* X/Y/Z axis enable. */
    write_reg(addr_acc,CTRL_REG1_A,reg_v);

    reg_v = 0;
   // reg_v |= 0x01 << 6;     /* 1: data MSB @ lower address */
    reg_v = 0x01 << 4;     /* +/- 4g */
    write_reg(addr_acc,CTRL_REG4_A,reg_v);

    /* -- mag --- */
    reg_v = 0;
    reg_v |= 0x04 << 2;     /* Minimum data output rate = 15Hz */
    write_reg(addr_mag,CRA_REG_M,reg_v);

    reg_v = 0;
    reg_v |= 0x01 << 5;     /* +-1.3Gauss */
    //reg_v |= 0x07 << 5;     /* +-8.1Gauss */
    write_reg(addr_mag,CRB_REG_M,reg_v);

    reg_v = 0;              /* Continuous-conversion mode */
    write_reg(addr_mag,MR_REG_M,reg_v);
}


bool LSM303DLHC::readcomp(float *mx, float *my, float *mz) 
{
    char mag[6];
    char temp;
     
    if (recv(addr_mag, OUT_X_M, mag, 6)) 
    {   
          for(int i=0; i<6; i+=2)
        {
            temp = mag[i];
            mag[i] = mag[i+1];                      //la boucle inverse les valeurs du table
            mag[i+1] = temp;
        }

    
        *mx = *((short*)(mag));///1100.0;
        *mz = *((short*)(mag+2));///980.0;   //ATTENTION: le z vient avant le y, c'est normal!!!!!
        *my = *((short*)(mag+4));///1100.0;
        
 
        return true;
    }
 
    return false;
}
bool LSM303DLHC::readacc(float *ax, float *ay, float *az) 
{
    char acc[6];
     
    if (recv(addr_acc, OUT_X_A, acc, 6)) 
    {
        *ax = *((short*)(acc)) >>4;///8192.0;  //32768/4=8192
        *ay = *((short*)(acc+2)) >>4;///8192.0;
        *az = *((short*)(acc+4)) >>4;///8192.0;
        //full scale magnetic readings are from -2048 to 2047
        //gain is x,y =1100; z = 980 LSB/gauss
        
          
 
        return true;
    }
 
    return false;
}

bool LSM303DLHC::recv(char sad, char sub, char *buf, int length) {
    if (length > 1) sub |= 0x80;
 
    return _LSM303.write(sad, &sub, 1, true) == 0 && _LSM303.read(sad, buf, length) == 0;
}