Changed MCP3221 I2C read from two 1-byte reads to one 2-byte read

Dependents:   DISCO-F746NG_LCD_TS_ADC

Fork of MCP3221 by David Styles

Revision:
0:db4e3d0374fe
Child:
1:2921687d299e
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MCP3221.cpp	Wed Oct 31 21:43:28 2012 +0000
@@ -0,0 +1,50 @@
+
+#include "MCP3221.h"
+
+//Create instance
+MCP3221::MCP3221(PinName sda, PinName scl, float supplyVoltage) : i2c(sda, scl), _supplyVoltage(supplyVoltage)
+{
+}
+
+//destroy instance
+MCP3221::~MCP3221()
+{
+}
+
+float MCP3221::read()
+{
+
+//You cannot write to an MCP3221, it has no writable registers.
+//MCP3221 also requires an ACKnowledge between each byte sent, before it will send the next byte. So we need to be a bit manual with how we talk to it.
+//It also needs an (NOT) ACKnowledge after the second byte or it will keep sending bytes (continuous sampling)
+//
+//From the datasheet.
+//
+//I2C.START
+//Send 8 bit device/ part address to open conversation.   (See .h file for part explanation)
+//read a byte (with ACK)
+//read a byte (with NAK)
+//I2C.STOP
+
+
+  //  char data[2];
+
+    i2c.start();
+    int acknowledged = i2c.write(MCP3221_CONVERSE); //send a byte to start the conversation. It should be acknowledged.
+    _data[0] = i2c.read(1);  //read a byte. acknowledge when we have it.
+    _data[1] = i2c.read(0);  //read the second byte. (n)acknowledge when we have it to stop the flow.
+    i2c.stop();
+ 
+    //convert to 12 bit.
+    short res;
+    int _12_bit_var; // 2 bytes
+    char _4_bit_MSnibble = _data[0]; // 1 byte, example 0000 1000
+    char _8_bit_LSByte = _data[1];   // 1 byte, example 1111 0000
+
+    _12_bit_var = ((0x0F & _4_bit_MSnibble) << 8) | _8_bit_LSByte;   //example 100011110000
+    res=_12_bit_var;
+
+    return  (_supplyVoltage/4096) * res;
+
+}
+