Voting resources, early voting, and poll worker information - VOTE. ... Adafruit is open and shipping.
0

Function to detect a given I2C device on bus?
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Function to detect a given I2C device on bus?

by rodneysparks on Mon Aug 31, 2020 12:31 pm

Hello!

Seems like a basic question, but I can't find an answer anywhere: I want to write my code so my serial data output includes the values from an MS8607 board connected via Stemma cable IF that sensor is included on the I2C bus, but the code would ignore that sensor and continue to do everything else in an uninterrupted manner if no device exists at the address in question. Basically, I want the code to handle things appropriately regardless of whether it's plugged in or not.

Can someone please point me in the direction of how to add this functionality? I imagine it could just be some kind of error handler upon initial comms with the device...

Thanks,

-Rodney

rodneysparks
 
Posts: 17
Joined: Mon May 08, 2017 11:42 am

Re: Function to detect a given I2C device on bus?

by rodneysparks on Mon Aug 31, 2020 12:57 pm

I did find this:
https://learn.adafruit.com/circuitpytho ... python-i2c
I imagine I could do a scan, store the results of the scan in an array, then see if my address is in the array in order to populate a "PthConnected" boolean that enables polling of that sensor and inclusion in the serial data output. I'm enough of a n00b that this is challenging for me, but if this is the best path, I'll figure it out. I'd rather do some kind of "if valid response from 0x76 and 0x40 then PthConnected = 1 else 0" code, if such a thing can be done without being halted by a runtime error.

rodneysparks
 
Posts: 17
Joined: Mon May 08, 2017 11:42 am

Re: Function to detect a given I2C device on bus?

by adafruit_support_carter on Mon Aug 31, 2020 3:26 pm

You could use a try/except block.

adafruit_support_carter
 
Posts: 16866
Joined: Tue Nov 29, 2016 2:45 pm

Re: Function to detect a given I2C device on bus?

by rodneysparks on Sun Sep 06, 2020 2:17 am

adafruit_support_carter wrote:You could use a try/except block.


You, my friend, are awesome. That worked like a charm. I've tested it with and without the OLED plugged in and it handles the two scenarios flawlessly. Thanks so much!

Here's my code snippet so others can benefit from it:
Code: Select all | TOGGLE FULL SIZE
try:
    dbus = displayio.I2CDisplay(board.I2C(), device_address=0x3D)
    dispGood = True
except:
    dispGood = False

and when I want to choose whether to send text to the display, I just do this:
Code: Select all | TOGGLE FULL SIZE
 if dispGood:
    display.show(disp_group)

rodneysparks
 
Posts: 17
Joined: Mon May 08, 2017 11:42 am

Please be positive and constructive with your questions and comments.