Reading multiple bytes with I2C.read

19 Aug 2010

Hi folks.

I'm trying to get a library up and running, with the PCF8575 (16 bit port expander), should be simple, so I used the PCF8574 library that was already up.
But when it comes to the read function, but i can't figure out how to return this data array from the lib.

Here's the code:

#include "PCF8575.h"
#include "mbed.h"

PCF8575::PCF8575(PinName sda, PinName scl, int address)
        : _i2c(sda, scl) {
    _address = address;
}

int PCF8575::read() {
    char foo[2];
    _i2c.read(_address, foo, 2);
    return foo;                     Here's the problem.
}

void PCF8575::write(int data0, int data1) {
    char foo[2];
    foo[0] = data0;
    foo[1] = data1;
    _i2c.write(_address, foo, 2);
}
#include "mbed.h"

#ifndef MBED_PCF8575_H
#define MBED_PCF8575_H

/** Interface to the popular PCF8574 I2C 8 Bit IO expander */
class PCF8575 {
public:
    /** Create an instance of the PCF8574 connected to specfied I2C pins, with the specified address.
     *
     * @param sda The I2C data pin
     * @param scl The I2C clock pin
     * @param address The I2C address for this PCF8575
     */
    PCF8575(PinName sda, PinName scl, int address);

    /** Read the IO pin level
     *
     * @return The byte read
     */
    int read();
    
    /** Write to the IO pins
     * 
     * @param data The 8 bits to write to the IO port
     */
    void write(int data0, int data1);

private:
    I2C _i2c;
    int _address;
};

#endif

19 Aug 2010

Hi Christian,

If I've undestood correctly, you want to return a 16-bit integer from the read.

This should do it. You may want to reverse the byte order, depending on what you are trying to do.

 

int PCF8575::read() {
    char foo[2];
    _i2c.read(_address, foo, 2);
    return (foo[0] << 8) | foo[1];                
}