Search code examples
python-3.xsensors

Read a dtoverlay controlled device via Python3?


How to read a dtoverlay controlled device, i.e. sensor via pyhon3?

I can read the device via a simple cat, for example...

# cat /sys/bus/i2c/devices/1-0077/iio\:device0/in_temp_input
27130

So I know the basic setup and such is good, sensor is at address 0x77, it is a BME280 sensor, etc.

I can also read the sensor via the various python3 libraries for such sensors, say the python library from Adafruit.

But I want to use the dtoverlay method of sensor control, i.e. read, and read the sensor from python3. This seemed obvious and straight forward, but apparently not, tried the following code and got the following error.

#!/usr/bin/python3
#
#

import os

#

theSensor=os.open('/sys/bus/i2c/devices/1-0077/iio\:device0/in_temp_input', os.O_RDONLY)
os.lseek(theSensor, 0, os.SEEK_SET)
print(os.read(theSensor, 2))
theSensor.close()

And the error...

# python3 BME280-OverLay.py
Traceback (most recent call last):
  File "/root/BME280-OverLay.py", line 17, in <module>
    theSensor=os.open('/sys/bus/i2c/devices/1-0077/iio\:device0/in_temp_input', os.O_RDONLY)
FileNotFoundError: [Errno 2] No such file or directory: '/sys/bus/i2c/devices/1-0077/iio\\:device0/in_temp_input'

Is there some trick to reading this specific device path via python3? The simple cat works.


Solution

  • In your initial cat command, you noticed that there's a \ inside the URL. That's an escape character. It might be there because you used autocompletion with the Tab key ; in this case bash adds it automatically, even though in fact cat doesn't need it, but deals with it.

    python doesn't (deal with it). You'll have to feed open() with the clear path syntax.

    By the way you can use a plain open() call and the with syntax :

    with open('/sys/bus/i2c/devices/1-0077/iio:device0/in_temp_input', 'r') as fd:
        temp = fd.read()
    print(temp)
    

    This way, the file gets closed before the print() call.

    PS: the fact that the file you are trying to read is on a virtual filesystem would have no impact.