ESPHome 2026.5.0b1
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::hx711 {
6
7static const char *const TAG = "hx711";
8
10 this->sck_pin_->setup();
11 this->dout_pin_->setup();
12 this->sck_pin_->digital_write(false);
13
14 // Read sensor once without publishing to set the gain
15 this->read_sensor_(nullptr);
16}
17
19 LOG_SENSOR("", "HX711", this);
20 LOG_PIN(" DOUT Pin: ", this->dout_pin_);
21 LOG_PIN(" SCK Pin: ", this->sck_pin_);
22 LOG_UPDATE_INTERVAL(this);
23}
25 uint32_t result;
26 if (this->read_sensor_(&result)) {
27 int32_t value = static_cast<int32_t>(result);
28 ESP_LOGD(TAG, "'%s': Got value %" PRId32, this->name_.c_str(), value);
29 this->publish_state(value);
30 }
31}
33 if (this->dout_pin_->digital_read()) {
34 ESP_LOGW(TAG, "HX711 is not ready for new measurements yet!");
35 this->status_set_warning();
36 return false;
37 }
38
39 uint32_t data = 0;
40 bool final_dout;
41
42 {
43 InterruptLock lock;
44 for (uint8_t i = 0; i < 24; i++) {
45 this->sck_pin_->digital_write(true);
47 data |= uint32_t(this->dout_pin_->digital_read()) << (23 - i);
48 this->sck_pin_->digital_write(false);
50 }
51
52 // Cycle clock pin for gain setting
53 for (uint8_t i = 0; i < static_cast<uint8_t>(this->gain_); i++) {
54 this->sck_pin_->digital_write(true);
56 this->sck_pin_->digital_write(false);
58 }
59 final_dout = this->dout_pin_->digital_read();
60 }
61
62 if (!final_dout) {
63 ESP_LOGW(TAG, "HX711 DOUT pin not high after reading (data 0x%" PRIx32 ")!", data);
64 this->status_set_warning();
65 return false;
66 }
67
69
70 if (data & 0x800000ULL) {
71 data |= 0xFF000000ULL;
72 }
73
74 if (result != nullptr)
75 *result = data;
76 return true;
77}
78
79} // namespace esphome::hx711
void status_clear_warning()
Definition component.h:306
virtual void setup()=0
virtual void digital_write(bool value)=0
virtual bool digital_read()=0
Helper class to disable interrupts.
Definition helpers.h:1952
constexpr const char * c_str() const
Definition string_ref.h:73
void setup() override
Definition hx711.cpp:9
bool read_sensor_(uint32_t *result)
Definition hx711.cpp:32
void update() override
Definition hx711.cpp:24
void dump_config() override
Definition hx711.cpp:18
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
static void uint32_t