Arduino称重传感器和 HX711 放大器(数字秤)
Arduino with Load Cell and HX711 Amplifier (Digital Scale)
In this guide, you’ll learn how to create a digital scale with the Arduino using a load cell and the HX711 amplifier. First, you’ll learn how to wire the load cell and the HX711 amplifier to the Arduino to build a scale. Then, we’ll show you how to calibrate the scale, and a simple example to get the weight of objects. Later, we’ll also add a display to show the measurements and a button to tare the scale.
在本指南中,您将学习通过 Arduino使用称重传感器和 HX711 放大器创建数字秤。首先,您将学习如何将称重传感器和 HX711 放大器连接到 Arduino 以构建秤。然后,将向您展示如何校准秤,以及获取物体重量的简单示例。稍后,我们还将添加一个显示测量值的显示屏和一个用于去皮的按钮。
Table of Contents 目录
In this tutorial, we’ll cover the following topics:
在本教程中,我们将介绍以下主题:
- Introducing Load Cells (Strain Gauges) 介绍称重传感器(应变片)
- HX711 Amplifier (HX711 功放)
- Setting Up Load Cell 设置称重传感器
- Wiring Load Cell and HX711 Amplifier to the Arduino 将称重传感器和 HX711 放大器连接到 Arduino
- Installing HX711 Library 安装 HX711 库
- Calibrating the Scale 校准刻度
- Weighting Objects – Code 加权对象 – 代码
- Digital Scale with Arduino 使用Arduino的数字秤
Introducing Load Cells 称重传感器简介
A load cell converts a force into an electrical signal that can be measured. The electrical signal changes proportionally to the force applied. There are different types of load cells: strain gauges, pneumatic, and hydraulic. In this tutorial, we’ll cover strain gauge load cells.
称重传感器将力转换为可测量的电信号。电信号与施加的力成正比变化。有不同类型的称重传感器:应变片、气动和液压。在本教程中,我们将介绍应变片称重传感器。
Strain gauge load cells are composed of a metal bar with attached strain gauges (under the white glue in the picture above). A strain gauge is an electrical sensor that measures force or strain on an object. The resistance of the strain gauges varies when an external force is applied to an object, which results in a deformation of the object’s shape (in this case, the metal bar). The strain gauge resistance is proportional to the load applied, which allows us to calculate the weight of objects.
应变片称重传感器由带有应变片的金属棒组成(在上图中的白色胶水下方)。应变片是一种电子传感器,用于测量物体上的力或应变。当外力施加到物体上时,应变片的阻力会发生变化,这会导致物体的形状(在这种情况下是金属棒)变形。应变片电阻与施加的载荷成正比,这使我们能够计算物体的重量。
Usually, load cells have four strain gauges hooked up in a Wheatstone bridge (as shown below) that allow us to get accurate resistance measurements. For a more detailed explanation of how strain gauges work, read this article.
通常,称重传感器在惠斯通电桥上连接了四个应变片(如下图所示),使我们能够获得准确的电阻测量值。有关应变片工作原理的更详细说明,请阅读此文。
The wires coming from the load cell usually have the following colors:
来自称重传感器的电线通常具有以下颜色:
- Red: VCC (E+) 红色:VCC (E+)
- Black: GND (E-) 黑色:GND(E-)
- White: Output – (A-) 白色:输出 – (A-)
- Green: Output + (A+) 绿色:输出 + (A+)
Applications 应用
Strain gauge load cells can be used in a wide variety of applications. For example:
应变片称重传感器可用于各种应用。例如:
- check if an object’s weight changes over time;
检查物体的重量是否随时间变化; - measure the weight of an object;
测量物体的重量; - detect the presence of an object;
检测物体的存在; - estimate a container’s liquid level;
估计容器的液位; - etc. 等。
Because the changes in strain when weighting objects are so small, we need an amplifier. The load cell we’re using is usually sold together with an HX711 amplifier. So, that’s the amplifier we’ll use.
因为改变物体重量时的应变变化非常小,所以我们需要一个放大器。我们使用的称重传感器通常与 HX711 放大器一起出售。
(HX711 Amplifier )HX711 功放
The HX711 amplifier is a breakout board that allows you to easily read load cells to measure weight. You wire the load cell wires on one side, and the microcontroller on the other side. The HX711 communicates with the microcontroller using two-wire interface (Clock and Data).
HX711 放大器是一款分线板,可让您轻松读取称重传感器以测量重量。您将称重传感器的电线连接到一侧,微控制器连接到另一侧。HX711 使用双线接口(时钟和数据)与微控制器通信。
You need to solder header pins on the GND, DT, SCK, and VCC pins to connect to the Arduino. I soldered the load cell wires directly to the E+, E-, A-, and A+ pins. The load cell wires were very thin and fragile, be careful when soldering to not damage the wires.
您需要在 GND、DT、SCK 和 VCC 引脚上焊接接头引脚才能连接到 Arduino。我将称重传感器线直接焊接到 E+、E-、A- 和 A+ 引脚上。称重传感器的电线非常细且易断,焊接时要小心,以免损坏电线。
For more information about the HX711 amplifier, you can consult the HX711 datasheet.
有关 HX711 放大器的更多信息,您可以查阅 HX711 数据表。
(Setting Up the Load Cell )设置称重传感器
Our load cell kit came with two acrylic plates and some screws to set up the load cell as a scale. You can use wood plates or 3D-print your own plates.
我们的称重传感器套件配有两块亚克力板和一些螺钉,用于将称重传感器设置为秤。您可以使用木板或3D打印自己的板。
You should attach the plates to the load cell in a way that creates a strain between the opposite ends of the metal bar. The bottom plate holds the load cell, and the upper plate is where you place the objects.
您应该将板连接到称重传感器上,以便在金属棒的两端之间产生应变。底板用于放置称重传感器,上板是放置物体的位置。
The following figure shows what my load cell with the acrylic plates looks like.
下图显示了带有亚克力板的称重传感器的外观。
带有HX711的称重传感器
- Load Cell with HX711 Amplifier
带HX711放大器的称重传感器
(Wiring Load Cell and HX711 Amplifier to the Arduino) 将称重传感器和 HX711 放大器连接到 Arduino
The HX711 amplifier communicates via two-wire interface. You can connect it to any digital pins of your Arduino board. We’re connecting the data pin (DT) to Pin 2 and the clock pin (CLK) to Pin 3.
HX711放大器通过两线接口进行通信。您可以将其连接到Arduino板的任何数字引脚。我们将数据引脚 (DT) 连接到引脚 2,将时钟引脚 (CLK) 连接到引脚 3。
Follow the next table or schematic diagram to wire the load cell to the Arduino board.
按照下表或原理图将称重传感器连接到Arduino板。
Load Cell 称重传感器 | HX711 | HX711 | Arduino |
---|---|---|---|
Red (E+) 红色 (E+) | E+ | GND | GND |
Black (E-) 黑色(E-) | E- | DT | Pin 2 引脚 2 |
White (A-) 白色 (A-) | A- | SCK | Pin 3 引脚 3 |
Green (A+) 绿色 (A+) | A+ | VCC | 5V |
Installing the HX711 Library 安装 HX711 库
There are several different libraries to get measurements from a load cell using the HX711 amplifier. We’ll use the HX711 library by bodge. It is compatible with the ESP32, ESP8266, and Arduino.
有几个不同的库可以使用HX711放大器从称重传感器获得测量值。我们将使用 bodge 的 HX711 库。它与 ESP32、ESP8266 和 Arduino 兼容。
Arduino IDE Arduino IDE集成电路
Follow the next instructions to install the library if you’re using Arduino IDE.
如果您使用的是 Arduino IDE,请按照以下说明安装库。
- Open Arduino IDE and go to Sketch > Include Library > Manage Libraries.
打开Arduino IDE并转到“草图”>“包括库”>“管理库”。 - Search for “HX711 Arduino Library” and install the library by Bogdan Necula.
搜索“HX711 Arduino Library”并安装 Bogdan Necula 的库。
Calibrating the Scale (Arduino with Load Cell) 校准秤(带称重传感器的Arduino)
At this time, we assume you have wired the load cell to the HX711 amplifier and the amplifier to the Arduino board. You should also have your scale set up (two plates wired on opposite ends on the load cell), and have installed the HX711 library.
此时,我们假设您已将称重传感器连接到HX711放大器,并将放大器连接到Arduino板。您还应该设置秤(称重传感器的两端连接两块板),并安装 HX711 库。
Before getting the weight of objects, you need to calibrate your load cell first by getting the calibration factor. Your calibration factor will be different than mine, so you shouldn’t skip this section.
在获得物体的重量之前,您需要先通过获取校准系数来校准称重传感器。您的校准因子将与我的校准因子不同,因此您不应跳过此部分。
1) Prepare an object with a known weight. I used my kitchen scale and weighed a glass with water (107g).
1) 准备一个具有已知重量的物体。我用厨房秤称了一杯水(107克)。
2) Upload the following code to your Arduino board. We wrote the following code taking into account the instructions to calibrate the load cell provided by the library documentation.
2)将以下代码上传到您的Arduino板。我们编写了以下代码,并考虑了库文档提供的校准称重传感器的说明。
/*Rui SantosComplete project details at https://RandomNerdTutorials.com/arduino-load-cell-hx711/Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files.The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
*/// Calibrating the load cell
#include "HX711.h"// HX711 circuit wiring
const int LOADCELL_DOUT_PIN = 2;
const int LOADCELL_SCK_PIN = 3;HX711 scale;void setup() {Serial.begin(57600);scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
}void loop() {if (scale.is_ready()) {scale.set_scale(); Serial.println("Tare... remove any weights from the scale.");delay(5000);scale.tare();Serial.println("Tare done...");Serial.print("Place a known weight on the scale...");delay(5000);long reading = scale.get_units(10);Serial.print("Result: ");Serial.println(reading);} else {Serial.println("HX711 not found.");}delay(1000);
}//calibration factor will be the (reading)/(known weight)
View raw code 查看原始代码
3) After uploading, open the Serial Monitor at a baud rate of 57600 and then press the Arduino on-board RESET button.
3) 上传后,以 57600 的波特率打开串口监视器,然后按下 Arduino 板载 RESET 按钮。
4) Follow the instructions on the Serial Monitor: remove any weights from the scale (it will tare automatically). Then, place an object with a known weight on the scale and wait until you get a value.
4) 按照串行监视器上的说明进行操作:从秤上取下所有砝码(它将自动去皮)。然后,将具有已知权重的物体放在秤上,并等待获得值。
5) Calculate your calibration factor using the formula:
5) 使用以下公式计算校准因子:
calibration factor = (reading)/(known weight)
In our case, the reading is -49171. The known weight is 107g, so our calibration factor will be: -49171/107 = -459.542.
在我们的例子中,读数是 -49171。已知重量为 107g,因此我们的校准系数为:-49171/107 = -459.542。
calibration factor = -49171/107 = -459.542
Save your calibration factor because you’ll need it later. Yours will be different than ours.
保存校准因子,因为以后会用到它。你的将与我们的不同。
Because the output of the sensor is proportional to the force applied to the load cell, you can calibrate your scale using whatever unit makes sense for you. I used grams, but you can use pounds, kilograms, or even pieces of cat food (as in this Andreas Spiess video).
由于传感器的输出与施加在称重传感器上的力成正比,因此您可以使用任何适合您的单位来校准秤。我用的是克,但你可以使用磅、公斤,甚至是猫粮片(就像这个 Andreas Spiess 视频一样)。
Weighting Objects (Arduino with Load Cell) 加权对象(带称重传感器的Arduino)
Now that you know your calibration factor, you can use your load cell to weight objects. Start by weighing objects with a known weight and repeat the calibration process if the values are not accurate.
现在您知道了校准系数,您可以使用称重传感器对物体进行称重。首先称量具有已知重量的物体,如果值不准确,则重复校准过程。
Copy the following code to your Arduino IDE. Before uploading it to your board, don’t forget to insert your calibration factor in line 43/44 of the code. The following code is the example provided by the library that demonstrates the use of most of its functions.
将以下代码复制到 Arduino IDE。在将其上传到电路板之前,请不要忘记在代码的第 43/44 行中插入校准因子。以下代码是该库提供的示例,演示了其大多数函数的使用。
/*** Complete project details at https://RandomNerdTutorials.com/arduino-load-cell-hx711/** HX711 library for Arduino - example file* https://github.com/bogde/HX711** MIT License* (c) 2018 Bogdan Necula*
**/#include <Arduino.h>
#include "HX711.h"// HX711 circuit wiring
const int LOADCELL_DOUT_PIN = 2;
const int LOADCELL_SCK_PIN = 3;HX711 scale;void setup() {Serial.begin(57600);Serial.println("HX711 Demo");Serial.println("Initializing the scale");scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);Serial.println("Before setting up the scale:");Serial.print("read: \t\t");Serial.println(scale.read()); // print a raw reading from the ADCSerial.print("read average: \t\t");Serial.println(scale.read_average(20)); // print the average of 20 readings from the ADCSerial.print("get value: \t\t");Serial.println(scale.get_value(5)); // print the average of 5 readings from the ADC minus the tare weight (not set yet)Serial.print("get units: \t\t");Serial.println(scale.get_units(5), 1); // print the average of 5 readings from the ADC minus tare weight (not set) divided// by the SCALE parameter (not set yet)scale.set_scale(-459.542);//scale.set_scale(-471.497); // this value is obtained by calibrating the scale with known weights; see the README for detailsscale.tare(); // reset the scale to 0Serial.println("After setting up the scale:");Serial.print("read: \t\t");Serial.println(scale.read()); // print a raw reading from the ADCSerial.print("read average: \t\t");Serial.println(scale.read_average(20)); // print the average of 20 readings from the ADCSerial.print("get value: \t\t");Serial.println(scale.get_value(5)); // print the average of 5 readings from the ADC minus the tare weight, set with tare()Serial.print("get units: \t\t");Serial.println(scale.get_units(5), 1); // print the average of 5 readings from the ADC minus tare weight, divided// by the SCALE parameter set with set_scaleSerial.println("Readings:");
}void loop() {Serial.print("one reading:\t");Serial.print(scale.get_units(), 1);Serial.print("\t| average:\t");Serial.println(scale.get_units(10), 5);delay(5000);
}
View raw code 查看原始代码
How the Code Works 代码的工作原理
Start by including the required library.
首先包括所需的库。
#include "HX711.h"
The following lines define the pins you’ll use to connect to the HX711 amplifier. We chose Pin 2 and Pin 3. You can use any other digital pins.
以下行定义了用于连接到 HX711 的引脚 amp扩音器。我们选择了引脚 2 和引脚 3。您可以使用任何其他数字引脚。
const int LOADCELL_DOUT_PIN = 2;
const int LOADCELL_SCK_PIN = 3;
Then, create an instance of the HX711 library called scale that you’ll use later on to get the measurements.
然后,创建一个名为 scale 的 HX711 库实例,稍后将使用它来获取测量值。
HX711 scale;
setup() 设置()
In the setup(), initialize the Serial monitor.
在 setup() 中,初始化串行监视器。
Serial.begin(57600);
Initialize the load cell by calling the begin() method on the scale object and passing the digital pins as arguments.
通过在秤对象上调用 begin() 方法并将数字引脚作为参数传递来初始化称重传感器。
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
Then, it calls several methods that you can use to get readings using the library.
然后,它调用几种方法,您可以使用这些方法使用库获取读数。
- read(): gets a raw reading from the sensor
read():从传感器获取原始读数 - read_average(number of readings): gets the average of the latest defined number of readings
read_average(读数):获取最新定义的读数的平均值 - get_value(number of readings): gets the average of the last defined number of readings minus the tare weight;
get_value(读数):获取最后定义的读数数减去皮重的平均值; - get_units(number of readings): gets the average of the last defined number of readings minus the tare weight divided by the calibration factor — this will output a reading in your desired units.
get_units(读数):获取最后定义的读数减去皮重除以校准系数的平均值 — 这将以您想要的单位输出读数。
Serial.println("Before setting up the scale:");
Serial.print("read: \t\t");
Serial.println(scale.read()); // print a raw reading from the ADCSerial.print("read average: \t\t");
Serial.println(scale.read_average(20)); // print the average of 20 readings from the ADCSerial.print("get value: \t\t");
Serial.println(scale.get_value(5)); // print the average of 5 readings from the ADC minus the tare weight (not set yet)Serial.print("get units: \t\t");
Serial.println(scale.get_units(5), 1); // print the average of 5 readings from the ADC minus tare weight (not set) divided
// by the SCALE parameter (not set yet)
In the following line, don’t forget to insert your calibration factor. It uses the set_scale() method.
在下一行中,不要忘记插入校准因子。它使用 set_scale() 方法。
scale.set_scale(INSERT YOUR CALIBRATION FACTOR)
Then, call the tare() method to tare the scale.
然后,调用 tare() 方法对刻度进行去皮。
scale.tare(); // reset the scale to 0
After this setup, the scale should be ready to get accurate readings in your desired unit. The example calls the same previous methods so that you can see the difference before and after setting up the scale.
完成此设置后,秤应准备好以所需单位获得准确的读数。该示例调用与前面相同的方法,以便您可以查看设置刻度之前和之后的差异。
Serial.print("read: \t\t");
Serial.println(scale.read()); // print a raw reading from the ADCSerial.print("read average: \t\t");
Serial.println(scale.read_average(20)); // print the average of 20 readings from the ADCSerial.print("get value: \t\t");
Serial.println(scale.get_value(5)); // print the average of 5 readings from the ADC minus the tare weight, set with tare()Serial.print("get units: \t\t");
Serial.println(scale.get_units(5), 1); // print the average of 5 readings from the ADC minus tare weight, divided
// by the SCALE parameter set with set_scale
loop() 循环()
In the loop(), the example calls the get_units() method in two different ways: to get one single reading (without any parameters) and to get the average of the last 10 readings.
在 loop()
中,该示例以两种不同的方式调用 get_units()
方法:获取一个读数(不带任何参数)和获取最近 10 个读数的平均值。
Serial.print("one reading:\t");
Serial.print(scale.get_units(), 1);
Serial.print("\t| average:\t");
Serial.println(scale.get_units(10), 5);
It shuts down the ADC that reads the sensor by using the power_down() method. Then, it waits for 5 seconds, powers up the ADC (power_up()), and the loop() repeats. So, you’ll get new readings on the Serial Monitor every 5 seconds.
它使用 power_down() 方法关闭读取传感器的 ADC。然后,它等待 5 秒钟,为 ADC (power_up()
) 上电,然后 loop()
重复。因此,您将每 5 秒在串行监视器上获得新读数。
scale.power_down(); // put the ADC in sleep mode
delay(5000);
scale.power_up();
Demonstration 示范
Upload the code to your Arduino board. After uploading, open the Serial Monitor at a baud rate of 115200.
将代码上传到您的Arduino板。上传后,以 115200 的波特率打开串行监视器。
Let the code run a few seconds so that it has time to set up the scale (you’ll see the message on the Serial Monitor). Then, place any object on the scale to measure it and you’ll get the results on the Serial Monitor.
让代码运行几秒钟,以便有时间设置刻度(您将在串行监视器上看到该消息)。然后,将任何物体放在秤上进行测量,您将在串行监视器上获得结果。
I experimented with several objects and compared them against the value on my kitchen scale, and the results were the same. So, I can say that my Arduino scale is at least as accurate as my kitchen scale.
我用几个物体进行了实验,并将它们与厨房秤上的值进行了比较,结果是一样的。所以,我可以说我的Arduino秤至少和我的厨房秤一样准确。
使用Arduino的数字秤(Digital Scale with Arduino )
In this section, we’ll create a simple digital scale with the Arduino. We’ll add an OLED display to show the results and a pushbutton to tare the scale.
在本节中,我们将使用 Arduino 创建一个简单的数字秤。我们将添加一个OLED显示屏来显示结果,并添加一个按钮来显示秤。
Parts Required 所需零件
Here’s a list of the parts required for this project:
以下是此项目所需的部件列表:
- Arduino UNO (read Best Arduino starter kits)
Arduino UNO(阅读最佳 Arduino 入门套件) - Load Cell with HX711 Amplifier
带HX711放大器的称重传感器 - I2C SSD1306 OLED Display
I2C SSD1306 OLED显示屏 - Pushbutton 按钮
- 10K Ohm Resistor 10K欧姆电阻
- Breadboard 面包板
- Jumper Wires 跳线
Schematic Diagram 原理图
Add an OLED display and a pushbutton to your previous circuit on the following pins:
在以下引脚上为之前的电路添加一个OLED显示屏和一个按钮:
OLED Display OLED显示屏 | Arduino |
---|---|
VCC | 3.3V or 5V* 3.3V 或 5V* |
GND | GND |
SDA | A4 |
SCL | A5 |
*connect to 3.3V or 5V depending on the model.
*根据型号连接到 3.3V 或 5V。
Not familiar with the OLED display? Read: Guide for I2C OLED Display with Arduino.
不熟悉OLED显示屏?阅读:使用Arduino的I2C OLED显示器指南。
Wire the pushbutton via a 10kOhm pull-down resistor to Pin 4. The other lead of the pushbutton should be connected to 5V. You can use any other Arduino digital pin.
通过 10kOhm 下拉电阻将按钮连接到引脚 4。按钮的另一根引线应连接到 5V。您可以使用任何其他Arduino数字引脚。
You can follow the next schematic diagram to wire your parts.
您可以按照下一个原理图对零件进行接线。
Arduino Digital Scale – Code Arduino数字秤–代码
For simplicity, we’ll handle the pushbutton using a simple library that detects button presses with debouncing (so we don’t need to worry about that in our code). To write to the OLED display, we’ll use the Adafruit SSD1306 and Adafruit GFX libraries.
为简单起见,我们将使用一个简单的库来处理按钮,该库通过去抖动来检测按钮按下(因此我们无需在代码中担心这一点)。要写入 OLED 显示屏,我们将使用 Adafruit SSD1306 和 Adafruit GFX 库。
Pushbutton Library 按钮库
There are many libraries with many functionalities to handle pushbuttons. We’ll use the pushbutton library by polulu. It is a simple library but comes with everything we need for this project. In your Arduino IDE, go to Sketch > Include Library > Manage Libraries and search for “pushbutton“. Install the pushbutton library by polulu.
有许多库具有许多处理按钮的功能。我们将使用 polulu 的按钮库。这是一个简单的库,但附带了这个项目所需的一切。在Arduino IDE中,转到“草图”>“包括库”>“管理库”,然后搜索“pushbutton”。通过 polulu 安装按钮库。
Alternatively, if you don’t want to use the library you can add the debounce code yourself (which is not difficult). For a debounce code example, in the Arduino IDE, you can go to File > Examples > Digital > Debounce
.
或者,如果您不想使用该库,您可以自己添加 debounce 代码(这并不难)。有关去抖动代码示例,在 Arduino IDE 中,您可以转到 文件 > 示例 > Digital > Debounce
。
OLED Libraries OLED库
We’ll use the following libraries to control the OLED display. Make sure you have these libraries installed:
我们将使用以下库来控制OLED显示屏。请确保已安装以下库:
- (Adafruit_SSD1306 library)
Adafruit_SSD1306库 - (Adafruit_GFX library) Adafruit_GFX库
You can install the libraries using the Arduino Library Manager. Go to Sketch > Include Library > Manage Libraries
and search for the library name.
您可以使用Arduino库管理器安装库。转到“项目”>“导入”>“管理库”
,然后搜索库名称。
代码(Code)
Copy the following code to your Arduino IDE. Before uploading it to the Arduino board, you need to insert your calibration factor (obtained previously).
将以下代码复制到 Arduino IDE。在将其上传到Arduino板之前,您需要插入校准因子(之前获得)。
/*Rui SantosComplete project details at https://RandomNerdTutorials.com/arduino-load-cell-hx711/Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files.The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
*/// Library HX711 by Bogdan Necula: https://github.com/bogde/HX711
// Library: pushbutton by polulu: https://github.com/pololu/pushbutton-arduino#include "HX711.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Pushbutton.h>// HX711 circuit wiring
const int LOADCELL_DOUT_PIN = 2;
const int LOADCELL_SCK_PIN = 3;HX711 scale;
int reading;
int lastReading;
//REPLACE WITH YOUR CALIBRATION FACTOR
#define CALIBRATION_FACTOR -476.592//OLED Display
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);//Button
#define BUTTON_PIN 4
Pushbutton button(BUTTON_PIN);void displayWeight(int weight){display.clearDisplay();display.setTextSize(1);display.setTextColor(WHITE);display.setCursor(0, 10);// Display static textdisplay.println("Weight:");display.display();display.setCursor(0, 30);display.setTextSize(2);display.print(weight);display.print(" ");display.print("g");display.display();
}void setup() {Serial.begin(57200);if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Serial.println(F("SSD1306 allocation failed"));for(;;);}delay(2000);display.clearDisplay();display.setTextColor(WHITE);Serial.println("Initializing the scale");scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);scale.set_scale(CALIBRATION_FACTOR); // this value is obtained by calibrating the scale with known weightsscale.tare(); // reset the scale to 0
}void loop() {if (button.getSingleDebouncedPress()){Serial.print("tare...");scale.tare();}if (scale.wait_ready_timeout(200)) {reading = round(scale.get_units());Serial.print("Weight: ");Serial.println(reading);if (reading != lastReading){displayWeight(reading); }lastReading = reading;}else {Serial.println("HX711 not found.");}
}
View raw code 查看原始代码
How the Code Works 代码的工作原理
Start by including the required libraries:
首先包括所需的库:
#include "HX711.h"
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Pushbutton.h>
Define the pins for the HX711 (load cell)—we’re using the same as previous examples:
定义 HX711(称重传感器)的引脚 - 我们使用的与前面的示例相同:
// HX711 circuit wiring
const int LOADCELL_DOUT_PIN = 2;
const int LOADCELL_SCK_PIN = 3;
Create an HX711 instance called scale.
创建名为 scale 的 HX711 实例。
HX711 scale;
The following variables will hold the current weight reading and the last weight reading. We only want to update the OLED display in case there’s a new reading, so that’s why we need these two variables. Additionally, we don’t want to measure decimals of grams which will make the scale too sensitive for our application—that’s why these variables are integers. If you need decimals in your measurements, you can define float variables instead.
以下变量将保存当前重量读数和上次重量读数。我们只想在有新读数的情况下更新OLED显示屏,所以这就是为什么我们需要这两个变量。此外,我们不想测量克的小数,因为这会使刻度对我们的应用程序过于敏感,这就是为什么这些变量是整数。如果测量中需要小数,则可以改为定义浮点变量。
int reading;
int lastReading;
Don’t forget to replace the next value with your calibration factor. In my case, that line of code looks as follows (my value is negative):
不要忘记将下面的值替换为您的校准因子。就我而言,该代码行如下所示(我的值为负数):
#define CALIBRATION_FACTOR -459.542
Next, we need to define the OLED width and height:
接下来,我们需要定义OLED的宽度和高度:
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
And create an instance of the Adafruit_SSD1306 library called display.
并创建一个名为 display 的 Adafruit_SSD1306 库实例。
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
Define the GPIO you’ll use to read the button and create a Pushbutton object called button on that pin.
定义将用于读取按钮的 GPIO,并在该引脚上创建一个名为 button 的 Pushbutton 对象。
#define BUTTON_PIN 4
Pushbutton button(BUTTON_PIN);
displayWeight() 函数
We created a function called displayWeight()
that accepts as arguments the weight you want to display on the OLED.
我们创建了一个名为displayWeight()的函数,该函数接受要在OLED上显示的权重作为参数。
void displayWeight(int weight){display.clearDisplay();display.setTextSize(1);display.setTextColor(WHITE);display.setCursor(0, 10);// Display static textdisplay.println("Weight:");display.display();display.setCursor(0, 30);display.setTextSize(2);display.print(weight);display.print(" ");display.print("g");display.display();
}
Not familiar with the OLED display? Read: Guide for I2C OLED Display with Arduino
不熟悉OLED显示屏?阅读:采用Arduino的I2C OLED显示器指南
setup() 设置()
In the setup(), initialize the Serial Monitor.
在 setup() 中,初始化串行监视器。
Serial.begin(57200);
Initialize the OLED display:
初始化OLED显示器:
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Serial.println(F("SSD1306 allocation failed"));for(;;);
}
delay(2000);
display.clearDisplay();
display.setTextColor(WHITE);
And finally, initialize the load cell:
最后,初始化称重传感器:
Serial.println("Initializing the scale");
scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);scale.set_scale(CALIBRATION_FACTOR); // this value is obtained by calibrating the scale with known weights
scale.tare(); // reset the scale to 0
loop()
The pushbutton library allows us to wait for an event in case of a pushbutton press or pushbutton release. In this case, we check whether the pushbutton was pushed using the getSingleDebouncePress() method and call the tare() function if the button was pressed.
按钮库允许我们在按下按钮或释放按钮的情况下等待事件。在本例中,我们使用 getSingleDebouncePress() 方法检查按钮是否被按下,如果按钮被按下,则调用 tare() 函数。
if (button.getSingleDebouncedPress()){Serial.print("tare...");scale.tare();
}
The HX711 provides a non-blocking method to get readings. It defines a maximum timeout to wait for the hardware to be initialized and doesn’t block your code in case the scale gets disconnected or in case of hardware failures.
HX711 提供了一种获取读数的非阻塞方法。它定义了等待硬件初始化的最大超时,并且在秤断开连接或硬件故障时不会阻止代码。
if (scale.wait_ready_timeout(200)) {reading = round(scale.get_units());Serial.print("Weight: ");Serial.println(reading);
In the loop(), we are constantly getting new readings and checking them against the latest reading. If we got a new measurement, we call the displayWeight() function to update the OLED display.
在 loop() 中,我们不断获得新的读数,并将它们与最新的读数进行检查。如果我们得到一个新的测量值,我们调用 displayWeight() 函数来更新 OLED 显示屏。
if (reading != lastReading){displayWeight(reading);
}
示范(Demonstration)
After uploading the code to your board, you can start weighing objects with your load cell. The readings will show up on the OLED display. You can tare the scale by pressing the pushbutton.
将代码上传到电路板后,您可以开始使用称重传感器称重物体。读数将显示在OLED显示屏上。您可以通过按下按钮来去皮秤。
Once again, the readings on my Arduino digital scale correspond to the readings on my kitchen scale.
再一次,我的Arduino数字秤上的读数与厨房秤上的读数相对应。
Wrapping Up 结束语
In this tutorial, you learned how to interface a strain gauge load cell with the Arduino board using the HX711 amplifier. The output of the load cell is proportional to the force applied. So, you can calibrate it to be used in g, kg, ib, or any other unit that makes sense for your project.
在本教程中,您学习了如何使用HX711放大器将应变片称重传感器与Arduino板连接起来。称重传感器的输出与施加的力成正比。因此,您可以将其校准为以 g、kg、ib 或任何其他对您的项目有意义的单位使用。
In summary, you learned how to calibrate the scale and how to get the weight of objects. You also learned how to create a simple digital scale with the Arduino using an OLED display to show the measurements and a pushbutton to tare the scale.
总之,您学习了如何校准秤以及如何获得物体的重量。您还学习了如何使用 Arduino 创建简单的数字秤,使用 OLED 显示屏显示测量结果,并使用按钮来去皮秤。
We hope you found this tutorial useful to get you started with a load cell. Besides being useful to measure the weight of objects, it can also be useful in many applications like detecting the presence of an object, estimating the level of liquid in a tank, calculating water’s evaporation rate, checking if there’s food on your pet’s bowl, etc.
我们希望本教程对您开始使用称重传感器有所帮助。除了用于测量物体的重量外,它还可用于许多应用,例如检测物体的存在、估计水箱中的液体液位、计算水的蒸发速率、检查宠物碗上是否有食物等。
We have tutorials for other popular sensors that you might find useful:
我们提供了其他常用传感器的教程,您可能会发现这些教程很有用:
- Arduino: K-Type Thermocouple with MAX6675 Amplifier (Temperature Sensor)
Arduino:带MAX6675放大器的K型热电偶(温度传感器) - Arduino with DS18B20: Temperature Sensor
带DS18B20的Arduino:温度传感器 - Guide for LM35, LM335, and LM34 Temperature Sensors with Arduino
采用 Arduino 的 LM35、LM335 和 LM34 温度传感器指南 - Arduino with BME680: Gas, Pressure, Humidity, and Temperature Sensor
带 BME680 的 Arduino:气体、压力、湿度和温度传感器 - Arduino with BME280: Temperature, Humidity, and Pressure Sensor
带 BME280 的 Arduino:温度、湿度和压力传感器 - Arduino with DHT11/DHT22: Temperature, and Humidity Sensor
带 DHT11/DHT22 的 Arduino:温度和湿度传感器 - Arduino with BMP388: Altimeter Sensor
带BMP388的Arduino:高度计传感器 - Arduino with Ultrasonic Sensor
带超声波传感器的Arduino - Arduino Guide for MPU-6050 Accelerometer and Gyroscope Sensor
MPU-6050加速度计和陀螺仪传感器的Arduino指南 - Arduino with BH1750 Ambient Light Sensor
带BH1750环境光传感器的Arduino - Arduino with TDS Sensor (Water Quality)
带TDS传感器的Arduino(水质)
提问:
-
how can I reduce the readout time? The HX711 currently needs 100ms between 2 measured points, I need about 10x as fast, i.e. 10ms. I’ve already increased the frequency in the circuit board to 80Hz, but I don’t see any difference. Thanks for a short note. Best Regards Rolando
如何缩短读出时间?HX711 目前在 2 个测量点之间需要 100 毫秒,我需要大约 10 倍的速度,即 10 毫秒。我已经将电路板中的频率提高到 80Hz,但我看不出有任何区别。 -
If I wanted to wire four load cells to increase the capacity of my scale how would I go about doing that? Would I need four amplifiers? Would I connect the load cells in parallel or series to power them?
如果我想连接四个称重传感器以增加体重秤的容量,我该怎么做?我需要四个放大器吗?我是并联还是串联称重传感器来为它们供电? -
Hi, how is gravity taking into account in this scale?
嗨,在这个规模中如何考虑重力?
In a usual scale you buy you get the mass because they are dividing the force measured by g
利用你购买的仪器,会得到质量,因为它们将测量的力除以 g
What happens here? 这里会发生什么?In this case, you simply use a proportion formula. 在这种情况下,您只需使用比例公式即可。 That’s why you need to measure with a known weight first. 这就是为什么您需要首先使用已知的重量进行测量的原因。
SMART HOME with Raspberry Pi, ESP32, and ESP8266 带有 Raspberry Pi、ESP32 和 ESP8266 的智能家居
理论:HX711AD +压力传感器(arduino) (zhihu.com)