1、物料

  • Raspberry 4B

image.png

  • 单点式称重传感器

image.png

  • HX711

image.png

2、接线方法:

称重传感器有根线,白黑红绿分别为:

红 ———-> E+ 黑 ———-> E- 白 ———-> A+ 绿 ———-> A-

称重传感器接HX711,如下图所示,传感器 红黑白绿;网上还有很多种接法,都试过之后,只有这种是稳定的;
image.png

HX711接树莓派接法如下图:
image.png
保证接线稳定后,打开树莓派建立Demo测试;

3、Demo

hx711.py

  1. """
  2. HX711 Load cell amplifier Python Library
  3. Original source: https://gist.github.com/underdoeg/98a38b54f889fce2b237
  4. Documentation source: https://github.com/aguegu/ardulibs/tree/master/hx711
  5. Adapted by 2017 Jiri Dohnalek
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License along
  15. with this program; if not, write to the Free Software Foundation, Inc.,
  16. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  17. """
  18. import RPi.GPIO as GPIO
  19. import time
  20. import sys
  21. class HX711:
  22. def __init__(self, dout, pd_sck, gain=128):
  23. """
  24. Set GPIO Mode, and pin for communication with HX711
  25. :param dout: Serial Data Output pin
  26. :param pd_sck: Power Down and Serial Clock Input pin
  27. :param gain: set gain 128, 64, 32
  28. """
  29. self.GAIN = 0
  30. self.OFFSET = 0
  31. self.SCALE = 1
  32. # Setup the gpio pin numbering system
  33. GPIO.setmode(GPIO.BCM)
  34. # Set the pin numbers
  35. self.PD_SCK = pd_sck
  36. self.DOUT = dout
  37. # Setup the GPIO Pin as output
  38. GPIO.setup(self.PD_SCK, GPIO.OUT)
  39. # Setup the GPIO Pin as input
  40. GPIO.setup(self.DOUT, GPIO.IN)
  41. # Power up the chip
  42. self.power_up()
  43. self.set_gain(gain)
  44. def set_gain(self, gain=128):
  45. try:
  46. if gain is 128:
  47. self.GAIN = 3
  48. elif gain is 64:
  49. self.GAIN = 2
  50. elif gain is 32:
  51. self.GAIN = 1
  52. except:
  53. self.GAIN = 3 # Sets default GAIN at 128
  54. GPIO.output(self.PD_SCK, False)
  55. self.read()
  56. def set_scale(self, scale):
  57. """
  58. Set scale
  59. :param scale, scale
  60. """
  61. self.SCALE = scale
  62. def set_offset(self, offset):
  63. """
  64. Set the offset
  65. :param offset: offset
  66. """
  67. self.OFFSET = offset
  68. def get_scale(self):
  69. """
  70. Returns value of scale
  71. """
  72. return self.SCALE
  73. def get_offset(self):
  74. """
  75. Returns value of offset
  76. """
  77. return self.OFFSET
  78. def read(self):
  79. """
  80. Read data from the HX711 chip
  81. :param void
  82. :return reading from the HX711
  83. """
  84. # Control if the chip is ready
  85. while not (GPIO.input(self.DOUT) == 0):
  86. # Uncommenting the print below results in noisy output
  87. # print("No input from HX711.")
  88. pass
  89. # Original C source code ported to Python as described in datasheet
  90. # https://cdn.sparkfun.com/datasheets/Sensors/ForceFlex/hx711_english.pdf
  91. # Output from python matched the output of
  92. # different HX711 Arduino library example
  93. # Lastly, behaviour matches while applying pressure
  94. # Please see page 8 of the PDF document
  95. count = 0
  96. for i in range(24):
  97. GPIO.output(self.PD_SCK, True)
  98. count = count << 1
  99. GPIO.output(self.PD_SCK, False)
  100. if(GPIO.input(self.DOUT)):
  101. count += 1
  102. GPIO.output(self.PD_SCK, True)
  103. count = count ^ 0x800000
  104. GPIO.output(self.PD_SCK, False)
  105. # set channel and gain factor for next reading
  106. for i in range(self.GAIN):
  107. GPIO.output(self.PD_SCK, True)
  108. GPIO.output(self.PD_SCK, False)
  109. return count
  110. def read_average(self, times=16):
  111. """
  112. Calculate average value from
  113. :param times: measure x amount of time to get average
  114. """
  115. sum = 0
  116. for i in range(times):
  117. sum += self.read()
  118. return sum / times
  119. def get_grams(self, times=16):
  120. """
  121. :param times: Set value to calculate average,
  122. be aware that high number of times will have a
  123. slower runtime speed.
  124. :return float weight in grams
  125. """
  126. value = (self.read_average(times) - self.OFFSET)
  127. grams = (value / self.SCALE)
  128. return grams
  129. def tare(self, times=16):
  130. """
  131. Tare functionality fpr calibration
  132. :param times: set value to calculate average
  133. """
  134. sum = self.read_average(times)
  135. self.set_offset(sum)
  136. def power_down(self):
  137. """
  138. Power the chip down
  139. """
  140. GPIO.output(self.PD_SCK, False)
  141. GPIO.output(self.PD_SCK, True)
  142. def power_up(self):
  143. """
  144. Power the chip up
  145. """
  146. GPIO.output(self.PD_SCK, False)

example_python3.py

  1. """
  2. HX711 Load cell amplifier Python Library
  3. Original source: https://gist.github.com/underdoeg/98a38b54f889fce2b237
  4. Documentation source: https://github.com/aguegu/ardulibs/tree/master/hx711
  5. Adapted by 2017 Jiri Dohnalek
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License along
  15. with this program; if not, write to the Free Software Foundation, Inc.,
  16. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  17. ##################
  18. PYTHON 3 EXAMPLE
  19. This version of example is python 3 compatible
  20. and outputs weight in grams.
  21. Make sure you enter the correct values for offset and scale!
  22. Also, don't forget to set the correct gain, default is 128.
  23. """
  24. import RPi.GPIO as GPIO
  25. import time
  26. import sys
  27. from hx711 import HX711
  28. # Force Python 3 ###########################################################
  29. if sys.version_info[0] != 3:
  30. raise Exception("Python 3 is required.")
  31. ############################################################################
  32. hx = HX711(5, 6)
  33. def cleanAndExit():
  34. print("Cleaning...")
  35. GPIO.cleanup()
  36. print("Bye!")
  37. sys.exit()
  38. def setup():
  39. """
  40. code run once
  41. """
  42. hx.set_offset(`Place offset here`)
  43. hx.set_scale(`Place ratio here`)
  44. def loop():
  45. """
  46. code run continuosly
  47. """
  48. try:
  49. val = hx.get_grams()
  50. print(val)
  51. hx.power_down()
  52. time.sleep(.001)
  53. hx.power_up()
  54. time.sleep(2)
  55. except (KeyboardInterrupt, SystemExit):
  56. cleanAndExit()
  57. ##################################
  58. if __name__ == "__main__":
  59. setup()
  60. while True:
  61. loop()

以上代码摘自Github,https://github.com/learn2develop/hx711py

Python library for the HX711 load cell amplifier and Raspberry Pi

在树莓派中执行

  1. git clone https://github.com/learn2develop/hx711py.git
  2. cd hx711py

如何校准
1、在树莓派中运行calibration.py

  1. python3 calibration.py

按照顺序开始,首先清空秤盘,回车
在秤盘上放一个已知重量的东西,如2KG的水瓶,回车
提示输入已知物重量,输入2000,回车
程序会自动计算出offset、scacle这两个值,如:Offset: 8252194.375 Scale: -27.108333333333334复制下来
2、修改example文件,如使用Python3,则修改example_python3.py,

  1. vim example_python3.py

修改代码中

  1. hx.set_offset(`Place offset here`)
  2. hx.set_scale(`Place ratio here`)

  1. hx.set_offset(8252194.375)
  2. hx.set_scale(-27.108333333333334)

然后运行代码测试效果

  1. python example_python3.py,

数值有点偏移,跟接线以及校准有问题,逐步改进中

本人小白一枚,如有共同爱好或者遇到同样问题欢迎沟通交流,QQ:1078246446