forked from adafruit/Adafruit_CircuitPython_Register
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregister_bit.py
More file actions
80 lines (56 loc) · 2.45 KB
/
register_bit.py
File metadata and controls
80 lines (56 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# SPDX-FileCopyrightText: Copyright (c) 2025 Tim Cocks for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_register.register_bit`
====================================================
Single bit registers that use RegisterAccessor
* Author(s): Tim Cocks
"""
__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Register.git"
class RWBit:
"""
Single bit register that is readable and writeable.
Values are `bool`
:param int register_address: The register address to read the bit from
:param int bit: The bit index within the byte at ``register_address``
:param int register_width: The number of bytes in the register. Defaults to 1.
:param bool lsb_first: Is the first byte we read from spi the LSB? Defaults to true
"""
def __init__(
self, register_address: int, bit: int, register_width: int = 1, lsb_first: bool = True
):
self.bit_mask = 1 << (bit % 8) # the bitmask *within* the byte!
self.address = register_address
self.buffer = bytearray(register_width)
self.lsb_first = lsb_first
self.bit_index = bit
if lsb_first:
self.byte = bit // 8 # Little-endian: bit 0 in first register byte
else:
self.byte = register_width - 1 - (bit // 8) # Big-endian: bit 0 in last register byte
def __get__(self, obj, objtype=None):
# read data from register
obj.register_accessor.read_register(self.address, self.buffer)
# check specified bit and return boolean
return bool(self.buffer[self.byte] & self.bit_mask)
def __set__(self, obj, value):
# read current data from register
obj.register_accessor.read_register(self.address, self.buffer)
# update current data with new value
if value:
self.buffer[self.byte] |= self.bit_mask
else:
self.buffer[self.byte] &= ~self.bit_mask
# write updated data to register
obj.register_accessor.write_register(self.address, self.buffer)
class ROBit(RWBit):
"""Single bit register that is read only. Subclass of `RWBit`.
Values are `bool`
:param int register_address: The register address to read the bit from
:param type bit: The bit index within the byte at ``register_address``
:param int register_width: The number of bytes in the register. Defaults to 1.
"""
def __set__(self, obj, value):
raise AttributeError()