MPL115A2 (I2C) Pressure sensor interface

Dependents:   MPL115A2Sample dataloger_for_modelrocket ARLISS2012_Hidaka

MPL115A2.h

Committer:
yamaguch
Date:
2011-04-26
Revision:
0:4df6d69700fa

File content as of revision 0:4df6d69700fa:

#ifndef MPL115A2
#define MPL115A

#include "mbed.h"

/**
 * MPL115A2 (I2C) pressure sensor
 */

class MPL115A2 {
public:
    /**
    * Create an MPL115A(I2C) interface with specified pins
    *
    * @param PinName sda SDA pin (default = p9)
    * @param PinName scl SCL pin (default = p10)
    */
    MPL115A2(PinName sda = p9, PinName scl = p10) : i2c(sda, scl) {
    }

    /**
    * Read current pressure and/or temperature
    *
    * @param puressure pointer to an int area to receive pressure
    * @param temperature pointer to a float area to receive temperature
    *
    * @returns 0 (success), or -1 (I2C error)
    */

    int read(int *pressure, float *temperature) {
        const char id = 0x60 << 1;
        char cmd[2] = {0x12, 0x01}; // read both
        char buf[16];

        if (i2c.write(id, cmd, 2) != 0)
            return -1;

        wait_ms(1);

        cmd[0] = 0;

        if (i2c.write(id, cmd, 1, true) != 0)
            return -1;

        if (i2c.read(id, buf, 16) == 0) {
            int padc = short((buf[0] << 8 | buf[1]) >> 6);
            int tadc = short((buf[2] << 8 | buf[3]) >> 6);
            int a0 = short(buf[4] << 8 | buf[5]);
            int b1 = short(buf[6] << 8 | buf[7]);
            int b2 = short(buf[8] << 8 | buf[9]);
            int c12 = short(buf[10] << 8 | buf[11]);
            int c11 = short(buf[12] << 8 | buf[13]);
            int c22 = short(buf[14] << 8 | buf[15]);
            int pcomp = ((a0 << 10) + b1 * padc + (b2 * tadc >> 1) +
                         (c11 * padc * padc >> 14) + (c12 * tadc * padc >> 11) + (c22 * tadc * tadc >> 17)) >> 13;

            if (temperature != 0)
                *temperature = 25.0 - (tadc - 472) / 5.35;

            if (pressure != 0)
                *pressure = (650 * pcomp + 512) / 1023 + 500;

            return 0;
        }

        return -1;
    }
    
    /**
    * Read current pressure
    *
    * @returns current pressure (in hPa)
    */
    int readPressure() {
        int pressure;
        return read(&pressure, 0) == 0 ? pressure : 0;
    }
    
    /**
    * Read current temperature
    *
    * @returns current temperature (in Celcius)
    */
    float readTemperature() {
        float temperature;
        return read(0, &temperature) == 0 ? temperature : -273.15;
    }

    /**
    * Operator shorthand for readPressure()
    */
    operator int() {
        return readPressure();
    }

    /**
    * Operator shorthand for readTemperature()
    */
    operator float() {
        return readTemperature();
    }

private:
    I2C i2c;
};

#endif