Library for Akizuki MCP3425 ADC module

Fork of MCP3425 by yasuyuki onodera

Library for MCP3425 ADC module from Akizuki-denshi.

MCP3425.h

Committer:
sakurahilljp
Date:
2016-04-15
Revision:
3:378672292488
Parent:
2:7375e645e806

File content as of revision 3:378672292488:

//**********************
// MCP3425.h for mbed
//
// (C)Copyright 2016 Satoshi Nihonyanagi, All Rights Reserved.
//
// (C)Copyright 2014 All rights reserved by Y.Onodera
// http://einstlab.web.fc2.com
//**********************

#ifndef MCP3425_H_
#define MCP3425_H_

#include "mbed.h"
/** MCP3425 class.
 *  Used for MCP3425 ADC module from Akizuki-denshi.
 *
 * Example:
 * @code
 * #include "mbed.h"
 * #include "MCP3425.h"
 * 
 * I2C i2c(dp13, dp15);
 * MCP3425 adc(i2c);
 * 
 * int main() 
 * {
 *     adc.set(MCP3425::G1);
 *     adc.set(MCP3425::W12);
 *     adc.set(MCP3425::CONTINUOUS);
 *
 *     short c = adc.code();
 *     float v = adc.read();
 * }
 * @endcode
 */

class MCP3425
{
public:    
    enum Gain { G1 = 0, G2 = 1, G4 = 2, G8 = 3 };
    enum Resolution {W12 = 0, W14 = 1, W16 = 2};
    enum Conversion {ONESHOT = 0, CONTINUOUS = 1};

    /** Construct a new instance.*/
    MCP3425(I2C& i2c);
    
    /** Construct a new instance with the specified I2C slave address. 
        ( Address of MCP3425 from akizuki-denshi is fixed to 0x0D.)
    */
    MCP3425(I2C& i2c, int addr);

    /** Specify gain. */
    void set(Gain gain);
    
    /** Specify resolution (sample bits). */
    void set(Resolution resolution);
    
    /** Specify conversion operation mode. */
    void set(Conversion conversion);

    /** Return AD code. */
    short get();
    
    /** Return voltage. */
    float read();

private:

    static const int ADDR;
    static const float VREF;

    typedef union
    {
        unsigned short int  Val;
        unsigned char v[2];
        short S;
        struct
        {
            unsigned char LB;
            unsigned char HB;
        } byte;
    } WORD_VAL;

    typedef union {
        unsigned char UC;
        struct {
            unsigned char G:2;      // 00=1, 01=2, 10=4, 11=8 Gain
            unsigned char S:2;      // 00=12bits, 01=14bits, 10=16bits
            unsigned char OC:1;     // 0=One-shot, 1=Continuous
            unsigned char C:2;      // NA
            unsigned char RDY:1;    // wrinting 1=Initiate, reading 0=Ready
        } bit;
    } CONFIG;

    I2C _i2c;
    int _addr;

    CONFIG _cfg;
    WORD_VAL _val;

    char _buf[3];

    void _init();
    void _write_cfg();
    short _get_code();
    float _c2v(short code);
};

#endif /* MCP3425_H_ */