ESPHome  2022.6.3
hx711.cpp
Go to the documentation of this file.
1 #include "hx711.h"
2 #include "esphome/core/log.h"
3 #include "esphome/core/helpers.h"
4 
5 namespace esphome {
6 namespace hx711 {
7 
8 static const char *const TAG = "hx711";
9 
11  ESP_LOGCONFIG(TAG, "Setting up HX711 '%s'...", this->name_.c_str());
12  this->sck_pin_->setup();
13  this->dout_pin_->setup();
14  this->sck_pin_->digital_write(false);
15 
16  // Read sensor once without publishing to set the gain
17  this->read_sensor_(nullptr);
18 }
19 
21  LOG_SENSOR("", "HX711", this);
22  LOG_PIN(" DOUT Pin: ", this->dout_pin_);
23  LOG_PIN(" SCK Pin: ", this->sck_pin_);
24  LOG_UPDATE_INTERVAL(this);
25 }
28  uint32_t result;
29  if (this->read_sensor_(&result)) {
30  int32_t value = static_cast<int32_t>(result);
31  ESP_LOGD(TAG, "'%s': Got value %d", this->name_.c_str(), value);
32  this->publish_state(value);
33  }
34 }
35 bool HX711Sensor::read_sensor_(uint32_t *result) {
36  if (this->dout_pin_->digital_read()) {
37  ESP_LOGW(TAG, "HX711 is not ready for new measurements yet!");
38  this->status_set_warning();
39  return false;
40  }
41 
42  this->status_clear_warning();
43  uint32_t data = 0;
44 
45  {
46  InterruptLock lock;
47  for (uint8_t i = 0; i < 24; i++) {
48  this->sck_pin_->digital_write(true);
50  data |= uint32_t(this->dout_pin_->digital_read()) << (23 - i);
51  this->sck_pin_->digital_write(false);
53  }
54 
55  // Cycle clock pin for gain setting
56  for (uint8_t i = 0; i < this->gain_; i++) {
57  this->sck_pin_->digital_write(true);
59  this->sck_pin_->digital_write(false);
61  }
62  }
63 
64  if (data & 0x800000ULL) {
65  data |= 0xFF000000ULL;
66  }
67 
68  if (result != nullptr)
69  *result = data;
70  return true;
71 }
72 
73 } // namespace hx711
74 } // namespace esphome
virtual void digital_write(bool value)=0
const float DATA
For components that import data from directly connected sensors like DHT.
Definition: component.cpp:18
void update() override
Definition: hx711.cpp:27
std::string name_
Definition: entity_base.h:54
bool read_sensor_(uint32_t *result)
Definition: hx711.cpp:35
void dump_config() override
Definition: hx711.cpp:20
virtual void setup()=0
void status_clear_warning()
Definition: component.cpp:148
void publish_state(float state)
Publish a new state to the front-end.
Definition: sensor.cpp:70
float get_setup_priority() const override
Definition: hx711.cpp:26
void status_set_warning()
Definition: component.cpp:140
virtual bool digital_read()=0
void setup() override
Definition: hx711.cpp:10
Helper class to disable interrupts.
Definition: helpers.h:533
Definition: a4988.cpp:4
void IRAM_ATTR HOT delayMicroseconds(uint32_t us)
Definition: core.cpp:29