A library to interface to the MCP3208 SPI-based ADC from Microchip. This chip provides eight analogue inputs, providing converted 12-bit values via SPI.

Dependents:   Nucleo_MCP3208_Test Nucleo_MCP3208_Ticker_Test BBMv2_eps ref_BBMv2_eps ... more

mcp3208.cpp

Committer:
Kemp
Date:
2011-05-23
Revision:
0:d37e8cb188c1
Child:
1:316f86115221

File content as of revision 0:d37e8cb188c1:

#include "mcp3208.h"


#define START_BIT   0x04
#define MODE_SINGLE 0x02    // Single-ended mode
#define MODE_DIFF   0x00    // Differential mode


MCP3208::MCP3208(SPI bus, PinName cs)
    : m_cs(cs), m_bus(bus)
{}

MCP3208::~MCP3208() {}


void MCP3208::select() {m_cs = 0;}
void MCP3208::deselect() {m_cs = 1;}


int MCP3208::read_input(int channel)
{
    int high_byte, low_byte;

    select();
    
    // Odd writing requirements, see the datasheet for details
    m_bus.write(START_BIT | MODE_SINGLE | (channel >> 2));
    high_byte = m_bus.write(channel << 6) & 0x0F;
    low_byte = m_bus.write(0);
    
    deselect();
    
    int conv_result = (high_byte << 8) | low_byte;
    
    return float(conv_result) / 4096;
}