8 years, 2 months ago.

many devices on on I2C peripheral

How does one write code for many different devices on an I2C bus. Different devices had different addresses, and that is ok. For instance, I would like to use 2 ea PCA9535, and several other I2C sensors. do I create an I2C object and then pass a reference of it to each PCA9535, and sensor constructor?

2 Answers

8 years, 2 months ago.

You can set the same pins for more than one i2c device, example below:

Example snip

#include "mbed.h"

I2C i2c(PB_11, PB_10); // sda, clk
EEPROM rom(PB_11, PB_10, 0, EEPROM::T24C32); // sda, clk

However each i2c device must have a different address from each other.

Some i2c devices are address programmable normally by hardware setting pins high or low on the device itself. This address must then be set in each of the i2c relevant device library.

So several instances of class I2C can access the same hardware peripheral. I2C i2c creates one instance and EEPROM rom() creates another class private instance. Both can talk to the same hardware peripheral on pins PB_11, PB_10. Probably better to have all the devices running at the same I2C speed. I will need a mutex if multiple threads are to use their own I2C instance.

posted by David Thedens 19 Feb 2016

Yes you should be able to add many devices using the same i2c port pins, only one device can be accessed at any one time. You can not switch to another device whilst data is being written or read it must be done sequentially. A break in the data flow to the device will cause unpredictable results. You must ensure no interrupt comes in breaking the communication until it has completed. Generally 400KHz is the optimum frequency, I think 100KHz is the default but depends on platform. Some devices will run up to 1MHz, but as a rule the higher the frequency the shorter the distance between MCU and device and lower values of pull up resistors will be needed.

posted by Paul Staron 19 Feb 2016
8 years, 2 months ago.

Have a look here. This will show you how to read a device on I2C. Each device needs to have a unique address as you seem to be aware. Just modify the code appropriately. Some "identical" I2C devices have external address pins to give each a unique address with a small range. Some vendors sell different devices to do the same function at different addresses.

https://developer.mbed.org/components/LM75B-Temperature-Sensor/