MPL115A2 (I2C) Pressure sensor interface

Dependents:   MPL115A2Sample dataloger_for_modelrocket ARLISS2012_Hidaka

MPL115A2.cpp

Committer:
yamaguch
Date:
2011-05-14
Revision:
2:d77bd4340924

File content as of revision 2:d77bd4340924:

#include "MPL115A2.h"

#define c2f(ch, cl, nbits, fbits, zpad) float(short(ch << 8 | cl) >> 16 - nbits) / (1 << fbits + zpad)

int MPL115A2::read(float *pressure, char *data) {
    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) {
        float padc = buf[0] << 2 | buf[1] >> 6;
        float tadc = buf[2] << 2 | buf[3] >> 6;
        float a0 = c2f(buf[4], buf[5], 16, 3, 0);
        float b1 = c2f(buf[6], buf[7], 16, 13, 0);
        float b2 = c2f(buf[8], buf[9], 16, 14, 0);
        float c12 = c2f(buf[10], buf[11], 14, 13, 9);
        float c11 = c2f(buf[12], buf[13], 11, 10, 11);
        float c22 = c2f(buf[14], buf[15], 11, 10, 15);

        float pcomp = a0 + (b1 + c11 * padc + c12 * tadc) * padc + (b2 + c22 * tadc) * tadc;

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

        if (data != 0)
            memcpy(data, buf, 16);

        return 0;
    }

    return -1;
}

float MPL115A2::readPressure() {
    float pressure;
    return read(&pressure, 0) == 0 ? pressure : 0;
}