Skip to content

Commit 62513f5

Browse files
committed
Add UnaryStruct to i2c_struct, simplified single value struct register.
1 parent 87c98f6 commit 62513f5

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

adafruit_register/i2c_struct.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,29 @@ def __set__(self, obj, value):
4747
ustruct.pack_into(self.format, self.buffer, 1, *value)
4848
with obj.i2c_device:
4949
obj.i2c_device.writeto(self.buffer)
50+
51+
class UnaryStruct:
52+
"""
53+
Arbitrary single value structure register that is readable and writeable.
54+
55+
Values map to the first value in the defined struct. See struct
56+
module documentation for struct format string and its possible value types.
57+
58+
:param int register_address: The register address to read the bit from
59+
:param type struct_format: The struct format string for this register.
60+
"""
61+
def __init__(self, register_address, struct_format):
62+
self.format = struct_format
63+
self.buffer = bytearray(1+ustruct.calcsize(self.format))
64+
self.buffer[0] = register_address
65+
66+
def __get__(self, obj, objtype=None):
67+
with obj.i2c_device:
68+
obj.i2c_device.writeto(self.buffer, end=1, stop=False)
69+
obj.i2c_device.readfrom_into(self.buffer, start=1)
70+
return ustruct.unpack_from(self.format, memoryview(self.buffer)[1:])[0]
71+
72+
def __set__(self, obj, value):
73+
ustruct.pack_into(self.format, self.buffer, 1, value)
74+
with obj.i2c_device:
75+
obj.i2c_device.writeto(self.buffer)

0 commit comments

Comments
 (0)