Library with PCF8591 support for the experiments for LPC812 MAX

Dependents:   lpc812_exp_solution_analog-in lpc812_exp_solution_7-segment lpc812_exp_solution_7-segment-shift lpc812_exp_solution_pwm ... more

Fork of lpc812_exp_lib_PCF8591 by EmbeddedArtists AB

Files at this revision

API Documentation at this revision

Comitter:
embeddedartists
Date:
Fri Nov 15 10:33:06 2013 +0000
Parent:
1:7eabc2242b8f
Child:
3:53bf66c0e0f6
Commit message:
Fixed reading bug. Changed speed back to 100kHz

Changed in this revision

PCF8591.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/PCF8591.cpp	Thu Nov 14 14:58:49 2013 +0000
+++ b/PCF8591.cpp	Fri Nov 15 10:33:06 2013 +0000
@@ -3,24 +3,30 @@
 
 PCF8591::PCF8591(PinName sda, PinName scl, int i2cAddr) : m_i2c(sda, scl)
 {
-    m_i2c.frequency(400000);
+    m_i2c.frequency(100000);
     m_addr = i2cAddr;
 }
     
 int PCF8591::read(AnalogIn port)
 {
-    char cmd = port & 0x3; // read from selcted port
-    char val[2] = { 0, 0 };
+    char cmd = (port & 0x3); // read from selected port
+    char data[2];
     
     // select the port
-    m_i2c.write(m_addr, &cmd, 1, true);
+    m_i2c.start();
+    m_i2c.write(m_addr);
+    m_i2c.write(cmd);
+    m_i2c.stop();
     
     // get the sample
-    if (m_i2c.read(m_addr, val, 2) == 0) {
-        // val[0] is conversion result code from last time (always 0x80)
-        // val[1] is the new value
-        return val[1];
-    }
-    return -1;
+    m_i2c.start();
+    m_i2c.write(m_addr | 1);
+    data[0] = m_i2c.read(1); // expect ACK
+    data[1] = m_i2c.read(0); // expect NACK
+    m_i2c.stop();
+    
+    // data[0] is a dummy byte so ignore it
+    // data[1] is the new value
+    return data[1];
 }