BMC150 magnetometer and accelerometer library.

Dependents:   acd52832_BMC150_example acd52832_bmc150_test

bmc150.cpp

Committer:
Dautor
Date:
14 months ago
Revision:
10:1d1123b3df76
Parent:
9:2d91d90f507d

File content as of revision 10:1d1123b3df76:

/*
 *  Bosch BMC150 6-axis eCompass library.
 *  Developed by Jurica Resetar @ aconno, 2017
 *  More info @ aconno.de
 *  All rights reserved.
 *
 */

#include "bmc150.h"
#include "utilities.h"
#include "bmc150_registers.h"

BMC150::BMC150(SPI spi, NRF52_DigitalOut cs) : spi(spi), cs(cs){
}

vector3_f BMC150::readAccelerometer_f(){
    vector3_f result;
    vector3_s data = readAccelerometer();
    floatToBuffer((float)data.x*ACC_LSB_VALUE*0.001f, (uint8_t *)&result.x);
    floatToBuffer((float)data.y*ACC_LSB_VALUE*0.001f, (uint8_t *)&result.y);
    floatToBuffer((float)data.z*ACC_LSB_VALUE*0.001f, (uint8_t *)&result.z);
    return result;
}

bool BMC150::setRegister(uint8_t regAddress, uint8_t data){
    cs = 0;
    spi.write(regAddress & SPI_WRITE);      // MSB bit has to be LOW to indicate Write command
    spi.write(data);
    cs = 1;
    return 0;
}

uint8_t BMC150::getRegister(uint8_t regAddress){
    uint8_t data;
    cs = 0;
    spi.write(regAddress | SPI_READ);
    data = spi.write(SPI_DUMMY_BYTE | SPI_READ);
    cs = 1;
    return (data);
}

vector3_s BMC150::readAccelerometer(){
    vector3_s result;
    int8_t msb, lsb;
        
    lsb = getRegister(DATA_ACC_X_LSB);
    msb = getRegister(DATA_ACC_X_MSB);
    result.x = convert<4>(msb,lsb);
    lsb = getRegister(DATA_ACC_Y_LSB);
    msb = getRegister(DATA_ACC_Y_MSB);
    result.y = convert<4>(msb,lsb);
    lsb = getRegister(DATA_ACC_Z_LSB);
    msb = getRegister(DATA_ACC_Z_MSB);
    result.z = convert<4>(msb,lsb);
    return result;
}

vector3_s BMC150::readMagnetometer(){
    vector3_s result;
    int8_t msb, lsb;
        
    lsb = getRegister(DATA_MAG_X_LSB);
    msb = getRegister(DATA_MAG_X_MSB);
    result.x = convert<5>(msb,lsb);
    lsb = getRegister(DATA_MAG_Y_LSB);
    msb = getRegister(DATA_MAG_Y_MSB);
    result.y = convert<5>(msb,lsb);
    lsb = getRegister(DATA_MAG_Z_LSB);
    msb = getRegister(DATA_MAG_Z_MSB);
    result.z = convert<7>(msb,lsb);
    
    return result;
}

uint8_t BMC150::readTemperature(){
    uint8_t temperature;        
    cs = 1; 
    wait_ms(1);
    spi.write(0x08);
    wait_ms(1); 
    temperature = spi.write(0x00);
    wait_ms(1); 
    cs = 0;
    return temperature;
}

void BMC150::calibrateAccelerometer(){
    cs = 0;
    // perform
    cs = 1;
}
void BMC150::initMagnetometer(){
    setRegister(0x4B, 0x01);    // Set Power Control bit.
    wait_ms(10);
    setRegister(0x4C, 0x38);    // Change magnetometer mode in Active mode
    setRegister(0x4E, 0x07);    // Enable magnetometer axes
    setRegister(0x4D, 0xFF);    // Enable interrupts for every axis and override
}