STMicroelectronics LPS331AP, LPS25H SPI Library. This library is base on https://developer.mbed.org/users/nyamfg/code/LPS331_I2C/
Dependents: LPS331_SPI_Test main_SPC
Fork of LPS331_I2C by
Diff: LPS331_I2C.cpp
- Revision:
- 0:3fd57444bc65
- Child:
- 1:b7d3d6e82049
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/LPS331_I2C.cpp Sun Oct 20 15:22:55 2013 +0000 @@ -0,0 +1,112 @@ +/* + * 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; +} +