Library for Akizuki MCP3425 ADC module
Fork of MCP3425 by
Library for MCP3425 ADC module from Akizuki-denshi.
Diff: MCP3425.cpp
- Revision:
- 2:7375e645e806
- Parent:
- 1:5ac344aa0aac
- Child:
- 3:378672292488
diff -r 5ac344aa0aac -r 7375e645e806 MCP3425.cpp --- a/MCP3425.cpp Tue Apr 12 14:56:07 2016 +0000 +++ b/MCP3425.cpp Wed Apr 13 14:45:11 2016 +0000 @@ -13,55 +13,103 @@ #include "mbed.h" #include "MCP3425.h" +const int MCP3425::ADDR = 0xD0; const float MCP3425::VREF = 2.048; -MCP3425::MCP3425 (PinName sda, PinName scl) : _i2c(sda, scl) { - init(); + +MCP3425::MCP3425(I2C& i2c) + : _i2c(i2c), _addr(ADDR) +{ + _init(); } -MCP3425::MCP3425 (I2C& p_i2c) : _i2c(p_i2c) { - init(); + +MCP3425::MCP3425(I2C& i2c, int addr) + : _i2c(i2c), _addr(addr) +{ + _init(); } +void MCP3425::set(MCP3425::Gain gain) +{ + _cfg.bit.G = (unsigned char)gain; + _write_cfg(); +} + +void MCP3425::set(MCP3425::Resolution resolution) +{ + _cfg.bit.S = (unsigned char)resolution; + _write_cfg(); +} + +void MCP3425::set(MCP3425::Conversion conversion) +{ + _cfg.bit.OC = (unsigned char)conversion; + _write_cfg(); +} 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; + return _get_code(); } float MCP3425::read() { + short code = get(); + 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; + if (_cfg.bit.G == 0) gain = 1; + else if (_cfg.bit.G == 1) gain = 2; + else if (_cfg.bit.G == 2) gain = 4; + else if (_cfg.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 ); + if (_cfg.bit.S == 0 ) maxcode = 2047; + else if (_cfg.bit.S == 1 ) maxcode = 8191; + else if (_cfg.bit.S == 2 ) maxcode = 32767; + + return code * VREF / gain / ( maxcode + 1 ); +} + +void MCP3425::_init() +{ + _cfg.bit.G = (unsigned char)G1; + _cfg.bit.S = (unsigned char)W16; + _cfg.bit.OC = (unsigned char)ONESHOT; + _cfg.bit.C = 0; + _cfg.bit.RDY = 0; + + _write_cfg(); } - -void MCP3425::init() +void MCP3425::_write_cfg() { - - 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); - + _buf[0] = _cfg.UC; + _i2c.write(_addr, _buf, 1); } +short MCP3425::_get_code() +{ + // Trigger updating value if one-shot Mode + if (_cfg.bit.OC == 0) + { + _cfg.bit.RDY = 1; + _write_cfg(); + } + + while(1) { + if( _i2c.read( ADDR, _buf, 3) != 0 ) + { + // failed to read (nack) + return 0; + } + + _val.byte.HB = _buf[0]; + _val.byte.LB = _buf[1]; + _cfg.UC = _buf[2]; + + if(_cfg.bit.RDY == 0 ) break; + wait_ms(5); // fastest rate: 240 SPS with 12-bit + } + + return _val.S; +}