ESPHome 2026.11.0-dev
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
7ESPHOME_LOG_TAG(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, LOG_STR_ARG(this->get_log_name()), 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 {
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 (!this->status_comm_result(final_dout)) {
63 ESP_LOGW(TAG, "HX711 DOUT pin not high after reading (data 0x%" PRIx32 ")!", data);
64 return false;
65 }
66
67 data = static_cast<uint32_t>(sign_extend<24>(data));
68
69 if (result != nullptr)
70 *result = data;
71 return true;
72}
73
74} // namespace esphome::hx711
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
const LogString * get_log_name() const
Get the name for a "%s" log argument (LOG_STR_ARG).
virtual void setup()=0
virtual void digital_write(bool value)=0
virtual bool digital_read()=0
Helper class to disable interrupts.
Definition helpers.h:2164
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:65
ESPHOME_LOG_TAG(TAG, "hx711")
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition hal.cpp:48
constexpr int32_t sign_extend(uint32_t value)
Sign-extend the low BITS bits of value, e.g. sign_extend<24>(0xFFFFFE) == -2. Higher bits are ignored...
Definition helpers.h:1012
static void uint32_t
SemaphoreHandle_t lock