Uncategorized

smbus 2 discussion notes

Asked 
Viewed 6 times
0

This example scans for any I2C slave address current on the I2C bus.
(I am using a RPi 3B+ with raspbian buster from september release)

Script trial_smbus.py:

from smbus2 import SMBus

channel = 1

i2c = SMBus(channel)

for i2c_addr in range(127):
    try:
        read_data = i2c.read_byte_data(i2c_addr, 0)
    except Exception as e:
        if e.errno == 121: 
            pass # no ACK
        else:
            print (e)
    else:
        print ("0x{:02X} => ACK!".format (i2c_addr))

It works nicely after a fresh boot of the RPi!

This script (not in the same script) simply ‘plays’ with the same IO pins:

Script trial_gpio.py:

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)

I run this script, and indeed the GPIO are set as input with pullup resistors.

Now, I run again script trial_smbus.py, and I got:

[Errno 5] Input/output error

That means 2 things: – that little trial_gpio.py script set something that SMBus2 does not like. – SMBus2 does not init everything correctly.

Now I reboot and run again script trial_smbus.py==> works:

Run again trial_gpio.py.

Run again trial_smbus.py, does not work.

Run the wiringpi tool:

gpio mode 8 alt0
gpio mode 9 alt0

Run again trial_smbus.py, does work.

The easy solution would be to call those 2 command lines with a system call from within python. however wiringpi is deprecated: http://wiringpi.com/wiringpi-deprecated/

Is there any alternative to set the pins in the correct mode?

 New contributor
  • Hi @karelv, Ah, let me see. (1) WiringPi once worked but now deprecated, so I am saying good bye without even once saying Hello. (2) SMBus1 works most of the time, but not always, eg no bus stretching, block read is buggy, but can get around by lowering I2C speed (from 100kHz to 10kHz!), (3) I once thought SMBus2 is new so would be better than SMBus1. I was very wrong. I tried it but gave up almost immediately. My conclusion is that I can only reluctantly bear SMBus1 for a couple of more years. – tlfong01 1 hour ago    
  • It is difficult to see what your question is. You cannot have 2 programs setting GPIO unless you release between uses. – Milliways 47 mins ago

Categories: Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: