Control Code with I/O and ADC working

Dependencies:   MODSERIAL mbed

LTC2487/LTC2487.cpp

Committer:
jrodenburg
Date:
2018-05-08
Revision:
13:604e6933366f
Parent:
12:1cada1fe4743
Child:
14:69cd53434783

File content as of revision 13:604e6933366f:

#include "mbed.h"
#include "LTC2487.h"
#include "MODSERIAL.h"


namespace {
    const uint8_t I2C_WRITE  = 0x00;
    const uint8_t I2C_READ   = 0x01;
    
    //Channel addresses (first two bits are fixed)
    //0b10  EN  SGL ODD A2  A1  A0
    //0b10  1   1   0   0   0   0   ch0 --> 0xb0
    //0b10  1   1   1   0   0   0   ch1 --> 0xb8
    //0b10  1   1   0   0   0   1   ch2 --> 0xb1
    //0b10  1   1   1   0   0   1   ch3 --> 0xb9
    

    //Config Section
    //      EN2 IM  FA  FB  SPD GS2 GS1 GS0
    //      1   0   0   0   0   0   1   0       //Initial
    //      1   0   0   0   1   0   1   1       //New Attempt with same gain (8x)
    //      1   0   0   0   1   0   0   0       //New Attempt with unity gain (1x)
    
    
    const uint8_t CHNL_0     = 0xb0;
    const uint8_t CHNL_1     = 0xb8;
    const uint8_t CHNL_2     = 0xb1;
    const uint8_t CHNL_3     = 0xb9;
};

LTC2487::LTC2487 (PinName sda, PinName scl, uint8_t address, int freq): i2c( sda, scl ){
    addrI2C = address;
    i2c.frequency(freq);
}

void LTC2487::setAddress(int address){
    addrI2C = address;
}

float LTC2487::readOutput(int chnl){
    char ADC_channel[1];
    char ADC_data_rx[3];
    char ADC_config[1];
    ADC_config[0] = 0b10001000;//0x82; //0b10000010
    char cmd[2];
        
    //select channel to read
    switch (chnl){
        case 0:
            ADC_channel[0] = CHNL_0;
            break;
        case 1:
            ADC_channel[0] = CHNL_1;
            break;
        case 2:
            ADC_channel[0] = CHNL_2;
            break;
        case 3:
            ADC_channel[0] = CHNL_3;
            break;
    } 
    
    cmd[0] = ADC_channel[0];
    cmd[1] = ADC_config[0];
    
    i2c.write((addrI2C<<1)|(I2C_WRITE), cmd, 2);
    
    /*//send message to select channel
    i2c.write((addrI2C<<1)|(I2C_WRITE), ADC_channel, 1);
    //must wait, otherwise breaks...
    wait(0.08);
    //send configuration (1 gain, autocalibration)
    i2c.write((addrI2C<<1)|(I2C_WRITE), ADC_config, 1);
    //must wait, otherwise breaks...*/
    wait(0.08);
    //Read data from selected channel --> 24bits --> 23bit=SIGN 22bit=MSB 21-7bits=DATA 5-0bits=JUNK
    i2c.read((addrI2C<<1)|(I2C_READ), ADC_data_rx, 3);
    //must wait, otherwise breaks...
    wait(0.08);
    //Stitch together the bytes into a 24bit value
    unsigned long data = (ADC_data_rx[0] << 16) | (ADC_data_rx[1] << 8)| ADC_data_rx[2];
    //Delete SIGN bit and MSB bit and remove 6 JUNK bits
    unsigned long ADC_Result = (data&0x3fffff)>>6;  
        
    return float(float(ADC_Result));

}