Using the I2C Interface

I got caught by a couple of minor traps when using the I2C interface.

  1. The mbed interface has switched from 7-bit to 8-bit I2C addresses.
  2. You need pull-up resistors connecting the SCL and SCA lines to the positive supply rail.

I was misled about addressing by an out-of-date code example in the cookbook, which I've now corrected. I forgot about the pull-ups becasue you don't need them on anarduino; the wire library turns on internal pull-ups automatically.

In order to help me find the fault I used this test program:

#include "mbed.h"

I2C i2c(p9,p10);
DigitalOut led1(LED1);
const int addr = 0x40; // define the (8-bit) I2C Address for the PC

int write(char byteOut) {
    char * cmd = new char[1];
    cmd[0] = byteOut;
    return i2c.write(addr, cmd, 1);
}

int main() {
    while (1) {
        /* now flash on-bosrd LED1 if the write to I2C works
           This confirms that you've got the right address
           and that you remembered the pull-up resistors on SCL/SDA :) */
        if (0 == write(0xff)) {
            led1 = 1;
            wait(0.2);
            led1 = 0;
        }
        write(0);
        wait(0.2);
    }
}

There is a PCF8574 library which is simpler to use, but won't help you fault-find. However, you can check that I2C is working and find all address of the I2C slaves on yur bus by using Simon Ford's I2CU utility.


0 comments

You need to log in to post a comment