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

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers mcp3208.cpp Source File

mcp3208.cpp

00001 #include "mcp3208.h "
00002 
00003 
00004 #define START_BIT   0x04
00005 #define MODE_SINGLE 0x02    // Single-ended mode
00006 #define MODE_DIFF   0x00    // Differential mode
00007 
00008 
00009 MCP3208::MCP3208(SPI bus, PinName cs)
00010     : m_cs(cs), m_bus(bus)
00011 {
00012     deselect();
00013 }
00014 
00015 MCP3208::~MCP3208() {}
00016 
00017 
00018 void MCP3208::select() {m_cs = 0;}
00019 void MCP3208::deselect() {m_cs = 1; wait_us(1);}
00020 
00021 
00022 float MCP3208::read_input(int channel)
00023 {
00024     int command_high = START_BIT | MODE_SINGLE | ((channel & 0x04) >> 2);
00025     int command_low = (channel & 0x03) << 6;
00026     
00027     select();
00028     
00029     // Odd writing requirements, see the datasheet for details
00030     m_bus.write(command_high);
00031     int high_byte = m_bus.write(command_low) & 0x0F;
00032     int low_byte = m_bus.write(0);
00033     
00034     deselect();
00035     
00036     int conv_result = (high_byte << 8) | low_byte;
00037     
00038     return ((float)conv_result) / 4096;
00039 }
00040 
00041 
00042 float MCP3208::read_diff_input(int channel, Polarity polarity)
00043 {
00044     int command_high = START_BIT | MODE_DIFF | ((channel & 0x02) >> 1);
00045     int command_low = ((channel & 0x01) << 7) | (polarity << 6);
00046 
00047     select();
00048     
00049     // Odd writing and reading requirements, see the datasheet for details.
00050     m_bus.write(command_high);
00051     int high_byte = m_bus.write(command_low) & 0x0F;
00052     int low_byte = m_bus.write(0);
00053     
00054     deselect();
00055     
00056     int conv_result = (high_byte << 8) | low_byte;
00057     
00058     return float(conv_result) / 4096;
00059 }