Satoshi Nihonyanagi / MCP3425AK

Fork of MCP3425 by yasuyuki onodera

MCP3425.cpp

Committer:
sakurahilljp
Date:
2016-04-12
Revision:
1:5ac344aa0aac
Parent:
0:b7bc51be525f
Child:
2:7375e645e806

File content as of revision 1:5ac344aa0aac:

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

#include "mbed.h"
#include "MCP3425.h"

const float MCP3425::VREF = 2.048;

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


short MCP3425::get()
{
    _i2c.read( MCP3425_ADDR, buf, 3);

    ad.byte.HB=buf[0];
    ad.byte.LB=buf[1];
    config.UC=buf[2];
    return ad.S;
}

float MCP3425::read()
{
    int gain = 1;
    if (config.bit.G == 0) gain = 1;
    else if (config.bit.G == 1) gain = 2;
    else if (config.bit.G == 2) gain = 4;
    else if (config.bit.G == 3) gain = 8;

    int maxcode = 2047;
    if (config.bit.S == 0 ) maxcode = 2047;
    else if (config.bit.S == 1 ) maxcode = 8191;
    else if (config.bit.S == 2 ) maxcode = 32767;
 
    short code = get();   
    return code * VREF / gain / ( maxcode + 1 ); 
}


void MCP3425::init()
{

    config.bit.RDY=1;
    config.bit.C=0;
    config.bit.OC=1;
    config.bit.S=2;
    config.bit.G=0;
    // Initiate Continuous 16bits, 15SPS
    buf[0]=config.UC;
    _i2c.write(MCP3425_ADDR, buf, 1);

}