1、物料
- Raspberry 4B
- 单点式称重传感器
- HX711
2、接线方法:
称重传感器有根线,白黑红绿分别为:
红 ———-> E+ 黑 ———-> E- 白 ———-> A+ 绿 ———-> A-
称重传感器接HX711,如下图所示,传感器 红黑白绿;网上还有很多种接法,都试过之后,只有这种是稳定的;
HX711接树莓派接法如下图:
保证接线稳定后,打开树莓派建立Demo测试;
3、Demo
hx711.py
"""
HX711 Load cell amplifier Python Library
Original source: https://gist.github.com/underdoeg/98a38b54f889fce2b237
Documentation source: https://github.com/aguegu/ardulibs/tree/master/hx711
Adapted by 2017 Jiri Dohnalek
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
import RPi.GPIO as GPIO
import time
import sys
class HX711:
def __init__(self, dout, pd_sck, gain=128):
"""
Set GPIO Mode, and pin for communication with HX711
:param dout: Serial Data Output pin
:param pd_sck: Power Down and Serial Clock Input pin
:param gain: set gain 128, 64, 32
"""
self.GAIN = 0
self.OFFSET = 0
self.SCALE = 1
# Setup the gpio pin numbering system
GPIO.setmode(GPIO.BCM)
# Set the pin numbers
self.PD_SCK = pd_sck
self.DOUT = dout
# Setup the GPIO Pin as output
GPIO.setup(self.PD_SCK, GPIO.OUT)
# Setup the GPIO Pin as input
GPIO.setup(self.DOUT, GPIO.IN)
# Power up the chip
self.power_up()
self.set_gain(gain)
def set_gain(self, gain=128):
try:
if gain is 128:
self.GAIN = 3
elif gain is 64:
self.GAIN = 2
elif gain is 32:
self.GAIN = 1
except:
self.GAIN = 3 # Sets default GAIN at 128
GPIO.output(self.PD_SCK, False)
self.read()
def set_scale(self, scale):
"""
Set scale
:param scale, scale
"""
self.SCALE = scale
def set_offset(self, offset):
"""
Set the offset
:param offset: offset
"""
self.OFFSET = offset
def get_scale(self):
"""
Returns value of scale
"""
return self.SCALE
def get_offset(self):
"""
Returns value of offset
"""
return self.OFFSET
def read(self):
"""
Read data from the HX711 chip
:param void
:return reading from the HX711
"""
# Control if the chip is ready
while not (GPIO.input(self.DOUT) == 0):
# Uncommenting the print below results in noisy output
# print("No input from HX711.")
pass
# Original C source code ported to Python as described in datasheet
# https://cdn.sparkfun.com/datasheets/Sensors/ForceFlex/hx711_english.pdf
# Output from python matched the output of
# different HX711 Arduino library example
# Lastly, behaviour matches while applying pressure
# Please see page 8 of the PDF document
count = 0
for i in range(24):
GPIO.output(self.PD_SCK, True)
count = count << 1
GPIO.output(self.PD_SCK, False)
if(GPIO.input(self.DOUT)):
count += 1
GPIO.output(self.PD_SCK, True)
count = count ^ 0x800000
GPIO.output(self.PD_SCK, False)
# set channel and gain factor for next reading
for i in range(self.GAIN):
GPIO.output(self.PD_SCK, True)
GPIO.output(self.PD_SCK, False)
return count
def read_average(self, times=16):
"""
Calculate average value from
:param times: measure x amount of time to get average
"""
sum = 0
for i in range(times):
sum += self.read()
return sum / times
def get_grams(self, times=16):
"""
:param times: Set value to calculate average,
be aware that high number of times will have a
slower runtime speed.
:return float weight in grams
"""
value = (self.read_average(times) - self.OFFSET)
grams = (value / self.SCALE)
return grams
def tare(self, times=16):
"""
Tare functionality fpr calibration
:param times: set value to calculate average
"""
sum = self.read_average(times)
self.set_offset(sum)
def power_down(self):
"""
Power the chip down
"""
GPIO.output(self.PD_SCK, False)
GPIO.output(self.PD_SCK, True)
def power_up(self):
"""
Power the chip up
"""
GPIO.output(self.PD_SCK, False)
example_python3.py
"""
HX711 Load cell amplifier Python Library
Original source: https://gist.github.com/underdoeg/98a38b54f889fce2b237
Documentation source: https://github.com/aguegu/ardulibs/tree/master/hx711
Adapted by 2017 Jiri Dohnalek
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
##################
PYTHON 3 EXAMPLE
This version of example is python 3 compatible
and outputs weight in grams.
Make sure you enter the correct values for offset and scale!
Also, don't forget to set the correct gain, default is 128.
"""
import RPi.GPIO as GPIO
import time
import sys
from hx711 import HX711
# Force Python 3 ###########################################################
if sys.version_info[0] != 3:
raise Exception("Python 3 is required.")
############################################################################
hx = HX711(5, 6)
def cleanAndExit():
print("Cleaning...")
GPIO.cleanup()
print("Bye!")
sys.exit()
def setup():
"""
code run once
"""
hx.set_offset(`Place offset here`)
hx.set_scale(`Place ratio here`)
def loop():
"""
code run continuosly
"""
try:
val = hx.get_grams()
print(val)
hx.power_down()
time.sleep(.001)
hx.power_up()
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
cleanAndExit()
##################################
if __name__ == "__main__":
setup()
while True:
loop()
以上代码摘自Github,https://github.com/learn2develop/hx711py
Python library for the HX711 load cell amplifier and Raspberry Pi
在树莓派中执行
git clone https://github.com/learn2develop/hx711py.git
cd hx711py
如何校准
1、在树莓派中运行calibration.py
python3 calibration.py
按照顺序开始,首先清空秤盘,回车
在秤盘上放一个已知重量的东西,如2KG的水瓶,回车
提示输入已知物重量,输入2000,回车
程序会自动计算出offset、scacle这两个值,如:Offset: 8252194.375 Scale: -27.108333333333334复制下来
2、修改example文件,如使用Python3,则修改example_python3.py,
vim example_python3.py
修改代码中
hx.set_offset(`Place offset here`)
hx.set_scale(`Place ratio here`)
为
hx.set_offset(8252194.375)
hx.set_scale(-27.108333333333334)
然后运行代码测试效果
python example_python3.py,
数值有点偏移,跟接线以及校准有问题,逐步改进中
本人小白一枚,如有共同爱好或者遇到同样问题欢迎沟通交流,QQ:1078246446