Skip to content

i2c.py, ValueError, out of range 0-256 in writing_bytes #49

Description

@javl

Not sure what causes this problem, but I'd though it might be useful to at least post an issue report.
I tried using the quick2wire library with a cheap accelerometer by running the following code:

from i2clibraries import i2c_adxl345
adxl345 = i2c_adxl345.i2c_adxl345(0)

But immediately I get the following error:

Traceback (most recent call last):
  File "./test1.py", line 6, in <module>
    adxl345 = i2c_adxl345.i2c_adxl345(0)
  File "/home/pi/projectfolder/i2clibraries/i2c_adxl345.py", line 100, in __init__
    self.setActivityThreshold()
  File "/home/pi/projectfolder/i2clibraries/i2c_adxl345.py", line 178, in setActivityThreshold
    self.setOption(self.ActivityThreshold, intervals)
  File "/home/pi/projectfolder/i2clibraries/i2c_adxl345.py", line 230, in setOption
    self.bus.write_byte(register, options)
  File "/home/pi/projectfolder/i2clibraries/i2c.py", line 14, in write_byte
    writing_bytes(self.addr, *bytes))
  File "/home/pi/projectfolder/quick2wire-python-api/quick2wire/i2c.py", line 97, in writing_bytes
    return writing(addr, bytes)
  File "/home/pi/projectfolder/quick2wire-python-api/quick2wire/i2c.py", line 108, in writing
    buf = bytes(byte_seq)
ValueError: bytes must be in range(0, 256)

Printing these values, I noticed at least one of them indeed isn't in this range: -3

As a quick hack I changed the function in i2c.py so it clamps the values in byte_seq before returning the message, after which everything works perfectly.

def writing(addr, byte_seq):
    lst = list(byte_seq)
    for i in range(0, len(lst)):
        lst[i] = max(0, min(255, lst[i]))
    byte_seq = tuple(lst)
    buf = bytes(byte_seq)
    return _new_i2c_msg(addr, 0, create_string_buffer(buf, len(buf)))

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions