0

I am using an air quality sensor with an I2C interface (datasheet: https://docs-emea.rs-online.com/webdocs/14cd/0900766b814cdbb8.pdf).

When running the below code asking for less than 8 bytes I get reasonable results. But when I ask for 9 bytes (which I need as the datasheet states) I get the result with strange characters such as "}" or "R" in the hex values.It states that 9 values have been returned but there are only 8. On rare occassions I will get 9 sensible bytes returned.

import pigpio
import RPi.GPIO as GPIO

pi = pigpio.pi()

if not pi.connected:
    print("no pi")
    exit()

bus = 1
address = 0x5a
read_bytes = 9

handle = pi.i2c_open(bus,address)
count, data = pi.i2c_read_device(handle, read_bytes)

pi.i2c_close(handle)
pi.stop()

print(count)
print(data)

exit()

result:

9
bytearray(b'\x01\xc2\x00\x00\x01\xcc\xed\x00}')

I have tried using SMBus with this component but that doesn't seem to be supported. Has anyone seen this before or know a workaround?

EDIT: may be a duplicate of smbus/I2C sensor returns fixed data

I tried using:

sudo pigpiod
pigs i2co 1 0x5A 0
pigs i2crd 0 9

and that seems to return reasonable results:

9 1 194 16 0 1 8 80 0 125

the first digit is returning the count. I'm still not able to run this in python though. Someone suggested it was the print buffer, but I'm closing I2c before printing.

EDIT 2:

The data sheet does state not to request more than 3 bytes. Could this be the problem? How would I request bytes 7-8?

1 Answer 1

1

That is how Python displays a bytearray.

If the character is a printable character it is shown as such (the '}') in your example. If the character is not printable it is displayed in escaped format, e.g. \xAB where A and B are hexadecimal digits.

For your example '\x01\xc2\x00\x00\x01\xcc\xed\x00}' the 9 returned bytes are

   Hex Dec
1  01   1
2  C2 194
3  00   0
4  00   0
5  01   1
6  CC 204
7  ED 237
8  00   0
9  7D 125
2
  • Okay great answer, makes complete sense. I'm assuming there is a way to decode the bytearray? Or is this something I will need to implement
    – Unfitacorn
    Commented Mar 11, 2018 at 18:41
  • I would just use data[0] to access the first byte, data[8] to access the 9th byte etc.
    – joan
    Commented Mar 11, 2018 at 18:48

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.