Fix Adafruit’s Raspberry Pi SMBus Detection Python Code

We’ve just started working on a project that involves talking to I2C-enabled devices using a Raspberry Pi. We’re using the excellent Pi Cobbler and an ADS1015 Analog-to-Digital Converter. Adafruit’s Python code for working with the ADC is available on GitHub. Following the example included in that code, it should be possible to read the power values off the ADC using some pretty simple python code. However, we were seeing that this example wasn’t working.

Pi Problems

When we ran it, we were seeing the following traceback:

$ sudo python ads1015_example.py
Error accessing 0x49: Check your I2C address
Error accessing 0x49: Check your I2C address
Traceback (most recent call last):
  File "ads1015_example.py", line 20, in 
    result = adc.readADCSingleEnded(0)
  File "/home/ben/ada/Adafruit_ADS1x15/Adafruit_ADS1x15.py", line 138, in readADCSingleEnded
    return ( (result[0] << 8) | (result[1] & 0xFF) )
TypeError: 'int' object has no attribute '__getitem__'

I reached out to the original developer of the Adafruit code, Kevin Townsend, to see if he had any advice on how to correct this. He pointed out an issue in a related file, Adafruit_I2C.py (one directory up from the ADS1015 code in that Git repo), that’s preventing the code from determining the correct SMBus to use to talk to the I2C devices. Between the different revisions of the Raspberry Pi, the correct SMBus has moved from bus 0 to bus 1. On line 23 of that file, there is the following method signature which tries to determine the correct SMBus based on the revision of the Pi hardware:

def __init__(self, address, bus=smbus.SMBus(1 if getPiRevision() > 1 else 0), debug=False):

The conditional on the bus parameter doesn’t work. getPiRevision(), which is also defined in that file, tries to read procinfo to try and determine the version of the Pi hardware, and there’s a bug somewhere along the line that is making the hardware version impossible to detect.

Solution

This problem is fixed by manually specifying the correct SMBus for your Pi’s hardware revision. Again, for original Pis, you want SMBus 0, and for newer Pis, you want SMBus 1. To do this, uncomment line 29 of Adafruit_I2C.py and specify the correct bus. We found that as soon as we made this change, the ADS1015 sample code, as well as our application-specific code, worked fine.

One Comment

  1. In “python” I get error:
    from smbus import SMBus
    File “/home/pi/myproject/smbus.py”, line 4, in
    bus = smbus.SMBus(1)
    AttributeError: ‘module’ object has no attribute ‘SMBus’
    I have no Idea the error come from.
    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>