That one looks fine. Adding gain is just a minor additional step. For interest, I also made a driver using SPI. In that case, MOSI is used as the clock signal. The SPI clock signal is not used. The core of the class is below. It was made for a LoPy, so it does not immediately run. The interesting parts are the data structures for clock and the lookup table for fast transformation. The reason for using SPI was, that the ESP32 just like the ESP8266 is not good at fast toggling and reading, eventually not matching the timing requirements of the HX711. Using SPI ensures fast timing.
Code: Select all
class HX711:
def __init__(self, dout, pd_sck, spi_clk, gain=128):
self.pSCK = Pin(pd_sck , mode=Pin.OUT)
self.pOUT = Pin(dout, mode=Pin.IN, pull=Pin.PULL_DOWN)
self.spi = SPI(0, mode=SPI.MASTER, baudrate=1000000, polarity=0, phase=0, pins=(spi_clk, pd_sck, dout))
self.pSCK(0)
self.clock_25 = b'\xaa\xaa\xaa\xaa\xaa\xaa\x80'
self.clock_26 = b'\xaa\xaa\xaa\xaa\xaa\xaa\xa0'
self.clock_27 = b'\xaa\xaa\xaa\xaa\xaa\xaa\xa8'
self.clock = self.clock_25
self.lookup = (b'\x00\x01\x00\x00\x02\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x04\x05\x00\x00\x06\x07\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x08\x09\x00\x00\x0a\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x0c\x0d\x00\x00\x0e\x0f')
self.in_data = bytearray(7)
self.set_gain(gain);
def set_gain(self, gain):
if gain is 128:
self.clock = self.clock_25
elif gain is 64:
self.clock = self.clock_27
elif gain is 32:
self.clock = self.clock_26
self.read()
def read(self):
# wait for the device to get ready
while self.pOUT() != 0:
idle()
# get the data and set channel and gain
self.spi.write_readinto(self.clock, self.in_data)
# pack the data into a single value
result = 0
for _ in range (6):
result = (result << 4) + self.lookup[self.in_data[_] & 0x55]
# return sign corrected result
return result - ((result & 0x800000) << 1)