-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.py
executable file
·49 lines (42 loc) · 2.08 KB
/
example.py
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
import RPi.GPIO as GPIO
import time
import sys
from hx711 import HX711
DATA_PIN = 5
CLOCK_PIN = 6
hx = HX711(DATA_PIN, CLOCK_PIN)
# I've found out that, for some reason, the order of the bytes is not always the same between versions of python, numpy and the hx711 itself.
# Still need to figure out why does it change.
# If you're experiencing super random values, change these values to MSB or LSB until to get more stable values.
# There is some code below to debug and log the order of the bits and the bytes.
# The first parameter is the order in which the bytes are used to build the "long" value.
# The second paramter is the order of the bits inside each byte.
# According to the HX711 Datasheet, the second parameter is MSB so you shouldn't need to modify it.
hx.set_reading_format("LSB", "MSB")
# HOW TO CALCULATE THE REFFERENCE UNIT
# To set the reference unit to 1. Put 1kg on your sensor or anything you have and know exactly how much it weights.
# In this case, 92 is 1 gram because, with 1 as a reference unit I got numbers near 0 without any weight
# and I got numbers around 184000 when I added 2kg. So, according to the rule of thirds:
# If 2000 grams is 184000 then 1000 grams is 184000 / 2000 = 92.
#hx.set_reference_unit(113)
hx.set_reference_unit(92)
hx.reset() # sleep cycles the chip
hx.tare(100) # you know
prev_t = 0
while True:
try:
# These three lines are usefull to debug wether to use MSB or LSB in the reading formats
# for the first parameter of "hx.set_reading_format("LSB", "MSB")".
# Comment the two lines "val = hx.get_weight(5)" and "print val" and uncomment the three lines to see what it prints.
#np_arr8_string = hx.get_np_arr8_string()
#binary_string = hx.get_binary_string()
#print binary_string + " " + np_arr8_string
t = time.time()
sys.stdout.write('Weight: {}\tFrequency: {}\t\r'.format(hx.get_weight(1), 1./ (t-prev_t)))
sys.stdout.flush()
prev_t = t
except (KeyboardInterrupt, SystemExit):
print "\nCleaning..."
GPIO.cleanup()
print "Bye!"
sys.exit()