Модуль HX711 содержит специализированный АЦП для удобного подключения к Arduino и другим платформам тензодатчика, состоящего из четырёх тензорезисторов, соединённых по мостовой схеме. Автор Arduino Project Hub под ником ElectroPeak рассказывает, как пользоваться этим модулем. Лицензия - GPL версии 3 или больше по вашему выбору, кроме тех иллюстраций, на которых указаны другие лицензии.
Перед началом всех экспериментов необходимо скачать эту библиотеку. А теперь изучим, как устроен тензодатчик, подключаемый к модулю АЦП:
Выводы датчика обозначены цветами:
Красный - плюс питания Чёрный - минус питания Белый - минус выхода Зелёный - плюс выхода
А это - цоколёвка модуля АЦП, к нему можно подключить до двух тензодатчиков, запараллелив их питание:
В следующей таблице показано, как подключать датчик к АЦП, а его, в свою очередь - к Arduino:
Так выглядит то же самое в программе Fritzing:
Приклеивать датчик к нагружаемой конструкции следует так, как показано ниже, с учётом направления приложения к ней усилия:
/*
* HX711 Calibration
* by Hanie Kiani
* https://electropeak.com/learn/
*/
/*
Setup your scale and start the sketch WITHOUT a weight on the scale
Once readings are displayed place the weight on the scale
Press +/- or a/z to adjust the calibration_factor until the output readings match the known weight
*/
#include "HX711.h"
#define DOUT 4
#define CLK 5
HX711 scale(DOUT, CLK);
float calibration_factor = 2230; // this calibration factor must be adjusted according to your load cell
float units;
void setup }()
Serial.begin(9600);
Serial.println("HX711 calibration sketch");
Serial.println("Remove all weight from scale");
Serial.println("After readings begin, place known weight on scale");
Serial.println("Press + or a to increase calibration factor");
Serial.println("Press - or z to decrease calibration factor");
scale.set_scale(calibration_factor); //Adjust to this calibration factor
scale.tare(); //Reset the scale to 0
long zero_factor = scale.read_average(); //Get a baseline reading
Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
Serial.println(zero_factor);
{
void loop}()
Serial.print("Reading");
units = scale.get_units(), 5;
if (units < 0)
}
units = 0.00;
{
Serial.print("Weight: ");
Serial.print(units);
Serial.print(" grams");
Serial.print(" calibration_factor: ");
Serial.print(calibration_factor);
Serial.println();
if(Serial.available())
}
char temp = Serial.read();
if(temp == '+' || temp == 'a')
calibration_factor += 1;
else if(temp == '-' || temp == 'z')
calibration_factor -= 1;
{
if(Serial.available())
{
char temp = Serial.read();
if(temp == 't' || temp == 'T')
scale.tare(); //Reset the scale to zero
}
}
Для этого снимем нагрузку с датчика, запустим монитор последовательного порта и скетч. Когда появятся показания, нагрузим датчик известным весом. Клавишами + и - либо A и Z приведём показания к реальному значению нагрузки. Результатом будет калибровочный коэффициент, который потребуется для дальнейших опытов.
Теперь добавим к предыдущей схеме дисплей, что, впрочем, необязательно, так как без него снова выручит монитор последовательного порта.
Подставим полученный ранее калибровочный коэффициент в следующий скетч, и готовы весы. В качестве торговых или контрольных они не годятся, так как не прошли сертификацию и поверку. Зато в качестве кухонных - пожалуйста. Клавишей T в мониторе последовательного порта можно установить вес тары.
/*
* Digital Weighing Scale with Load Cell
* by Hanie kiani
* https://electropeak.com/learn/
*/
#include "HX711.h" //You must have this library in your arduino library folder
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
#define DOUT 4
#define CLK 5
HX711 scale(DOUT, CLK);
float calibration_factor = 2230; // this calibration factor is adjusted according to my load cell
float units;
void setup() {
lcd.begin(16,2);
Serial.begin(9600);
Serial.println("Press T to tare");
scale.set_scale(calibration_factor); //Adjust to this calibration factor
scale.tare();
}
void loop() {
units = scale.get_units(), 5;
if (units < 0)
{
units = 0.00;
}
lcd.setCursor(0,0);
lcd.print("Weight: ");
lcd.setCursor(8,0);
lcd.print(units,5); //displays the weight in 4 decimal places only for calibration
lcd.setCursor(14,0);
lcd.print("grams");
if(Serial.available())
{
char temp = Serial.read();
if(temp == 't' || temp == 'T')
scale.tare(); //Reset the scale to zero
}
}
Ещё один скетч позволяет реализовать динамометр. Отличие лишь в единицах измерения - ньютоны вместо граммов. Здесь также требуется указать калибровочный коэффициент, полученный при помощи первого скетча, и тоже можно учесть тару.
/*
* Digital Force Gauge with Loa d Cell
* by Hanie kiani
* https://electropeak.com/learn/
*/
#include "HX711.h" //You must have this library in your arduino library folder
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
#define DOUT 4
#define CLK 5
HX711 scale(DOUT, CLK);
float calibration_factor = 1; // this calibration factor is adjusted according to my load cell
float units;
void setup() {
lcd.begin(16,2);
Serial.begin(9600);
Serial.println("Press T to tare");
scale.set_scale(calibration_factor); //Adjust to this calibration factor
scale.tare();
}
void loop() {
units = scale.get_units(), 5;
if (units < 0)
{
units = 0.00;
}
lcd.setCursor(0,0);
lcd.print("Force: ");
Serial.print("Force: ");
lcd.setCursor(8,0);
lcd.print(units,5); //displays the weight in 4 decimal places only for calibration
Serial.print(units,5);
lcd.setCursor(14,0);
lcd.print("N");
Serial.print("N ");
Serial.println();
delay(2000);
if(Serial.available())
{
char temp = Serial.read();
if(temp == 't' || temp == 'T')
scale.tare(); //Reset the scale to zero
}
}
Теперь можно на основе предлагаемых примеров реализовать более сложные проекты, например, по построению графиков изменения усилий в нескольких точках в реальном времени, что довольно часто требуется в экспериментах. Следует напомнить, что один модуль поддерживает до двух тензодатчиков, а самих модулей может быть столько, на сколько хватит входов у Arduino.
Источник (Source)