Skip to content

Commit eb01f1f

Browse files
authored
Merge pull request #9 from supcik/main
Add fast reading function and refactor read_channel methods for HX711
2 parents c8d557a + bb1baa0 commit eb01f1f

File tree

1 file changed

+30
-13
lines changed

1 file changed

+30
-13
lines changed

adafruit_hx711/hx711.py

Lines changed: 30 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626

2727
import time
2828

29+
import microcontroller
30+
2931
try:
3032
from typing import Union
3133

@@ -37,6 +39,31 @@
3739
__repo__ = "https://github.com/your-repo/Adafruit_CircuitPython_HX711.git"
3840

3941

42+
def read_fast(clock_pin: digitalio.DigitalInOut, data_pin: digitalio.DigitalInOut, size: int):
43+
value: int = 0 # return value
44+
assert not clock_pin.value
45+
assert size > 0
46+
# The first iteration of the while loop takes longer, so to cancel
47+
# this problem, we skip the first clock
48+
clock_to_skip: int = 1
49+
# Disable interrupts just before the loop
50+
microcontroller.disable_interrupts()
51+
while size > 0:
52+
if clock_to_skip <= 0: # no more skipping
53+
clock_pin.value = True
54+
size -= 1
55+
microcontroller.delay_us(1)
56+
if clock_to_skip > 0:
57+
clock_to_skip -= 1 # decrement skip counter and do not read
58+
else:
59+
value = (value << 1) | data_pin.value
60+
clock_pin.value = False
61+
microcontroller.delay_us(1)
62+
# Re-enable interrupts as soon as possible
63+
microcontroller.enable_interrupts()
64+
return value
65+
66+
4067
class HX711:
4168
"""HX711 ADC driver"""
4269

@@ -78,7 +105,8 @@ def read_channel_blocking(self, chan_gain: int) -> int:
78105
:param chan_gain: Gain and channel configuration.
79106
:return: ADC value.
80107
"""
81-
self._read_channel(chan_gain) # First, set the desired gain and discard this read
108+
# First, set the desired gain and discard this read
109+
self._read_channel(chan_gain)
82110
return self._read_channel(chan_gain) # Now perform the actual read
83111

84112
def _read_channel(self, chan_gain: int) -> int:
@@ -103,18 +131,7 @@ def _read_channel_raw(self, chan_gain: int) -> int:
103131
pass # Wait until the HX711 is ready
104132

105133
self._clock_pin.value = False
106-
value = 0
107-
for _ in range(24): # Read 24 bits from DOUT
108-
self._clock_pin.value = True
109-
time.sleep(0.000001) # 1 microsecond delay
110-
value = (value << 1) | self._data_pin.value
111-
self._clock_pin.value = False
112-
time.sleep(0.000001) # 1 microsecond delay
113-
114-
# Set gain for next reading
115-
for _ in range(chan_gain - 24):
116-
self._clock_pin.value = True
117-
self._clock_pin.value = False
134+
value = read_fast(self._clock_pin, self._data_pin, chan_gain) >> (chan_gain - 24)
118135

119136
# Convert to 32-bit signed integer
120137
if value & 0x80_00_00:

0 commit comments

Comments
 (0)