Saturday, June 28, 2014

Using 2 I2C Buses on the Beaglebone Black

The Beaglebone Black (rev. B or C) has two I2C buses that are accessible by user programs.  This post shows how you can use two I2C devices with the same device address, with each one on a separate bus.  The new version of the Sparkfun TMP102 temperature sensor can be configured to use different I2C device addresses, but this requires removing a solder jumper, so I have used two of them for this example.

In order to use both I2C buses, you need to load a device mapping overlay file, /lib/firmware/BB-I2C1-00A0.dtbo.  This is accomplished via the shell echo command in the code below.

The code below reads the temperature from two TMP102s and prints the reading from each (converted to degrees Fahrenheit) to the terminal window.

In looking into this, I found "BeagleBone Black I2C References" by Joshua Datko very helpful.

The Python code below requires the SMBus library.  The following apt-get command (run as root) will install this library.

apt-get install python-smbus


TMP102 #1  Beaglebone Black
VCC        D9 3
GND        D9 1
SDA        D9 20  (/dev/i2c-1 bus 1)
SCL        D9 19  (/dev/i2c-1 bus 1)
ADD0       (Not connected)

TMP102 #2 Beaglebone Black
VCC       D9 3
GND       D9 1
SDA       D9 18   (/dev/i2c-2 bus 2)
SCL       D9 17   (/dev/i2c-2 bus 2)
ADD0      (Not connected)

Python Code

# -*- coding: utf-8 -*-
# Need to declare encoding in line above in order to use degree sign
import os
import smbus
import time

# Path to slots on Beaglebone Black rev. C
slots = "/sys/devices/bone_capemgr.9/slots"
os.system("echo BB-I2C1 > %s" % slots)

bus1 = smbus.SMBus(1) # pins D9 19, 20, /dev/i2c-1
bus2 = smbus.SMBus(2) # pins D9 17, 18, /dev/i2c-2

tmp102_addr = 0x48

   data = bus1.read_i2c_block_data(tmp102_addr, 0)
   msb = data[0]
   lsb = data[1]
   t1 = (((msb << 8) | lsb) >> 4) * 0.0625
   data = bus2.read_i2c_block_data(tmp102_addr, 0)
   msb = data[0]
   lsb = data[1]
   t2 =  (((msb << 8) | lsb) >> 4) * 0.0625
   print "t1: %.3f°  t2: %.3f°" % (t1 * 9/5 + 32,
      t2 * 9/5 + 32)

No comments:

Post a Comment