STMicroelectronics LPS331 I2C Library.

Dependents:   LPS331_HelloWorld mbed_vfd_thermometer lon-lof

LPS331_I2C.cpp

Committer:
nyamfg
Date:
2013-10-20
Revision:
0:3fd57444bc65
Child:
1:b7d3d6e82049

File content as of revision 0:3fd57444bc65:

/*
 *  I2C/SPI digital pressure sensor "LPS331AP" library for I2C mode.
 *
 *  Copyright(c) -2013 unos@NYAMFG, 
 *  Released under the MIT License: http://mbed.org/license/mit
 *
 *  revision: see LPS331_I2C.h.
 */

#include "LPS331_I2C.h"

LPS331_I2C::LPS331_I2C(PinName sda, PinName scl, bool sa0) : _i2c(sda, scl)
{
    if(sa0 == LPS331_I2C_SA0_HIGH) {
        _address = LPS331_I2C_ADDRESS_SA0_HIGH;
    } else {
        _address = LPS331_I2C_ADDRESS_SA0_LOW;
    }
    _i2c.frequency(400 * 1000);
    _ctrlreg1 = 0x20;
}

LPS331_I2C::~LPS331_I2C()
{
}

char LPS331_I2C::whoami()
{
    return _read(0x0f);
}

bool LPS331_I2C::isAvailable()
{
    if(whoami() == 0xbb) { return true; }
    
    return false;
}

void LPS331_I2C::setResolution(char pressure_avg, char temp_avg)
{
    _write(0x10, ((temp_avg & 0x07) << 4) | (pressure_avg & 0x0f));
}

void LPS331_I2C::setActive(bool is_active)
{
    if(is_active) {
        _ctrlreg1 |= 0x80;
    } else {
        _ctrlreg1 &= ~0x80;
    }

    _write(0x20, _ctrlreg1);
}

void LPS331_I2C::setDataRate(char datarate)
{
    datarate &= 0x07;
    
    _ctrlreg1 &= ~(0x07 << 4);
    _ctrlreg1 |= datarate << 4;
    
    _write(0x20, _ctrlreg1);
}

    
float LPS331_I2C::getPressure()
{
    float pressure = 0;
    pressure += _read(0x28);
    pressure += _read(0x29) << 8;
    pressure += _read(0x2a) << 16;
    pressure /= 4096.0;
    
    return pressure;
}

float LPS331_I2C::getTemperature()
{
    short temp = 0;
    temp = _read(0x2b);
    temp |= _read(0x2c) << 8;
    
    return (float)(42.5 + temp / 480.0);
}


void LPS331_I2C::_write(char subaddress, char data)
{
    _i2c.start();
    _i2c.write(_address);
    _i2c.write(subaddress);
    _i2c.write(data);
    _i2c.stop();
}

char LPS331_I2C::_read(char subaddress)
{
    char result = 0;
    
    _i2c.start();
    _i2c.write(_address);
    _i2c.write(subaddress);
    
    _i2c.start();
    _i2c.write(_address | 1);
    result = _i2c.read(0);
    
    _i2c.stop();
    
    return result;
}