A Library for MCP3008

Dependents:   Nucleo_MCP3008_Test ProjetoBB KIK01 MASTER_SPI_MCP3008

Revision:
0:77e81ce22442
Child:
1:49d7a43f1368
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mcp3008.cpp	Fri Jun 09 03:59:25 2017 +0000
@@ -0,0 +1,68 @@
+#include "mcp3008.h"
+
+
+#define START_BIT   0x01
+#define MODE_SINGLE 0x80    // Single-ended mode
+#define MODE_DIFF   0x00    // Differential mode
+
+
+MCP3008::MCP3008(SPI bus, PinName cs)
+    : m_cs(cs), m_bus(bus)
+{
+    deselect();
+}
+
+MCP3008::~MCP3008() {}
+
+
+void MCP3008::select() {m_cs = 0;}
+void MCP3008::deselect() {m_cs = 1; wait_us(1);}
+
+
+float MCP3008::read_input(int channel)
+{
+    /*
+    int command_high = START_BIT | MODE_SINGLE | ((channel & 0x04) >> 2);
+    int command_low = (channel & 0x03) << 6;
+    */
+    int command_high = START_BIT;
+    int command_low = MODE_SINGLE | ((channel & 0x07) << 4);
+    
+    select();
+    
+    // Odd writing requirements, see the datasheet for details
+    m_bus.write(command_high);
+    int high_byte = m_bus.write(command_low) & 0x03;
+    int low_byte = m_bus.write(0);
+    
+    deselect();
+    
+    int conv_result = (high_byte << 8) | low_byte;
+    
+    return ((float)conv_result) / 1024;
+}
+
+#if 0   // not tested.
+float MCP3008::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);
+    */
+    int command_high = START_BIT;
+    int command_low = MODE_DIFF | ((channel & 0x03) << 5) | (polarity << 4);
+    
+    select();
+    
+    // Odd writing and reading requirements, see the datasheet for details.
+    m_bus.write(command_high);
+    int high_byte = m_bus.write(command_low) & 0x03;
+    int low_byte = m_bus.write(0);
+    
+    deselect();
+    
+    int conv_result = (high_byte << 8) | low_byte;
+    
+    return float(conv_result) / 1024;
+}
+#endif