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
Diff: mcp3208.cpp
- Revision:
- 0:d37e8cb188c1
- Child:
- 1:316f86115221
diff -r 000000000000 -r d37e8cb188c1 mcp3208.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mcp3208.cpp Mon May 23 22:58:59 2011 +0000 @@ -0,0 +1,36 @@ +#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; +}