4

I'm using I2Ctools to read data off of some devices attached to a raspberry pi via the I2C interface. I want to check if a device in a certain address is present or not. If present, read the data from it. If not, read data off another device.

Right now if the device is not present, I'm checking for an error string "Error: Read failed". I don't think this is the most robust way of doing this, so I was hoping someone might point something out.

I'm limited to using shell scripts.

EDIT: To clarify, I'm using i2cget on a particular address and storing the value in a variable. If the value is literally "Error: Read failed", I know that the device is not present and so move on from there.

3
  • 1
    What's wrong with parsing i2cdetect -y 1?
    – goldilocks
    Commented Jan 13, 2015 at 21:55
  • is there a generic tool i can use to parse this? or how should I approach this? Commented Jan 13, 2015 at 23:12
  • 2
    In terms of generic parsing, there's stuff like awk, sed and grep, if you are restricted to fundamental shell tools. I'm sure there's a quick way to do this that way, but they are things of last resort for me and I won't claim the necessary expertise. You might want to clarify further exactly what your current methodology is so people do not waste their time suggesting things that are equally "not the most robust".
    – goldilocks
    Commented Jan 13, 2015 at 23:37

1 Answer 1

3

No doubt there's some awk/sed wizard around who can do this in one line, but shell clutz that I am:

#!/bin/bash

bus=1
if [[ -n $2 ]]; then
    bus=$2
fi

mapfile -t data < <(i2cdetect -y $bus)

for i in $(seq 1 ${#data[@]}); do
    line=(${data[$i]})
    echo ${line[@]:1} | grep -q $1
    if [ $? -eq 0 ]; then
        echo "$1 is present."
        exit 0
    fi
done

echo "Not found."
exit 1  

Takes one or two arguments. The first is the 2 digit hexadecimal address you are looking for, and the second is the i2c-dev bus number (defaults to 1).

Remember, running i2cdetect has some warnings attached to it. I'm actually not sure how seriously they apply on the pi though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.