B4R Question several i2c devices on single bus

peacemaker

Expert
Licensed User
Longtime User
Hi, All

What should be coding if several I2C devices are used on a single bus ?
I'm trying to use a sensor IC and LCD display, both are i2C, addresses are different, sure.

And they work OK only once: one measure and next printing to LCD. At next loop the sensor IC is not responding, and no printing also. Display cannot be reset until re-powering.

The sensor is controlled by rWire lib directly, the LCD is controlled by rLiquidCrystal_I2C lib (that uses I2C by C code, i guess). Each module initializes the I2C bus of ESP8266:
SDA = GPIO4 (D2)
SCL = GPIO5 (D1)

Addresses by the scanner are different for sure:
I2C device found at address: 0x27 (39) 'display
I2C device found at address: 0x38 (56) 'sensor

Independently each device works OK in a loop. But how to use them both one by one correctly ?
 
Last edited:

peacemaker

Expert
Licensed User
Longtime User
SOLVED: for several devices on a single bus - the BUSY flag is strongly required, to avoid interrupting one device by another and when the bus hungs and no one is working until re-power.
 
Last edited:
Upvote 0

Cableguy

Expert
Licensed User
Longtime User
Hi,

Could you be troubled into making a small snippet about this? (covering also the electronics side of things)

Thanks
 
Upvote 0

peacemaker

Expert
Licensed User
Longtime User
But it's simplest, as i can see:
1) use I2C bus of your board: 2 pins SCL and SDA to connect several devices in parallel (and power wires, 5V or 3.3V and GND according to the device need).
1652717470365.png

2) make sure the addresses of devices are different: https://www.b4x.com/android/forum/threads/i2c-address-scanner.75815/
3) declare the public variable flag (i2cBusy As Boolean) in a shared module (Main)
4) and in each device code check the flag at start:
B4X:
    If Main.i2cBusy Then
        Log("i2cBusy = ", Main.i2cBusy, ",  ignoring")
        Return    'waiting for pause
    End If
    Main.i2cBusy = True

When finished working - make Main.i2cBusy = False.
 
Last edited:
Upvote 0

janderkan

Well-Known Member
Licensed User
Longtime User
B4R does not run concurrently, so no need for a busy flag.
You should define the I2C connection only once.
Then your subs just access the I2C with the different device ID's.
 
Upvote 0
Top