Raspberry Pi HX711 Python Bindings
Python bindings for Raspberry Pi HX711 C++ Library
- Use with Raspberry Pi
- Read from a HX711 using Python
- Code tested inside virtual Raspberry Pi Zero/3/4 environments on GitHub and builds automatically uploaded to PyPI
- This repo automatically rebuilds when the C++ library is updated
Sample Output
The .gif above illustrates the output of a simple Python script on a Raspberry Pi Zero W where the HX711 chip was operating at 80Hz. In this example, each time the .weight
function is called the median of three samples was used to calculate the weight in grams.
Examples
from HX711 import *
with SimpleHX711(2, 3, -370, -367471) as hx:
hx.setUnit(Mass.Unit.OZ)
hx.zero()
while True:
print(hx.weight(35))
Alternative Syntax (w/out with
)
from HX711 import *
hx = SimpleHX711(2, 3, -370, -367471)
hx.setUnit(Mass.Unit.OZ)
hx.zero()
while True:
print(hx.weight(35))
Keep in mind that calling .weight()
will return a Mass
object, but you can do the following:
hx.setUnit(Mass.Unit.OZ)
m = hx.weight(35)
num = float(m)
s = str(m)
print(m)
m.setUnit(Mass.Unit.G)
grams_as_str = str(m)
m2 = m.convertTo(Mass.Unit.KG)
kgs_as_str = str(m2)
The list of different Mass.Unit
s can be viewed here.
Time-Based Sampling
You can use datetime.timedelta
to obtain as many samples as possible within the time period.
from HX711 import *
from datetime import timedelta
with SimpleHX711(2, 3, -370, -367471) as hx:
while True:
print(hx.weight(timedelta(seconds=1)))
Options
.weight()
, .zero()
, and .read()
can all take an Options
parameter. You can use this to fine tune how you want the scale to behave.
hx.zero(Options(
timedelta(seconds=1),
ReadType.Average))
num = hx.read(Options(
100,
ReadType.Median))
m = hx.weight()
m = hx.weight(3)
m = hx.weight(Options())
m = hx.weight(Options(
3,
ReadType.Median))
opts = Options()
opts.timeout = timedelta(seconds=5)
opts.stratType = StrategyType.Time
m = hx.weight(opts)
Install
-
Install libhx711
-
pip3 install --upgrade hx711-rpi-py
Calibrate
There is a Python script in the src
directory you can use to calibrate your load cell and obtain the reference unit and offset values referred to above. The simplest way to use it after installing hx711-rpi-py
is as follows:
pi@raspberrypi:~ $ wget https://raw.githubusercontent.com/endail/hx711-rpi-py/master/src/calibrate.py
pi@raspberrypi:~ $ python3 calibrate.py [data pin] [clock pin]
Substitute [data pin]
and [clock pin]
with the GPIO pin numbers which are connected to the HX711's data pin and clock pin, respectively.
Documentation
As the Python code relies upon the underlying C++ library, the documentation is identical. However, not all of the code is exposed to Python. You can check precisely which functionality is accessible through Python in the bindings.cpp file.