Microchip MCP342x ADC library
Diff: mcp342x.cpp
- Revision:
- 4:9480edf3926d
- Parent:
- 3:03911aa07029
- Child:
- 5:0ca445d2d2bc
diff -r 03911aa07029 -r 9480edf3926d mcp342x.cpp --- a/mcp342x.cpp Tue Jul 18 09:43:27 2017 +0000 +++ b/mcp342x.cpp Mon Sep 10 17:02:22 2018 +0000 @@ -1,6 +1,7 @@ #include "mcp342x.h" #define LEN_ONE_BYTE 1 +extern Serial pc; MCP342x::MCP342x(I2C *i2c, uint8_t device_address) { @@ -14,7 +15,7 @@ // Initialise to default settings: channel 1, gain 1x, 12 bits. // It is necessary to do this to ensure that the variables // _resolution and _pga are properly set. - _configuration = 0x10; + _configuration = 0x10; // Continuous mode set_channel(CHANNEL_1); set_resolution(RESOLUTION_12); set_pga(PGA_1); @@ -50,7 +51,7 @@ // // _max_code is the maximum output code, and it is equal to // 2^(N-1) - 1 (datasheet Table 4-3). - switch(_resolution){ + switch(_resolution) { case RESOLUTION_12: _lsb = 2 * 2.048 / 4096; _max_code = 2047; @@ -103,14 +104,47 @@ void MCP342x::_write_configuration() { +// pc.printf("MCP3424 config %0X\r\n", _configuration ); _i2c_command[0] = _configuration; _i2c->write(_address, _i2c_command, LEN_ONE_BYTE); } +uint8_t MCP342x::read_configuration() +{ +// pc.printf("MCP3424 config %0X\r\n", _configuration ); + _i2c_command[0] = _configuration; + _i2c->read(_address, _i2c_command, LEN_ONE_BYTE); + return _i2c_command[0]; +} + +void MCP342x::_startRead() +{ + _i2c_command[0] = _configuration | 0x80; + _i2c->write(_address, _i2c_command, LEN_ONE_BYTE); +} + uint32_t MCP342x::read() { uint32_t adc_value = 0; - _i2c->read(_address, _i2c_command, COMMAND_N_BYTES); + uint8_t readConfig = 0; + int byteNum = 3; + + if( (_configuration & 0x10) == 0 ) + _startRead(); + + // Read config register + if (_resolution == RESOLUTION_18 ) { + byteNum = 4; + } + + _i2c->read(_address, _i2c_command, byteNum); + + while( (_i2c_command[byteNum-1] & 0x80) == 0x80 ) { + wait_ms(10); + // pc.printf("MCP3424 config %0X %0X %0X %0X\r\n", _i2c_command[0],_i2c_command[1],_i2c_command[2],_i2c_command[3] ); + _i2c->read(_address, _i2c_command, byteNum); + } + switch (_resolution) { case RESOLUTION_12: @@ -130,14 +164,15 @@ case RESOLUTION_18: adc_value = (_i2c_command[0] << 16) | - (_i2c_command[1] << 8) | _i2c_command[2]; + (_i2c_command[1] << 8) | _i2c_command[2]; adc_value &= 0x3ffff; break; } return adc_value; } -float MCP342x::read_volts(){ +float MCP342x::read_volts() +{ float volts = 0.0; uint32_t adc_value = read();