ESPHome 2026.2.1
Loading...
Searching...
No Matches
hx711.cpp
Go to the documentation of this file.
1#include "hx711.h"
3#include "esphome/core/log.h"
4
5namespace esphome {
6namespace hx711 {
7
8static const char *const TAG = "hx711";
9
11 this->sck_pin_->setup();
12 this->dout_pin_->setup();
13 this->sck_pin_->digital_write(false);
14
15 // Read sensor once without publishing to set the gain
16 this->read_sensor_(nullptr);
17}
18
20 LOG_SENSOR("", "HX711", this);
21 LOG_PIN(" DOUT Pin: ", this->dout_pin_);
22 LOG_PIN(" SCK Pin: ", this->sck_pin_);
23 LOG_UPDATE_INTERVAL(this);
24}
26 uint32_t result;
27 if (this->read_sensor_(&result)) {
28 int32_t value = static_cast<int32_t>(result);
29 ESP_LOGD(TAG, "'%s': Got value %" PRId32, this->name_.c_str(), value);
30 this->publish_state(value);
31 }
32}
33bool HX711Sensor::read_sensor_(uint32_t *result) {
34 if (this->dout_pin_->digital_read()) {
35 ESP_LOGW(TAG, "HX711 is not ready for new measurements yet!");
36 this->status_set_warning();
37 return false;
38 }
39
40 uint32_t data = 0;
41 bool final_dout;
42
43 {
44 InterruptLock lock;
45 for (uint8_t i = 0; i < 24; i++) {
46 this->sck_pin_->digital_write(true);
48 data |= uint32_t(this->dout_pin_->digital_read()) << (23 - i);
49 this->sck_pin_->digital_write(false);
51 }
52
53 // Cycle clock pin for gain setting
54 for (uint8_t i = 0; i < static_cast<uint8_t>(this->gain_); i++) {
55 this->sck_pin_->digital_write(true);
57 this->sck_pin_->digital_write(false);
59 }
60 final_dout = this->dout_pin_->digital_read();
61 }
62
63 if (!final_dout) {
64 ESP_LOGW(TAG, "HX711 DOUT pin not high after reading (data 0x%" PRIx32 ")!", data);
65 this->status_set_warning();
66 return false;
67 }
68
70
71 if (data & 0x800000ULL) {
72 data |= 0xFF000000ULL;
73 }
74
75 if (result != nullptr)
76 *result = data;
77 return true;
78}
79
80} // namespace hx711
81} // namespace esphome
void status_set_warning(const char *message=nullptr)
void status_clear_warning()
virtual void setup()=0
virtual void digital_write(bool value)=0
virtual bool digital_read()=0
Helper class to disable interrupts.
Definition helpers.h:1547
constexpr const char * c_str() const
Definition string_ref.h:73
void setup() override
Definition hx711.cpp:10
bool read_sensor_(uint32_t *result)
Definition hx711.cpp:33
void update() override
Definition hx711.cpp:25
void dump_config() override
Definition hx711.cpp:19
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition core.cpp:28