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-24
- Revision:
- 2:93009a423b45
- Parent:
- 1:316f86115221
- Child:
- 3:e7de500b1f2d
File content as of revision 2:93009a423b45:
#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;} float MCP3208::read_input(int channel) { int command_high = START_BIT | MODE_SINGLE | ((channel & 0x04) >> 2); int command_low = (channel & 0x03) << 6; select(); // Odd writing requirements, see the datasheet for details m_bus.write(command_high); int high_byte = m_bus.write(command_low) & 0x0F; int low_byte = m_bus.write(0); deselect(); int conv_result = (high_byte << 8) | low_byte; return float(conv_result) / 4096; } float MCP3208::read_diff_input(int channel, Polarity polarity) { int command_high = START_BIT | MODE_DIFF | ((channel & 0x02) >> 1); int command_low = ((channel & 0x01) << 7) | (polarity << 6); select(); // Odd writing and reading requirements, see the datasheet for details. m_bus.write(command_high); int high_byte = m_bus.write(command_low) & 0x0F; int low_byte = m_bus.write(0); deselect(); int conv_result = (high_byte << 8) | low_byte; return float(conv_result) / 4096; }