MPL115A2 library

Dependents:   mbed_MPL115

See http://developer.mbed.org/users/yasuyuki/notebook/MPL115A2/

MPL115.cpp

Committer:
yasuyuki
Date:
2014-10-16
Revision:
1:12912b2da7d9
Parent:
0:ae28484ad07d

File content as of revision 1:12912b2da7d9:

//**********************
// MPL115.cpp for mbed
//
// MPL115A2 mpl115a2(P0_5,P0_4);
// or
// I2C i2c(P0_5,P0_4);
// MPL115A2 mpl115a2(i2c);
//
// (C)Copyright 2014 All rights reserved by Y.Onodera
// http://einstlab.web.fc2.com
//**********************

#include "mbed.h"
#include "MPL115.h"

MPL115A2::MPL115A2 (PinName sda, PinName scl) : _i2c(sda, scl) {
    init();
}
MPL115A2::MPL115A2 (I2C& p_i2c) : _i2c(p_i2c) {
    init();
}


void MPL115A2::start()
{

    // Start Conversion
    buf[0] = 0x12;
    buf[1] = 0x01;
    _i2c.write(MPL115_ADDR, buf, 2);

    wait_ms(5);
    
    // Read Results
    buf[0] = 0x00;
    _i2c.write(MPL115_ADDR, buf, 1, false); // no stop, repeated
    _i2c.read( MPL115_ADDR, buf, 4);

    Padc.byte.HB=buf[0];
    Padc.byte.LB=buf[1];
    Tadc.byte.HB=buf[2];
    Tadc.byte.LB=buf[3];

}


short MPL115A2::temperature()
{
    start();
    
    Tadc.Val >>= 6;     // to adjust 10 bit
    return Tadc.S;
}


short MPL115A2::pressure()
{

    // Pcomp = a0 + (b1 + c12 * Tadc) * Padc + b2 * Tadc
    int c12x2, a1, a1x1, y1, a2x2, Pcomp;

    start();

    Padc.Val >>= 6;   // to adjust 10 bit
    Tadc.Val >>= 6;   // to adjust 10 bit
    c12x2 = (((int)c12.S) * (int)Tadc.S) >> 11; // c12x2 = c12 * Tadc
    a1 = (int)b1.S + c12x2;                     // a1 = b1 + c12x2
    a1x1 = a1 * (int)Padc.S;                    // a1x1 = a1 * Padc
    y1 = (((int)a0.S) << 10) + a1x1;            // y1 = a0 + a1x1
    a2x2 = (((int)b2.S) * (int)Tadc.S) >> 1;    // a2x2 = b2 * Tadc
    Pcomp = (y1 + a2x2) >> 9;                   // Pcomp = y1 + a2x2

    return (short)Pcomp;

    // hPa = (Pcomp/16) * (115.0-50.0)/1023.0 +  50.0
}

void MPL115A2::init()
{

    buf[0] = 0x04;
    _i2c.write(MPL115_ADDR, buf, 1, false); // no stop, repeated
    _i2c.read( MPL115_ADDR, buf, 8);
    
    a0.byte.HB=buf[0];
    a0.byte.LB=buf[1];
    b1.byte.HB=buf[2];
    b1.byte.LB=buf[3];
    b2.byte.HB=buf[4];
    b2.byte.LB=buf[5];
    c12.byte.HB=buf[6];
    c12.byte.LB=buf[7];
    
}